Repository navigation
feat(merk,grovedb): reject NonCounted/NotCountedOrSummed in provable count parents - #672
Conversation
…count parents `Provable*` count trees commit their aggregate count into every node's hash via `node_hash_with_count`. Hosting a `NonCounted` (or `NotCountedOrSummed`) child would commit a cryptographic count that diverges from the actual number of stored elements — confusing for callers and a footgun for proof-driven readers of `AggregateCountOnRange` queries, whose answer IS that committed count. This change enforces the rule at every insert surface so the problematic shape can never land on disk going forward: - `TreeType::accepts_non_counted_children` (CountTree | CountSumTree). - `TreeType::accepts_not_counted_or_summed_children` (CountSumTree only). Both predicates are stricter than `is_count_*_bearing` (which still answer the structural question "does this tree track count/sum?" for the aggregate logic that legitimately needs that). The existing predicates are unchanged. Guard sites switched to the new predicates: - `merk/src/element/insert.rs` — `insert`, `insert_reference`, `insert_subtree` (3 guards × 2 wrappers each). - `grovedb/src/batch/mod.rs` — batch validation + `RefreshReference` trusted path. Tests updated: - 6 existing tests that asserted acceptance in `ProvableCount*` parents flipped to assert the new rejection. - 4 new direct-and-batch rejection tests in `non_counted_tests.rs` pin both wrappers against both `Provable*` count parents. - `non_counted_still_accepted_in_count_sum_tree` pins the deliberate remaining acceptance. - TreeType-level unit tests for the two new predicates. No grove-version gate: matches the approach used when the wrappers were originally added (PR #654, #666). Platform upgrades are coordinated and no production data currently uses the now-rejected shape. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (8)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## develop #672 +/- ##
===========================================
+ Coverage 91.20% 91.21% +0.01%
===========================================
Files 205 205
Lines 60156 60228 +72
===========================================
+ Hits 54864 54936 +72
Misses 5292 5292
🚀 New features to boost your workflow:
|
Following PR #672 (merged into develop after this branch was opened), `NonCounted` and `NotCountedOrSummed` can no longer be inserted into `ProvableCountTree` / `ProvableCountSumTree` at the GroveDB or merk insert path. That structurally closes the P1 finding raised on this PR: a Contained subtree containing `[counted-a, NonCounted-b, counted-c]` would have subtree_count = 2 and collapse on offset = 2 to HashWithCount, hiding the regular-pagination divergence (which would return [c]). Two changes here: 1. **Tests**: - Add `p1_noncounted_in_provable_count_tree_rejected_at_insert` as the authoritative regression test — asserts the GroveDB insert refuses NonCounted into a ProvableCountTree, citing #672. - Remove the now-obsolete `rejects_count_offset_with_non_counted_entry` test (which inserted NonCounted then expected the prover to reject on descent; the insert itself now fails earlier). Leave a comment block pointing to the new test and to the merk-level unit test that still covers the prover-side guard symmetric. 2. **Book chapter** (`count-offset-paginated-queries.md`): - Rewrite the "Unsupported in-range value shapes" section so the NonCounted row points to #672 as the primary defense (with the merk prover + verifier checks staying as defense-in-depth against pre-#672 data on disk or lower-level builders). - Add a "Why the NonCounted rejection is enforced at insert time" subsection explaining the collapse-path divergence rationale. - Soften the "follow-up work" bullet for NonCounted: it's unlikely to ever become legal in a ProvableCountTree, since the entire model depends on subtree_count == entry count. Test totals after merge of develop + this commit: - merk: 534/534 - grovedb: 1749/1749 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Merges develop (which brings in PR #672 — rejection of NonCounted/ NotCountedOrSummed in ProvableCountTree/ProvableCountSumTree). PR #672 was scoped to the two count-bearing Provable* hosts that existed at the time; this commit extends the same rule to the dual-axis `ProvableCountProvableSumTree` host introduced by this PR. **Why PCPS rejects the same wrappers** PCPS commits BOTH count AND sum into every node hash via `node_hash_with_count_and_sum`. A `NonCounted` child contributes own_count = 0 to the parent, so the cryptographically-committed count would diverge from the actual number of stored elements — the same footgun PR #672 closed for the single-axis count hosts. By identical reasoning, `NotCountedOrSummed` is also rejected (it would diverge on BOTH committed axes). `NotSummed` is intentionally left accepted under PCPS, matching PR #672's deferral of the NotSummed-in-Provable* question. **No new predicate logic needed** The existing `TreeType::accepts_non_counted_children()` and `accepts_not_counted_or_summed_children()` predicates from PR #672 already exclude PCPS (they `matches!(self, CountTree | CountSumTree)` which doesn't include ProvableCountProvableSumTree). The merk insert guards (`merk/src/element/insert.rs`) and the GroveDB batch guard (`grovedb/src/batch/mod.rs`) call these predicates, so PCPS rejection is automatic after the merge. **Test changes** - `non_counted_pcps_inserts_into_pcps_parent_without_incrementing_count` → `non_counted_rejected_under_provable_count_provable_sum_tree_parent` Flipped from acceptance to rejection assertion. - `not_counted_or_summed_pcps_inserts_into_pcps_parent_and_zeros_both_axes` → `not_counted_or_summed_rejected_under_provable_count_provable_sum_tree_parent` Flipped from acceptance to rejection assertion. - `not_summed_pcps_inserts_into_pcps_parent_and_zeros_sum_contribution` Unchanged — still asserts NotSummed acceptance (PR #672 pattern). - `tree_type::accepts_non_counted_children` test extended to assert PCPS is in the rejection set (also adds PCPS to the count-bearing implication loop). - `tree_type::accepts_not_counted_or_summed_children` test extended to assert PCPS is in the rejection set. **Doc updates** - `grovedb-element/src/element/mod.rs` and `grovedb-element/src/element/constructor.rs`: doc comments for `NotCountedOrSummed` now enumerate both `ProvableCountSumTree` and `ProvableCountProvableSumTree` as parents that reject the wrapper. - `grovedb/src/tests/provable_count_provable_sum_tree_tests.rs` module docstring updated to describe the new rejection rule. **Merge conflict resolution** Both conflicts were in doc comments only (element/mod.rs:174-188 and element/constructor.rs:616-625). Resolved by extending develop's strict-rejection wording to also cover PCPS. All 1733 grovedb + 559 merk tests pass; cargo fmt clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…untSumTree single-range queries (#669) * feat(grovedb,merk): provable offset paginated queries on ProvableCount(Sum)Tree Adds a new proof flow that honors `SizedQuery::offset` for single-range queries against `ProvableCountTree` and `ProvableCountSumTree`. Skipped in-range subtrees collapse to a single hash-bound `HashWithCount` op (the same shape `AggregateCountOnRange` already uses), so the offset region pays O(log n) proof size per skipped subtree rather than O(skipped). Items inside the limit window emit as normal count-bearing value nodes, so the verifier-side result shape matches what a regular range query without offset would produce. ## What's reused vs. new - **Reuses** `Node::HashWithCount` (existing opcode, no new proof variants) for the offset-window collapse — the same mechanism AggregateCountOnRange uses. - **Reuses** `node_hash_with_count` for ProvableCountSumTree (sum is not bound to the node hash for that variant, so the count-only HashWithCount is sufficient). - **Reuses** the `aggregate_common::classify_subtree` Disjoint / Contained / Boundary classification. - **New** module: `merk/src/proofs/query/count_offset/{mod,prove,emit,verify,tests}.rs`. - **New** entry: `Merk::prove_count_offset_on_range(range, offset, limit, left_to_right, ...)` and `verify_count_offset_on_range_proof`. - **New** validators: `SizedQuery::validate_count_offset_paginated` and `PathQuery::validate_count_offset_paginated`. ## Scope - **Tree types**: `ProvableCountTree` and `ProvableCountSumTree` only. - **Query shape**: a single `QueryItem` range. Multi-item queries, subqueries, and conditional branches are out of scope (they continue to reject offset, same as before). - **Direction**: both ascending and descending. The descending walk is a structural mirror — walks the right child first, emits inverted ops, treats "the first N in-range keys" as the N highest keys. - **Truncated offset**: when the requested offset exceeds the in-range population, the prover skips everything it can and returns 0 items. The verifier surfaces this as `skipped < requested_offset`. ## Algorithm sketch Prover (`emit_count_offset_proof`): 1. Classify the current subtree (Disjoint / Contained / Boundary). 2. If Disjoint, emit a single `HashWithCount(count)` and bubble the structural count up — no offset/limit consumption. 3. If Contained AND `subtree_count <= offset_remaining`, collapse the whole subtree into one `HashWithCount` and decrement offset. 4. If Contained AND offset is 0 and limit is exhausted, collapse the whole subtree (past-limit) with no state change. 5. Otherwise descend per-element in directional order: walk first- direction child → emit self (as `KVDigestCount` for skipped / past-limit / out-of-range, or `KVCount` / `KVValueHashFeatureType` for returned items) → walk second-direction child. Verifier (`verify_count_offset_on_range_proof`): - Phase 1: reconstruct the proof tree via `execute_with_options`, allowlisting the four node kinds an honest prover ever emits. - Phase 2: walk the reconstructed tree directionally, deriving `own_count` in O(1) from each node's immediate children's count fields (so the in-order state machine knows the disposition before recursing into the second-direction child). State mutations are gated by (in_range, own_count, offset_remaining, limit_remaining). - Validates the recursive return matches each child's claimed count field, locking the structural counts across the whole tree. ## Wiring at the GroveDB layer - `prove_query_non_serialized_v{0,1}`: relaxed the hard offset gate — if offset is set the prover now runs `validate_count_offset_paginated` (syntactic) plus opens the target merk and confirms tree_type. Both surface clear errors on mismatch. - `prove_subqueries{,_v1}`: added a leaf-level short-circuit mirroring the aggregate-count / aggregate-sum branches, routing to the new merk-level prover. - `verify_query_with_options`: same syntactic relaxation as the prover. - `verify_layer_proof{,_v1}`: added a leaf-level dispatch routing to `verify_count_offset_on_range_proof`, then translating returned items into `ProvedPathKeyOptionalValue` rows. ## Tests - **Merk-level** (`merk/src/proofs/query/count_offset/tests.rs`): 9 round-trip tests covering offset+limit composition, both directions, empty trees, offset-past-end (truncated skip), partial-range queries, and tree-type rejection. - **Grovedb-level** (`grovedb/src/tests/count_offset_paginated_tests.rs`): 8 end-to-end tests through the full path-query stack including `ProvableCountSumTree` and the no-count-tree-target rejection case. Total: 17 new tests, all green. Full merk suite: 502/502. Full grovedb suite: 1721/1721 (no regression). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(count_offset): adversarial verifier + validator branch coverage Addresses codecov/patch coverage on PR #669. Adds 18 tests covering rejection branches that the happy-path round-trips don't exercise. ## Merk-level adversarial tests (+8) `merk/src/proofs/query/count_offset/tests.rs`: - `rejects_wrong_inner_range` — verifier called with a different range than the prover; classification shifts trigger shape rejections. - `rejects_wrong_direction` — proof emitted ascending, verified descending (and vice versa); state-machine mismatch. - `rejects_wrong_offset_smaller` / `rejects_wrong_offset_larger` — verifier expects a different number of digest skips than the proof contains. - `rejects_wrong_limit_smaller` — proof emits more value nodes than the verifier's limit window allows. - `rejects_byte_mutated_proof` — single-byte flip in the proof; either the verifier returns Err or it returns Ok with a non-matching root hash (both are acceptable rejections). - `rejects_truncated_proof` — last 10 bytes dropped; decoder or stack check rejects. - `rejects_trailing_garbage` — extra bytes after the encoded ops. ## GroveDB-level validator tests (+10) `grovedb/src/tests/count_offset_paginated_tests.rs`: - One test per branch in `SizedQuery::validate_count_offset_paginated`: no offset / offset=0 / aggregate-count wrapper / aggregate-sum wrapper / default-subquery subquery / default-subquery subquery_path / multi-item query. - `validate_accepts_single_range_variants` — sanity sweep across all 10 allowed `QueryItem` variants. - `path_query_validate_rejects_empty_path` — PathQuery-level empty-path rejection. - `path_query_has_non_zero_offset` — three-case truth table for the helper. Test totals after this commit: - merk count_offset: 17/17 (8 round-trips + 9 adversarial; was 9) - grovedb count_offset: 18/18 (8 end-to-end + 10 validator; was 8) - full merk suite: 510/510 - full grovedb suite: 1731/1731 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(count_offset): address CodeRabbit review on PR #669 Six follow-ups from the review: **Actionable (3)** 1. `check_count_offset_target_tree_type` in `grovedb/src/operations/proof/generate.rs` now normalizes `open_transactional_merk_at_path` errors to `Error::InvalidQuery`. Previously a missing path or other storage-layer error leaked through verbatim while a wrong-tree-type case got the intended message — callers got two different error contracts for the same actionable meaning ("you can't run count-offset against this path"). Captured comment explains why we don't propagate the raw open error. 2. Removed a stale rustdoc block describing `prove_aggregate_sum_on_range` that ended up sitting above `prove_count_offset_on_range` after the previous insertion in `merk/src/merk/prove.rs`. The function's own docstring is unchanged. 3. Phase-2 verifier call in `merk/src/proofs/query/count_offset/verify.rs` now uses `cost_return_on_error_no_add!` instead of an open-coded `match` early-return, matching the project standard. The `_no_add` variant is right here because `verify_count_offset_shape` returns a plain `Result<u64, Error>` without accumulating internal cost. **Nitpicks (3)** 4. Two end-to-end rejection tests now assert `Err(Error::InvalidQuery(_))` via `matches!` instead of bare `is_err()`. Catches regressions where some unrelated error (storage I/O, etc.) accidentally satisfies the assertion. 5. Both `subtree.prove_count_offset_on_range(...)` call sites in `generate.rs` (v0 and v1 short-circuits) now wrap downstream merk failures via `Error::CorruptedData(format!("prove_count_offset_on_range failed: {}", e))` instead of bare `Error::MerkError(_)`, matching the wrapping the existing `prove_aggregate_sum_on_range` calls use a few hundred lines up. 6. `verify_query_with_options`'s entry-level offset check switched from the inline `query.query.offset.is_some() && query.query.offset != Some(0)` to `query.has_non_zero_offset()`, matching the leaf-level dispatches in the same file. Test totals unchanged: merk count_offset 17/17, grovedb count_offset 18/18, full merk 510/510, full grovedb 1731/1731. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(count_offset): cover V0 proof envelope + nonexistent-path branch Improves codecov/patch coverage on PR #669. Three new tests targeting specifically the lines the previous test suite missed: 1. `end_to_end_offset_ascending_against_v0_envelope` — runs the ascending round-trip against `GROVE_V2`, which uses the v0 proof envelope. The default `GroveVersion::latest()` (v3) only exercises the v1 paths; this test reaches the v0 prove + verify short-circuits in `generate.rs` / `verify.rs`. 2. `end_to_end_offset_descending_against_v0_envelope` — same as above for the descending direction. 3. `end_to_end_offset_rejects_against_nonexistent_path` — opens the `Err(_)` arm of `open_transactional_merk_at_path` inside `check_count_offset_target_tree_type`, which the prior tests couldn't reach (they all had valid target paths). Confirms the error gets normalized to `InvalidQuery` instead of leaking whatever low-level error `open_transactional_merk_at_path` produced. Test totals: grovedb count_offset 21/21 (was 18), full grovedb 1734/1734. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(count_offset): close two soundness gaps from CodeRabbit review Addresses CodeRabbit's two actionable comments on PR #669: ## Fix 1: reject unexpected `lower_layers` in the leaf fast path `SizedQuery::validate_count_offset_paginated` rejects subqueries, so an honest count-offset leaf proof always has empty `lower_layers`. The count-offset short-circuit was returning before the V1 succinctness pass, so a malicious prover could attach arbitrary child layers that the verifier would silently ignore. Both the V1 (`verify_layer_proof_v1`) and V0 (`verify_layer_proof`) short-circuits now check `layer_proof.lower_layers.is_empty()` immediately after the syntactic gate and return `Error::InvalidProof` otherwise. ## Fix 2: surface committed value-hash + child-hash-verified per item The synthesized `proof = value_hash(value)` and `child_hash_verified = true` were both wrong: - For Items in a count tree, `H(value)` is the right value-hash — but only by coincidence. The regular merk verifier surfaces the value-hash the proof committed, not a recomputed one. - For tree-flavored entries the committed value-hash is `combine_hash(H(value), child_root)` (or `combine_hash(H(value), NULL_HASH)` for empty trees), not `H(value)`. Returning the wrong value here breaks downstream chain checks for tree returns. - `child_hash_verified = true` was a placebo: the count-offset prover never emits `KVValueHashFeatureTypeWithChildHash`, so the flag should always be `false`. Setting it `true` silently bypasses the V1 strict-mode invariant for any returned non-empty tree. Changes: - Extended `CountOffsetReturnedItem` with `value_hash: CryptoHash` and `child_hash_verified: bool`. - The merk verifier now surfaces these per-item: for `KVCount` it computes `H(value)` explicitly; for `KVValueHashFeatureType` / `KVValueHash` it forwards the proof-carried value-hash unchanged. `child_hash_verified` is always `false` (the prover doesn't emit the with-child-hash variant). - The GroveDB layer (both V0 and V1 short-circuits) now uses the surfaced metadata when constructing `ProvedKeyOptionalValue` instead of synthesizing. ## Fix 3 (defense-in-depth): reject non-empty tree returns Since `child_hash_verified` is correctly `false` for tree returns, running the V1 strict checks would reject non-empty tree returns anyway — but the count-offset short-circuit bypasses those checks. To close the gap explicitly, both V0 and V1 short-circuits deserialize each returned item and return `Error::NotSupported` if any deserializes to a non-empty tree, pointing at the prover's missing `KVValueHashFeatureTypeWithChildHash` support as a known limitation. Items, references, and empty trees are unaffected. ## Tests Two new adversarial tests in `grovedb/src/tests/count_offset_paginated_tests.rs`: - `rejects_count_offset_proof_with_forged_lower_layers` — decodes an honest proof envelope, surgically attaches a bogus child layer to the count-tree leaf, re-encodes, confirms the verifier rejects with `InvalidProof`. - `rejects_count_offset_with_non_empty_tree_return` — builds a count tree containing `[Item("a"), non-empty Tree("b"), Item("c")]`, runs an offset=1+limit=1 query that lands on the tree element, and confirms the verifier rejects with `NotSupported`. Test totals: count_offset 40/40 (17 merk + 23 grovedb, was 38), full merk 510/510, full grovedb 1736/1736. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(verify): collapse if-let-and-condition to satisfy CI clippy CI's `cargo clippy --workspace --all-features -- -D warnings` flagged two `clippy::collapsible_if` errors at the new non-empty-tree-return rejection check in `grovedb/src/operations/proof/verify.rs:502` and `:1562` (the V1 and V0 short-circuits). Replaced the nested if let Ok(elem) = Element::deserialize(...) { if elem.into_underlying().is_non_empty_tree() { ... } } with the let-chain form if let Ok(elem) = Element::deserialize(...) && elem.into_underlying().is_non_empty_tree() { ... } Matches the let-chain idiom already in use elsewhere in the file. No behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(count_offset): forge proofs to exercise verifier rejection branches Closes the codecov/patch gap on `merk/src/proofs/query/count_offset/verify.rs`. The previous coverage was 67% (the round-trips and adversarial parameter-mismatch tests left most rejection branches untouched because they only fire on *forged* proofs, not on honest proofs with mismatched parameters). This commit adds 14 tests that build proof byte streams from hand-crafted `Op` sequences and feed them straight to the verifier. Each one targets a specific named rejection branch: • `rejects_unknown_node_kind_in_proof` — `execute_with_options` allowlist • `rejects_kv_value_hash_inside_count_tree` — `classify_self` KVValueHash arm • `rejects_kv_value_hash_feature_type_with_basic_feature` — `aggregate_of_proof_tree_node` non-count feature • `rejects_boundary_key_outside_inherited_bounds` — `key_strictly_inside` • `rejects_hash_with_count_with_attached_child` — "must be a leaf" at Disjoint/Contained • `rejects_hash_with_count_at_boundary_position` — "cannot appear at Boundary" • `rejects_child_counts_exceeding_parent_aggregate` — `own_count` underflow check • `rejects_kv_count_at_out_of_range_position` — `classify_self` KVCount out-of-range • `rejects_kv_count_with_wrong_own_count` — `classify_self` KVCount own_count != 1 • `rejects_kv_value_hash_feature_type_at_out_of_range` • `rejects_kv_value_hash_feature_type_with_wrong_own_count` • `rejects_kv_digest_count_with_limit_remaining` — `apply_self_state` digest-at-offset=0-with-limit-free • `rejects_hash_with_count_at_contained_with_limit_remaining` • `rejects_hash_with_count_exceeding_offset_remaining` Coverage on `verify.rs`: 67% → 83% (+16 percentage points; 49 fewer uncovered lines). The remaining ~17% is split between defense-in-depth branches that are unreachable in practice (the `execute_with_options` allowlist filters them before they hit the shape walker — e.g. `aggregate_of_proof_tree_node`'s catch-all arm) and bound-check branches that the proof-encoding's strict key ordering blocks at decode time. Test totals: merk count_offset 31/31 (was 17), full merk 524/524, full grovedb 1736/1736. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(count_offset): more forging tests targeting remaining verifier branches Pushes verify.rs coverage from 83% → 87%. Adds five targeted tests: • `rejects_kv_count_with_zero_own_count` — KVCount(count=0) hits `classify_self`'s `own_count != 1` arm directly (the `own_count > 1` check in the caller intercepts the count=2 case used in the existing test, so count=0 is the specific lever for the in-branch reject). • `rejects_kv_value_hash_feature_type_with_zero_own_count` — same shape for the tree/reference returned-item path. • `rejects_kv_value_hash_at_out_of_range` — exercises the `!in_range` arm of the `KVValueHash` branch in `classify_self`. • `accepts_kv_value_hash_feature_type_with_count_sum_feature` — exercises the `ProvableCountedSummedMerkNode` arm of `aggregate_of_proof_tree_node` (count-sum variant). • `accepts_kv_digest_count_past_limit` — past-limit digest emission with `offset = 0, limit = Some(0)`. This is a *valid* proof shape (no error); the test confirms the verifier accepts and returns zero items / zero skipped. Test totals: merk count_offset 36/36 (was 31), full merk 529/529. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(verify): mark allowlist-protected catch-alls unreachable; drop dead consistency check Two simplifications in `merk/src/proofs/query/count_offset/verify.rs`, no behavior change for honest callers: ## 1. `unreachable!()` for allowlist-protected catch-all arms The `execute_with_options` allowlist at the top of `verify_count_offset_on_range_proof` accepts exactly five node kinds: `HashWithCount`, `KVDigestCount`, `KVCount`, `KVValueHash`, and `KVValueHashFeatureType`. Three internal dispatch matches further down (`aggregate_of_proof_tree_node`, the per-element key-extraction switch in `verify_count_offset_shape`, and `classify_self`) had explicit "other" arms that returned `Error::InvalidProofError` — but those arms are unreachable as long as the allowlist stays in sync. Replaced each with `unreachable!()` plus a comment explaining the dependency. If the allowlist is ever widened without updating these matches, the panic surfaces immediately at the offending site instead of silently fabricating a polite error. ## 2. Drop the tautological recursive-vs-immediate aggregate check The previous code recursively called `verify_count_offset_shape` on each child, captured the returned aggregate, and compared it against the same child's count field already read via `aggregate_of_proof_tree_node`. But both reads come from the same `ProofTree` node's count field — referentially transparent for any given node — so they're tautologically equal. The mismatch error could never fire. Removed the captured return values and the comparison; the recursive call is still made for its state-mutation side effects on descendants (offset/limit accounting). If a future refactor changes `verify_count_offset_shape`'s return contract such that it could disagree with `aggregate_of_proof_tree_node`, this check would need to be re-added. The commit message and inline comment document this. Test totals unchanged: merk count_offset 36/36, grovedb count_offset 23/23, full merk 529/529. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(count_offset): V0-envelope rejection coverage Adds V0-envelope counterparts for three GroveDB-level rejection tests. The default `GroveVersion::latest()` (v3) only exercises the V1 envelope, leaving the V0 short-circuits in `verify_layer_proof` and `prove_query_non_serialized_v0` uncovered. • `rejects_count_offset_v0_proof_with_forged_lower_layers` — surgical-mutation forge against `GroveDBProofV0` / `MerkOnlyLayerProof`. Covers the V0 lower_layers check. • `rejects_count_offset_v0_with_non_empty_tree_return` — non-empty tree inside a count tree, offset=1+limit=1 lands on the tree element. Covers the V0 non-empty-tree-return rejection. • `rejects_count_offset_v0_against_non_count_tree` — offset query against a `NormalTree` via GROVE_V2. Covers the V0 tree-type-check in `check_count_offset_target_tree_type`'s call site at `prove_query_non_serialized_v0`. Test totals: grovedb count_offset 26/26 (was 23), full grovedb 1739/1739. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(verify): extract shared count-offset layer dispatch helper The V0 and V1 count-offset short-circuits in `verify_layer_proof` / `verify_layer_proof_v1` were ~75 lines of near-identical code, differing only in how the merk proof bytes are unwrapped from the envelope (`MerkOnlyLayerProof.merk_proof: Vec<u8>` vs `LayerProof.merk_proof: ProofBytes::Merk(...)`). Extracted the shared logic into `run_count_offset_layer_dispatch`, leaving each short-circuit as a 9-line call site. Functional impact: none. The single new helper runs the same `validate_count_offset_paginated` gate, the same `lower_layers` emptiness check, the same `verify_count_offset_on_range_proof` invocation, the same per-item non-empty-tree-return rejection, and the same `ProvedPathKeyOptionalValue` construction loop. All 26 grovedb-level count-offset tests still pass unchanged. Side benefit: collapses ~140 lines of duplicate code into ~85 lines (helper + two call sites), which has the downstream effect of nudging codecov/patch coverage up without changing semantics. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(emit): mark walk-returned-None branches unreachable Mirrors the verify.rs `unreachable!()` cleanup. The `walker.walk(dir)` calls in `emit_count_offset_proof` return `None` only when the link was missing, but each call site checks `link(dir).is_some()` immediately above (and the walker isn't aliased between the check and the walk), so the None branch is structurally unreachable. Replaced the two explicit `Error::CorruptedState` returns with `unwrap_or_else(|| unreachable!(...))` so a future refactor that broke the invariant would panic loudly instead of silently fabricating a polite error. Same defensive intent as before; collapses 12 lines into 2. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * revert(v0): keep V0 proofs frozen; add DO NOT MODIFY banners V0 proofs are a shipped wire format — grove versions v1 and v2 set `prove_query_non_serialized: 0` and verify those bytes in production. Earlier PR commits widened V0's accepted query shapes to include count-offset paginated proofs. That was the wrong call: any change to which inputs V0 accepts (or which proof bytes V0 emits) is a consensus-breaking change for already-deployed validators. Bugfix only on V0 is the project contract; new features go on V1. This commit restores V0 to its pre-PR rejection contract and adds loud guard rails so future contributors don't make the same mistake. ## Code changes ### `grovedb/src/operations/proof/generate.rs` - `prove_query_non_serialized_v0`: restored the unconditional `if offset.is_some() → InvalidQuery` rejection (matches original). - `prove_subqueries` (V0): removed the count-offset short-circuit branch. Honest V0 proofs no longer emit count-offset bytes. - Added `⚠⚠⚠ DO NOT MODIFY V0 PROOFS ⚠⚠⚠` banner doc-comments on both V0 entry functions explaining the wire-format invariant and pointing future contributors to V1. ### `grovedb/src/operations/proof/verify.rs` - Removed the V0 count-offset short-circuit in `verify_layer_proof` (the V0 sibling of `verify_layer_proof_v1`). - Moved the offset gate from individual public entry points down into `verify_proof_internal` and `verify_proof_raw_internal` (the V0/V1 dispatch points). Centralizing here means *every* caller — `verify_query_with_options`, `verify_query_raw`, `verify_query_get_parent_tree_info_with_options` — gets the uniform contract: V0 envelope rejects offset unconditionally, V1 envelope accepts only count-offset-paginated queries. - Added the same `⚠⚠⚠ DO NOT MODIFY V0 PROOFS ⚠⚠⚠` banner on `verify_layer_proof`. ### `grovedb/src/tests/count_offset_paginated_tests.rs` - Replaced the three V0-positive round-trip / forging tests with two V0-rejection pins: - `v0_prover_rejects_offset_on_count_tree` — pins that the V0 prover rejects offset on any query shape, including those a future change might be tempted to accept. - `v0_verifier_rejects_offset_on_query` — pins the verifier-side rejection by pairing a legitimate V0 (no-offset) proof with an offset-bearing path query. ## Tests - V1 round-trip + adversarial coverage unchanged (23 grovedb-level tests, 36 merk-level tests). - Full grovedb suite: 1736/1736. - Full merk suite: 524/524. - Clippy: clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(query): reject QueryItem::Key in count-offset paginated validator `QueryItem::Key(k)` matches at most one in-range item — so `offset > 0` on a single-key query is structurally guaranteed to return zero items. The previous code accepted this combination and would silently produce an empty result. That's almost always a user error (the caller probably meant a range), so we reject explicitly with a pointed `InvalidQuery` message instead. Range variants stay accepted. Replaced the `Key` arm in `validate_accepts_single_range_variants` with a positive rejection test, `validate_rejects_single_key`, that pins the new contract. Test totals: grovedb count_offset 24/24 (one less round-trip arm, one new rejection test), full grovedb 1737/1737. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(merk): move prove_count_offset_on_range into its own file + version-gate at 0 The method now lives in its own file (`merk/src/merk/prove_count_offset.rs`) with a `check_merk_v0_with_cost!` gate at the entry. The split keeps the version contract immediately visible at the file level and isolates the method from the rest of `Merk::prove*` so future behavior changes can be reviewed in isolation. ## Versioning Added a new `MerkProofVersions` struct under `MerkVersions` with a `prove_count_offset_on_range: FeatureVersion` field. Initial implementation version is **0**, set across all shipped grove versions (v1, v2, v3): - **v3**: 0 — the method is reachable here via the V1 proof envelope (which honors count-offset paginated queries). - **v1 / v2**: 0 — the method is *not* reachable from these versions in normal use because their V0 proof envelope rejects offsets at the grovedb dispatch layer before reaching merk. The field is kept consistent so a direct merk caller (outside the grovedb proof dispatch) doesn't trip the version gate spuriously. Bumping `prove_count_offset_on_range` from 0 → 1 in a future grove version is the prescribed path if the prover's emitted op stream needs to change shape in a way that requires a coordinated verifier update. ## Files - New: `merk/src/merk/prove_count_offset.rs` - New struct: `MerkProofVersions` in `grovedb-version/src/version/merk_versions.rs` - Updated: `merk/src/merk/mod.rs` registers the new module - Updated: `merk/src/merk/prove.rs` no longer holds the method (a pointer comment in its place) - Updated: `grovedb-version/src/version/v{1,2,3}.rs` carry the new field No behavior change for any caller — the method's body is byte-identical to the previous version, just gated and relocated. Test totals: merk count_offset 36/36, grovedb count_offset 24/24, full merk 529/529, full grovedb 1737/1737. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * chore(prove): drop pointer comment to prove_count_offset.rs The pointer comment was redundant — the module registration in `merk/src/merk/mod.rs` already makes the split discoverable, and the sibling file's own header doc-comment explains the rationale. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(book): add Count-Offset Paginated Queries chapter Parallel to `aggregate-count-queries.md` — documents the new count-offset paginated proof feature added to PR #669. Covers: - What the feature is and the problem it solves (paginated provable range queries on count trees with O(log(skipped) + limit) proof size). - The seven eligibility rules enforced by `SizedQuery::validate_count_offset_paginated`, including why `QueryItem::Key` is rejected (always-empty result). - **V1-only contract.** V0 proofs are a shipped wire format and don't support count-offset; documented prominently so future contributors understand the boundary. - Why this only works on `ProvableCountTree` / `ProvableCountSumTree` (count is hash-bound via `node_hash_with_count`). - How the proof is built: prover state machine, collapse rules, per-element emission inside descents, direction-awareness. - Verifier shape walk: state-machine mirroring, op-shape validation against position classification, attack rejection table. - Non-empty tree returns are rejected for now; lifting this is a follow-up. - API surface (same entry points as regular path queries). - Comparison table vs regular query / aggregate count. - Future work. Registered in `docs/book/src/SUMMARY.md` after the aggregate-sum-on-range chapter. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(count_offset): reject NonCounted / Reference / non-empty-tree in-range entries Three findings from the P1/P2 review (PR #669): **P1 — NonCounted entries silently omitted from verified results.** The prover emitted in-range NonCounted nodes as `KVDigestCount` (own_struct = 0 branch); the verifier classified that as `PathLikeOrNonCounted` and returned nothing. A valid count tree like `[a, NonCounted(b), c]` queried as `a..=z, offset=1, limit=2` would verify while returning only `[c]`; regular GroveDB returns `[b, c]`. **P1 — Returned references not dereferenced on the count-offset path.** The short-circuit serializes raw merk ops and returns before GroveDB's normal reference post-processing. A verified count-offset page could surface the stored `Element::Reference` instead of the target element. **P2 — Honest prover / verifier disagreement on non-empty tree returns.** The prover happily emitted these; the verifier rejected the same output as `NotSupported`. An honest-but-unverifiable proof is a prover-side bug. ## Fix shape (Path B — conservative scope) All three findings get the same treatment: the count-offset proof flow's supported scope is **plain `Item`/`SumItem`/`ItemWithSumItem` and empty trees inside a count tree.** The three rejected shapes surface explicit errors at both prove and verify time: • **NonCounted-wrapped in-range entry**: merk prover refuses to descend through `own_struct = 0` in-range entries with `InvalidProofError`. Merk verifier rejects `KVDigestCount` at in-range with `own_count = 0`. GroveDB verifier rejects `is_non_counted()` returned values as `InvalidProof` (a NonCounted value in `returned_items` is only reachable via forgery). • **Reference / ReferenceWithSumItem**: merk prover detects via `Element::deserialize().is_reference()` and rejects. GroveDB verifier rejects same via `NotSupported`. • **Non-empty tree**: merk prover detects via `is_non_empty_tree()` and rejects upfront — symmetric with the existing verifier-side rejection (now defense-in-depth instead of the only line of defense). ## Test additions • `rejects_count_offset_with_non_counted_entry` — count tree with `[a, NonCounted(b), c]`, offset=1 limit=2, asserts the prover errors with a message mentioning "NonCounted". • `rejects_count_offset_with_reference_entry` — count tree with `[a, Reference(→a), c]`, asserts the prover errors mentioning "Reference". • `rejects_count_offset_with_non_empty_tree_return` (existing, tightened) — now asserts prover-side rejection specifically rather than "prover OR verifier". ## Docs `docs/book/src/count-offset-paginated-queries.md` rewrites the "Returned tree elements — what's supported" section into a "Unsupported in-range value shapes (P1 / P2)" table covering all three rejected shapes with rationale and lift-restriction roadmap. Test totals: merk 529/529, grovedb 1739/1739, count_offset 36 merk + 26 grovedb. No behavior change for the supported scope. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(query): fix validate_count_offset_paginated rustdoc — Key is rejected The eligibility list in the rustdoc for SizedQuery::validate_count_offset_paginated listed QueryItem::Key alongside the range variants, but the implementation at line 293 explicitly rejects QueryItem::Key with an InvalidQuery error (a single-key match has at most one item, so offset > 0 is structurally guaranteed to return zero items). Remove Key from the allowed list and add an explicit note that it's rejected. No behavior change. Addresses CodeRabbit review comment on PR #669. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(count_offset): tighten error-variant matching and pin full payload Two CodeRabbit nitpicks on the count-offset test suite: 1. **Validator tests** (grovedb/src/tests/count_offset_paginated_tests.rs): Replace the 9 `format!("{:?}", err)` + `msg.contains(...)` patterns with `matches!(err, crate::Error::InvalidQuery(msg) if msg.contains(...))`. The tests now pin the exact `Error::InvalidQuery` variant in addition to the substring, instead of relying on Debug formatting that could shift if the error type changed but happened to keep the same textual representation. The Display-format assertions in the end-to-end prover tests are left as-is (different scope — those tests assert on user-facing strings spanning multiple error variants). 2. **Returned-item payload** (merk/src/proofs/query/count_offset/tests.rs): The `round_trip_keys` helper used by all happy-path round-trips compares only the `key` field of each returned item, which means a regression that silently rewrote `value`, `value_hash`, or `child_hash_verified` would slip through unobserved. Add a new dedicated test `returned_items_carry_full_committed_payload` that prove → encode → verify against the 15-key fixture and asserts the full `CountOffsetReturnedItem` for the first returned row (key "f", value [5], value_hash = H([5]), child_hash_verified = false) and that the other two rows expose Item-flavored value_hash + the prover-invariant `child_hash_verified = false`. This pins down the prover/verifier metadata contract. Test totals after this change: - merk: 530/530 (was 529) - grovedb: 1739/1739 (no count change — same set, stronger asserts) No behavior change. Addresses CodeRabbit nitpicks on PR #669. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * refactor(verify): factor count-offset envelope gate + test verify_query path Two changes targeting the codecov/patch gate (currently 88.72%, threshold 90%): 1. Factor the V0-rejects / V1-relaxes offset envelope check out of `verify_proof_internal` and `verify_proof_raw_internal` into a shared `apply_count_offset_envelope_gate` helper. Removes ~10 lines of literal duplication and gives each entry point one call site, so a single test exercises the gate logic for both surfaces. 2. Add two GroveDB-layer tests that go through `verify_query` (the deserialized entry point) instead of `verify_query_raw`: - `end_to_end_offset_via_verify_query` — happy-path V1 round-trip dispatched through `verify_proof_internal` rather than the `_raw` variant. - `v0_verify_query_rejects_offset` — V0 envelope + offset query paired and run through `verify_query`; must reject as `NotSupported`. Having tests behind each public surface ensures a refactor that drops the gate on one side gets caught. Test totals: grovedb 1741/1741 (was 1739, +2), no behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(count_offset): add forged-proof tests for verifier defense-in-depth After the merk prover started rejecting NonCounted-wrapped / Reference / non-empty-tree in-range entries, the GroveDB-layer defense-in-depth checks in `run_count_offset_layer_dispatch` became unreachable by honest proofs. To keep those branches exercised (they're the only guard against a forged proof that bypassed the prover), add three tests that surgically rewrite one value-bearing op in a real proof to carry forged value bytes: **Forge mechanism**: replace `KVCount(key, value, count)` (what the prover emits for ProvableCountedMerkNode Items) with `KVValueHashFeatureType(key, FORGED_VALUE, H(original_value), ProvableCountedMerkNode(count))`. The merk-level kv_hash is computed from the committed value_hash field — not from the value bytes — so the merk-level chain hash stays intact, the count check (`provable_count_from_aggregate`) still returns the right count, and the count-offset verifier surfaces the forged value bytes into `CountOffsetReturnedItem.value`. The GroveDB-layer `Element::deserialize` then triggers the right defense-in-depth rejection. Three forge variants: - **NonCounted-wrapped item** → rejected as `InvalidProof` mentioning "NonCounted" - **Reference** → rejected as `NotSupported` mentioning "Reference" - **Non-empty Tree** (`Element::Tree(Some(root_key), _)`) → rejected as `NotSupported` mentioning "non-empty tree" Shared helpers: `forge_count_offset_proof_replacing_value` (decode V1 envelope → mutate one op in the leaf merk_proof → re-encode) and `forge_fixture` (the standard 15-item ProvableCountTree + the `a..=o` offset 5 limit 3 path query). Test totals: grovedb 1744/1744 (was 1741, +3). No behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test+docs(count_offset): align with #672 NonCounted insert rejection Following PR #672 (merged into develop after this branch was opened), `NonCounted` and `NotCountedOrSummed` can no longer be inserted into `ProvableCountTree` / `ProvableCountSumTree` at the GroveDB or merk insert path. That structurally closes the P1 finding raised on this PR: a Contained subtree containing `[counted-a, NonCounted-b, counted-c]` would have subtree_count = 2 and collapse on offset = 2 to HashWithCount, hiding the regular-pagination divergence (which would return [c]). Two changes here: 1. **Tests**: - Add `p1_noncounted_in_provable_count_tree_rejected_at_insert` as the authoritative regression test — asserts the GroveDB insert refuses NonCounted into a ProvableCountTree, citing #672. - Remove the now-obsolete `rejects_count_offset_with_non_counted_entry` test (which inserted NonCounted then expected the prover to reject on descent; the insert itself now fails earlier). Leave a comment block pointing to the new test and to the merk-level unit test that still covers the prover-side guard symmetric. 2. **Book chapter** (`count-offset-paginated-queries.md`): - Rewrite the "Unsupported in-range value shapes" section so the NonCounted row points to #672 as the primary defense (with the merk prover + verifier checks staying as defense-in-depth against pre-#672 data on disk or lower-level builders). - Add a "Why the NonCounted rejection is enforced at insert time" subsection explaining the collapse-path divergence rationale. - Soften the "follow-up work" bullet for NonCounted: it's unlikely to ever become legal in a ProvableCountTree, since the entire model depends on subtree_count == entry count. Test totals after merge of develop + this commit: - merk: 534/534 - grovedb: 1749/1749 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Resolves conflicts with develop's PRs #669 (provable count-offset paginated queries) and #672 (reject NonCounted/NotCountedOrSummed in provable count parents). This merge round is **much smaller** than the prior three — most content auto-merged cleanly because the on-disk discriminant bytes finally stabilized when the previous merge shifted cidx to bytes 20/21 (ElementType) and 12/13 (TreeType). Develop's two new PRs add functionality without touching byte slots that overlap with this PR's cidx variants. Two trivial content conflicts resolved: - `docs/book/src/SUMMARY.md`: union the two new chapters (`count-offset-paginated-queries.md` from develop + `count-indexed-tree.md` from this PR). - `grovedb/src/tests/mod.rs`: union the two new test modules (`count_offset_paginated_tests` from develop + `count_indexed_tree_tests` from this PR). **Wrapper-acceptance fix for cidx primaries.** PR #672 introduced two new predicates that are stricter than `is_count_*_bearing`: - `TreeType::accepts_non_counted_children` — true only for non- provable count-bearing parents. - `TreeType::accepts_not_counted_or_summed_children` — true only for the non-provable count-AND-sum-bearing parent. The new insert-guards in `merk/src/element/insert.rs` and `grovedb/src/batch/mod.rs` route through these predicates. As landed, `accepts_non_counted_children` only matched `CountTree | CountSumTree`, which incorrectly rejected `NonCounted` children in non-provable cidx primaries (`CountIndexedTree`). Two existing cidx tests began failing: - `batch_insert_non_counted_wrapped_into_count_indexed_tree` - `non_counted_item_does_not_increment_aggregate_count` The fix extends `accepts_non_counted_children` to include `CountIndexedTree`. `ProvableCountIndexedTree` is intentionally NOT included — it commits its aggregate count cryptographically (via `ProvableCountedMerkNode`) for the same reason `ProvableCountTree` doesn't accept NonCounted. The `accepts_not_counted_or_summed_children` predicate is unchanged: cidx primaries don't carry a sum aggregate, so they can't host `NotCountedOrSummed` regardless of provable-ness — the existing test for that predicate is extended to assert false for both cidx variants. The same implication-loop test that asserts "every parent that accepts a NonCounted child is count-bearing" is also extended to exercise both cidx variants. Verified: - `cargo test --workspace --lib`: 3300+ tests, 0 failures - All previously failing cidx batch + wrapper tests now pass. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Removed references that read as stale dev-process noise to a reader encountering the code months later, with no information loss about the code's current behavior or rationale: **PR # references (8 sites)** - generate.rs (combined-aggregate gate): "PR #670 / grove v3+ feature" → "grove v3+ feature". - count_offset_paginated_tests.rs (assert message + 2 docs): "PR #672 closes the P1 finding" / "the P1 finding's root cause" → describe the actual rule (NonCounted inserts into ProvableCountTree rejected). - provable_count_provable_sum_tree_tests.rs (4 docs): "PR #672 for ProvableCountTree…" → "Same rejection rule that applies to…". - aggregate_count_query_tests.rs (forgery test branches): drop "added in PR #663" / "added in this PR" qualifiers from documentation of two error-branches. - not_counted_or_summed_tests.rs: drop "PR #666's contract" qualifier. - reference_with_sum_item_tests.rs (2 sites): drop "added in PR #667" / "added in this PR" / "PR #667 already covers" — rephrase as factual statements. - aggregate_sum_query_tests.rs (test-section header): drop "PR #662's no-proof query_aggregate_count" → "Sum-side mirror of the no-proof query_aggregate_count tests." - query.rs (query_aggregate_sum doc): drop "Mirrors PR #662's". - non_counted_tests.rs (module header): drop "Codex review of PR #654". **CodeRabbit references (3 sites)** - count_offset_paginated_tests.rs (2 sites): drop "(CodeRabbit review on grovedb#669)" parenthetical. - merk/mod.rs (test doc): drop "Tightened (per CodeRabbit review)". - merk/proofs/query/aggregate_count/tests.rs (comment): drop "(per CodeRabbit review)". **Temporal markers — "Before this fix" / "in this PR" framing (4 sites)** - merk/mod.rs (2 docs): "Before this fix the supports_count match…" → "the support check delegates to is_count_bearing(), so any hand-rolled match here would be a drift-risk regression." / "previously omitted from this manual match" → drop the temporal qualifier. - aggregate_sum_carrier_query_tests.rs (test doc): "previously blanket — it blocked legitimate root-carrier queries" → describe current shape-aware behavior. - provable_count_provable_sum_tree_tests.rs (2 sites): "fixed in this PR — without KVRefValueHashCountSum" → "rely on the KVRefValueHashCountSum dispatch arm — without it". "both gained Element::ProvableCountProvableSumTree arms in this PR" → "both carry Element::ProvableCountProvableSumTree arms". **"before this feature" comments (2 sites)** - aggregate_count_query_tests.rs + aggregate_sum_carrier_query_tests.rs (per-key symmetry tests): "same proof bytes it did before this feature" → "same proof bytes whether the caller verifies via verify_aggregate_X_query or the per-key entry point." **"Before this module existed" / "forthcoming" framing (2 sites)** - aggregate_common.rs: "Before this module existed each axis carried its own private copy" → "These items would otherwise be byte-identical copies across each axis. Centralizing them here…" - aggregate_count/mod.rs: "The same leaf/carrier shape will apply to forthcoming aggregate variants (sum, average)" → "The same leaf/carrier shape applies to the sum and combined axes — see the sibling … modules." - grovedb-query/src/aggregate_count.rs: "Forthcoming aggregate variants (sum, average) will live in sibling modules" → "The sum and combined axes live in sibling modules." **Renamed:** `p1_noncounted_in_provable_count_tree_rejected_at_insert` → `noncounted_in_provable_count_tree_rejected_at_insert` to drop the "P1" audit-finding prefix from the test name itself. No behavior changes. All tests still pass. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
What the attack is The count-offset paginated proof verifier (introduced in PR #669) had a KV-to-KVValueHash proof forgery: an attacker can rewrite an honest KVCount(k, real_value, count) proof node as KVValueHashFeatureType( k, serialized_forged_Item, H(real_value), // committed value-hash ProvableCountedMerkNode(count) // honest feature_type ) The merk tree-hash chain still reconstructs because KVValueHashFeatureType consumes the proof-supplied value_hash directly rather than recomputing it from value. The own-count assertion (own_count == 1) still passes because the feature_type carries the honest count. classify_self surfaces ValueReturned { value: forged_bytes, value_hash: H(real_value) } and the GroveDB translation pushes the forged Item to the caller under the original committed root hash. The downstream GroveDB blacklist (NonCounted / Reference / non-empty tree) was insufficient — it could not distinguish a forged Item-shape return from an honest tree-shape return. The regular V1 query verifier already has the strict-mode guard for this exact pattern (merk/src/proofs/query/verify.rs:427 rejects KVValueHashFeatureType whose value deserializes to an element with has_simple_value_hash() == true). The count-offset verifier was missing the parallel check. Fix — two-layer defense in depth 1. Merk-level strict-mode guard in count_offset/verify.rs classify_self (KVValueHashFeatureType arm): reject any value whose element type has has_simple_value_hash() == true. Mirrors the V1 strict-mode check in the regular execute_proof. Closes the primary forgery vector — Item / SumItem / ItemWithSumItem (and their NonCounted twins, which resolve via base() to the same simple shapes) cannot be smuggled through KVValueHashFeatureType. 2. GroveDB-side empty-tree value-hash equality check in run_count_offset_layer_dispatch: for any returned element that deserializes as a tree but is not non-empty, recompute combine_hash(H(value), NULL_HASH) and assert it equals the proof-supplied value_hash. Catches the residual forgery where an attacker substitutes an empty-tree-shape value (which has has_simple_value_hash() == false and thus slips past the merk-level guard) with a forged hash. Also makes deserialization failure explicit (was silently accepting non-Element bytes). Tests Three regression tests in count_offset_paginated_tests.rs: - verifier_rejects_kv_to_kvvaluehash_item_forgery — exact attack described in the finding: plain Item substituted via KVValueHashFeatureType. Rejected at the merk-level guard. - verifier_rejects_forged_empty_tree_with_simple_value_hash — Element::Tree(None, _) forgery that slips past the merk guard. Rejected at the GroveDB-level combine_hash(H(value), NULL_HASH) equality check. - verifier_rejects_forged_non_counted_returned_item (existing test, assertion updated) — NonCounted(Item) forgery. Now rejected at the merk-level guard (NonCountedItem.base() == Item which has simple_value_hash). The test accepts rejection at either layer. 3962 workspace lib tests pass, 0 fail. Clippy clean. The fix does not affect the legacy regular V1 verifier (already had its own strict-mode guard) or V0 proofs (frozen wire format). The NonCounted whole-subtree collapse the finding mentions is fixed by PR #672's insert-time invariant, as noted. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
#864) (#924) * fix(proofs): count-offset proofs refuse to collapse over non-unit rows (#864) A nested count-bearing tree (CountTree, ProvableCountTree, ...) stored in a ProvableCount* host contributes its own aggregate count to the host — 0 when empty, N with N descendants — but is one row to ordinary pagination. The count-offset prover's offset collapse consumed a subtree's committed count as if it were rows, so a collapsed HashWithCount over such a row skipped N rows' worth of offset for one physical row and proved a different page than the trusted read, with a perfectly valid count commitment. Reproduced live at the GroveDB layer in both directions, for an empty child tree, and for a truncated offset. Platform's `range_countable` indexes nest CountTree value trees under a ProvableCountTree on purpose, so the shape cannot be refused at insert time the way NonCounted was (#672), and a collapsed op commits nothing about physical row count, so the verifier cannot detect it either. The prover now walks every subtree it is about to collapse for offset and refuses the query unless each row's own contribution (aggregate − left − right) is exactly one; a non-unit row met on descent (in range or on the path) is refused with the same message instead of producing an unverifiable proof. Disjoint and past-limit collapses never touch the offset budget and are unchanged. The walk costs O(skipped) node loads — the same I/O the trusted read pays — and the proof stays a single op. Proof format and verifier are unchanged and honest proofs are byte-identical, so no version gate. The verifier's `skipped` is documented as count units, which equal rows on every host an honest prover serves. Tests: merk-level collapse/descent/zero-unit/truncated refusals plus Disjoint and past-limit acceptance and a cost check; GroveDB-level row-page comparisons against query_raw with a batch-built fixture that asserts its AVL root. The refusal tests fail when the walk is disabled. Co-Authored-By: Claude Fable 5.1 <[email protected]> * test(count-offset): pin exact seek counts for the pre-collapse walk; scope the unit-row rule in the book Each prove now runs on a fresh fixture (a walk upgrades pruned links in memory, so a second prove on the same merk sees no seeks) and asserts 6 seeks without the walk versus 8 with it — e and g being the two nodes only the unit-row walk reads — with zero hash calls on both. Co-Authored-By: Claude Fable 5.1 <[email protected]> * refactor(count-offset): build the unit-row walk's corruption guards eagerly The two `CorruptedState` guards in `ensure_every_row_is_a_unit` (link aggregates exceeding the node aggregate; `walk` returning `None` for a link checked present a line earlier) are unreachable on a consistent tree, and as separate match arms they were the only eight uncovered lines of the patch (89.18% against the 90% bar). Express them as eager `ok_or` errors inside `cost_return_on_error_no_add!` so the guards keep their fail-closed behaviour without leaving an unreachable region. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix(proofs): preserve zero-count subtrees after the page limit --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
Why
ProvableCountTreeandProvableCountSumTreebind their aggregate count into every node hash vianode_hash_with_count. That committed count IS the answer to anAggregateCountOnRangequery.Today,
NonCountedandNotCountedOrSummedchildren are accepted in those parents (viais_count_bearing/is_count_and_sum_bearing). They contributeown_count = 0, so the cryptographically-committed count silently disagrees with the actual number of stored elements — confusing for callers, and a footgun for proof-driven readers who reasonably assume "if I iterate this range I'll get the same number the proof returned."This PR makes that shape impossible going forward, while leaving the wrappers fully usable in the non-provable count-bearing parents where the count is plain bookkeeping rather than a cryptographic commitment.
Rule
NonCountedCountTree,CountSumTreeProvableCountTree,ProvableCountSumTreeNotCountedOrSummedCountSumTreeProvableCountSumTreeNotSummedis_sum_bearing)is_count_bearingandis_count_and_sum_bearingare unchanged — they still answer the structural question "does this tree track count/sum?" for the aggregate logic that legitimately needs that. The new wrapper-acceptance rule lives in two new dedicated predicates:Guard sites updated
merk/src/element/insert.rs—insert,insert_reference,insert_subtree.grovedb/src/batch/mod.rs— batch validation guard, plus theRefreshReferencetrusted path.Direct (per-merk) and batch surfaces both now reject the disallowed combinations with
InvalidInputError/InvalidBatchOperation.Tests
merk/src/element/insert.rs,grovedb/src/tests/not_counted_or_summed_tests.rs, andgrovedb/src/tests/aggregate_count_query_tests.rsflipped to assert rejection.non_counted_tests.rspin both wrappers against bothProvable*count parents.non_counted_still_accepted_in_count_sum_treepins the deliberate remaining acceptance so a future tightening (e.g., "onlyCountTree") surfaces here.Full local results:
cargo test -p grovedb-merk --lib→ 497 / 497 pass.cargo test -p grovedb --lib→ 1718 / 1718 pass.cargo test -p grovedb-element→ 4 / 4 pass.cargo fmt --all -- --check→ clean.Compatibility
No grove-version gate — same approach used when the wrappers were originally added in #654 and #666. Platform upgrades are coordinated, and no production data currently uses the now-rejected shape (these wrappers landed recently). The dead verifier paths that handled
own_count = 0in proof walks remain in place as defensive code for any historical reader.🤖 Generated with Claude Code