Skip to content

fix(proof)!: prove a path through an empty provable tree (GROVE_V4) - #1010

Merged
QuantumExplorer merged 1 commit into
developfrom
fix/prove-through-empty-provable-tree
Oct 6, 2026
Merged

QuantumExplorer merged 1 commit into
developfrom
fix/prove-through-empty-provable-tree

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

Basic explanation

Some range totals cannot be proved today. If the path to the counted range goes through a provable count or sum tree that is still empty, the prover fails with "Cannot create proof for empty tree", even though the answer (zero) is obvious. With this change, from GROVE_V4, the prover proves that tree empty and stops there, the same way it already proves any other empty tree it meets. Older grove versions behave exactly as before.

Issue being fixed or feature implemented

Dash Platform keeps a provable count tree for an index's first property from the moment a contract is registered. Before the first document, that tree is empty. A count over a range below it (for example brand == "acme" AND color > "blue" through an index [brand, color], while a rangeCountable index on [brand] makes brand a ProvableCountTree) builds this path query:

path:  [.., "widget", "brand", "acme", "color"]
query: AggregateCountOnRange(RangeAfter("blue"..))

Before (any grove version):

prove_query(..) -> Err(InternalError("failed to generate proof for query_items [Key(acme)] error is : corrupted code execution error Cannot create proof for empty tree"))

The unproven read answers zero, so a client asking for a proof gets an internal error for a valid query. The same happens for sums (an empty ProvableSumTree), count-and-sum reads (an empty ProvableCountProvableSumTree), and carrier queries whose IN keys sit under the empty tree.

After (GROVE_V4):

prove_query(..) -> Ok(proof)   // brand proved empty in its parent layer, no lower layer
verify_query(proof, PathQuery::new_single_key([.., "widget", "brand", "acme"], "color"))
    -> Ok((root_hash, []))     // root_hash is the real root

What was done?

  • Root cause. In prove_subqueries_v1 (grovedb/src/operations/proof/generate.rs), the empty-host arms for ProvableCountTree / ProvableCountSumTree / ProvableCountProvableSumTree (count), ProvableSumTree / ProvableCountProvableSumTree (sum) and ProvableCountProvableSumTree (count and sum) descend into any empty tree of those types the query routes through. That descent is meant for the aggregate terminal, where aggregate_at_depth short-circuits and an empty Merk answers zero. Above the terminal, the child is an ordinary layer over an empty Merk, and generate_merk_proof cannot prove an empty Merk.
  • Fix. A per-layer flag, descends_into_empty_aggregate_tree, keeps those arms for the aggregate terminal only. An empty tree above the terminal falls through to the existing generic empty-tree arm: it is proved in its parent layer with no lower layer (and charged as an empty layer), and its value hash binds it to the empty child root. The resulting proof is byte-identical to the proof of the single-key query over the same path.
  • Version gate. New slot GroveDBOperationsProofVersions::empty_tree_above_aggregate_terminal: 0 in GROVE_V1..GROVE_V3 (always descend, the old behaviour) and 1 in GROVE_V4 (descend only at the terminal). Any other value is a VersionError. Released grove versions produce the same proofs and the same refusals.
  • Verifiers are unchanged. The aggregate verifiers still require a descent at every key down to the terminal, so they refuse these proofs ("aggregate-count proof missing lower layer for path key ..."). verify_query with the single-key query over the same path verifies them, which is what Platform's verifiers fall back to. Extending the aggregate verifiers to read such a proof as zero is left out: it touches about a dozen descent sites across the three axes and needs a decision on how an empty tree at the terminal and an empty carrier key should read.
  • An empty tree at the terminal is still descended into, with identical proof bytes under GROVE_V3 and GROVE_V4.
  • CHANGELOG.md entry, and a paragraph in the book's "Empty subtrees" section (docs/book/src/aggregate-count-queries.md).

How Has This Been Tested?

New module grovedb/src/tests/aggregate_through_empty_tree_tests.rs. Each test runs six cases: count over an empty PCT, PCST and PCPS; sum over an empty PST and PCPS; count and sum over an empty PCPS.

  • grove_v3_still_refuses_to_prove_through_an_empty_aggregate_tree: the leaf and carrier shapes still fail under GROVE_V3, and the plain single-key query proves and verifies.
  • grove_v4_proves_a_leaf_aggregate_through_an_empty_aggregate_tree: the proof generates, has no layer under the empty tree, is byte-identical to the single-key query's proof, and verify_query returns an empty result against the real root; the aggregate verifiers' refusal is pinned.
  • grove_v4_proves_a_carrier_aggregate_whose_path_ends_in_an_empty_aggregate_tree: the same for the carrier shape.
  • grove_v4_proves_a_carrier_key_that_is_an_empty_aggregate_tree_above_the_terminal: a populated key is descended into, an empty one is proved without a layer.
  • an_empty_aggregate_terminal_is_proved_identically_under_grove_v3_and_v4: unchanged bytes at the terminal, verifying to zero.
  • a_populated_tree_cannot_be_passed_off_as_the_empty_tree_on_the_path: an honest proof over a populated tree, rewritten to claim an empty tree with its lower layer dropped, is rejected by verify_query ("empty tree value hash mismatch", the [audit][P20] V1 descent can treat unbound tree classification as verified absence #869 binding) and by the aggregate verifier.
  • an_unknown_empty_tree_above_aggregate_terminal_version_is_refused: slot value 2 is a VersionError.

With the old generate.rs restored, the three grove_v4_proves_* tests fail with "Cannot create proof for empty tree", and the unknown-version test fails too.

  • cargo test -p grovedb -p grovedb-version: grovedb lib 3545 passed (8 ignored), integration tests passed, grovedb-version 56 passed, doc tests passed.
  • cargo clippy -p grovedb -p grovedb-version --all-targets -- -D warnings and cargo fmt --all -- --check are clean.
  • Dash Platform's Drive library tests (4,107) pass against this commit, including a new range total through an empty count tree that proves and verifies to zero at Platform protocol version 14 and is still refused at 13.

Breaking Changes

GroveDBOperationsProofVersions gains a public field, empty_tree_above_aggregate_terminal, so code that builds the struct by hand must set it. Proof bytes and refusals under GROVE_V1..GROVE_V3 do not change.

Checklist:

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

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • GROVE_V4 can now generate proofs when an empty aggregate tree appears above the aggregate-query endpoint. The empty tree is proven in its parent layer; empty trees at the endpoint still return an authenticated zero.
    • GROVE_V1–V3 retain their previous behavior and may fail to generate proofs for empty trees above the endpoint.
  • Documentation
    • Added guidance on how these proofs behave and how single-key and aggregate queries verify them.

PR Hygiene · 0741852

  • Bots — coderabbitai ✓ · thepastaclaw ✓
  • Self-review — post /self-reviewed
  • Within your 5 open PRs
  • Build green
  • Approvals — you own every area touched; none needed

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

An aggregate-on-range proof (AggregateCountOnRange, AggregateSumOnRange,
AggregateCountAndSumOnRange, leaf or carrier shape) whose path, or whose
carrier key followed by a subquery_path, runs through an EMPTY
ProvableCountTree, ProvableCountSumTree, ProvableSumTree or
ProvableCountProvableSumTree above the aggregate terminal failed to
generate with "Cannot create proof for empty tree". The V1 prover's
empty-host arms descend into such a tree so that an empty terminal
answers with the aggregate short-circuit's authenticated zero, but above
the terminal the descent reaches an ordinary layer over an empty Merk,
which has no Merk proof.

From GROVE_V4 (new slot proof.empty_tree_above_aggregate_terminal: 1)
those arms descend only into the aggregate terminal itself. An empty tree
above it falls through to the generic empty-tree arm and is proved in its
parent layer with no lower layer, as an empty tree of any other type
there already was; its value hash binds it to the empty child root, and
verify_query with the single-key query over the same path verifies the
proof (the proof is byte-identical to that query's own proof). The
aggregate verifiers are unchanged and still refuse a path that ends
before the terminal. An empty terminal is still descended into, with
identical proof bytes under GROVE_V3 and GROVE_V4. GROVE_V1..V3 keep
failing, so released proofs and refusals do not change.

Breaking: GroveDBOperationsProofVersions gains a field.

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

coderabbitai Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ad8633fe-6d54-4b38-ab56-99557dd27769
📥 Commits

Reviewing files that changed from the base of the PR and between 96b50c1 and 0741852.

📒 Files selected for processing (10)
  • CHANGELOG.md
  • docs/book/src/aggregate-count-queries.md
  • grovedb-version/src/version/grovedb_versions.rs
  • grovedb-version/src/version/v1.rs
  • grovedb-version/src/version/v2.rs
  • grovedb-version/src/version/v3.rs
  • grovedb-version/src/version/v4.rs
  • grovedb/src/operations/proof/generate.rs
  • grovedb/src/tests/aggregate_through_empty_tree_tests.rs
  • grovedb/src/tests/mod.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

GROVE_V4 proves an empty aggregate tree above an aggregate-on-range terminal in its parent layer without a lower layer. GROVE_V1–V3 retain the prior descent behavior. Aggregate verifiers remain unchanged, and empty trees at the terminal are still descended into.

Changes

Aggregate proofs through empty trees

Layer / File(s) Summary
Versioned prover rule
grovedb-version/src/version/grovedb_versions.rs, grovedb-version/src/version/v1.rs, grovedb-version/src/version/v2.rs, grovedb-version/src/version/v3.rs, grovedb-version/src/version/v4.rs
The proof-version configuration adds empty_tree_above_aggregate_terminal. GROVE_V1–V3 set the slot to 0, while GROVE_V4 sets it to 1.
Empty-tree proof generation
grovedb/src/operations/proof/generate.rs
The V1 prover uses the selector to decide whether to descend through an empty aggregate tree. Count, sum, and combined count-and-sum branches use this rule. Unknown selector values return a version mismatch error.
Proof cases and documented behavior
grovedb/src/tests/aggregate_through_empty_tree_tests.rs, grovedb/src/tests/mod.rs, docs/book/src/aggregate-count-queries.md, CHANGELOG.md
Tests cover GROVE_V3 failures, GROVE_V4 proofs, empty terminals, forged proofs, and unsupported selector values. Documentation describes proof behavior and verifier outcomes.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant AggregateRangeQuery
  participant V1Prover
  participant GroveVersion
  participant ParentLayer
  AggregateRangeQuery->>V1Prover: request aggregate-range proof
  V1Prover->>GroveVersion: read empty-tree descent version
  GroveVersion-->>V1Prover: return selector
  V1Prover->>ParentLayer: prove empty tree without a lower layer when above terminal
Loading

Merge Risk: ⚪ Minimal · up to 07418

No identified issue blocks merging the versioned empty-tree proof behavior after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 07418

The change is narrowly version-gated and preserves the inspected proof-authentication controls. The new proofs still require different handling from ordinary aggregate proofs. Correct downstream fallback and trusted-root comparison were not established, so some integration uncertainty remains.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The relevant attack surface is a proof consumer receiving adversarial proof bytes and deciding whether a requested path is empty. The inspected change affects aggregate count, sum, and combined queries routed through empty ancestors; service, tenant, credential, or environment exposure cannot be determined from this library-level evidence.

Security Findings and Attack Paths

  • observed — The new adversarial test removes a populated tree's lower layer and substitutes empty-tree bytes while preserving its committed hash. It asserts that single-key verification rejects the empty claim with a value-hash mismatch and that aggregate verification also rejects it. This is counterevidence to that specific forgery, not exhaustive coverage of every carrier or indexed-tree attack.

Trust Boundaries and Controls

  • inferred — verify_query reconstructs and returns a root rather than accepting an independently trusted root. Authenticity therefore requires the consumer to compare that result with its trusted root before treating authenticated absence as zero. This responsibility predates the PR; the new single-key fallback exercises it, and production enforcement was not inspected.

Resilience and Maintainability Implications

  • observed — Generation retains one snapshot transaction for all recursive layers and creates a fresh per-request limit state. Recursive errors propagate before the complete proof is returned, while empty-ancestor handling charges the existing empty-layer budget. The inspected change does not introduce a persistent write or recovery transition.

Hardening Proposals

  • proposed — For downstream adoption, explicitly require trusted-root equality and authenticated absence for the intended query before mapping a fallback result to zero. Do not translate arbitrary aggregate-verification failures into zero, and distinguish wholly absent paths from mixed populated/empty carrier results.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 73.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 30 functions across 8 files. (2 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the proof change and the GROVE_V4 version, though it does not specify that the empty tree is above an aggregate terminal.
Full details: Docstring Coverage

Explanation

Docstring coverage is 73.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 30 functions across 8 files. (2 skipped: 2 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

❤️ Share

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

@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Waiting for bot review — coderabbitai ✓ · thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

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

thepastaclaw commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

✅ Final review complete — no blockers (commit 0741852) · triage: normal · Phase 2 only (no Phase 1 for this repository)

@codecov

codecov Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.19%. Comparing base (96b50c1) to head (0741852).

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1010      +/-   ##
===========================================
+ Coverage    93.14%   93.19%   +0.04%     
===========================================
  Files          336      336              
  Lines       105645   105687      +42     
===========================================
+ Hits         98399    98490      +91     
+ Misses        7246     7197      -49     
Components Coverage Δ
grovedb-core 91.58% <100.00%> (+0.09%) ⬆️
merk 94.03% <ø> (ø)
storage 91.94% <ø> (ø)
commitment-tree 95.62% <ø> (ø)
mmr 95.43% <ø> (ø)
bulk-append-tree 93.72% <ø> (ø)
element 97.18% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@thepastaclaw thepastaclaw 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.

Final validation — Phase 2 only (no Phase 1 for this repository)

The GROVE_V4 change correctly limits descent into empty aggregate trees to the aggregate terminal and reuses the existing authenticated empty-tree handling above it, while preserving older-version behavior. The aggregate verifiers’ continued refusal is real, but extending their result semantics is explicitly outside this PR’s prover-and-single-key-fallback contract; no in-scope actionable findings remain. Validation was static only; the supplied exact-head CI snapshot reports all Ubuntu test shards, linting, formatting, security audit, and book build passing, with PR Hygiene pending.

Review provenance

Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.1-sol (effort low) — The version-gated change to prove_subqueries_v1 in grovedb/src/operations/proof/generate.rs changes authenticated proof generation, but its contained empty-tree routing logic is not large or intricate enough to meet the critical tier.
  • Phase 1 reviewers: not run (disabled for this repository)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer

@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Oct 6, 2026
QuantumExplorer added a commit to dashpay/platform that referenced this pull request Oct 6, 2026
Protocol versions up to 13 verify and answer as released:
- The six range-total verifiers keep version 0 as released. A new
  version 1, selected only by protocol version 14
  (DRIVE_VERIFY_METHOD_VERSIONS_V3), wraps it and reads a proof that the
  range holds nothing (a missing key, or an empty tree of a kind the read
  does not aggregate) as a zero total or no carrier branch
  (`or_empty_range_total`).
- The unproven range total reads an absent value as zero only where that
  verifier is at version 1 (`aggregate_or_zero_when_absent`); before, it
  fails as released.
- The composite verifier gains a version 1 (protocol version 14) that
  reads sum-bearing items as documents; version 0 reads them as released.

Other fixes:
- The chained verifier reads a sum-bearing outer document. Edited in
  place: a chained query needs an indexOnly inner type, which only
  protocol version 14 parses.
- Chained and composite reads without a proof are refused before any read
  when an indexOnly index lacks a property, as a documents query through
  it is (`refuse_an_uncovered_index_only_projection`).
- drive-abci maps a missing required property to a query error only for
  indexOnly documents, with the refusal text Drive shares.
- Two preallocated indexes sharing leading properties queue each tree
  once.
- The meta-schema v3 description and the book list only the `where`
  values a reference can name, and say group counts need rangeCountable.
- Counter chain comments, private range refusals, the shared absence
  predicate at three more sites.

Tests: the absent-brand total errors and its proof is refused at protocol
version 13 and both read zero at 14; a carrier under an empty sum tree; a
chained join into summable posts; the chained no-proof refusal (Drive and
drive-abci; the join tests use a like that byLiker holds whole); composite
refusals; two preallocated counters sharing a prefix; a range total
through an empty count tree (ignored until the grovedb pin carries
dashpay/grovedb#1010); a shared dpp refusal assertion, widget helpers, a
literal Swift assertion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@QuantumExplorer
QuantumExplorer merged commit 02db008 into develop Oct 6, 2026
18 of 19 checks passed
@QuantumExplorer
QuantumExplorer deleted the fix/prove-through-empty-provable-tree branch October 6, 2026 01:09
QuantumExplorer added a commit that referenced this pull request Oct 6, 2026
…e version (#1011)

#1010 gated its prover change behind proof.empty_tree_above_aggregate_terminal
so GROVE_V1..V3 kept their behaviour, but that behaviour was a failure:
proving an aggregate-on-range query whose path runs through an empty
provable tree above the terminal always ended in "Cannot create proof for
empty tree". No proof that generated before changes, so the gate protected
nothing and cost a public version field, a dispatcher, and GROVE_V3 users
keeping the failure.

prove_subqueries_v1 now descends into an empty aggregate tree only when it
is the aggregate terminal, at every grove version that proves aggregate
queries (GROVE_V3 and later; GROVE_V1 and V2 use the untouched V0 prover).
The slot, its values in GROVE_V1..V4 and the dispatcher are removed; the
tests run under GROVE_V3 and GROVE_V4; the changelog entry and the book
paragraph drop the version.

The slot was never released, so nothing breaks relative to the last
release.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

waiting-self-review Waiting for the author to post /self-reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants