Skip to content

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

Merged
QuantumExplorer merged 1 commit into
developfrom
fix/worst-case-sum-item-cost-size
Oct 12, 2026
Merged

QuantumExplorer merged 1 commit into
developfrom
fix/worst-case-sum-item-cost-size

Conversation

@QuantumExplorer

Copy link
Copy Markdown
Member

Basic explanation

What this does: GroveDB can also estimate the worst-case cost of a batch of writes, which is meant to be an upper bound. A sum item is always stored as if its number took 9 bytes, whatever its value. The worst-case estimate counted the number at its compact size (1 byte for a small value), so it came in up to 8 bytes below the real cost for each sum item. From GROVE_V4, the worst case counts a sum item the way it is stored. Older grove versions estimate exactly as before. #1019 made the same correction to the average-case estimate.

Value: A worst-case estimate below the real cost is not a worst case. Code that relies on it as an upper bound, such as a fee bound checked before a write is applied, could under-reserve by up to 8 bytes (216,000 credits of storage fee on Dash Platform) per sum item.

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) for each inserted SumItem or ItemWithSumItem, by the same amount for each replaced ItemWithSumItem, and by 1 byte for each replaced wrapped SumItem. Applied costs, stored data and proofs do not change. Code that builds GroveDBOperationsWorstCaseVersions 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 worst-case estimators sized the same elements differently:

  • worst_case_merk_insert_element sized every element that is not one of its four sized tree types by serialized_size, which encodes the sum as a varint. SumItem(-3) serializes to 3 bytes and is applied at 11.
  • worst_case_merk_replace_element sized a SumItem by SUM_ITEM_COST_SIZE plus flags but without a wrapper's byte, and an ItemWithSumItem by serialized_size.

One batch inserting the item into the root (a normal tree) of an empty db, GroveVersion::latest(), added_bytes:

item                           worst case before   worst case after   applied
SumItem(-3)                           142                 150            150
SumItem(-3), 3-byte flags             146                 154            154
ItemWithSumItem("v1", -3)             145                 153            153
ItemWithSumItem, 3-byte flags         149                 157            157

Replacing the only child of a count-sum tree with itself, bytes written (added plus replaced) above replacing a plain item of the same wrapping:

item                           worst case before   worst case after   applied
SumItem(-3)                           +6                  +6             +6
ItemWithSumItem("v1", -3)             +1                  +9             +9
NonCounted(SumItem(-3))               +5                  +6             +6
NonCounted(ItemWithSumItem)           +1                  +9             +9

What was done?

  • New slot GroveDBOperationsWorstCaseVersions::worst_case_sum_item_cost_size: 0 in GROVE_V1..GROVE_V3, 1 in GROVE_V4. Any other value is a VersionError.
  • worst_case_merk_insert_element and worst_case_merk_replace_element move into mod.rs / v0.rs / v1.rs dispatch modules under grovedb/src/estimated_costs/worst_case_costs/, the same layout fix(estimated-costs)!: size sum items as the apply does in average-case estimates (GROVE_V4) #1019 used for the average-case pair. Each dispatcher keeps the function's existing version check and then matches on the new slot. v0 is the previous body unchanged (checked byte for byte).
  • Insert v1: an element outside the sized tree arm is sized by specialized_value_defined_cost when it has one, else by serialized_size as before.
  • Replace v1: a SumItem and an ItemWithSumItem are sized by specialized_value_defined_cost. The arms keep their shapes: a SumItem is still a same-size replace, and an ItemWithSumItem is still charged as a replace that may grow.
  • CHANGELOG.md entry and a GROVE_V4 module doc entry.

Not in this PR, both seen while writing the tests:

  • The worst-case batch passes TreeType::NormalTree as the parent tree type for every op (WorstCaseTreeCacheKnownPaths::execute_ops_on_path), so a child of a sum or count tree is not charged its node's aggregate bytes. A plain item inserted under a count-sum tree is estimated 32 bytes below its applied added_bytes. The tests for wrapped items, which only go under count trees, compare deltas against a plain item for that reason.
  • The SumItem replace arm assumes the replaced element had the same size. Replacing a plain Item(b"") with a SumItem is estimated at 0 added bytes, while the apply adds 8.

How Has This Been Tested?

New tests in grovedb/src/batch/estimated_costs/worst_case_costs.rs, over SumItem, SumItem with flags, ItemWithSumItem, ItemWithSumItem with flags, and NonCounted SumItem and ItemWithSumItem:

  • test_batch_sum_bearing_item_insert_worst_case_covers_actual: the four unwrapped items inserted into a normal tree; the latest worst case's added_bytes equal the applied ones and the whole worst case covers the applied cost (worse_or_eq_than). With the GROVE_V4 slot at 0 it fails (142 vs 150 for the first item).
  • test_batch_sum_bearing_item_worst_case_sizing_tracks_actual: all six items under a count-sum tree, inserted and replaced; writing the sum-bearing item rather than a plain one of the same wrapping raises the worst case by what it raises the apply. With the slot at 0 it fails (-2 vs +6 for the first item).
  • test_batch_sum_bearing_item_worst_case_pinned_before_v4: GROVE_V3 figures for every scenario above, pinned to the values measured before this change.
  • test_worst_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 sum_bearing_item, worst_case_sum_item_cost_size and worst_case: 108 passed.
  • cargo test -p grovedb-version: 56 passed.
  • cargo clippy -p grovedb -- -D warnings over every feature except grovedbg (its build script downloads a release artifact, which timed out locally) and cargo fmt --all -- --check are clean.

Breaking Changes

GroveDBOperationsWorstCaseVersions gains a public field, worst_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 worst-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

… 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) 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]>
@coderabbitai

coderabbitai Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 1d2869ab-5f8b-4e17-b085-287b0e3c816f

📥 Commits

Reviewing files that changed from the base of the PR and between e8a12a5 and f7c524b.


📒 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/worst_case_costs.rs
  • grovedb/src/estimated_costs/worst_case_costs.rs
  • grovedb/src/estimated_costs/worst_case_costs/merk_insert_element/mod.rs
  • grovedb/src/estimated_costs/worst_case_costs/merk_insert_element/v0.rs
  • grovedb/src/estimated_costs/worst_case_costs/merk_insert_element/v1.rs
  • grovedb/src/estimated_costs/worst_case_costs/merk_replace_element/mod.rs
  • grovedb/src/estimated_costs/worst_case_costs/merk_replace_element/v0.rs
  • grovedb/src/estimated_costs/worst_case_costs/merk_replace_element/v1.rs

 __________________________________
< Jazz Jackrabbit is my alter ego. >
 ----------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
✨ 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.

@QuantumExplorer
QuantumExplorer merged commit 5cb0962 into develop Oct 12, 2026
9 of 10 checks passed
@QuantumExplorer
QuantumExplorer deleted the fix/worst-case-sum-item-cost-size branch October 12, 2026 10:40
@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 f7c524b. 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 86.96682% with 55 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.20%. Comparing base (e8a12a5) to head (f7c524b).
⚠️ Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
...d_costs/worst_case_costs/merk_insert_element/v0.rs 55.55% 16 Missing ⚠️
..._costs/worst_case_costs/merk_replace_element/v0.rs 67.39% 15 Missing ⚠️
...vedb/src/batch/estimated_costs/worst_case_costs.rs 96.04% 7 Missing ⚠️
..._costs/worst_case_costs/merk_insert_element/mod.rs 85.00% 6 Missing ⚠️
...costs/worst_case_costs/merk_replace_element/mod.rs 85.00% 6 Missing ⚠️
..._costs/worst_case_costs/merk_replace_element/v1.rs 91.48% 4 Missing ⚠️
...d_costs/worst_case_costs/merk_insert_element/v1.rs 97.22% 1 Missing ⚠️

❌ Your patch status has failed because the patch coverage (86.96%) 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    #1020      +/-   ##
===========================================
- Coverage    93.21%   93.20%   -0.02%     
===========================================
  Files          346      352       +6     
  Lines       108102   108428     +326     
===========================================
+ Hits        100771   101062     +291     
- Misses        7331     7366      +35     
Components Coverage Δ
grovedb-core 91.57% <86.96%> (-0.02%) ⬇️
merk 94.20% <ø> (ø)
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 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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants