Skip to content

fix(estimated-costs)!: size sum items as the apply does in average-case estimates (GROVE_V4) - #1019

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

QuantumExplorer merged 1 commit into
developfrom
fix/average-case-sum-item-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. A sum item is always stored as if its number took 9 bytes, whatever its value. The estimate instead counted the number at its compact size (1 byte for a small value), so it missed up to 8 bytes for each sum item it wrote. From GROVE_V4, the estimate counts a sum item the way it is stored. 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. Platform writes sum items for identity balances, token balances, summable count counters and summable index-only entries. Each one a batch inserted was estimated up to 8 bytes (216,000 credits of storage fee) below its real cost, and so was each replaced ItemWithSumItem. Replacing a SumItem, such as a balance update, was already estimated correctly.

Risks: Low. Only GROVE_V4 estimates change, and they only go up: by 9 bytes less the sum value's varint width (8 for a small value, 0 for a value that needs all 9) for each inserted SumItem or ItemWithSumItem, and by the same amount in replaced bytes for each replaced ItemWithSumItem. 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

The apply writes a SumItem or ItemWithSumItem (wrapped or not) with Op::PutWithSpecializedCost, sized by Element::specialized_value_defined_cost: SUM_ITEM_COST_SIZE (11: the sum at its fixed 9-byte width, the type byte, the flags option byte), plus the flags, plus the item bytes and their length for an ItemWithSumItem, plus one byte for a wrapper. The average-case estimators sized the same elements differently:

  • average_case_merk_insert_element sized every element that is not a tree by serialized_size, which encodes the sum as a varint. SumItem(-3) serializes to 3 bytes and is applied at 11.
  • average_case_merk_replace_element already sized a SumItem by SUM_ITEM_COST_SIZE, but an ItemWithSumItem fell through to serialized_size.

This was noted as out of scope in #1018. One batch on an empty db creating a sum tree with one child, GroveVersion::latest(), added_bytes:

child                          estimate before   estimate after   applied
Item("v1")                          282               282           282
SumItem(-3)                         280               288           288
SumItem(-3), 3-byte flags           284               292           292
ItemWithSumItem("v1", -3)           283               291           291
NonCounted(SumItem(-3))  *          306               314           314
NonCounted(ItemWithSumItem) *       309               317           317

* under a count-sum tree

What was done?

  • New slot GroveDBOperationsAverageCaseVersions::average_case_sum_item_cost_size: 0 in GROVE_V1..GROVE_V3, 1 in GROVE_V4. Any other value is a VersionError.
  • average_case_merk_insert_element and average_case_merk_replace_element move into mod.rs / v0.rs / v1.rs dispatch modules under grovedb/src/estimated_costs/average_case_costs/. Each dispatcher keeps the function's existing version check and then matches on the new slot. v0 is the previous body unchanged.
  • Insert v1: an element that is not a tree is sized by specialized_value_defined_cost when it has one (a sum-bearing item, wrapped or not), else by serialized_size as before. This is the same choice the apply makes in insert_into_batch_operations.
  • Replace v1: an ItemWithSumItem is sized by specialized_value_defined_cost. Every other arm is unchanged, including the SumItem arm, which already matched the apply.
  • ReferenceWithSumItem and the backward-reference sum variants are unaffected: the apply sizes them by their serialized length, and they have no specialized cost.
  • CHANGELOG.md entry and a GROVE_V4 module doc entry.

Not in this PR:

  • The worst-case estimator has the same gap (worst_case_merk_insert_element sizes sum items by serialized_size; worst_case_merk_replace_element does so for ItemWithSumItem). It is a separate change with its own slot.
  • [audit][C014] Average insertion estimates omit wrapped-tree storage overhead #911 (a wrapped tree inserted through average_case_merk_insert_element is sized without its wrapper byte) is in the same function but is a tree-sizing question; this PR leaves the tree arm as it was.

How Has This Been Tested?

New tests in grovedb/src/batch/estimated_costs/average_case_costs.rs, next to #1018's, each over six children: SumItem, SumItem with flags, ItemWithSumItem, ItemWithSumItem with flags (under a sum tree), and NonCounted SumItem and ItemWithSumItem (under a count-sum tree):

  • test_batch_sum_bearing_item_created_with_its_tree_average_case_added_bytes_match_actual: one batch creating the tree with the child; the latest estimate's added_bytes equal the applied ones. With the GROVE_V4 slot at 0 it fails (280 vs 288 for the first child).
  • test_batch_sum_bearing_item_replace_average_case_replaced_bytes_track_actual: a batch replacing the child with itself. A replace estimate over-counts its propagation, so its total is above the applied one; the test checks the element's own share: replacing the sum-bearing child instead of a plain item must raise the estimate's replaced_bytes by as much as it raises the applied ones, and the estimate must cover the applied cost. With the slot at 0 it fails for ItemWithSumItem (+1 vs +9).
  • test_batch_sum_bearing_item_average_case_pinned_before_v4: GROVE_V3 insert and replace estimates for all six children, pinned to the figures measured before this change.
  • test_average_case_sum_item_cost_size_unknown_version_is_refused: slot value 9 is a VersionError from both the insert and the replace dispatcher.

Runs:

  • cargo test -p grovedb --lib filtered to the estimate tests (sum_bearing_item, average_case, estimated_costs, aggregate_tree_created): 166 passed.
  • The two v0 bodies were checked to be byte-identical to the removed functions after their version check.
  • Full suite, clippy and Dash Platform Drive results: see the comment below once they finish.

Breaking Changes

GroveDBOperationsAverageCaseVersions gains a public field, average_case_sum_item_cost_size, 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 · dd5fb6c

  • Bots — coderabbitai ✓ · thepastaclaw not yet — /skip-bots proceeds without the ones not yet reported
  • Self-review — post /self-reviewed
  • Build failed
  • 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

  • Updates
    • Average-case insert and replacement cost estimates for sum-bearing items in GROVE_V4 and later now use the specialized sizing method, charging the sum value at a fixed 9 bytes.
    • GROVE_V1 through GROVE_V3 retain their existing estimate behavior.

…se estimates (GROVE_V4)

The apply writes a SumItem or ItemWithSumItem (wrapped or not) with its
specialized cost, which charges the sum value at its fixed 9-byte width
(SUM_ITEM_COST_SIZE). average_case_merk_insert_element sized it by its
serialized size instead, which encodes the sum as a varint, and
average_case_merk_replace_element did the same for an ItemWithSumItem.
The estimate then came in below the applied bytes by up to 8 per item:
a SumItem(-3) inserted with its sum tree was estimated at 280 added
bytes and applied at 288.

From GROVE_V4 both size a sum-bearing item by the specialized cost,
through the new operations.average_case.average_case_sum_item_cost_size
slot (0 in V1..V3, 1 in V4). The two estimators move into
mod.rs/v0.rs/v1.rs dispatch modules; v0 is the previous body unchanged,
so older grove versions estimate exactly as before.

BREAKING CHANGE: GroveDBOperationsAverageCaseVersions gains the public
field average_case_sum_item_cost_size.

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: 5f3809b7-0c4b-420f-ac88-d6b718ce3c1f

📥 Commits

Reviewing files that changed from the base of the PR and between 99c0f4f and dd5fb6c.


📒 Files selected for processing (14)
  • 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
  • grovedb/src/estimated_costs/average_case_costs.rs
  • grovedb/src/estimated_costs/average_case_costs/merk_insert_element/mod.rs
  • grovedb/src/estimated_costs/average_case_costs/merk_insert_element/v0.rs
  • grovedb/src/estimated_costs/average_case_costs/merk_insert_element/v1.rs
  • grovedb/src/estimated_costs/average_case_costs/merk_replace_element/mod.rs
  • grovedb/src/estimated_costs/average_case_costs/merk_replace_element/v0.rs
  • grovedb/src/estimated_costs/average_case_costs/merk_replace_element/v1.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 enables versioned average-case cost sizing for SumItem and ItemWithSumItem inserts and replacements. The new estimators use specialized costs for version 1. GROVE_V1 through GROVE_V3 retain version 0 sizing. Tests cover estimates, applied costs, and unsupported versions.

Changes

Sum-item cost estimates

Layer / File(s) Summary
Sizing version and version defaults
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
Adds average_case_sum_item_cost_size. GROVE_V1–GROVE_V3 set it to version 0; GROVE_V4 sets it to version 1. The changelog documents the sizing behavior.
Versioned insert estimates
grovedb/src/estimated_costs/average_case_costs.rs, grovedb/src/estimated_costs/average_case_costs/merk_insert_element/*, grovedb/src/batch/estimated_costs/average_case_costs.rs
Adds version dispatch for insert estimates. Version 0 uses serialized size for non-tree elements; version 1 uses specialized element cost when available. Tests compare estimates with applied added bytes and pin V3 results.
Versioned replacement estimates
grovedb/src/estimated_costs/average_case_costs/merk_replace_element/*, grovedb/src/batch/estimated_costs/average_case_costs.rs
Adds version dispatch for replacement estimates. The estimators account for element type, flags, wrapper overhead, and propagation. Tests compare estimates with applied replaced bytes, pin V3 results, and check unsupported versions.

Priority: ➖ Normal

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

Change: Bug fix


Merge Risk: ⚪ Minimal · up to dd5fb

No identified issue prevents merging 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: updating average-case sum-item sizing to match apply behavior for GROVE_V4.
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 13 files. (1 skipped: …
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

Copy link
Copy Markdown
Contributor

🕓 Review not started yet because the new head is waiting for the 30-minute push debounce.

  • Request normal review — click when the PR is ready for review.
  • Request priority review — click to move this review to the front of the queue.

Commit dd5fb6c. Normal review starts when eligible; priority review starts as soon as a slot is available.

@codecov

codecov Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.04878% with 49 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.21%. Comparing base (99c0f4f) to head (dd5fb6c).

Files with missing lines Patch % Lines
...osts/average_case_costs/merk_replace_element/v0.rs 67.44% 14 Missing ⚠️
...costs/average_case_costs/merk_insert_element/v0.rs 67.85% 9 Missing ⚠️
...db/src/batch/estimated_costs/average_case_costs.rs 96.17% 7 Missing ⚠️
...osts/average_case_costs/merk_replace_element/v1.rs 85.71% 7 Missing ⚠️
...osts/average_case_costs/merk_insert_element/mod.rs 85.00% 6 Missing ⚠️
...sts/average_case_costs/merk_replace_element/mod.rs 85.00% 6 Missing ⚠️

❌ Your patch check has failed because the patch coverage (88.04%) is below the target coverage (90.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1019      +/-   ##
===========================================
- Coverage    93.22%   93.21%   -0.01%     
===========================================
  Files          340      346       +6     
  Lines       107777   108102     +325     
===========================================
+ Hits        100475   100771     +296     
- Misses        7302     7331      +29     
Components Coverage Δ
grovedb-core 91.58% <88.04%> (-0.01%) ⬇️
merk 94.20% <ø> (+<0.01%) ⬆️
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.

@QuantumExplorer

Copy link
Copy Markdown
Member Author

Reviewed

@QuantumExplorer
QuantumExplorer merged commit e8a12a5 into develop Oct 12, 2026
13 of 15 checks passed
@QuantumExplorer
QuantumExplorer deleted the fix/average-case-sum-item-sizing branch October 12, 2026 09:02
QuantumExplorer added a commit that referenced this pull request Oct 12, 2026
… estimates (GROVE_V4) (#1020)

The apply writes a SumItem or ItemWithSumItem (wrapped or not) with its
specialized cost, which charges the sum value at its fixed 9-byte width
(SUM_ITEM_COST_SIZE) and counts a wrapper's byte.
worst_case_merk_insert_element sized it by its serialized size instead,
which encodes the sum as a varint; worst_case_merk_replace_element did
the same for an ItemWithSumItem and left out a wrapped SumItem's
wrapper byte. The worst case then came in below the applied bytes by up
to 8 per item and was not an upper bound: a SumItem(-3) inserted into a
normal tree was estimated at 142 added bytes and applied at 150.

From GROVE_V4 both size a sum-bearing item by the specialized cost,
through the new operations.worst_case.worst_case_sum_item_cost_size slot
(0 in V1..V3, 1 in V4). The two estimators move into mod.rs/v0.rs/v1.rs
dispatch modules; v0 is the previous body unchanged, so older grove
versions estimate exactly as before. This is the worst-case twin of
#1019.

BREAKING CHANGE: GroveDBOperationsWorstCaseVersions gains the public
field worst_case_sum_item_cost_size.

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-bots Waiting for the review bots to report on this head

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants