Skip to content

fix(merk): charge ordinary replacements of specialized values from their own bytes (#908) - #918

Merged
QuantumExplorer merged 2 commits into
developfrom
fix/908-stale-specialized-cost-on-ordinary-replacement
Sep 6, 2026
Merged

QuantumExplorer merged 2 commits into
developfrom
fix/908-stale-specialized-cost-on-ordinary-replacement

Conversation

@QuantumExplorer

Copy link
Copy Markdown
Member

Fixes #908 (audit C010).

What was wrong

A Merk node loaded from storage is stamped with the value_defined_cost of the element it holds (TreeNode::decode + Element::value_defined_cost_for_serialized_value). Trees and sum items carry a fixed cost size, so for them the stamp is Some(fixed size). The ordinary replacements — TreeNode::put_value (Op::Put) and TreeNode::put_value_and_reference_value_hash (Op::PutCombinedReference) — only swapped the value bytes and kept the stamp. Replacing a tree or a sum item with an Item or a Reference was therefore charged at the predecessor's fixed size, and because the stamp disables needs_value_verification, the physical-size check that would have caught it was skipped. The full replacement bytes were still written.

Reproduced on develop (9a21bbc), direct insert and apply_batch alike. Replacing a SumItem with a 200-byte Item inside a sum tree:

added replaced
Item(5 bytes) → Item(200 bytes), same shape (control) 196 470
SumItem → Item(200 bytes) 0 473

Tree → Item and SumTree → Item behave the same way. The reverse direction (Item → SumItem / Tree) was always right because the specialized puts stamp the metadata from the new operation. Value hashes were never affected.

Fix (gated to GROVE_V4)

Charged bytes feed Platform's fee replay, and GROVE_V3 is live, so the change is version-gated:

  • New MerkTreeVersions { put_value } in grovedb-version (merk_versions.tree.put_value): 0 for grove v1..v3, 1 for v4.
  • merk/src/tree/put_value/{mod.rs,v0.rs,v1.rs}: the two ordinary put methods move into a versioned dispatch module. v0 is the previous body verbatim. v1 replaces the value through the new KV::put_ordinary_value_no_update_of_hashes, which clears the stamp, so the charge is measured from the replacement's own bytes and verified on commit.
  • grove_version is threaded through Walker::put_value / put_value_and_reference_value_hash (the walker already had it for fetches).
  • Old-value removal accounting is untouched: it is always derived from the stored predecessor bytes through old_specialized_cost.
  • Estimated costs need no change: add_cost_case_merk_replace* and worst_case_merk_replace_element already size from the new element only, so on v4 the actual charge matches the estimate's assumption.

On v4, SumItem → Item(200) now charges 193 added / 473 replaced: the same 666 total as the control, and the 193 added bytes are exactly what the reverse Item → SumItem replacement frees.

Tests

  • merk/src/tree/put_value/mod.rs: sum item → item / reference, tree → item / reference, sum tree → item through the default Element insert entry points with a storage batch commit (the path that prices and verifies writes). v4 added == new cost − old cost using Element::specialized_costs_for_key_value as an independent oracle and equals the same-shape ordinary control; reverse replacements free exactly what the forward ones charged; v3 pinned to zero added bytes; ordinary → ordinary and ordinary → specialized identical across v3/v4; unknown put_value version rejected.
  • grovedb/src/tests/ordinary_replacement_cost_tests.rs: the same matrix end-to-end through GroveDb::insert and apply_batch, with GROVE_V3 legacy and GROVE_V4 figures pinned.
  • Changelog and book (merk-tree.md KV section) updated.

Note: cargo test -p grovedb --features full,estimated_costs does not compile on develop without unsafe-dump-load (non_merk_integrity_audit_tests uses raw_storage); the suite was run with that feature added.

🤖 Generated with Claude Code

…eir own bytes (#908)

A node loaded from storage is stamped with the value_defined_cost of the
element it holds. The ordinary puts (Op::Put / Op::PutCombinedReference)
kept that stamp, so replacing a tree or a sum item with an Item or a
Reference was charged at the predecessor's fixed size with physical-size
verification disabled, while the full replacement bytes were written.

Gate to GROVE_V4 via merk_versions.tree.put_value (0 for v1..v3, 1 for
v4). The two ordinary put methods move into merk/src/tree/put_value/
{mod.rs,v0.rs,v1.rs}; v1 clears the stamp through
KV::put_ordinary_value_no_update_of_hashes. Old-value removal accounting
and the ordinary -> specialized direction are unchanged; estimated costs
already size from the new element only.

Tests at the merk level (formula oracle against
Element::specialized_costs_for_key_value, v3 legacy pins, reverse-mirror
invariant, unknown-version rejection) and end to end through
GroveDb::insert and apply_batch with GROVE_V3 and GROVE_V4 figures pinned.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 43 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Team

Run ID: 6725e7d0-71ad-4c07-b3db-0a69fd8ea977

📥 Commits

Reviewing files that changed from the base of the PR and between 6d47366 and 58c538e.

📒 Files selected for processing (16)
  • CHANGELOG.md
  • docs/book/src/merk-tree.md
  • grovedb-version/src/version/merk_versions.rs
  • grovedb-version/src/version/v1.rs
  • grovedb-version/src/version/v2.rs
  • grovedb-version/src/version/v3.rs
  • grovedb-version/src/version/v4.rs
  • grovedb/src/tests/mod.rs
  • grovedb/src/tests/ordinary_replacement_cost_tests.rs
  • merk/src/tree/kv.rs
  • merk/src/tree/mod.rs
  • merk/src/tree/ops.rs
  • merk/src/tree/put_value/mod.rs
  • merk/src/tree/put_value/v0.rs
  • merk/src/tree/put_value/v1.rs
  • merk/src/tree/walk/mod.rs

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.

@codecov

codecov Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.57983% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.42%. Comparing base (6d47366) to head (58c538e).

Files with missing lines Patch % Lines
merk/src/tree/put_value/v0.rs 97.64% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #918      +/-   ##
===========================================
+ Coverage    92.39%   92.42%   +0.03%     
===========================================
  Files          302      305       +3     
  Lines        93476    93865     +389     
===========================================
+ Hits         86369    86758     +389     
  Misses        7107     7107              
Components Coverage Δ
grovedb-core 90.48% <ø> (+<0.01%) ⬆️
merk 93.35% <99.57%> (+0.11%) ⬆️
storage 91.70% <ø> (ø)
commitment-tree 96.38% <ø> (ø)
mmr 95.11% <ø> (ø)
bulk-append-tree 92.78% <ø> (ø)
element 97.98% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@QuantumExplorer

Copy link
Copy Markdown
Member Author

This is Claude. @coderabbitai review — the first pass hit the review limit; requesting the review now that capacity is back.

@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

@QuantumExplorer I will review the changes in #918.

⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@QuantumExplorer

Copy link
Copy Markdown
Member Author

This is Claude. @coderabbitai review — retrying after the review-limit window.

@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

@QuantumExplorer I will review the changes in #918.

⚠️ Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

…ialized-cost-on-ordinary-replacement

# Conflicts:
#	CHANGELOG.md
@QuantumExplorer

Copy link
Copy Markdown
Member Author

Reviewed

@QuantumExplorer
QuantumExplorer merged commit 1fe7967 into develop Sep 6, 2026
13 checks passed
@QuantumExplorer
QuantumExplorer deleted the fix/908-stale-specialized-cost-on-ordinary-replacement branch September 6, 2026 23:36
QuantumExplorer added a commit that referenced this pull request Sep 6, 2026
Conflict resolution notes:

- get/mod.rs: `follow_reference_with_max_hop` keeps develop's
  `underlying()`-based hop detection (#858) and adds the bidirectional
  edge as a hop that also caps the remaining budget with its declared
  `max_hop`; the terminal is returned wrapper-intact but with its
  referrer list stripped (the logical form forward references commit to).
- lib.rs `verify_grovedb`: a bidirectional reference's self hash is
  `combine(inner, backrefs)`; develop's `reference_terminal_as_committed`
  selection is applied to that self hash and the terminal's LOGICAL hash
  is what the chain commits to.
- proof/generate.rs: every V1 dereferencing site threads the bidi
  `max_hop` and self-hash override into develop's committed-terminal
  selection; the backward-references item arm charges rows through the
  per-instance limit state (#844/#845).
- insert/add_element_on_transaction/v2.rs (#858): carries the same
  backward-references arms as v1 (family items store like their plain
  twins, bidirectional references fail closed outside the MerkCache flow,
  references commit to the terminal's logical hash).
- grovedb-version v4.rs: `add_element_on_transaction: 2` from develop;
  the `*_without_transaction` slots removed by this branch stay removed.
- sum-budget row binding (#870): `KVBackwardsReferencesValueHash` rows
  are reported by the merk verifier as hash-bound (their combined hash is
  recomputed from the presented bytes into the root), so the window
  verifier accepts backward-references sum items.
- get/mod.rs (#923): develop's seeded-`visited` walk
  (`follow_reference_as_stored_visiting`, used by
  `follow_reference_as_stored_for_write` to refuse a chain running back
  through the written position) and this branch's per-edge hop budget now
  share one walk, `follow_reference_with_max_hop_visiting`; the two public
  entry points are thin wrappers over it.
- merk/src/tree/mod.rs (#918): `put_value` / `put_value_and_reference_value_hash`
  moved to the versioned `put_value/` module on develop; the provided-hash
  put (with its post-JIT rehash) stays in `tree/mod.rs`.
- V1 prover stack frame: both sides had grown `prove_subqueries_v1`'s
  debug frame to the edge of the 2 MiB test-thread stack (94 KiB before
  the merge, 100 KiB after — `proof_generation_succeeds_at_reasonable_depth`
  overflowed at depth 20). The self-contained sections — the count-offset
  short-circuit, the non-Merk lower-layer descents and the reference-row
  rewrites — now live in `#[inline(never)]` helpers so their locals stop
  being reserved in every recursion level. V0 prover untouched.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
QuantumExplorer added a commit that referenced this pull request Sep 7, 2026
Conflict resolution notes:

- get/mod.rs: `follow_reference_with_max_hop` keeps develop's
  `underlying()`-based hop detection (#858) and adds the bidirectional
  edge as a hop that also caps the remaining budget with its declared
  `max_hop`; the terminal is returned wrapper-intact but with its
  referrer list stripped (the logical form forward references commit to).
- lib.rs `verify_grovedb`: a bidirectional reference's self hash is
  `combine(inner, backrefs)`; develop's `reference_terminal_as_committed`
  selection is applied to that self hash and the terminal's LOGICAL hash
  is what the chain commits to.
- proof/generate.rs: every V1 dereferencing site threads the bidi
  `max_hop` and self-hash override into develop's committed-terminal
  selection; the backward-references item arm charges rows through the
  per-instance limit state (#844/#845).
- insert/add_element_on_transaction/v2.rs (#858): carries the same
  backward-references arms as v1 (family items store like their plain
  twins, bidirectional references fail closed outside the MerkCache flow,
  references commit to the terminal's logical hash).
- grovedb-version v4.rs: `add_element_on_transaction: 2` from develop;
  the `*_without_transaction` slots removed by this branch stay removed.
- sum-budget row binding (#870): `KVBackwardsReferencesValueHash` rows
  are reported by the merk verifier as hash-bound (their combined hash is
  recomputed from the presented bytes into the root), so the window
  verifier accepts backward-references sum items.
- get/mod.rs (#923): develop's seeded-`visited` walk
  (`follow_reference_as_stored_visiting`, used by
  `follow_reference_as_stored_for_write` to refuse a chain running back
  through the written position) and this branch's per-edge hop budget now
  share one walk, `follow_reference_with_max_hop_visiting`; the two public
  entry points are thin wrappers over it.
- merk/src/tree/mod.rs (#918): `put_value` / `put_value_and_reference_value_hash`
  moved to the versioned `put_value/` module on develop; the provided-hash
  put (with its post-JIT rehash) stays in `tree/mod.rs`.
- merk/src/merk/restore.rs (#840): develop computes the parent-link
  values inside `rewrite_parent_link` and refuses a bare-`Hash` chunk root
  there; this branch captures them in `process_chunk` (before the write,
  applied only after it succeeds), so the descriptive refusal moved to that
  capture and the rewrite keeps its parameters. `NULL_HASH` import taken
  from develop.
- replication/verify.rs (#840): the post-restore value-hash binding pass
  learns the backward-references family — a bidirectional reference
  binds `combine(combine(inner, referrer list), end hash)` with the end
  hash being the terminal's logical hash (bidirectional edges are hopped
  like any other), the item variants bind `combine(inner, referrer list)`.
- replication_session_tests.rs (#840): both sides appended tests at the
  same spot; the bidirectional-reference round trip and develop's indexed
  / incremental / version tests are all kept.
- V1 prover stack frame: both sides had grown `prove_subqueries_v1`'s
  debug frame to the edge of the 2 MiB test-thread stack (94 KiB before
  the merge, 100 KiB after — `proof_generation_succeeds_at_reasonable_depth`
  overflowed at depth 20). The self-contained sections — the count-offset
  short-circuit, the non-Merk lower-layer descents and the reference-row
  rewrites — now live in `#[inline(never)]` helpers so their locals stop
  being reserved in every recursion level. V0 prover untouched.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
QuantumExplorer added a commit that referenced this pull request Sep 7, 2026
Conflict resolution notes:

- get/mod.rs: `follow_reference_with_max_hop` keeps develop's
  `underlying()`-based hop detection (#858) and adds the bidirectional
  edge as a hop that also caps the remaining budget with its declared
  `max_hop`; the terminal is returned wrapper-intact but with its
  referrer list stripped (the logical form forward references commit to).
- lib.rs `verify_grovedb`: a bidirectional reference's self hash is
  `combine(inner, backrefs)`; develop's `reference_terminal_as_committed`
  selection is applied to that self hash and the terminal's LOGICAL hash
  is what the chain commits to.
- proof/generate.rs: every V1 dereferencing site threads the bidi
  `max_hop` and self-hash override into develop's committed-terminal
  selection; the backward-references item arm charges rows through the
  per-instance limit state (#844/#845).
- insert/add_element_on_transaction/v2.rs (#858): carries the same
  backward-references arms as v1 (family items store like their plain
  twins, bidirectional references fail closed outside the MerkCache flow,
  references commit to the terminal's logical hash).
- grovedb-version v4.rs: `add_element_on_transaction: 2` from develop;
  the `*_without_transaction` slots removed by this branch stay removed.
- sum-budget row binding (#870): `KVBackwardsReferencesValueHash` rows
  are reported by the merk verifier as hash-bound (their combined hash is
  recomputed from the presented bytes into the root), so the window
  verifier accepts backward-references sum items.
- get/mod.rs (#923): develop's seeded-`visited` walk
  (`follow_reference_as_stored_visiting`, used by
  `follow_reference_as_stored_for_write` to refuse a chain running back
  through the written position) and this branch's per-edge hop budget now
  share one walk, `follow_reference_with_max_hop_visiting`; the two public
  entry points are thin wrappers over it.
- merk/src/tree/mod.rs (#918): `put_value` / `put_value_and_reference_value_hash`
  moved to the versioned `put_value/` module on develop; the provided-hash
  put (with its post-JIT rehash) stays in `tree/mod.rs`.
- merk/src/merk/restore.rs (#840): develop computes the parent-link
  values inside `rewrite_parent_link` and refuses a bare-`Hash` chunk root
  there; this branch captures them in `process_chunk` (before the write,
  applied only after it succeeds), so the descriptive refusal moved to that
  capture and the rewrite keeps its parameters. `NULL_HASH` import taken
  from develop.
- replication/verify.rs (#840): the post-restore value-hash binding pass
  learns the backward-references family — a bidirectional reference
  binds `combine(combine(inner, referrer list), end hash)` with the end
  hash being the terminal's logical hash (bidirectional edges are hopped
  like any other), the item variants bind `combine(inner, referrer list)`.
- replication_session_tests.rs (#840): both sides appended tests at the
  same spot; the bidirectional-reference round trip and develop's indexed
  / incremental / version tests are all kept.
- V1 prover stack frame: both sides had grown `prove_subqueries_v1`'s
  debug frame to the edge of the 2 MiB test-thread stack (94 KiB before
  the merge, 100 KiB after — `proof_generation_succeeds_at_reasonable_depth`
  overflowed at depth 20). The self-contained sections — the count-offset
  short-circuit, the non-Merk lower-layer descents and the reference-row
  rewrites — now live in `#[inline(never)]` helpers so their locals stop
  being reserved in every recursion level. V0 prover untouched.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[audit][C010] Ordinary replacements retain stale specialized storage charges

1 participant