Skip to content

fix(batch): commit bidirectional referrers to the bytes the flags callback stores - #991

Merged
QuantumExplorer merged 2 commits into
developfrom
fix/bidi-ref-flags-callback-stale-referrers
Sep 23, 2026
Merged

QuantumExplorer merged 2 commits into
developfrom
fix/bidi-ref-flags-callback-stale-referrers

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Issue being fixed or feature implemented

Under GROVE_V4, a batch that rewrites a flagged backward-references item left every referrer committed to a hash the item no longer has. Drive's flags callback triggers this on every cross-epoch document update. The root hash stayed deterministic and plain get returned correct values, but verify_grovedb reported each referrer as corrupted, and honest V1 proofs of those referrers failed with V1 mismatch in lower layer hash. The affected documents became permanently unprovable.

The 2026-09-23 audit found this; it has not been filed as an issue. It is V4-only (backward-reference elements are refused on V1–V3, and apply_batch.backward_references_maintenance = 1 only in v4.rs), so it has to land before V4 activates.

Root cause. The batch planner committed each referrer, and every upstream chain member, to the logical hash of the target's caller-supplied bytes (plan_element_update's new_logical_hash, and pass 2's target_value_hash from the staged overlay). Merk then runs the just-in-time flags update with the caller's callback and rehashes only the target's own node from its final bytes. StorageFlags::update_element_flags rewrites the flags on every cross-epoch update:

  • same size: resets to the old flags
  • larger: merges into MultiEpoch
  • smaller: combines the removed bytes

So the referrers keep the supplied hash. Later writes don't fix it, because the stored and supplied flags keep differing under that callback. The test comment that said the next write "heals" this was wrong.

Plain references written in the same batch had a related flaw. Their prediction (process_old_element_flags) measured the target's stripped shape, while Merk measures the full stored element, referrer list included. It also treats a family sum item as a fixed-cost sum item that just copies the old flags over, but Merk gives family items no value-defined cost and does run the callback. Both cases are reproduced by the new tests.

What was done?

  • Prediction through Merk's own routine. TreeNode::provided_value_hash_put_final_value (merk) runs the same steps a PutWithProvidedValueHash over a stored value performs (install value and feature type, just_in_time_tree_node_value_update) on a detached node and returns the final bytes. A merk unit test pins it to a real apply.

  • One set of apply callbacks. The four closures execute_ops_on_path hands Merk moved verbatim into batch/just_in_time_value_update.rs. The apply and the prediction (predict_provided_value_hash_put) now call the same functions. This is a pure extraction with no behavior change.

  • Pass 3 in the backward-references preprocessor (Expansion::settle_end_hashes). It runs after planning, once every registration has been folded in, because the flags a callback derives depend on the item's full size. It predicts the landed bytes of every flagged family item written over a stored value. Where the landed logical hash differs from the one referrers were committed to, it re-propagates it along the referrer chains (reusing plan_propagation and the existing merge rules). Later rounds re-predict only items a propagation rewrote (dropping a dangling entry); two rounds settle any batch with deterministic callbacks. A callback that never settles is refused as a client error.

  • One prediction, checked after the apply. The pass returns the predicted landed elements, and the apply uses them in two ways:

    • same-batch plain references to a family item hash its predicted bytes (landed_backward_references_item_value_hash), with no second read or prediction;
    • after the Merk apply, each predicted item's stored bytes are compared with the prediction, and the batch is refused (JustInTimeElementFlagsClientError) if they differ. That can only happen if a callback isn't deterministic.

    apply_batch_with_element_flags_update now documents that its callbacks must be deterministic.

  • Merk: provided-value-hash puts drop an inherited value-defined cost ([audit][C010] Ordinary replacements retain stale specialized storage charges #908's twin). A family item written over a sum item was sized at the sum item's fixed cost: a 196-byte growth was charged as 0 added bytes under an inert callback. Only V4 family writes use this op, so no gate is needed.

  • The overlay store keeps the committed bytes it already reads in a separate map (no extra seeks, no extra clones on element reads).

  • Behavior note: a same-batch plain reference to a family item that switches between its item and sum-item forms is now accepted, since the prediction follows Merk. Before, the reference path's process_old_element_flags refused it with NotSupported. The V1–V3 Item arm is unchanged.

Versioning and costs.

  • No new GroveVersion slot. Every changed path runs only under V4: the preprocessor runs only when batch_maintains_backward_references, and the family arms of follow_reference_get_value_hash are unreachable on V1–V3, where family elements are refused at batch entry.
  • The closure extraction touches the shared apply path but is the same logic moved into functions. V1–V3 behavior and costs are unchanged. The Item/SumItem plain-reference arm (process_old_element_flags) is left alone.
  • Estimated costs are not touched. Actual V4 costs change only for batches that write a flagged family item over a stored value: extra hash calls when a flags-changing callback moves a referenced item's hash, and correct (larger) storage charges when a family item replaces a sum item or tree.

How Has This Been Tested?

New grovedb/src/tests/backward_references_flags_update_tests.rs, using Drive's real StorageFlags callbacks. Each case asserts that verify_grovedb is clean and that an honest proof of each referrer verifies against the live root:

  • same-size, larger and smaller epoch-3 updates, with a direct referrer and an upstream chain member
  • three successive cross-epoch updates (the claimed "heal": the stored flags never match the supplied ones)
  • pass 2: new referrers (and a reference stacked on one) in the same batch as the target update, including a target whose only referrer is the new registration
  • an item replacing a flagged bidirectional reference (its carried referrer)
  • same-batch plain references, and a family sum item in a sum tree
  • a plain reference above a deeper target; count-tree host; the ItemWithSumItem family variant; an item-to-sum-item switch with a plain reference
  • a family item replacing a sum item is charged for its own size (fails without the Merk fix)
  • a generic mutating callback; a stateful callback refused after the apply; a failing callback (its own error surfaces, root unchanged)
  • a registration-only batch whose re-propagation drops a dangling entry and has to settle again
  • worst-case estimate still covers a flagged overwrite plus new referrer under Drive's epoch flags (batch_backward_references_cost_tests)

These tests fail without the fix:

  • Without the settling pass, 7 of the 8 value-update cases fail.
  • With the old plain-reference arm, both plain-reference cases fail.
  • Without the Merk fix, the sum-item replacement is charged 0 added bytes instead of 196.

Other checks:

  • merk: provided_value_hash_put_final_value_matches_the_apply compares the helper with a real apply, for a growing and a shrinking write.
  • cargo test -p grovedb --lib: 3505 passed, 0 failed.
  • cargo clippy -p grovedb -p grovedb-merk --all-targets -- -D warnings and cargo fmt --check are clean.

Breaking Changes

None. TreeNode::provided_value_hash_put_final_value is a new public merk API. No existing signature changes (apply_batch_with_element_flags_update only binds its callback parameters as mut).

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

PR Hygiene · 635bd46

  • Bots — coderabbitai not yet · thepastaclaw not yet — /skip-bots proceeds without the ones not yet reported
  • Self-review — post /self-reviewed once the bots are done
  • Within your 5 open PRs
  • Build running
  • Approvals — you own every area touched; none needed

When every box is checked the PR Hygiene check passes and this can merge.

Summary by CodeRabbit

  • Bug Fixes
    • Backward references now remain correctly linked when batch updates change an item’s stored flags or value size, including across chains of references and different item types.
    • Batch updates now fail without changing stored data when flag callbacks fail or produce inconsistent results, preventing references from pointing to incorrect values.
    • Cost estimates now account for updates to flagged items with backward references.

…lback stores

Under GROVE_V4 the backward-references batch planner committed every
referrer of a family item to the logical hash of the caller-supplied
bytes. Merk then runs the caller's just-in-time flags update, and Drive's
StorageFlags::update_element_flags rewrites flags on every cross-epoch
update (same size: old flags; larger: MultiEpoch merge; smaller: removed
bytes combined). Only the item's own node was rehashed, so verify_grovedb
flagged every referrer and honest V1 proofs of them failed.

- merk: TreeNode::provided_value_hash_put_final_value runs the apply's
  own just-in-time update on a detached node and returns the final bytes.
- batch: the apply's four JIT callbacks move verbatim into
  just_in_time_value_update.rs so the apply and the prediction share them.
- preprocessor pass 3 (settle_end_hashes): after planning, predict each
  flagged, referenced family item's landed bytes and re-propagate the
  landed logical hash where it moved.
- same-batch plain references to a family item hash the predicted landed
  bytes, measured on the full element against the committed predecessor
  (the old prediction measured the stripped shape and treated family sum
  items as fixed-cost sum items).

V4-only paths; V1-V3 behavior and costs are unchanged. Corrects the test
comment that claimed the next write heals stale referrers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: fd5b0ae9-07c9-4371-8b7c-01c7e56547ba

📥 Commits

Reviewing files that changed from the base of the PR and between 2d92ac4 and 635bd46.

📒 Files selected for processing (11)
  • grovedb/src/batch/backward_references.rs
  • grovedb/src/batch/just_in_time_reference_update.rs
  • grovedb/src/batch/just_in_time_value_update.rs
  • grovedb/src/batch/mod.rs
  • grovedb/src/bidirectional_references/semantics.rs
  • grovedb/src/tests/backward_references_flags_update_tests.rs
  • grovedb/src/tests/batch_backward_references_cost_tests.rs
  • grovedb/src/tests/batch_backward_references_tests.rs
  • grovedb/src/tests/mod.rs
  • merk/src/tree/just_in_time_value_update.rs
  • merk/src/tree/mod.rs
 _____________________________________________
< HD, 4K, 8K...I see bugs in all resolutions. >
 ---------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Sep 23, 2026
@thepastaclaw

thepastaclaw commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🕓 Queued for automated review — 6th in line, estimated start in ~1.4 h (commit 635bd46)
Estimated review time once started: ~35 min (two-phase automated review; median of recent runs).

  • Request priority review — click to move this review to the front of the queue.

@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.04861% with 17 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.09%. Comparing base (d5a54b7) to head (635bd46).
⚠️ Report is 14 commits behind head on develop.

Files with missing lines Patch % Lines
grovedb/src/batch/backward_references.rs 94.18% 10 Missing ⚠️
grovedb/src/batch/mod.rs 91.78% 6 Missing ⚠️
grovedb/src/batch/just_in_time_value_update.rs 99.38% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #991      +/-   ##
===========================================
+ Coverage    92.95%   93.09%   +0.14%     
===========================================
  Files          331      332       +1     
  Lines       104500   105213     +713     
===========================================
+ Hits         97138    97949     +811     
+ Misses        7362     7264      -98     
Components Coverage Δ
grovedb-core 91.45% <96.00%> (+0.22%) ⬆️
merk 94.03% <100.00%> (+0.05%) ⬆️
storage 91.94% <ø> (ø)
commitment-tree 95.62% <ø> (ø)
mmr 95.43% <ø> (ø)
bulk-append-tree 93.72% <ø> (+0.94%) ⬆️
element 97.18% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…diction

Review follow-ups for the flags-callback settling pass:

- The settling pass now predicts every flagged family item written over a
  stored value and hands the apply one map of landed elements. Same-batch
  plain references hash from it (no second, apply-time read and
  prediction), and the apply checks each item's stored bytes against it,
  refusing the batch when a non-deterministic callback answers the apply
  differently (JustInTimeElementFlagsClientError). The callback contract is
  documented on apply_batch_with_element_flags_update.
- Later settling rounds re-predict only the items the previous round
  rewrote; non-convergence is reported as a callback (client) error.
- The overlay store keeps committed bytes in their own map, so element
  reads no longer clone them.
- merk: a provided-value-hash put drops the value-defined cost inherited
  from its predecessor (issue #908's twin). A family item written over a
  sum item was billed at the sum item's fixed size (196 grown bytes
  charged as 0 under an inert callback). Only V4 family writes use this op.
- Prediction errors carry context.
- Tests: worst-case estimate under Drive's epoch flags, a plain reference
  above a deeper target, count-tree host, ItemWithSumItem family variant,
  item-to-sum-item switch with a plain reference, the sum-item cost, a
  stateful callback refused, and the failing-callback error kind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@QuantumExplorer
QuantumExplorer merged commit 7797e2d into develop Sep 23, 2026
12 of 14 checks passed
@QuantumExplorer
QuantumExplorer deleted the fix/bidi-ref-flags-callback-stale-referrers branch September 23, 2026 19:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

waiting-bots Waiting for the review bots to report on this head

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants