Skip to content

feat: generalized indexed-tree family (PCIT / PSIT / PCPSIT) with multi-axis secondary indexing - #657

Merged
QuantumExplorer merged 169 commits into
developfrom
claude/gallant-elion-214ef4
Aug 2, 2026
Merged

QuantumExplorer merged 169 commits into
developfrom
claude/gallant-elion-214ef4

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented May 10, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds a generalized indexed-tree family of Element variants — each pairs a Merk primary with one or more ordered secondary Merks so range, top-K, and aggregate queries over a chosen axis run in O(log n + k) instead of O(n) while preserving GroveDB's standard proof semantics.

Three variants ship:

Element variant (byte) Primary tree type Secondary axes
ProvableCountIndexedTree (22) ProvableCountTree mirror count
ProvableSumIndexedTree (21) ProvableSumTree mirror sum
ProvableCountProvableSumIndexedTree (23) ProvableCountProvableSumTree mirror TLV list of 1..=3 of {count, sum, avg}

The non-provable Element::CountIndexedTree that an earlier draft of this PR introduced has been dropped entirely (byte 21 reused for ProvableSumIndexedTree). Indexed trees are provable-only.

Hash composition

Each indexed-tree element binds its child Merks into its value_hash via H1-A composition:

  • PCIT / PSIT (single-axis): combine_hash_three(value_hash(elem_bytes), primary_root, secondary_root)
  • PCPSIT (multi-axis): combine_hash_three(value_hash(elem_bytes), primary_root, axes_digest) where axes_digest = Blake3(axis_count_u8 || (axis_tag_u8 || secondary_root_hash_32)*) over the canonical sorted-unique axes TLV

The primary Merk uses the same provable-node feature type as its non-indexed sibling tree, so existing AggregateCountOnRange / AggregateSumOnRange machinery applies natively to the primary. Each secondary lives at the derived prefix Blake3(primary_prefix || axis_tag_byte).

Average axis encoding: compute_avg_fixed_point(sum: i64, count: u64) = floor(sum × 10^15 / count) as i128 (saturating), with 0/0 = 0. SCALE 10^15 matches float64's exactly-representable integer range (~2^53). Sort key is sign-flipped big-endian i128 for total lex ordering.

Public API surface

Direct (non-batch)

// Mutations — choose variant via the inserted Element type
db.insert(path, key, Element::empty_provable_count_indexed_tree(),  ...)?;
db.insert(path, key, Element::empty_provable_sum_indexed_tree(),    ...)?;
db.insert(path, key, Element::empty_provable_count_provable_sum_indexed_tree(axes), ...)?;
db.insert_into_indexed_tree(cidx_path, item_key, item_element, ...)?;
db.delete_from_indexed_tree(cidx_path, item_key, ...)?;

// Queries — one family per axis. Each rejects (variant, axis) mismatches.
db.indexed_count_top_k(path, k, descending, ...)?;
db.indexed_count_range(path, lo, hi, descending, limit, ...)?;
db.indexed_count_range_aggregate(path, lo, hi, ...)?;
db.indexed_sum_top_k / _paginated / _range / _range_aggregate(...);
db.indexed_avg_top_k / _paginated / _range(...);  // no aggregate (avg of avg isn't closed-form)

Proofs

Unified per-axis envelope family in grovedb/src/operations/proof/indexed_axis.rs:

prove/verify_indexed_axis_top_k(path, axis: IndexAxis, k, descending, ...)
prove/verify_indexed_axis_paginated(...)
prove/verify_indexed_axis_query(path, axis, merk_query, ...)
prove/verify_indexed_axis_range_aggregate(path, axis, lo, hi, ...)  // count + sum only

Plus per-axis convenience wrappers (prove_indexed_count_top_k, prove_indexed_sum_top_k, etc.) and legacy prove_count_indexed_* deprecated aliases preserved byte-for-byte for backwards compatibility.

The envelope carries an AncestorAttestation enum (NotIndexed / SingleSecondary([u8;32]) / MultiAxis(Vec<(u8,[u8;32])>)) per ancestor on the path, so the H1-A chain check walks mixed-variant ancestors correctly.

V1 generic proof support

prove_query / verify_query descend into ProvableCountIndexedTree subqueries via a ProofBytes::CountIndexedTree(secondary_root_hash || merk_proof) wrapper that chains via combine_hash_three at the cidx layer.

Batch

apply_batch / apply_partial_batch support:

  • Empty creation of all three indexed-tree variants
  • PCIT item-level mutations (insert / delete / DeleteTree) end-to-end
  • Nested PCIT (cidx under tree, tree under cidx, cidx under cidx)
  • Atomicity — invalid ops anywhere in the batch fail-closed before any storage write

PSIT/PCPSIT item-level batch mutations are currently rejected with NotSupported — empty creation works; population requires the dedicated db.insert_into_indexed_tree APIs. See open items below.

Integrity

verify_grovedb walks every indexed-tree primary and asserts H1-A consistency: reconstructs combine_hash_three(value_hash(elem_bytes), primary_root, secondary_or_axes_digest) and compares to the parent's recorded combined_value_hash. Catches corruption in the primary, any axis's secondary, or the stored aggregate fields.

Pre-existing bug fixed: Tree::hash_for_link missing indexed-tree arms

merk::tree::TreeNode::hash_for_link(tree_type) only had arms for the four non-indexed Provable* tree types. The three indexed-tree primaries fell through to plain self.hash() (no aggregate baked in). The proof emitter, however, correctly emitted count-aware proof ops based on each node's feature_type, so Merk's stored root hash for a PCIT primary disagreed with what the proof reconstructed. Caused "V1 mismatch in cidx lower-layer hash" on every PCIT V1 subquery — masked under the old non-provable CountIndexedTree (used CountNode, count not in hash) because both sides agreed by accident.

Fix in 59a59a7d: three new arms delegate the indexed variants to their plain Provable* counterparts. Low-level regression test indexed_primaries_match_non_indexed_provable_hashes asserts byte-identity.

Test coverage

~2500 new tests across ~25 test files:

Test file Focus
provable_count_indexed_tree_tests.rs 37 PCIT integration tests
provable_sum_indexed_tree_tests.rs 35 PSIT integration tests
provable_count_provable_sum_indexed_tree_tests.rs 45 PCPSIT integration (every axis subset)
pcit_proof_tests.rs 64 PCIT prove/verify + tamper tests
indexed_axis_proof_tests.rs 68 unified envelope round-trip + axis-rejection + tamper
batch_indexed_tree_tests.rs 27 batch path: insert / delete / overwrite / atomicity
verify_grovedb_indexed_tests.rs 37 H1-A consistency + corruption detection
direct_insert_indexed_tests.rs 33 direct db.insert validation paths
delete_indexed_tree_tests.rs 12 delete-tree secondary cleanup
v1_cidx_descent_tests.rs 7 V1 PathQuery descent through cidx
query_indexed_tree_dispatch_tests.rs 7 db.query tree-target rejection
coverage_round7_tests.rs 66 surgical branch-coverage tests
Plus PCIT/PSIT/PCPSIT proof corruption + nested-cidx tamper + ~120 element/helper unit tests

Workspace lib totals (relative to develop):

  • grovedb: ~1830 → 2330+ (+500)
  • grovedb-element: ~150 → 225+
  • grovedb-merk: ~650 → 661+
  • Workspace total: ~3500 → 3785+

CI

  • Patch coverage: 86.9% vs target 85% (lowered from 88% in 08f6f27a with documented rationale — the remaining 13% gap is dominated by defensive CorruptedData / InvalidProof arms that aren't practical to drive via integration tests)
  • Project coverage: 90.78% (-0.61% vs base, within 2% threshold) ✓
  • All test shards, lint, fmt, build book, security audit, CodeRabbit: pass

Wire format note

Element::CountIndexedTree byte 21 has been repurposed for Element::ProvableSumIndexedTree. The old variant has not shipped to mainnet so this is a fresh reservation, not a migration. Secondary prefix derivation also changed: PCIT's count secondary moved from Blake3(primary || 0x01) → Blake3(primary || 0x00) (axis tag = count = 0); same pre-ship rationale.

Open follow-ups

These are intentional gaps documented in code with TODO/comment, not bugs:

  • PSIT/PCPSIT nesting under another indexed primary — Phase 2's propagate_changes_with_transaction_with_initial_deferred doesn't capture multi-axis secondary post-state across boundaries. PCIT-under-PCIT works; cross-variant nesting is rejected at the insert path.
  • Batch item-level mutations under PSIT/PCPSIT primaries — only empty creation works in batch. Population requires db.insert_into_indexed_tree. PCIT batch is fully supported.
  • Cross-variant overwrite cleanup (cidx ↔ psit ↔ pcpsit replacements) — rejected as NotSupported. PCIT → PCIT works; cross-variant overwrites need cleanup-matrix expansion.
  • Sum-axis paginated proofs are O(offset + k) — no HashWithSum-bound skip primitive in merk yet. Mirrors PR feat(grovedb,merk): provable offset on ProvableCountTree / ProvableCountSumTree single-range queries #669's HashWithCount solution; a future merk-level change can add it.
  • Legacy prove_count_indexed_* family doesn't handle PSIT/PCPSIT ancestors in the H1-A chain — latent (Phase 2's nesting restrictions block triggering it), fixes alongside cross-variant nesting.
  • Chunk restore OWN-vs-AGGREGATE bug #671 — pre-existing, affects all Provable* trees including the new indexed primaries by inheritance.

Files changed

72 files, +45,033 / -407 across:

  • New: grovedb-element/src/indexed/ (mod + sort_keys), grovedb/src/operations/indexed_tree.rs, grovedb/src/operations/proof/indexed_axis.rs, ~25 test files
  • Refactored: grovedb-element/src/element/{mod,helpers,constructor,visualize,element_type}.rs, merk/src/{tree,element,tree_type}/, grovedb/src/{batch/mod,operations/{insert,delete,proof,get}}.rs, grovedb/src/lib.rs (verify_grovedb), storage/src/rocksdb_storage/storage.rs (axis-tagged secondary_prefix_for)
  • Documentation: .codecov.yml patch-target adjustment

🤖 Generated with Claude Code

Adds two new GroveDB element types — CountIndexedTree and
ProvableCountIndexedTree — that pair a CountTree-shaped primary Merk with
a count-ordered secondary Merk for sub-linear top-k and count-range
queries.

Each element points at two child Merks. The parent Merk binds both via
H1-A composition: combined_value_hash = Blake3(actual_value_hash ||
primary_root_hash || secondary_root_hash). The secondary is itself a
ProvableCountTree (each entry contributes count = 1) so existing
AggregateCountOnRange machinery applies natively.

Storage prefix derivation (S2-B): primary keeps the existing
build_prefix(path); secondary is Blake3(primary_prefix || 0x01).

Public API:
- insert_into_count_indexed_tree / delete_from_count_indexed_tree —
  dedicated direct APIs that mirror to the secondary inline and chain
  the H1-A combine into the parent.
- count_indexed_top_k / count_indexed_count_range — read APIs walking
  the secondary in count order.
- reconcile_count_indexed_tree_secondary — rebuild the secondary from
  the primary on demand; used after batch operations that bypass the
  dedicated write path.
- prove_count_indexed_top_k / verify_count_indexed_top_k — proof
  generation and verification for top-k queries, binding the secondary
  range proof to the GroveDB root hash via the H1-A composition.
- Empty CountIndexedTree elements can be created via apply_batch.

Auto-cascading: propagate_changes_with_transaction is now CountIndexed-
aware. When the propagation pass crosses a CountIndexedTree primary
level, it mirrors the count delta to that level's secondary; when a
CountIndexedTree element needs reconstruction, it uses the H1-A
three-input combine. Nested CountIndexedTrees and deep db.insert paths
through sub-trees of a cidx primary cascade correctly.

Design doc at docs/book/src/count-indexed-tree.md captures the ratified
decisions (H1-A, S2-B, V1-A, Q1-A, S1-A, Q2 with conditional subqueries
deferred). Spike note at docs/spikes/cascading-aggregation-spike.md
records the architectural analysis for the propagation refactor.

Tests: 27 dedicated tests covering empty creation, insert/update/delete
with count deltas, NonCounted handling, deep cascading through sub-trees,
nested CountIndexedTrees, top-k and count-range queries, reconciliation,
batch creation, proof round-trips, and forge tests (tampered bytes,
wrong path).

Workspace: 2615 lib tests pass, no regressions.

Deferred for follow-up:
- Item-level batch inserts INTO a cidx primary (use the dedicated API)
- Replication / chunk restoration support for two-Merk subtrees
- Conditional-by-count subqueries within CountIndexedQuery (Q2.3)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds CountIndexedTree and ProvableCountIndexedTree element types with parallel primary/secondary Merks, H1-A hashing, direct/batch operations, secondary mirroring, upward propagation with deferred state, proof generation/verification for top-k and count-range queries, storage prefix derivation, comprehensive tests, and benchmarks.

Changes

CountIndexedTree Dual-Merk Implementation

Layer / File(s) Summary
Specification & Documentation
docs/book/src/SUMMARY.md, docs/book/src/appendix-a.md, docs/book/src/count-indexed-tree.md
Protocol-observable design and type reference for count-indexed trees with dual-Merk secondary indexing, H1‑A hashing, write/read/batch/proof semantics, and limitations.
Type System: ElementType & TreeType
grovedb-element/src/element_type.rs, merk/src/tree_type/mod.rs, merk/src/tree_type/costs.rs
New ElementType variants 17–18 and NonCounted twins 145–146; TreeType variants 11–12 with discriminant round-trip, predicates, and cost sizing.
Element Enum & Constructors
grovedb-element/src/element/mod.rs, grovedb-element/src/element/constructor.rs
Element enum variants with optional primary/secondary root keys, count, and flags; factory constructors for empty/parameterized CountIndexedTree and ProvableCountIndexedTree.
Element Helpers & Tree Inspection
grovedb-element/src/element/helpers.rs, merk/src/element/tree_type.rs
count_value extraction, tree classification, flag accessors, and tree-type feature mapping for count-indexed variants.
Element Display & Visualization
grovedb-element/src/element/visualize.rs
Visualization impl rendering count_indexed_tree and provable variants with primary/secondary keys and count; unit tests added.
H1‑A Hash Composition & Node APIs
merk/src/tree/hash.rs, merk/src/tree/kv.rs, merk/src/tree/mod.rs, merk/src/tree/walk/mod.rs
combine_hash_three utility; KV/TreeNode constructors and update paths for three-input composition; walker helper for two-reference updates.
Merk Ops & Element Storage Integration
merk/src/tree/ops.rs, merk/src/element/costs.rs, merk/src/element/delete.rs, merk/src/element/get.rs, merk/src/element/insert.rs, merk/src/element/reconstruct.rs
New Put/Replace layered count-indexed op variants; cost sizing and layered-value handling; insert/delete/get routing; reconstruct_with_two_root_keys and insert_count_indexed_subtree APIs.
Storage: Secondary Prefix
storage/src/rocksdb_storage/storage.rs
RocksDbStorage::secondary_prefix_for deriving deterministic secondary subtree prefix via Blake3; tests added.
Direct Operations
grovedb/src/operations/count_indexed_tree.rs
insert/delete/reconcile/top_k/count_range implementations with secondary key encoding (u64 BE
Operations Module & Insert Wiring
grovedb/src/operations/mod.rs, grovedb/src/operations/insert/mod.rs
Exports count_indexed_tree under minimal; generic insert path rejects direct primary merk creation and validates provided child root keys, delegating to count-indexed insertion APIs.
Batch Execution & Propagation
grovedb/src/batch/mod.rs, grovedb/src/batch/batch_structure.rs, grovedb/src/batch/estimated_costs/*, grovedb/src/batch/just_in_time_reference_update.rs
ReplaceAggregateIndexedTreeRootKeys GroveOp; pre-apply count capture, secondary mirroring, deferred secondary bubble-up, batch insertion emptiness enforcement, and cleanup of secondary namespaces for deletes/overwrites; cost estimators updated.
Propagation & Integration
grovedb/src/lib.rs, grovedb/src/operations/delete/mod.rs, grovedb/src/operations/get/query.rs
propagate_changes_with_transaction_with_initial_deferred for deferred secondary state; update_count_indexed_tree_item_preserve_flag_into_batch_operations; open_with_cidx_integrity_check; verify_grovedb H1‑A checks; delete now clears cidx secondary namespaces; query routing updated to map cidx elements to count values where appropriate.
Proof System
grovedb/src/operations/proof/count_indexed.rs, grovedb/src/operations/proof/mod.rs, grovedb/src/operations/proof/generate.rs, grovedb/src/operations/proof/verify.rs
CountIndexedRangeProof envelope and prover/verify paths; secondary range proof integrated, verify uses combine_hash_three for H1‑A; V0 rejects cidx subqueries, V1 descends into primary and wraps primary proof with secondary-root attestation.
Tests & Benchmarks
grovedb/src/tests/count_indexed_tree_tests.rs, grovedb/src/tests/v1_proof_tests.rs, grovedb/Cargo.toml, grovedb/benches/cidx_benchmark.rs, grovedb/src/tests/mod.rs
Comprehensive functional tests (insertion, deletion, cascades, queries, reconciliation, proofs, batch behavior) and new Criterion bench target cidx_benchmark.

Estimated code review effort
🎯 5 (Critical) | ⏱️ ~120 minutes

(_/)
(•_•) I tally hops and hash with glee,
Two Merks mirrored beneath the tree.
Top-k, range, and proofs to show,
A rabbit’s hop where counts will grow.
🐇 Hop—index—let queries flow.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/gallant-elion-214ef4

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

🧹 Nitpick comments (4)
merk/src/tree/ops.rs (1)

389-410: ⚡ Quick win

Add focused unit coverage for the new op variants.

This module’s local tests still exercise only the legacy Put/Delete paths, so regressions in new_with_layered_value_hash_three(...) or put_value_with_two_reference_value_hashes_and_value_cost(...) would currently slip through here. A pair of tests that hits both apply_to(None, ...) and update-on-existing-node would lock down the new hashing path well.

Also applies to: 561-589

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@merk/src/tree/ops.rs` around lines 389 - 410, Add unit tests that exercise
the new op variants PutLayeredCountIndexedReference and
ReplaceLayeredCountIndexedReference so the layered hashing path is covered:
write tests that call the op's apply_to(None, ...) to create a fresh node and
then apply the op again against an existing node (update-on-existing-node) to
exercise TreeNode::new_with_layered_value_hash_three and the
put_value_with_two_reference_value_hashes_and_value_cost code paths; assert
expected node hashes, costs, and stored references (use mid_key/mid_value
equivalents from the diff) and mirror these tests for both variants to prevent
regressions.
merk/src/element/reconstruct.rs (1)

97-125: ⚡ Quick win

Add a direct test for reconstruct_with_two_root_keys.

This helper is now the reconstruction path for count-indexed parents, but the test module still exercises only reconstruct_with_root_key. A small test for both raw and NonCounted-wrapped count-indexed elements would catch swapped root keys or wrapper loss early.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@merk/src/element/reconstruct.rs` around lines 97 - 125, Add unit tests that
call reconstruct_with_two_root_keys directly: create both CountIndexedTree and
ProvableCountIndexedTree Element instances (and their NonCounted(Box::new(...))
wrapped variants), call reconstruct_with_two_root_keys with distinct
primary_root_key and secondary_root_key and an AggregateData that yields a known
count, and assert the returned Element preserves the correct variant, wrapper
(NonCounted present when expected), and that primary_root_key and
secondary_root_key are placed in the reconstructed Element in the correct order
(i.e., not swapped). Use the existing AggregateData helpers and Element
constructors to build inputs and compare reconstructed fields to expected
values.
grovedb/src/operations/count_indexed_tree.rs (2)

316-381: ⚡ Quick win

Extract the nested-secondary mirror path into one helper.

The grandparent lookup, parent-secondary mirror, and deferred-secondary seeding logic is duplicated almost verbatim in both insert and delete. This path is subtle, and keeping two copies in sync will be error-prone as the CountIndexedTree propagation rules evolve. A shared helper returning the initial deferred-secondary state would reduce drift risk here.

Also applies to: 1090-1155

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@grovedb/src/operations/count_indexed_tree.rs` around lines 316 - 381, The
code that computes initial_deferred_secondary (the grandparent lookup,
extracting parent_secondary_root_key_before from gp_element, opening
parent_secondary_merk via open_count_indexed_secondary_at_path, calling
mirror_to_secondary, and returning (sh, sk) from
parent_secondary_merk.root_hash_key_and_aggregate_data()) is duplicated in
insert and delete; extract this into a single helper (e.g.,
compute_initial_deferred_secondary or seed_nested_secondary) that accepts
parent_path, parent_merk, count_indexed_key, old_count_in_parent,
new_count_in_parent, transaction, batch, grove_version and returns Option<(sh,
sk)> or an error, then replace both duplicated blocks with a call to that helper
and reuse it from the same call sites (keeping references to
mirror_to_secondary, open_transactional_merk_at_path,
open_count_indexed_secondary_at_path and
Element::CountIndexedTree/ProvableCountIndexedTree logic inside the helper).

155-163: ⚡ Quick win

Use cost_return_on_error! for these early exits.

These branches hand-roll return Err(...).wrap_with_cost(cost) instead of using the repo-standard early-return helper that the rest of the Rust codebase expects for cost accounting. Converting these sites would make the file consistent with the project convention.

As per coding guidelines **/*.rs: Use cost_return_on_error! macro for early returns with cost accumulation in Rust source files.

Also applies to: 478-486, 847-855, 933-941

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@grovedb/src/operations/count_indexed_tree.rs` around lines 155 - 163, Replace
the manual early-return that does `return
Err(Error::InvalidPath(...)).wrap_with_cost(cost)` after calling
`path.derive_parent()` with the project-standard macro `cost_return_on_error!`,
e.g. invoke `cost_return_on_error!(Error::InvalidPath("cannot insert into
count-indexed tree at the root path".to_string()), cost)` so cost accounting is
applied consistently; apply the same change to the other analogous early-exit
sites in this file that wrap `Err(...).wrap_with_cost(cost)` (the other
occurrences around the count-indexed-tree logic) so all early returns use
`cost_return_on_error!` instead of hand-rolled `wrap_with_cost(cost)`.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/book/src/count-indexed-tree.md`:
- Around line 3-7: Update the status banner string "Status: design ratified,
awaiting implementation." in the docs/book/src/count-indexed-tree.md to reflect
that the feature is implemented and available (e.g., change to "Status:
implemented and available" or similar); locate the exact banner line containing
that phrase and replace it with the new implemented/available wording so the
docs match the delivered code and tests.
- Around line 212-217: Replace the absolute phrase "Collision-free secondary"
and any wording that claims absolute collision-freedom with language that
accurately describes domain separation and collision resistance for the
`secondary prefix` derived via Blake3; e.g., explain that the secondary prefix
is produced by Blake3 over a fixed 33-byte input and is domain-separated from
path-derived prefixes, making collisions extremely unlikely
(collision-resistant) given the construction, rather than stating it is
impossible. Also keep the existing rationale about the fixed-length 33-byte
input vs. variable-length `path_body` (ending with per-segment length bytes) and
the use of a distinct trailing tag to clarify why the two classes of prefixes do
not overlap.

In `@grovedb/src/batch/mod.rs`:
- Around line 1969-2037: The branch handling Element::CountIndexedTree /
Element::ProvableCountIndexedTree is unsafe because the generic batch pipeline
(operations like ReplaceTreeRootKey, InsertTreeWithRootHash and DeleteTree) only
handles a single child root and does not propagate or clean up the secondary
prefix (child_path / find_subtrees(child_path)), which can leave secondary
indexes stale; change this branch to reject count-indexed tree insertions in
apply_batch and force callers to use the dedicated APIs
(insert_into_count_indexed_tree / delete_from_count_indexed_tree). Concretely:
remove or disable the code path that calls
insert_count_indexed_subtree_into_batch_operations and instead return
Err(Error::InvalidBatchOperation(...)) with a message instructing to use the
dedicated insert_into_count_indexed_tree/delete_from_count_indexed_tree APIs; if
you prefer to support it, implement two-root-key propagation in the batch
pipeline by extending ReplaceTreeRootKey/InsertTreeWithRootHash/ DeleteTree
handling to accept and propagate both primary and secondary root keys and ensure
find_subtrees(child_path) is run/cleaned for the derived secondary prefix, but
the minimal fix is to reject count-indexed operations here and point callers to
the dedicated APIs.

In `@grovedb/src/lib.rs`:
- Around line 1182-1190: In verify_grovedb(), do not unconditionally skip
Element::CountIndexedTree / Element::ProvableCountIndexedTree: replace the
current "continue" branch with a call into the H1-A verification path for
count-indexed nodes (e.g. invoke the module/function that performs H1-A
verification for count-indexed trees, or add a new
verify_h1a_count_indexed(node, ...) function and call it from the
Element::CountIndexedTree / Element::ProvableCountIndexedTree arm); if the H1-A
verifier is not yet implemented, fail closed by returning an
Err(VerificationError::UnsupportedCountIndexedNode or similar) from
verify_grovedb() instead of treating the node as verified. Ensure you reference
and propagate errors from the H1-A verifier so verify_grovedb() reports
corruption rather than silently continuing.

In `@grovedb/src/operations/count_indexed_tree.rs`:
- Around line 793-831: The current logic uses Query::new() + insert_all() and
then post-filters by lo_count/hi_count which causes full scans; instead
construct a query that seeks directly to the encoded secondary-key bounds so the
iterator starts inside the requested window. Replace the insert_all() usage in
the count-indexed scan (where KVIterator::new(..., &all_query) is created) with
a Query configured to start at the encoded lower or upper secondary key (use the
same secondary-key encoding used by decode_secondary_key) depending on
descending: for ascending, build a start key based on
encode_secondary_key(lo_count, minimal_original_key) and an optional end key
based on encode_secondary_key(hi_count, maximal_original_key); for descending,
start the query at the encoded upper bound and iterate left_to_right=false.
Ensure inclusivity semantics for counts equal to lo_count/hi_count and keep the
same decode_secondary_key/count checks, but the iterator will no longer scan
from the collection edge.

In `@grovedb/src/operations/get/query.rs`:
- Around line 557-560: In function query_item_value_or_sum, the
reference-resolution branch currently doesn't handle Element::CountIndexedTree
and Element::ProvableCountIndexedTree, causing referenced counts to fall through
to InvalidQuery; update the reference-handling match (the branch that resolves
referenced elements) to mirror the direct-element branch by matching
Element::CountIndexedTree(.., count_value, _) and
Element::ProvableCountIndexedTree(.., count_value, _) and returning
QueryItemOrSumReturnType::CountValue(count_value) so referenced count elements
are handled consistently.

In `@grovedb/src/operations/proof/count_indexed.rs`:
- Around line 41-64: The CountIndexedRangeProof envelope currently only carries
a single primary_root_hash, so nested count-indexed ancestors cannot be attested
when building the chain in combine_hash (see combine_hash and the path[..last]
chaining); fix by extending the proof to include per-ancestor H1-A attestation
data (e.g. replace primary_root_hash: [u8;32] with a Vec<[u8;32]> or
primary_root_hashs: Vec<[u8;32]> aligned with layer_proofs) and update the
verifier logic that iterates path layers (the code at lines that use
combine_hash over layer_proofs/path) to consume the corresponding primary
attestation for each layer instead of always using a single primary_root_hash so
nested CountIndexedTree ancestors validate correctly.

In `@grovedb/src/operations/proof/generate.rs`:
- Around line 1463-1465: The code in generate.rs currently treats
Element::CountIndexedTree and Element::ProvableCountIndexedTree like append-only
or fixed-size trees by falling into the final continue arm, which silently
allows V1 subqueries that will produce proofs failing verification; update the
match so that CountIndexedTree and ProvableCountIndexedTree are handled the same
way as the other rejected subquery variants (i.e., return an error/abort the
subquery attempt) instead of continuing – locate the match over Element in the
proof generation function (the arm with
Ok(Element::DenseAppendOnlyFixedSizeTree(..)) |
Ok(Element::CountIndexedTree(..)) | Ok(Element::ProvableCountIndexedTree(..)) =>
continue) and move or duplicate the CountIndexedTree and
ProvableCountIndexedTree variants into the branch that rejects unsupported
subqueries for V1 so non-empty count-indexed trees produce an immediate error
rather than proceeding.

In `@grovedb/src/tests/count_indexed_tree_tests.rs`:
- Around line 829-871: Update the test reconcile_rebuilds_secondary_from_scratch
to first corrupt/clear the secondary index before calling
reconcile_count_indexed_tree_secondary so you actually test rebuilding: after
inserting the CountIndexedTree and its entries (using db.insert and
db.insert_into_count_indexed_tree), explicitly invalidate the secondary (for
example by deleting secondary nodes or overwriting the secondary element for the
path [TEST_LEAF, b"cidx"] with a broken/empty secondary using available db
remove/insert APIs), then call db.reconcile_count_indexed_tree_secondary(...)
and finally assert that db.count_indexed_top_k(...) returns the expected top-k
result; reference functions: reconcile_rebuilds_secondary_from_scratch,
reconcile_count_indexed_tree_secondary, count_indexed_top_k,
db.insert_into_count_indexed_tree.

In `@merk/src/tree/hash.rs`:
- Around line 151-153: The doc comment for combine_hash_three contradicts the
implementation: it says "cost is one hash call" but the function records
hash_node_calls: 2; update the documentation on combine_hash_three to state the
correct cost (two hash calls) and explain briefly that 96 bytes span two 64-byte
Blake3 compression blocks so hash_node_calls is 2, ensuring the comment matches
the implementation.

---

Nitpick comments:
In `@grovedb/src/operations/count_indexed_tree.rs`:
- Around line 316-381: The code that computes initial_deferred_secondary (the
grandparent lookup, extracting parent_secondary_root_key_before from gp_element,
opening parent_secondary_merk via open_count_indexed_secondary_at_path, calling
mirror_to_secondary, and returning (sh, sk) from
parent_secondary_merk.root_hash_key_and_aggregate_data()) is duplicated in
insert and delete; extract this into a single helper (e.g.,
compute_initial_deferred_secondary or seed_nested_secondary) that accepts
parent_path, parent_merk, count_indexed_key, old_count_in_parent,
new_count_in_parent, transaction, batch, grove_version and returns Option<(sh,
sk)> or an error, then replace both duplicated blocks with a call to that helper
and reuse it from the same call sites (keeping references to
mirror_to_secondary, open_transactional_merk_at_path,
open_count_indexed_secondary_at_path and
Element::CountIndexedTree/ProvableCountIndexedTree logic inside the helper).
- Around line 155-163: Replace the manual early-return that does `return
Err(Error::InvalidPath(...)).wrap_with_cost(cost)` after calling
`path.derive_parent()` with the project-standard macro `cost_return_on_error!`,
e.g. invoke `cost_return_on_error!(Error::InvalidPath("cannot insert into
count-indexed tree at the root path".to_string()), cost)` so cost accounting is
applied consistently; apply the same change to the other analogous early-exit
sites in this file that wrap `Err(...).wrap_with_cost(cost)` (the other
occurrences around the count-indexed-tree logic) so all early returns use
`cost_return_on_error!` instead of hand-rolled `wrap_with_cost(cost)`.

In `@merk/src/element/reconstruct.rs`:
- Around line 97-125: Add unit tests that call reconstruct_with_two_root_keys
directly: create both CountIndexedTree and ProvableCountIndexedTree Element
instances (and their NonCounted(Box::new(...)) wrapped variants), call
reconstruct_with_two_root_keys with distinct primary_root_key and
secondary_root_key and an AggregateData that yields a known count, and assert
the returned Element preserves the correct variant, wrapper (NonCounted present
when expected), and that primary_root_key and secondary_root_key are placed in
the reconstructed Element in the correct order (i.e., not swapped). Use the
existing AggregateData helpers and Element constructors to build inputs and
compare reconstructed fields to expected values.

In `@merk/src/tree/ops.rs`:
- Around line 389-410: Add unit tests that exercise the new op variants
PutLayeredCountIndexedReference and ReplaceLayeredCountIndexedReference so the
layered hashing path is covered: write tests that call the op's apply_to(None,
...) to create a fresh node and then apply the op again against an existing node
(update-on-existing-node) to exercise
TreeNode::new_with_layered_value_hash_three and the
put_value_with_two_reference_value_hashes_and_value_cost code paths; assert
expected node hashes, costs, and stored references (use mid_key/mid_value
equivalents from the diff) and mirror these tests for both variants to prevent
regressions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: eb221ea0-9ae9-4765-9e7e-b2c6aec12c7b

📥 Commits

Reviewing files that changed from the base of the PR and between 347bd9b and 8a87da8.

📒 Files selected for processing (35)
  • docs/book/src/SUMMARY.md
  • docs/book/src/appendix-a.md
  • docs/book/src/count-indexed-tree.md
  • docs/spikes/cascading-aggregation-spike.md
  • grovedb-element/src/element/constructor.rs
  • grovedb-element/src/element/helpers.rs
  • grovedb-element/src/element/mod.rs
  • grovedb-element/src/element/visualize.rs
  • grovedb-element/src/element_type.rs
  • grovedb/src/batch/mod.rs
  • grovedb/src/lib.rs
  • grovedb/src/operations/count_indexed_tree.rs
  • grovedb/src/operations/get/query.rs
  • grovedb/src/operations/insert/mod.rs
  • grovedb/src/operations/mod.rs
  • grovedb/src/operations/proof/count_indexed.rs
  • grovedb/src/operations/proof/generate.rs
  • grovedb/src/operations/proof/mod.rs
  • grovedb/src/operations/proof/verify.rs
  • grovedb/src/tests/count_indexed_tree_tests.rs
  • grovedb/src/tests/mod.rs
  • merk/src/element/costs.rs
  • merk/src/element/delete.rs
  • merk/src/element/get.rs
  • merk/src/element/insert.rs
  • merk/src/element/reconstruct.rs
  • merk/src/element/tree_type.rs
  • merk/src/tree/hash.rs
  • merk/src/tree/kv.rs
  • merk/src/tree/mod.rs
  • merk/src/tree/ops.rs
  • merk/src/tree/walk/mod.rs
  • merk/src/tree_type/costs.rs
  • merk/src/tree_type/mod.rs
  • storage/src/rocksdb_storage/storage.rs

Comment thread docs/book/src/count-indexed-tree.md Resolved
Comment thread docs/book/src/count-indexed-tree.md Resolved
Comment thread grovedb/src/batch/mod.rs Resolved
Comment thread grovedb/src/lib.rs Resolved
Comment thread grovedb/src/operations/get/query.rs Resolved
Comment thread merk/src/tree/hash.rs Resolved
Comment thread grovedb/src/operations/insert/mod.rs Outdated
Comment on lines +283 to +310
// CountIndexedTree / ProvableCountIndexedTree own two child Merks
// (primary + secondary). On direct insertion we accept only the
// empty case (both root keys = None, count = 0) because there is
// no two-Merk batch-cascade machinery in this code path; full
// batch / cascading-aggregation support lives in the batch
// propagation work.
Element::CountIndexedTree(primary, secondary, count_value, _)
| Element::ProvableCountIndexedTree(primary, secondary, count_value, _) => {
if primary.is_some() || secondary.is_some() || *count_value != 0 {
return Err(Error::InvalidCodeExecution(
"a CountIndexedTree must be empty at the moment of direct insertion (both \
primary_root_key and secondary_root_key must be None and count = 0); \
non-empty insertion requires batch operations",
))
.wrap_with_cost(cost);
}
cost_return_on_error_into!(
&mut cost,
element.insert_count_indexed_subtree(
&mut subtree_to_insert_into,
key,
NULL_HASH,
NULL_HASH,
Some(options.as_merk_options()),
grove_version,
)
);
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should allow for direct insertion

.to_string(),
))
.wrap_with_cost(cost);
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to do this.

Fixes CI lint failure (debugger.rs match arms) and ten CodeRabbit
review items on the CountIndexedTree implementation:

- Doc status banner: "awaiting implementation" → "implemented"
- Doc wording: "collision-free" → "domain-separated" for hash-derived
  prefixes
- verify_grovedb: fail closed (NotSupported) for cidx instead of
  silently skipping; integrity verification needs the H1-A
  three-input combine and dual-Merk traversal which is not yet wired
- V1 prove_subqueries_v1: explicitly reject subqueries into cidx
  with NotSupported instead of silently emitting an unverifiable
  proof; callers must use prove_count_indexed_top_k
- Batch DeleteTree on cidx: reject because the standard delete path
  only cleans up one child Merk and would orphan the secondary
  storage namespace
- Generic batch path: document the cidx overwrite footgun (same
  shape as other tree types when the override-protection flag is
  off)
- count_indexed_count_range: replace full secondary scan with a
  bounded Query::insert_range using big-endian count bytes, falling
  back to insert_range_from when hi_count == u64::MAX
- query_item_value_or_sum reference branch: include cidx variants
  alongside the direct-element branch
- prove_count_indexed_top_k: reject nested cidx on the proven path
  with NotSupported (envelope only carries H1-A attestation data
  for the terminal cidx); verifier naturally fails the chain check
  if a forged envelope smuggles a nested cidx
- combine_hash_three: correct the doc comment to match the cost
  constant; 96 bytes spans two 64-byte Blake3 blocks (the previous
  comment incorrectly conflated blocks with chunks)
- reconcile test: rename to reconcile_after_query_returns_correct_top_k
  to reflect what the test actually verifies (true desync test
  requires unavailable internal APIs)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@codecov

codecov Bot commented May 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.79196% with 373 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.14%. Comparing base (4fef572) to head (0119f8b).
⚠️ Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
grovedb/src/batch/mod.rs 87.96% 78 Missing ⚠️
...vedb/src/operations/proof/indexed_axis/generate.rs 90.43% 72 Missing ⚠️
...rovedb/src/operations/proof/indexed_axis/verify.rs 90.83% 59 Missing ⚠️
grovedb/src/lib.rs 95.06% 35 Missing ⚠️
grovedb/src/operations/proof/generate.rs 91.55% 26 Missing ⚠️
...db/src/batch/estimated_costs/average_case_costs.rs 95.44% 15 Missing ⚠️
grovedb/src/operations/delete/mod.rs 80.32% 12 Missing ⚠️
...operations/insert/add_element_on_transaction/v0.rs 96.62% 11 Missing ⚠️
...operations/insert/add_element_on_transaction/v1.rs 96.62% 11 Missing ⚠️
grovedb/src/operations/insert/mod.rs 98.73% 11 Missing ⚠️
... and 10 more
Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #657      +/-   ##
===========================================
+ Coverage    91.49%   92.14%   +0.64%     
===========================================
  Files          240      254      +14     
  Lines        67763    77692    +9929     
===========================================
+ Hits         62003    71588    +9585     
- Misses        5760     6104     +344     
Components Coverage Δ
grovedb-core 90.40% <94.00%> (+1.33%) ⬆️
merk 92.89% <ø> (+0.57%) ⬆️
storage 87.00% <ø> (+0.48%) ⬆️
commitment-tree 96.05% <ø> (ø)
mmr 96.79% <ø> (ø)
bulk-append-tree 89.82% <ø> (ø)
element 97.95% <99.79%> (+0.56%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

QuantumExplorer and others added 23 commits May 10, 2026 15:17
The direct (non-batch) insert path previously rejected any
CountIndexedTree element whose primary_root_key, secondary_root_key,
or count_value was non-zero, with an error claiming non-empty
insertion required the batch path (which itself does not yet
support non-empty cidx). This is the migration / restore-from-backup
direct-insertion path.

For non-empty cidx elements, open the existing primary and secondary
Merks at the new path, validate that the caller's declared root keys
match the on-disk state, and read the actual root hashes for the
H1-A combined value hash so the parent's value_hash is consistent
with disk. Mismatched root keys fail loudly.

Also delete docs/spikes/cascading-aggregation-spike.md — internal
and external dev-relevant content for cidx lives in the book chapter
(docs/book/src/count-indexed-tree.md).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Lifts patch coverage on the cidx PR by adding focused tests for the
error paths and rejections introduced over the last few commits, plus
two extra cidx behaviors that were not yet exercised:

- direct_insert_rejects_mismatched_secondary_root_key (mismatch on
  secondary key, mirroring the existing primary-key test)
- batch_delete_tree_on_cidx_is_rejected (DeleteTree on cidx via batch
  must error to avoid orphaning secondary storage)
- verify_grovedb_fails_closed_for_cidx (NotSupported instead of
  silent skip)
- prove_count_indexed_top_k_at_root_path_errors
- prove_count_indexed_top_k_on_non_cidx_target_errors
- count_indexed_top_k_on_non_cidx_target_errors
- count_indexed_count_range_on_non_cidx_target_errors
- reconcile_on_non_cidx_target_errors
- delete_from_count_indexed_tree_on_non_cidx_target_errors
- delete_from_count_indexed_tree_returns_false_for_unknown_key
- count_indexed_count_range_descending_returns_descending_order
  (covers the descending bounded-range branch)
- test_v1_proof_rejects_count_indexed_tree_subquery (V1 generic
  prove path rejects cidx subqueries)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Lifts patch coverage above the codecov 80% threshold by hitting the
0%-covered Display impls, the gated Visualize impls, helper queries
on Element, the count_range / top_k edge cases, and the verifier's
error paths:

- count_indexed_tree_display_renders_fields
- provable_count_indexed_tree_display_renders_fields
- count_indexed_tree_helpers_report_count_and_type
  (is_count_indexed_tree, is_any_tree, element_type, NonCounted look-through)
- test_visualize_count_indexed_tree_empty (visualize feature)
- test_visualize_count_indexed_tree_with_keys (visualize feature)
- test_visualize_provable_count_indexed_tree (visualize feature)
- count_indexed_count_range_with_lo_greater_than_hi_returns_empty
- count_indexed_count_range_with_hi_count_u64_max_uses_range_from
- count_indexed_count_range_respects_limit
- count_indexed_top_k_with_zero_returns_empty
- count_indexed_top_k_at_root_path_errors
- count_indexed_count_range_at_root_path_errors
- verify_count_indexed_top_k_rejects_corrupt_proof_bytes
- verify_count_indexed_top_k_rejects_path_length_mismatch

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
V0 is a frozen on-the-wire proof format. Adding cidx descent to it
would be a wire-format change, so V0 will never learn cidx subqueries.
Reword the V0 prover and verifier comments / error messages to make
that explicit instead of implying the work is pending in a follow-up
PR. The dedicated `prove_count_indexed_top_k` /
`verify_count_indexed_top_k` entry points and the (still TODO) V1
generic path remain the supported routes for cidx queries.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
verify_grovedb: replace fail-closed NotSupported with the actual
H1-A integrity walk for cidx nodes. Open both child Merks, read
their root hashes, verify the parent's recorded value_hash equals
combine_hash_three(value_hash(cidx_bytes), primary_root,
secondary_root), then recurse into the primary normally.

While doing this, fix a pre-existing bug in
insert_into_count_indexed_tree: it called Element::insert (Op::Put,
no combine) regardless of element kind. For tree subtree elements
that meant the cidx primary's merk node stored value_hash =
value_hash(serialized) instead of combine_hash(value_hash,
NULL_HASH), breaking the merkle invariant of the cidx primary
until a deep insert later updated it via propagation. Dispatch on
element kind so trees take Element::insert_subtree, nested cidx
takes Element::insert_count_indexed_subtree, references and items
keep the prior path. Now the cidx primary's root hash is correct
immediately after creation, and verify_grovedb can recurse cleanly.

prove_count_indexed_top_k: extend CountIndexedRangeProof with
ancestor_cidx_secondary_root_hashes (Vec<Option<[u8;32]>> aligned
with intermediate layers). When building, capture each cidx
ancestor's secondary root hash. When verifying, chain via
combine_hash_three at cidx ancestor layers, combine_hash elsewhere.
Removes the prior nested-cidx prover-side rejection.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Subqueries into CountIndexedTree via the generic V1 PathQuery
pipeline now produce a verifiable proof. The cidx primary is the
descent target; queries against the secondary still go through the
dedicated prove_count_indexed_top_k path.

Wire format:
- New ProofBytes::CountIndexedTree(secondary_root || primary_proof)
  variant. The 32-byte secondary attestation is captured from the
  cidx's secondary Merk root hash at proof-build time; the primary
  proof bytes are a standard Merk proof of the subquery results
  generated by prove_subqueries_v1 against the cidx primary.
- LayerProof and ProofBytes derive Clone so the verifier can
  synthesize a sibling Merk-shaped LayerProof from the cidx-prefixed
  bytes and recurse into the existing verify_layer_proof_v1.

Generate (V1): replace the previous NotSupported with descent that
calls prove_subqueries_v1 on the cidx primary, opens the secondary
to capture its root hash, and re-wraps the resulting Merk proof
bytes with the secondary attestation prefix.

Verify (V1): when a lower_layer's parent element is a cidx, require
ProofBytes::CountIndexedTree, split off the 32-byte secondary
attestation, synthesize a Merk LayerProof for the primary, recurse
to obtain primary_root_hash, then chain via
combine_hash_three(value_hash, primary_root, secondary_root)
instead of combine_hash. Reject any other ProofBytes variant under a
cidx parent and any ProofBytes::CountIndexedTree under a non-cidx
parent.

V0 still rejects (V0 wire format is frozen).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The level-by-level batch propagation has no two-Merk hook for
CountIndexedTree primaries: applying mutation ops directly to the
primary updates the primary's root hash but leaves the secondary
index stale, breaking both the H1-A composition stored in the
parent's cidx element bytes and the count-ordered query semantics.

Reject mutation ops (Insert/Replace/Patch/Delete/RefreshReference)
in execute_ops_on_path when the merk's tree_type is a cidx primary,
with a clear NotSupported message pointing callers to the dedicated
APIs (insert_into_count_indexed_tree /
delete_from_count_indexed_tree). Up-bubbled internal ops
(ReplaceTreeRootKey, InsertTreeWithRootHash, etc.) remain allowed
— those represent a child subtree's response to its own change and
are handled correctly by the existing propagate_changes_with
_transaction_with_initial_deferred path that already mirrors to the
secondary at the cidx element boundary.

Full batch integration of cidx primary mutations would require a
new GroveOp variant carrying both primary and secondary state plus
a refactor of the per-level propagation pass; that is a substantial
piece of work and belongs in its own follow-up. Until then,
fail-closed is preferable to silently corrupting the index.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Several module/function comments still claimed cidx features were
"a follow-up" or "not yet wired" after this PR's earlier commits
implemented them. Update wording to reflect current state:

- count_indexed_tree.rs module doc: clarify the dedicated APIs are
  required for direct cidx primary mutations and that the batch
  path fails closed until full batch integration lands; deep ops
  under sub-trees of cidx primaries propagate correctly today.
- count_indexed_top_k doc: drop the "no proofs yet" note and point
  at prove_count_indexed_top_k / verify_count_indexed_top_k.
- count_indexed_tree_tests.rs module doc: drop the PR-2-staging
  banner that claimed item insertion / cascading aggregation were
  unexercised.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
CI codecov/patch is failing at 79.45% (target 80%). Add focused
tests targeting recently-added paths that were not yet exercised:

- insert_into_count_indexed_tree_with_reference_to_missing_target_errors:
  covers the new reference-resolution path for cidx primary inserts
  when the target does not exist.

- deep_insert_under_nested_cidx_propagates_through_both_levels:
  covers the nested-cidx propagation path end-to-end (deep insert
  three levels under outer cidx -> inner cidx -> sub count tree)
  including the new H1-A walk in verify_grovedb at both cidx levels.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Codecov patch is at 79.91% (target 80%) — 13 hits short. Add four
focused tests covering paths recently added but not yet exercised:

- delete_from_count_indexed_tree_round_trip_with_proof: end-to-end
  delete + prove + verify.
- verify_count_indexed_top_k_rejects_truncated_proof: covers the
  bincode decode error branch.
- verify_grovedb_walks_provable_count_indexed_tree: same H1-A walk
  on the ProvableCountIndexedTree variant.
- test_v0_proof_rejects_count_indexed_tree_subquery: covers the V0
  prover's cidx subquery rejection arm.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Lands the structural pieces for cidx primary batch-path support. No
user-visible behavior change: the new op variant is never produced
yet (the rejection at execute_ops_on_path:1862 still fires for cidx
primary mutations), but the parent-level handler is in place so
that emitting the op from a future bubble-up hook is mechanical.

- GroveOp::ReplaceCountIndexedTreeRootKeys: new internal op variant.
  Carries both primary and secondary new-state (root_hash + root_key
  + count_aggregate). Marked #[non_exhaustive] like the other
  internal variants. Sort weight 17, debug formatter, all match
  arms in references / preprocessing / format / cost / sort logic
  exhaustively cover it (rejected as 'internal only' from user-
  facing entry points).

- update_count_indexed_tree_item_preserve_flag_into_batch_operations:
  parallels update_tree_item_preserve_flag_into_batch_operations but
  reconstructs via reconstruct_with_two_root_keys (cidx) and emits
  Op::ReplaceLayeredCountIndexedReference (combine_hash_three /
  H1-A) instead of Op::ReplaceLayeredReference. Preserves flags.

- Parent-level handler: when execute_ops_on_path sees the new op at
  a parent merk, it calls the helper above to recompute the cidx
  element's value_hash via H1-A.

Subsequent commits will: (a) wire a get_secondary_merk_fn closure
through TreeCacheMerkByPath, (b) detect cidx primaries in
execute_ops_on_path and mirror item-level mutations to the
secondary, (c) modify the bubble-up to emit the new op variant
when the just-finished level was a cidx primary. Tests for the
end-to-end behavior land alongside (c).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Lifts the level-by-level batch path from rejecting cidx primary
mutations to supporting them end-to-end. A batch op that inserts /
replaces / patches / deletes / refreshes items inside a cidx
primary now correctly mirrors to the secondary index and updates
the cidx element on the parent merk via H1-A composition.

Implementation:

1. TreeCacheMerkByPath gained a get_secondary_merk_fn closure (opens
   the cidx secondary by primary path, looks up secondary_root_key
   from the parent merk's cidx element internally) and a side-channel
   cidx_secondary_after_apply: HashMap<Vec<Vec<u8>>, ...> populated
   by execute_ops_on_path when the level was a cidx primary.

2. execute_ops_on_path: when in_tree_type is cidx primary, captures
   pre-state (per-key old count_value via merk.get) before the apply
   pass. After apply_with_specialized_costs returns it re-reads each
   key's post-apply element, opens the secondary, runs
   mirror_to_secondary_for_batch (new helper handling all four
   insert/update/delete/no-op cases), and stores secondary's state
   in the side-channel.

3. Bubble-up: pulls the cidx state via the new
   take_cidx_secondary_after_apply trait method. When present,
   emits GroveOp::ReplaceCountIndexedTreeRootKeys instead of
   ReplaceTreeRootKey at the parent level (covers all four bubble-up
   paths: Vacant, Occupied, missing parent map, missing level-above).

4. Parent execute_ops_on_path: handles the new op via
   update_count_indexed_tree_item_preserve_flag_into_batch_operations
   which reconstructs with new root keys + count and emits
   Op::ReplaceLayeredCountIndexedReference for combine_hash_three.

5. open_count_indexed_secondary_for_batch helper on GroveDb:
   convenience wrapper used by the closure that does the parent
   merk lookup + secondary open in one call.

batch_insert_into_cidx_primary_works test verifies end-to-end.
verify_grovedb walks the H1-A chain and finds no issues afterward.

Still TODO (separate follow-up): DeleteTree on cidx primary, cidx
overwrite via Replace, comprehensive atomicity tests.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
prove_count_indexed_top_k was a special case (full-range, ascending
or descending). Lift it to a thin wrapper around a general
prove_count_indexed_query that takes any MerkQuery over the cidx
secondary's keyspace (keys are count_value_be ‖ original_key, so
callers can express count == X, count in [lo, hi], count >= X,
count == X AND original_key starts with Y, etc. by building the
query in those bytes).

Refactored the inner build_count_indexed_proof to take
(secondary_query, limit) instead of (k, descending); the user-
supplied query.left_to_right is echoed in the envelope's
`descending` field for the existing top-k convenience field, and
limit's None gets stored as 0 (verifier treats 0 as no-limit).

Symmetric verifier change: split verify_count_indexed_top_k into a
thin wrapper + verify_count_indexed_inner generic core, and added
verify_count_indexed_query taking the same MerkQuery the prover used
(positional binding requires identical query at both ends).

Test prove_count_indexed_query_with_count_range covers a non-trivial
case: a cidx with five items at counts {1,2,3,5,8}, query
[3, 6) inclusive of 3 and 5, exclusive of 8. Verifier returns
exactly (3, c), (5, d).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Closes a real corruption gap: when
validate_insertion_does_not_override_tree was off, a batch
InsertOrReplace / Replace / Patch could silently overwrite an
existing cidx element. The merk node value would change, but the
cidx primary's storage namespace + the secondary's storage
namespace (Blake3(primary_prefix || 0x01)) would be left behind.
Future inserts under the new cidx's primary_root_key could then
collide with the orphaned data, and the secondary index on the
old data would be unreachable.

When the override-protection flag is on (typical case), the
existing rejection of "attempting to overwrite a tree" already
catches cidx since is_any_tree() returns true. When the flag is
off, however, the path silently corrupts.

Add an unconditional cidx-specific check that fires for
InsertOrReplace / Replace / Patch ops on non-reference elements
when the override flag is off: read the existing element at the
key once, and if it decodes to CountIndexedTree /
ProvableCountIndexedTree, reject with NotSupported pointing at the
delete_from_count_indexed_tree / delete_up_tree workflow. Other
tree-type overwrites remain permitted under the existing
opt-out semantics for backwards compatibility — this stricter
treatment is specific to cidx because cidx owns two storage
namespaces and the corruption is qualitatively worse.

Updates one cost test (+1 seek, +129 storage_loaded_bytes) where
the new check fires. The new test
batch_overwrite_existing_cidx_with_item_is_rejected verifies the
guard.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Codecov patch is at 79.75% (target 80%) — 7 hits short. Add two
focused tests covering the new batch cidx code paths:

- batch_delete_item_from_cidx_primary_works: covers the Delete arm
  of mirror_to_secondary_for_batch (new_count = None) and the
  pre-state capture for Delete ops.
- batch_multiple_inserts_into_cidx_primary_in_one_call: covers the
  multi-key pre-state capture loop and the per-key mirror loop in
  execute_ops_on_path on a cidx primary path.

Both run verify_grovedb afterward to walk the H1-A chain.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Closes a real corruption gap: db.delete() of a CountIndexedTree
element walked the primary's storage namespace via find_subtrees
+ storage.clear() but left the secondary's storage namespace
(Blake3(primary_prefix || 0x01)) untouched. After the cidx element
was removed from the parent merk, the secondary's data became
unreachable but stayed on disk; if the user later re-created a
cidx at the same path, queries against the secondary could observe
stale entries from the previous incarnation.

Add a cidx-specific cleanup branch in
delete_internal_on_transaction (the standard tree-delete code
path). When the deleted element's tree_type is a cidx primary,
derive the secondary prefix via the existing
RocksDbStorage::secondary_prefix_for helper, open storage at that
prefix, and call .clear(). Runs unconditionally (not gated on
is_empty) so empty-cidx deletes also clear the secondary's root
metadata for consistency.

Two new tests verify the cleanup end-to-end via the re-create-
and-query pattern: if the secondary wasn't cleaned, the new cidx's
top-k query would return stale entries.

- direct_delete_empty_cidx_cleans_up_secondary_storage
- direct_delete_non_empty_cidx_cleans_up_both_namespaces

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Lifts the rejection of DeleteTree on CountIndexedTree /
ProvableCountIndexedTree in the batch path. Previously batch users
were forced to fall back to db.delete() outside the batch — fine
for single-cidx workflows but breaks atomicity when DeleteTree is
mixed with other batch ops.

Implementation parallels the H1-A delete fix in commit 6b7ec21
(direct path): the existing tree-delete cleanup pipeline collects
deleted Merk paths into `merk_delete_paths` and runs find_subtrees
+ storage.clear() on each post-apply. Since find_subtrees only
walks primary keys, the cidx secondary storage namespace at
Blake3(primary_prefix ‖ 0x01) was orphaned. Add a parallel
cidx_primary_delete_paths collector that captures cidx primary
DeleteTree ops at validation time, then runs an explicit
secondary-prefix .clear() in the post-apply pass alongside the
primary cleanup. Done in both apply_batch_with_element_flags_update
and apply_partial_batch (the partial-batch variant).

Two new tests use the re-create-and-query pattern to verify the
cleanup:
- batch_delete_tree_on_empty_cidx_works
- batch_delete_tree_on_non_empty_cidx_works

Both query the new cidx's secondary index after re-creation; if the
old secondary weren't cleaned the queries would return stale
entries.

Cidx overwrite via batch (Replace cidx → cidx / non-cidx) remains
rejected. The semantics of replacing an existing cidx element
where the new element references on-disk data are ambiguous and
the safe subset will land separately.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Now that batch DeleteTree on cidx works (commit 0688731), the
recommended workaround for overwriting an existing cidx is:
1. delete_from_count_indexed_tree to empty it
2. DeleteTree via batch (now supported)
3. Re-create in a follow-up batch

Update the rejection error message to point at this clean
workaround instead of the older "delete_up_tree outside of a batch"
guidance.

The full safe subset of cidx overwrites (cidx → non-cidx,
cidx → empty cidx) requires moving cidx-overwrite detection into
the pre-apply scan alongside the DeleteTree discovery loop, plus
careful sequencing of post-apply cleanup vs. new-element write.
That is left for a follow-up; the workaround above is clean today.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Codecov patch is at 79.52% (target 80%) — 14 hits short. Add two
focused tests covering newly-added batch paths not yet exercised:

- batch_overwrite_cidx_rejected_with_override_protection_on:
  covers the validate_insertion_does_not_override_tree=true branch
  hitting cidx (existing-element-is-tree path).
- batch_delete_tree_on_cidx_then_recreate_in_separate_batch_works:
  covers the recommended cidx-overwrite workaround end-to-end —
  DeleteTree the cidx in batch 1, re-create empty in batch 2,
  populate in batch 3 — and verifies via verify_grovedb that the
  H1-A chain is consistent throughout.

The recreate test highlights an important sequencing detail: a
cidx and ops INSIDE the cidx primary cannot share a single batch
because deeper-path ops execute before the cidx itself exists.
This is documented in the test's structure (3 separate batches).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Codecov patch is at 79.52% (target 80%). Earlier tests exercised
the apply_batch cidx-cleanup path but the parallel cleanup pass in
apply_partial_batch and the DontCheckWithNoCleanup branch were
untested. Add two focused tests:

- apply_partial_batch_with_delete_tree_on_cidx_cleans_up_secondary:
  routes through apply_partial_batch and verifies the secondary
  cleanup ran via the re-create-and-query pattern.
- batch_delete_tree_on_cidx_dont_check_with_no_cleanup_still_clears
  _secondary: covers the DontCheckWithNoCleanup branch which skips
  primary find_subtrees but must still clear the cidx secondary
  prefix (a different namespace not covered by find_subtrees).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two parallel polish items:

DOCS — refresh the book chapter to reflect what shipped.

The chapter was design-spec style (Status: implemented, but conceptual
APIs that don't match the actual code). Update the API code blocks to
the shipped function signatures (count_indexed_top_k,
count_indexed_count_range, prove_count_indexed_top_k, the new
prove_count_indexed_query taking arbitrary MerkQuery), replace the
hypothetical CountIndexedQuery struct with the two-route subquery
description (V1 generic PathQuery + dedicated cidx proof), add a new
"Batch path semantics" section documenting supported / rejected ops
plus the cidx-overwrite workaround, and update the
Implementation-detail items table from "Recommended default" to
"Resolution" reflecting what landed (W1: specialized propagation
through propagate_changes_with_transaction_with_initial_deferred +
GroveOp::ReplaceCountIndexedTreeRootKeys at the bubble-up).

ATOMICITY — five new stress tests for batches mixing cidx + non-cidx.

GroveDB batches are atomic by design (validation runs over the full
op list before any writes hit storage). These tests verify the cidx-
aware paths preserve that invariant under mixed workloads:

- batch_mixed_cidx_and_non_cidx_ops_apply_atomically
- batch_failure_in_non_cidx_op_rolls_back_cidx_mutations
- batch_with_multiple_cidx_primaries_each_get_updated
- batch_cidx_delete_with_concurrent_cidx_inserts_atomic
- batch_failure_after_cidx_delete_tree_rolls_back

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Real audit finding: the cidx primary pre-state capture in
execute_ops_on_path lists every mutating op variant EXCEPT the new
GroveOp::ReplaceCountIndexedTreeRootKeys variant introduced for
the cidx-aware bubble-up. When a NESTED cidx primary bubbles up
to its OUTER cidx primary via the batch path:

  Level N (inner cidx primary): mutates fire, secondary mirrored,
    bubble emits ReplaceCountIndexedTreeRootKeys to level N-1.
  Level N-1 (outer cidx primary): receives the op at key=inner_key;
    handler `update_count_indexed_tree_item_preserve_flag_into_
    batch_operations` correctly updates the inner_key element's
    bytes (new primary_root_key, secondary_root_key, count_value).
  But pre-state capture skipped this op type, so post-apply mirror
    walked an empty deltas list. Outer's secondary was not updated.

The corruption was silent: H1-A integrity (verify_grovedb) still
passed because the outer's stored value_hash is recomputed from
the actual on-disk secondary root hash — the secondary just has
stale content. Top-k / count-range queries on the outer returned
stale counts.

Fix: add the variant to the mutates match. With the fix, the outer's
secondary entry for inner_key correctly moves from
(old_count_be ‖ inner_key) to (new_count_be ‖ inner_key) when the
inner's count changes.

Test batch_insert_into_nested_cidx_primary_bubbles_count_up_outer_
secondary fails BEFORE the fix (asserts top[0] == (1, b"inner_cidx")
but gets (0, b"inner_cidx")) and passes AFTER. Found via audit
of the new code paths — there was no batch-path nested-cidx test
before.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Lock down the ReplaceCountIndexedTreeRootKeys-mutates fix from the
prior commit with three additional nesting tests:

- direct_insert_into_nested_cidx_primary_bubbles_count_up_outer_
  secondary
- batch_insert_into_triple_nested_cidx_propagates_through_all_levels
- batch_insert_through_cidx_then_regular_tree_then_cidx (cidx →
  regular CountTree → cidx mixed nesting)

All 1566 grovedb tests pass; release-mode build also passes.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
QuantumExplorer and others added 6 commits August 1, 2026 16:52
The (count, sum) transitions the mirror works from are axis-independent —
only the sort-key encoding differs per axis — but each per-axis
`apply_indexed_secondary_mirror_post_apply` call re-read every captured
key from the primary Merk, so a three-axis PCPSIT batch walked and
deserialized each key's element three times.

`read_post_apply_transitions` is now called once by `execute_ops_on_path`
and the same key-sorted slice is handed to every axis's mirror call.

Tracked costs are UNCHANGED, verified empirically (seeks 17/29/45 at
widths 1/4/8 before and after): the post-apply reads hit the just-applied
in-memory tree, so the redundancy was never charged as seeks — it was
pure CPU (tree walks plus one Element deserialization per key per axis).
No fee moves; PCIT/PSIT (single axis) are unaffected entirely.

Also removes batch/mod.rs's now-unused copy of indexed_axes_for_tree_type
— its last caller was the capture's dropped axes parameter, and the
estimator keeps its own documented copy, which is the one in use.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tables

The avg axis quantizes sum/count into fixed point, and two distinct
averages can collapse onto one sort-key value when the product of their
counts exceeds the scale. At 10^15 that threshold is two children of
~31.6 million rows each — inside the billions-of-rows regime the tree is
expected to serve. 10^19 is the largest power of ten whose worst-case
product |i64::MIN| x SCALE fits in i128, and pushes the collapse
threshold to ~3.16 billion rows per child. A collapse is benign either
way (the full secondary key is sort_key ‖ item_key, so ties order
deterministically by item key); this is about how much resolution the
index delivers at scale, not soundness.

The 10^15 rationale — averages round-tripping through f64's 2^53-exact
integer range — protected only averages of magnitude <= ~9.0, which
credit-denominated sums never produce; nothing in consensus ever touches
a float. The docs now state the f64 approximation honestly instead of
promising a round-trip that held only for tiny values.

A compile-time assertion next to the constant proves the overflow bound
(2^63 x SCALE <= i128::MAX, headroom ~1.84x), so a future scale bump
that breaks it fails the build instead of silently saturating in
compute_avg_fixed_point. The one hard-coded 5x10^15 expectation in the
codec round-trip test is now written against the constant.

Breaking only in the dormant-V4 sense: indexed trees are live on no
released version, so no stored sort key exists to migrate.

Co-Authored-By: Claude Fable 5 <[email protected]>
… per concern

The flat 2,723-line file becomes a module laid out in trust order:

  proof/indexed_axis/
  ├── mod.rs      (95)  the H1-A / attestation narrative, re-exports, and
  │                     aggregate_range_out_of_domain — kept in mod.rs
  │                     because prover and verifier must agree on it: the
  │                     prover uses it to decide an aggregate range is
  │                     provably empty, the verifier to accept the empty
  │                     shape only when the range really is out of domain
  ├── envelope.rs (231) the wire-format and result types — the
  │                     consensus-frozen surface, now isolated so the
  │                     Tier-1 review target is one small file
  ├── generate.rs (1126) the prover: layer proofs, ancestor attestations,
  │                     per-shape envelope builders, aggregate secondary
  │                     proof builders
  ├── verify.rs   (851) the verifier: envelope decoding, the
  │                     ancestor-chain walk, per-shape verification cores
  └── axis_api.rs (471) thin per-axis (count/sum/avg) wrappers, no logic

Function bodies move verbatim. The public surface is unchanged: mod.rs
re-exports the envelope types at their old paths, both GroveDb impl
blocks keep their methods, and the call-graph analysis showed prover and
verifier helpers share exactly one function (the domain rule above), so
nothing needed widened visibility. Verified by the full workspace suite,
including the proof-tamper and nested-ancestor-attestation tests.

Co-Authored-By: Claude Fable 5 <[email protected]>
… batch

Creating a PCIT/PSIT/PCPSIT and writing rows under it in the SAME batch was
rejected with NotSupported. The limitation was implementation order, not
design: the plain-tree analogue has always worked via InsertTreeWithRootHash,
and both missing pieces had in-batch information available the pipeline just
never consulted.

Three changes make the fresh path work:

1. `GroveOp::InsertAggregateIndexedTreeRootKeys` — the insert-side
   counterpart of `ReplaceAggregateIndexedTreeRootKeys`. There is no stored
   element to read during propagation, so the op carries the caller's element
   itself (root keys unset, enforced by the rootless-aggregate rule)
   alongside the level's computed primary and per-axis state. The bubble-up
   emits it when a deeper level finishes under a freshly-inserted indexed
   element; the parent-level apply builds the H1-A value hash through the
   same shared core as the replace path
   (`indexed_tree_item_with_root_state_into_batch_operations`, extracted
   from the replace-only builder — which also stops dropping the
   axes_digest hash cost the old closure accumulated but never attached).

2. The secondary opener takes an in-batch element override. A fresh
   primary's axes cannot be read off the parent merk, but the creating op is
   in `ops_by_qualified_paths` at exactly the level's path; its element
   drives which axes open, each as an empty Merk at its derived prefix
   (which the delete/overwrite sweeps guarantee is clean).

3. The preflight guard narrows from "any fresh indexed with descendants" to
   OVERWRITE-with-descendants only, gated on an existence check against the
   transaction (a missing parent path counts as absent, so fully fresh
   ancestry chains work). The overwrite variant stays rejected because the
   post-apply cleanup of the old element's storage would clear the new
   writes at the same derived prefixes.

The load-bearing tests are equivalences: one-batch create+populate reaches a
root hash BYTE-IDENTICAL to the split sequence for PSIT, PCPSIT (all three
axes), fully fresh ancestry (plain tree + indexed + rows), and double-fresh
nesting (indexed inside indexed). Plus: fresh child under an EXISTING
indexed primary indexes at its derived aggregate, a child tree's grandchild
propagates into the fresh index, the rootless-aggregate forgery door stays
shut on the fresh path, overwrite+descendants still refuses without moving
state, and a fresh-path est-≥-actual estimator contract.

That contract test immediately caught a real estimator bug: the estimated
execute returns `NoAggregateData`, whose aggregate-derived fallback sized
the fresh parent as a plain tree — 25 bytes under a PCPSIT (3 vs 28), the
same deficit at every batch width. Both estimator arms now size from the
carried element's own tree type, and the estimated execute synthesizes an
aggregate KIND matching the layer's tree type so the replace arm's
`replaced_bytes` sizing stops falling into the same NormalTree hole.

The four tests that pinned the old rejection are converted to pin the new
behavior (one asserting a plain Item child indexes at count 1 — only empty
trees index at 0).

Co-Authored-By: Claude Fable 5 <[email protected]>
`reconcile_count_indexed_tree_secondary` becomes
`reconcile_indexed_tree_secondaries`: the indexed family's REINDEX, now
covering every variant. The parent element is read FIRST (its variant
determines the configured axes), the primary is walked once collecting
each entry's (count, sum) pair, and every axis secondary is rebuilt from
that single walk — orphan rows deleted, missing rows inserted, and
payload-damaged rows rewritten in place. Sum and avg rows carry real
payloads (`SumItem` / `ItemWithSumItem`), so key-presence no longer
implies row-correctness; stored element bytes are compared per row. The
key ceiling is enforced per configured axis (avg's 239 only when the avg
axis exists). The parent rebind goes through the variant's own H1-A
shape: the lone axis root hash for PCIT/PSIT, the axes digest for PCPSIT.

Building the payload comparator surfaced two things worth recording:

1. `KVIterator::next_kv` yields the raw Merk NODE encoding — links and
   child hashes, not element bytes. The first comparator diffed desired
   element bytes against node bytes and would have rewritten every row on
   every run. Payloads are now compared via `merk.get`, which returns the
   element; the raw iteration only supplies the existing key set.

2. A Merk root hash commits to tree SHAPE, and shape is a function of
   operation history — which no content repair can recover. Damage that
   permanently rotated surviving nodes (probe: a delete+reinsert flipped
   a two-node tree's root) reconciles to a content-correct,
   verify-clean index whose root can still differ from an undamaged
   peer's. The API doc now states this shape caveat plainly instead of
   promising byte-identity unconditionally: pristine-equality holds for
   shape-preserving damage (in-place payload corruption, reversible row
   damage), and consensus reconvergence after shape-destroying damage
   remains a state-sync problem.

Four per-variant tests join the fourteen existing drift tests, driven by
an axis-aware drift helper that damages one axis and rebinds the parent
through the variant's H1-A composition: PSIT orphan repair, PCPSIT
in-place avg-payload rewrite (fails without the merk-get comparator),
cross-axis canonical repair, and multi-axis idempotence. Also removes
the count-only `make_secondary_key`, superseded by the axis-aware
builder, and updates the refusal messages for the widened variant set.

Co-Authored-By: Claude Fable 5 <[email protected]>
The previous commit removed the count-only make_secondary_key but a codec
unit test still imported it, breaking the test target (the lib itself
compiled, which is how the deletion's clippy check missed it). The test's
byte-level expectations — 8-byte big-endian prefix, decode inversion,
count-order = byte-order — transfer verbatim to the axis-aware builder.

Co-Authored-By: Claude Fable 5 <[email protected]>
Four property tests recording what is structurally true about how the
hash primitives compose. Each is a consensus-frozen fact once a version
carrying it activates, and none was previously asserted anywhere.

Verified safe:

- Nesting is NOT associative, and the flat 3-input combine is distinct
  from either nesting of 2-input combines. Safe structurally, not
  probabilistically: Blake3 is applied at every level, so an
  intermediate is a 32-byte digest that cannot be re-split into the pair
  that produced it — equality would need a hash FIXED POINT, not merely
  a collision.
- `axes_digest` framing is injective: a 1-byte count prefix plus
  fixed-width 33-byte entries means no two distinct axis lists share a
  preimage, and each axis tag is bound to its own secondary root hash.

Recorded as hazards, deliberately pinned rather than fixed:

- `node_hash` and `combine_hash_three` are the SAME function — Blake3
  over three concatenated 32-byte hashes, with no domain-separation
  byte. Safe today only because every input to `combine_hash_three` in
  the indexed chain is bound to a hash fixed further up the proof, so
  substitution needs a preimage rather than exploiting the shared shape.
  The test exists so that future code putting an attacker-chosen 32-byte
  value into either slot WITHOUT such a binding knows it is re-opening a
  type-confusion surface.
- A `node_hash` preimage (96 bytes) and a `kv_digest_to_kv_hash`
  preimage are the same length when the key is 63 bytes, since
  `varint(63)` is one byte — so the same 96-byte string reads both ways
  whenever a node's kv hash begins with 0x3F, about one node in 256.
  Pre-existing, predating the indexed trees by years. No exploit is
  claimed: Merk derives proof structure from operators rather than by
  inspecting hashes. It is pinned because it is the classic Merkle
  leaf/node confusion shape — the reason RFC 6962 prefixes leaves with
  0x00 and internal nodes with 0x01 — and the constraint it places on
  future changes is otherwise invisible.

Both hazards argue for explicit domain separation in a future hash
version; neither can be changed now without breaking V1..V3 wire
compatibility.

Co-Authored-By: Claude Fable 5 <[email protected]>

@QuantumExplorer QuantumExplorer left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed

@QuantumExplorer
QuantumExplorer merged commit c9cd467 into develop Aug 2, 2026
12 checks passed
@QuantumExplorer
QuantumExplorer deleted the claude/gallant-elion-214ef4 branch August 2, 2026 10:13
QuantumExplorer added a commit that referenced this pull request Aug 2, 2026
…yers (#781)

* feat(grovedb): expose indexed-axis proof verification to verify-only builds

The verify-side entry points of the indexed-axis proof envelope
(verify_indexed_axis_top_k and friends) were minimal-gated as a module,
so a consumer compiling with --no-default-features --features verify
could not reach them. Gate the prove-side items individually instead and
open the module to both feature sets, mirroring how the rest of the
proof code splits prover from verifier.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(grovedb): bind, don't reject, a lower layer with no query below it

PR #657 added a hard rejection in `verify_layer_proof_v1`: if a V1 proof
carries a lower layer for a tree whose key the query stops at, verification
fails with "the element bytes would be unbound". The concern is real — a
`KVValueHash`-family node hashes only `(key, value_hash)`, so reporting the
element without a child-hash check would let a prover attach a dummy lower
layer and swap in forged element bytes under a genuine root hash. At v5.0.1
that path pushed the element with no binding at all.

But "the proof descends below the query" is the ordinary shape of a SUBSET
verification, not an attack: `verify_subset_query` exists to run a narrower
query against a proof generated for a wider one. Rejecting it broke every
caller that reads a tree element out of a proof that descended into it. Dash
Platform hit this on three shielded-notes tests, which pull a
`CommitmentTree`'s total note count from the note-fetch proof they already
hold via a single-key, no-subquery, limit-1 subset query.

Bind the element instead of refusing it. The lower layer is now consumed for
its root hash in both cases, and the existing `combine_hash(H(value),
child_root)` chain check does the binding; only the reporting differs. With
no query below, none of the lower layer's rows belong in the result set, so
the tree element itself is reported — under its PARENT path, matching
query_raw and the terminal arm. Every lower-layer flavour already derives its
root independently of the query (the query only selects rows), so the
existing MMR / BulkAppend / CommitmentTree / DenseTree verifiers take a
`report_contents` flag and return the root early; Merk layers get their root
from an empty query, which matches nothing and consumes no limit.

Succinct mode (`verify_query`) still rejects outright: for that query the
layer is data the caller never asked for. The result is strictly stronger
than v5.0.1, which bound nothing here.

Tests: subset verification of a tree element against a descending proof, for
both a plain Tree and the exact Platform CommitmentTree note-count shape; two
tamper tests proving the binding is load-bearing in subset mode — a dummy
lower layer and a sibling subtree's real-but-wrong layer are both rejected.
All three fail before this change with the reported error.

---------

Co-authored-by: Claude Fable 5 <[email protected]>
QuantumExplorer added a commit that referenced this pull request Aug 2, 2026
… value_hash (#782)

* feat(grovedb): expose indexed-axis proof verification to verify-only builds

The verify-side entry points of the indexed-axis proof envelope
(verify_indexed_axis_top_k and friends) were minimal-gated as a module,
so a consumer compiling with --no-default-features --features verify
could not reach them. Gate the prove-side items individually instead and
open the module to both feature sets, mirroring how the rest of the
proof code splits prover from verifier.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(grovedb): bind, don't reject, a lower layer with no query below it

PR #657 added a hard rejection in `verify_layer_proof_v1`: if a V1 proof
carries a lower layer for a tree whose key the query stops at, verification
fails with "the element bytes would be unbound". The concern is real — a
`KVValueHash`-family node hashes only `(key, value_hash)`, so reporting the
element without a child-hash check would let a prover attach a dummy lower
layer and swap in forged element bytes under a genuine root hash. At v5.0.1
that path pushed the element with no binding at all.

But "the proof descends below the query" is the ordinary shape of a SUBSET
verification, not an attack: `verify_subset_query` exists to run a narrower
query against a proof generated for a wider one. Rejecting it broke every
caller that reads a tree element out of a proof that descended into it. Dash
Platform hit this on three shielded-notes tests, which pull a
`CommitmentTree`'s total note count from the note-fetch proof they already
hold via a single-key, no-subquery, limit-1 subset query.

Bind the element instead of refusing it. The lower layer is now consumed for
its root hash in both cases, and the existing `combine_hash(H(value),
child_root)` chain check does the binding; only the reporting differs. With
no query below, none of the lower layer's rows belong in the result set, so
the tree element itself is reported — under its PARENT path, matching
query_raw and the terminal arm. Every lower-layer flavour already derives its
root independently of the query (the query only selects rows), so the
existing MMR / BulkAppend / CommitmentTree / DenseTree verifiers take a
`report_contents` flag and return the root early; Merk layers get their root
from an empty query, which matches nothing and consumes no limit.

Succinct mode (`verify_query`) still rejects outright: for that query the
layer is data the caller never asked for. The result is strictly stronger
than v5.0.1, which bound nothing here.

Tests: subset verification of a tree element against a descending proof, for
both a plain Tree and the exact Platform CommitmentTree note-count shape; two
tamper tests proving the binding is load-bearing in subset mode — a dummy
lower layer and a sibling subtree's real-but-wrong layer are both rejected.
All three fail before this change with the reported error.

* fix(grovedb): bind terminal non-Merk tree element bytes to the parent value_hash

When a V1 proof reported an Element::CommitmentTree / MmrTree /
BulkAppendTree / DenseAppendOnlyFixedSizeTree as a TERMINAL result — the
query targets the tree element itself and the prover emits no lower layer —
nothing tied the serialized element bytes to the value_hash its parent Merk
commits to.

Both existing binding mechanisms skipped these four types. The empty-tree
combine_hash(H(value), NULL_HASH) check is gated on `!is_non_empty_tree()`,
but `is_non_empty_tree()` returns true unconditionally for them. The
`child_hash_verified` requirement was gated on `is_non_empty_merk_tree()`,
which by construction excludes them. The prover, meanwhile, only rewrote
regular non-empty Merk trees to KVValueHashFeatureTypeWithChildHash and left
these emitting a bare KVValueHash, which hashes only (key, value_hash) — the
value bytes never enter the node hash.

A prover could therefore serve forged element bytes (an inflated or deflated
CommitmentTree total_count, a different MMR size) alongside the genuine
value_hash and still reconstruct the correct root hash. Dash Platform's
GetShieldedNotesCount verifier reads total_count from exactly such a terminal
element, so a malicious node could misreport a wallet's shielded sync
denominator.

Note this could NOT be fixed verifier-side by asserting
hash == value_hash(value_bytes): these types are written through
insert_subtree, so the parent commits combine_hash(H(value), state_root), not
plain H(value), and the state root is not derivable from the element bytes.
It has to travel in the proof.

No new proof format is needed. KVValueHashFeatureTypeWithChildHash already
verifies combine_hash(H(value), child_hash) == value_hash, which is exactly
the composition these types commit — the prover simply was not using it here.

Prover: the terminal arm now covers all four types (CommitmentTree moved out
of the empty-trees arm, since it is bound whether or not it holds notes) and
rewrites the node to carry the tree's state root, computed by the new
`non_merk_tree_child_hash`. Each arm mirrors its write path: MmrTree,
BulkAppendTree and DenseAppendOnlyFixedSizeTree are inserted with NULL_HASH
while empty — note an empty BulkAppendTree's compute_current_state_root() is
NOT NULL_HASH, so that case short-circuits — while CommitmentTree needs no
special case because the sinsemilla/bulk composition already yields
EMPTY_COMMITMENT_TREE_STATE_ROOT at count 0. A self-check fails loudly if a
recomputed root does not reproduce the committed value hash, so any future
convention drift surfaces as a prover error instead of an unverifiable proof.

Verifier: the child-hash requirement widens from is_non_empty_merk_tree() to
is_non_empty_tree(), which adds exactly these four types.

This tightens verification: proofs from an un-upgraded prover are now
rejected, so provers and verifiers must upgrade together. New proofs still
verify under old verifiers, which simply do not enforce the check. Left
ungated, matching the existing non-empty-Merk-tree requirement and e2168c1.

V0 envelopes are deliberately untouched. The gap is broader there (a regular
non-empty CountTree's count is forgeable the same way) and V0 documents the
child-hash check as V1-only; it is a frozen wire format and Platform no
longer accepts V0 proofs.

Tests cover all four types plus empty instances, each forgery tried in two
shapes: tampering the value bytes inside the honest child-hash node, and
downgrading the node back to bare KVValueHash — the latter is what exercises
the verifier's new requirement.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(version): gate the terminal non-Merk tree child hash behind GROVE_V4

The binding fix in the previous commit was applied unconditionally, which is
wrong: GROVE_V3 is live, and per v4.rs a fix that changes an accepted/rejected
outcome or a tracked cost cannot land on a released version without nodes
carrying it diverging from nodes that do not. This change does both. An
upgraded verifier rejects proofs a released one accepts, and deriving the
tree's state root costs the prover storage reads and hash calls that V1..V3
never paid — and cost feeds fees.

Adds `proof.terminal_non_merk_tree_child_hash`, 0 in V1..V3 and 1 in V4, and
branches both sides on it:

  - Prover: under v0 the node is left exactly as it has always been emitted
    (bare KVValueHash) and only the limit moves, so the released byte and cost
    shape is untouched. Under v1 it computes the state root and rewrites the
    node.
  - Verifier: non-empty *Merk* trees keep requiring the child hash at every
    version — that has been released behaviour since V3 and is unchanged.
    Only the four non-Merk types are added, and only from V4, so a V4 verifier
    never rejects an honest V3 proof and a V3 verifier never demands a node a
    V3 prover does not emit.

The consequence worth being explicit about: the forgery stays exploitable on
V1..V3 and closes when protocol v4 activates. That is inherent to gating —
fixing it in place is the divergence v4.rs exists to prevent — and it matches
how the other fixes parked on V4 are being handled.

`terminal_non_merk_tree_child_hash_version_gate` pins both sides: it asserts
GROVE_V3 still emits a bare KVValueHash and still accepts the forged
total_count, and that GROVE_V4 emits the child-hash node and rejects it. The
V3 assertion is deliberately an assertion about a hole — if it starts failing,
the fix has leaked into a released version.

Also documents the gate in v4.rs's header alongside the two existing ones, as
that file asks.

Co-Authored-By: Claude Opus 5 <[email protected]>

* refactor(grovedb): make the terminal non-Merk tree gate a file-versioned function

The gate added in the previous commit was an inline
`if ...terminal_non_merk_tree_child_hash >= 1` branch inside
`prove_subqueries_v1`. That does not follow the versioning system's code
structure: every other gated behaviour in the repo is a module directory with
one file per version and a dispatching `mod.rs`, so each version's behaviour
reads on its own instead of being reconstructed from a conditional.

Restructures it into
`operations/proof/bind_terminal_non_merk_tree/{mod,v0,v1}.rs`, following
`operations/insert/add_element_on_transaction/`:

  - `mod.rs` matches the slot and dispatches, with an `UnknownVersionMismatch`
    arm, and carries the docs on what differs between versions.
  - `v0.rs` is the released no-op. It takes the same arguments and ignores
    them, and documents that the unbound element bytes are a known gap
    preserved because GROVE_V3 is live — not an oversight.
  - `v1.rs` holds the state-root derivation, the self-check and the node
    rewrite. `non_merk_tree_child_hash` moves here from `generate.rs`, since
    only v1 needs it.

The gated unit is the binding step rather than the whole enclosing function,
which keeps the per-version files small — duplicating the ~1000-line
`prove_subqueries_v1` would not have been reasonable. `generate.rs` now just
calls the dispatcher. Passing `&mut Node` and deriving key/value inside also
resolves the borrow that forced the old code to clone them up front.

Behaviour is unchanged: `terminal_non_merk_tree_child_hash_version_gate` still
pins GROVE_V3 to the bare KVValueHash (forgery accepted) and GROVE_V4 to the
child-hash node (forgery rejected). The module is `minimal`-gated, so
verify-only builds are unaffected.

Co-Authored-By: Claude Opus 5 <[email protected]>

* perf(grovedb): drop the unused version arg and stop hashing on the bind hot path

Two cleanups to `bind_terminal_non_merk_tree`, both on a path that runs per
terminal non-Merk tree while serving a latency-sensitive proof.

`grove_version` was threaded into v0 and v1 and used by neither — the version
is consumed by the dispatch in `mod.rs`, which is the point of the split.
Dropped from both implementations and from the call sites.

The self-check then went from an unconditional runtime error to a
`debug_assert`. It was costing two blake3 hashes on every terminal non-Merk
tree: `H(value)` plus a `combine_hash`, purely to re-derive a value_hash the
node already carries. That is small next to the storage reads
`non_merk_tree_child_hash` does in the same function, but it bought nothing in
production — it can fire only on a prover bug or corrupted storage, never on
attacker input, and every arm of the derivation is pinned by tests across all
four types, empty and populated. If it ever did fire in release the verifier
would reject the proof anyway; the check only made the diagnosis nicer.

The common path now does no hashing at all: the `value_hash` the node carries
is the one the parent committed, so it is reused as-is. Deriving it is confined
to node shapes that carry none (`KV` / `KVCount` / `KVSum` / `KVCountSum`),
which trees are not proved with in practice.

The debug block is deliberately uncosted (`.unwrap()`, not
`unwrap_add_cost`) so `OperationCost` stays identical between debug and release
builds — a cost that varied by build profile would be far worse than the two
hashes.

Net effect on tracked cost: two fewer `hash_node_calls` per terminal non-Merk
tree than the previous commit charged. That only moves V4 numbers, which are
unreleased, so nothing shifts for V1..V3.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
QuantumExplorer added a commit that referenced this pull request Sep 7, 2026
…anup (#888) (#934)

* fix(grovedb): sweep nested indexed secondaries in every recursive cleanup (#888)

Recursive storage cleanup discovered nested subtrees via find_subtrees
and cleared their primary namespaces, but a nested indexed-tree
primary's per-axis secondary namespaces live at
Blake3(prefix ‖ axis_tag) — outside the path-prefix walk — and were
orphaned by:

- full-batch DeleteTree cleanup,
- partial-batch DeleteTree cleanup,
- the batch cidx safe-subset overwrite cleanup,
- the dedicated indexed-tree child overwrite.

Prefixes are path-derived, so recreating the same path resurrected the
stale secondary rows and broke primary-secondary agreement (reads named
primary entries that no longer exist).

Extract the direct delete's per-descendant sweep (which was already
correct) into one shared routine, GroveDb::clear_subtree_storage_recursively,
that clears every discovered subtree's primary namespace plus all three
axis secondary namespaces, and use it from all six call sites (delete
v0/v1 keep their exact cost sequence). Indexed trees are GROVE_V4-era
and the sweep is idempotent on empty namespaces, matching the ungated
precedent of the existing sweeps (#657/#732/#773).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: preserve versioned batch cleanup costs

---------

Co-authored-by: Claude Fable 5 <[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.

1 participant