Skip to content

fix(batch)!: size aggregating trees as themselves in average-case batch estimates (GROVE_V4) - #1018

Merged
QuantumExplorer merged 1 commit into
developfrom
fix/average-case-aggregate-tree-sizing
Oct 12, 2026
Merged

QuantumExplorer merged 1 commit into
developfrom
fix/average-case-aggregate-tree-sizing

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

Basic explanation

What this does: GroveDB can estimate what a batch of writes will cost without running it. Sum trees and count trees store a few more bytes than plain trees (their running total). When a batch creates one of these trees together with its first contents, the estimate counted it as a plain tree and missed those bytes. From GROVE_V4, the estimate counts the tree as what it is. Older grove versions estimate exactly as before.

Value: Dash Platform uses this estimate as the fee bound a write is checked against before it is applied, so the estimate must be at least the real cost. For a document under a summable index, the estimate was 18 bytes (486,000 credits) below the real storage fee; with this change it is not below it. Count, count-sum and big-sum trees get the same correction.

Risks: Low. Only GROVE_V4 estimates change, and they only go up: by 9 bytes per aggregate axis (16 for a big sum) for each such tree created with its contents, and by the same amount in replaced bytes when such a tree's root key is replaced. Applied costs, stored data and proofs do not change. Code that builds GroveDBOperationsAverageCaseVersions by hand must set one new field.

Issue being fixed or feature implemented

In an average-case batch estimate, each level hands an aggregate up to the op that writes its tree element in the parent, and that op sizes the element by the aggregate's tree type. AverageCaseTreeCacheKnownPaths::execute_ops_on_path returned an aggregate only for the three indexed tree types and NoAggregateData for every other one. When a tree is inserted in the same batch as its contents, the insert becomes InsertTreeWithRootHash { aggregate_data, .. }, and average_case_merk_insert_tree sizes it with aggregate_data.parent_tree_type().cost_size(): TREE_COST_SIZE (3) instead of SUM_TREE_COST_SIZE (12), COUNT_SUM_TREE_COST_SIZE (21) and so on. The apply sizes the same element by its real type, so the estimate's added_bytes came in below the applied ones.

Seen from Dash Platform: inserting one document into a type with an index { properties: [tier], summable: "weight" } (u8 and i8 properties) creates a SumTree value tree and a SumTree [0] bucket in the same batch as the document's reference.

Before (GROVE_V4, Platform protocol version 14):

dry-run storage fee   20_682_000
applied storage fee   21_168_000   (18 bytes more: two sum trees x 9)

After:

dry-run storage fee >= applied storage fee

In GroveDB alone, one batch inserting an empty tree and one item inside it (added_bytes):

                     GROVE_V3 estimate   GROVE_V4 estimate   applied
SumTree                     273                 282             282
CountTree                   273                 282             282
CountSumTree                289                 307             307
BigSumTree                  289                 305             305

Before this change GROVE_V4 gave the GROVE_V3 figures.

What was done?

  • execute_ops_on_path (average case) returns AggregateData::from(tree_type.empty_tree_feature_type()) under the new slot value 1: the aggregate kind of the level's own tree type (values zero, only the variant drives sizing). The three indexed types map exactly as before; non-Merk trees and plain trees still report NoAggregateData.
  • New slot GroveDBOperationsAverageCaseVersions::average_case_propagated_aggregate_kind: 0 in GROVE_V1..GROVE_V3 (indexed trees only, the old behaviour), 1 in GROVE_V4. Any other value is a VersionError.
  • The same aggregate also reaches ReplaceTreeRootKey, which average_case_merk_replace_tree v1 sizes by replacing_tree_type: replacing a sum tree's root key now charges its 12 bytes, not 3, as replaced bytes.
  • The worst-case estimator is unchanged: WorstCaseLayerInformation carries no tree type to derive an aggregate from.
  • CHANGELOG.md entry and a GROVE_V4 module doc entry.

Not in this PR: inserting a SumItem is estimated by its serialized length (3 bytes for a small value) while the apply charges the fixed SUM_ITEM_COST_SIZE (11), so an estimate can still come in under an apply that writes sum items. The new tests use plain items as children to keep that case separate.

How Has This Been Tested?

New tests in grovedb/src/batch/estimated_costs/average_case_costs.rs, each over all eight aggregating Merk tree types (sum, big sum, count, count-sum, provable count, provable count-sum, provable sum, provable count provable sum):

  • test_batch_aggregate_tree_created_with_contents_average_case_added_bytes_match_actual: one batch creating the tree with an item inside; the GROVE_V4 estimate's added_bytes equal the applied ones. With the slot at 0 this fails for every type.
  • test_batch_aggregate_tree_created_with_contents_average_case_pinned_before_v4: GROVE_V4 minus GROVE_V3 estimated added_bytes is exactly the aggregate bytes (9 / 16 / 18), so V1..V3 output is unchanged.
  • test_average_case_propagated_aggregate_kind_unknown_version_is_refused: slot value 9 is a VersionError.
  • test_batch_root_one_sum_item_replace_op_average_case_costs now pins both versions: GROVE_V3 keeps 5,594 replaced bytes, GROVE_V4 gives 5,603 (the replaced sum tree root key, +9).

Runs:

  • cargo test -p grovedb --lib: 3,610 passed, 8 ignored, run before the unknown-version test was added and the bound test tightened to equality; those four tests pass on the final commit.
  • cargo test -p grovedb-version: 56 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 against this change (applied on the currently pinned rev): all pass after five pinned protocol-version-14 dry-run figures move by +3,600 credits of processing fee (one sum tree root key replace, 9 replaced bytes); storage figures and every earlier protocol version are unchanged. New Platform tests for sum, range-sum, count and count-sum indexes fail without this change and pass with it.

Breaking Changes

GroveDBOperationsAverageCaseVersions gains a public field, average_case_propagated_aggregate_kind, so code that builds the struct by hand must set it. Estimates under GROVE_V1..GROVE_V3 do not change; GROVE_V4 average-case estimates rise as described above.

Checklist:

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

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

PR Hygiene · b51f2b3

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

When every merge requirement is met, the PR Hygiene check passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.

Summary by CodeRabbit

  • Bug Fixes
    • Improved average-case batch cost estimates in GroveDB V4 to account for aggregate data from all tree types, including trees updated in the same batch and replacements of existing root keys.
    • GroveDB V1–V3 retain their previous estimation behavior.

…ch estimates (GROVE_V4)

A level of an average-case batch estimate reported an aggregate to the
op writing its tree element in the parent only for indexed trees. A sum,
big sum, count or count-sum tree inserted in the same batch as its
contents became an InsertTreeWithRootHash carrying no aggregate, so the
estimator sized it as a plain tree and the estimate's added bytes came
in below the applied ones by the aggregate's bytes (9 per axis, 16 for a
big sum). A replaced root key of such a tree was under-sized the same
way in replaced bytes.

From GROVE_V4 every level reports the aggregate of its own tree type,
through the new operations.average_case.average_case_propagated_aggregate_kind
slot (0 in V1..V3, 1 in V4). Older grove versions estimate exactly as
before.

BREAKING CHANGE: GroveDBOperationsAverageCaseVersions gains the public
field average_case_propagated_aggregate_kind.

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

coderabbitai Bot commented Oct 12, 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: 1aa35c67-aeaa-4b62-9adf-f6068eb17aa2

📥 Commits

Reviewing files that changed from the base of the PR and between b50a583 and b51f2b3.


📒 Files selected for processing (7)
  • CHANGELOG.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/batch/estimated_costs/average_case_costs.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

Average-case batch estimates now use a versioned rule for propagating tree aggregates. V1–V3 retain indexed-only sizing. V4 includes each tree type’s aggregate when sizing parent writes, including aggregate bytes in replaced root-key estimates.

Changes

Average-case aggregate sizing

Layer / File(s) Summary
Define and configure the sizing version
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, CHANGELOG.md
A new version slot controls propagated aggregate sizing. V1–V3 set the slot to 0, while V4 sets it to 1. The changelog records the versioned behavior.
Apply versioned sizing in batch estimates
grovedb/src/batch/estimated_costs/average_case_costs.rs
The estimator keeps indexed-only aggregate sizing for version 0 and uses each tree type’s aggregate for version 1. Tests cover estimate byte counts, replaced root-key sizing, and rejection of unsupported versions.

Priority: ⬇️ Low

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

Change: Bug fix


Merge Risk: ⚪ Minimal · up to b51f2

No actionable issue remains from this review; the PR is mergeable after normal checks.

Pre-merge checks | Passed 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: correcting average-case batch sizing for aggregating trees in GROVE_V4.
Docstring Coverage Passed Docstring coverage is 81.82% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 6 files. (1 skipped: 1 …
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.

✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR


🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

  • Autofix · 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 12, 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 12, 2026
@thepastaclaw

thepastaclaw commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

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

@codecov

codecov Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.58974% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.22%. Comparing base (b50a583) to head (b51f2b3).

Files with missing lines Patch % Lines
...db/src/batch/estimated_costs/average_case_costs.rs 93.58% 10 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1018      +/-   ##
===========================================
- Coverage    93.22%   93.22%   -0.01%     
===========================================
  Files          340      340              
  Lines       107628   107777     +149     
===========================================
+ Hits        100338   100475     +137     
- Misses        7290     7302      +12     
Components Coverage Δ
grovedb-core 91.59% <93.58%> (+<0.01%) ⬆️
merk 94.20% <ø> (-0.02%) ⬇️
storage 91.68% <ø> (ø)
commitment-tree 95.62% <ø> (ø)
mmr 95.43% <ø> (ø)
bulk-append-tree 93.72% <ø> (ø)
element 97.39% <ø> (ø)
🚀 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)

Independently verified the complete diff at b51f2b3 and the aggregate conversion, batch propagation, and parent-element sizing paths; no in-scope defects were found. The new feature slot preserves V1–V3 behavior, enables corrected aggregate sizing only in V4, and retains accumulated costs on unsupported-version errors; regression tests cover all eight aggregating Merk tree types, historical sizing, and version rejection. Validation was static only: the supplied exact-head CI snapshot reports passing test shards, formatting, linting, security audit, and coverage checks, with PR Hygiene still 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: low by gpt-6.1-sol (effort low) — The change is a small, contained correction to aggregate-type propagation in average-case cost estimates with an explicit version gate and regression tests, not a large or intricate change to a critical surface.
  • 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 medium); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort medium); agent phase2-reviewer, gpt-6.1-sol — platform-versioning (completed, effort medium); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort medium); agent phase2-reviewer

@github-actions

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 12, 2026
@QuantumExplorer
QuantumExplorer merged commit 99c0f4f into develop Oct 12, 2026
15 of 16 checks passed
@QuantumExplorer
QuantumExplorer deleted the fix/average-case-aggregate-tree-sizing branch October 12, 2026 07:57
QuantumExplorer added a commit to dashpay/platform that referenced this pull request Oct 12, 2026
… (PV14)

dashpay/grovedb#1018 merged (99c0f4fb6f), followed by #1019 and #1020,
which size inserted sum items (and replaced ItemWithSumItem) at the
fixed width the apply charges in the average- and worst-case
estimators, from GROVE_V4. Pin develop's head; the lockfile changes
only the grovedb rev. PV14 note 93 now covers the sum item sizing too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
QuantumExplorer added a commit that referenced this pull request Nov 8, 2026
…tinuation-dd8070

develop's #1021 landed this branch's two GROVE_V4 fixes (same-batch
reference prediction and the Unchanged re-measure) with later review
fixes of its own, so those now exist once, in develop's form. What this
branch adds over develop is the settlement mode:

- the prediction keeps develop's runs_value_update and post-apply
  check; a settling batch uses version 1 on every grove version
- CHANGELOG: the fixes stay under develop's entries in 6.1.0, and the
  settlement entries move to Unreleased
- same_batch_reference_prediction_tests is develop's file with the
  settling modes added, its helpers shared with settle_test_support
- the option-off estimate pins are retaken from develop at 0ea327d:
  18 of the 66 latest-version rows moved with #1018..#1020 and none of
  the 66 grove v3 rows did
- a settled tree's lookup comment says why it is still needed after #1018

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