Skip to content

perf(drive): build batch deletes without copying the pending batch - #5004

Merged
QuantumExplorer merged 3 commits into
v4.2-devfrom
claude/brave-nobel-8629f7
Sep 26, 2026
Merged

QuantumExplorer merged 3 commits into
v4.2-devfrom
claude/brave-nobel-8629f7

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Issue being fixed or feature implemented

Drive's batch delete helpers hand GroveDB the operations already pending in the batch being built, so GroveDB can account for them (a tree whose children the batch already deletes counts as empty, a tree the batch writes into does not). GroveDB took them as a slice (an owned Vec for the up-tree builder), while Drive keeps its batch as LowLevelDriveOperations, so every call started with LowLevelDriveOperation::grovedb_operations_batch(drive_operations), which clones every pending grove operation, element values included. Building k deletes into one batch therefore cost O(k^2) copies, while applying the finished batch stays linear.

dashpay/grovedb#995 lets GroveDB borrow the pending operations (PendingOperations): it asks for the ones at the deleted tree's own path, and only when the deleted element is a tree.

Measured on a release build (Apple M4, one thread), building the same batch of deletes into one batch:

Deletes in the batch Before After
about 400 21 ms 2.8 ms
about 4,000 1.9 s 27 ms

The before numbers were taken on an idle machine and the after numbers (best of six runs) with other builds running, so the gain is if anything larger.

What was done?

  • Bump GroveDB from 74818ceb to dce8252f (perf!: borrow the pending batch when building delete operations grovedb#995 and the fixes merged before it, listed under the in-place section). Cargo.lock changes only the GroveDB sources.
  • New util::grove_operations::pending_grove_operations: the batch's grove operations, ephemeral ones included, borrowed (the operations grovedb_operations_batch copies).
  • batch_delete / batch_delete_with_options, batch_remove_raw, batch_move, batch_delete_items_in_path_query, batch_move_items_in_path_query and batch_delete_up_tree_while_empty pass them to GroveDB as they are, on the stateful path only (the estimation path never used the copy). The up-tree helper chains check_existing_operations after its own batch, as it appended them before.
  • batch_remove_raw finds the first pending operation on its key by reference, with the same comparison remove_if_insert made on the copy, and clones only the element it returns.

Before and after, with n operations already in the batch:

before: every delete copies all n pending grove operations for GroveDB
after:  every delete lends GroveDB the batch; GroveDB reads the operations at the
        deleted tree's path, and none for a delete it is told is not a tree

GroveDB's default PendingOperations answers by scanning the lent operations, once per tree it deletes, so a tree delete still reads the batch (without copying it). The operations built into the batch, their order and their costs are the same.

In-place changes to shipped generations

Every method below has only a v0, selected by DRIVE_GROVE_METHOD_VERSIONS_V1 at every protocol version (1 through 14):

  • batch_delete v0 (batch_delete_v0, batch_delete_with_options_v0)
  • batch_remove_raw v0
  • batch_move v0
  • batch_delete_items_in_path_query v0
  • batch_move_items_in_path_query v0
  • batch_delete_up_tree_while_empty v0

Why consensus cannot change:

  • Drive side. GroveDB receives the same pending operations, in the same order, lent instead of copied. In batch_remove_raw, remove_if_insert used to drop an insert at the removed key from the copy before GroveDB saw it; GroveDB only reads operations under that key (at path followed by key), never the one at it, so lending it changes nothing. Each edited call site says so.
  • GroveDB 74818ceb..dce8252f, as it reaches Drive:
    • dashpay/grovedb#995: delete_operation_for_delete_internal v0, which GROVE_V1..GROVE_V3 select (protocol versions 1 through 13), reads the same pending operations by the same rule, and the batch apply's own deleted-key set is refactored with the same comparison. From GROVE_V4 (protocol version 14 only, unreleased) a pending DeleteTree with SubelementsDeletionBehavior::Skip no longer counts as emptying a tree; Drive never builds one (its tree deletes are DontCheckWithNoCleanup, and DeleteChildren for epoch trees), so that path is unreachable from Drive. add_delete_operations_for_delete_up_tree_while_empty now appends to its Vec once every level is built; Drive does not call it.
    • dashpay/grovedb#991: GROVE_V4 only, and only for elements that carry backward references, which Drive never stores; GROVE_V1..GROVE_V3 behaviour and costs unchanged.
    • dashpay/grovedb#974, #988, #990: proof verification (MMR sizes no real MMR has, count-offset proofs with backward-reference rows, bulk-append and commitment-tree extraction bounds); honest proofs verify as before.
    • dashpay/grovedb#975, #989: state sync chunk decoding and serving, not block execution.

How Has This Been Tested?

  • pending_grove_operations/tests.rs keeps verbatim copies of the old batch_delete_with_options, batch_delete_up_tree_while_empty and batch_remove_raw (each copying the whole batch, now lent to the bumped GroveDB as a slice) and builds the same batch through old and new, comparing the whole operation list (operations and calculated costs) and the result, for:
    • item deletes, with and without the not-a-tree hint, and estimated deletes;
    • tree deletes: an empty tree, a tree with children, a sum tree, and a non-empty tree with errors off;
    • tree deletes after earlier deletes in the batch: both children deleted (tree counts as empty), the same in the ephemeral batch, one child deleted, a sibling deleted, a grandchild deleted, and an insert into an empty tree;
    • delete-up-tree chains at stop heights 0 to 3, above the path and none, a chain stopped by a sibling, climbing once the sibling is deleted earlier in the batch or in check_existing_operations, stopped by an insert, and unaffected by writes beside the emptied trees;
    • raw removals with nothing pending, a missing key, a pending insert, replace, delete or insert-if-new at the key, and a tree the batch empties or does not;
    • the removals built when a contested vote poll ends, rebuilt through the old helper and compared.
  • should_not_copy_the_pending_batch_for_each_delete counts the pending operations copied (a test-only counter in grovedb_operations_batch): 400 not-a-tree deletes copy none (the old helper copies 79,800), and tree and up-tree deletes copy none.
  • Mutation checks: lending batch_delete's GroveDB call an empty batch, or dropping check_existing_operations from the up-tree call, each fails the comparison tests.
  • A release build produced byte-identical operation lists before this pull request (old code, old GroveDB) and after it, for batches of about 400, 4,000 and 8,000 deletes (hash of the full Debug output, costs included).
  • cargo clippy --workspace --all-targets --all-features --locked -- --no-deps -D warnings, cargo test -p drive (all passing), cargo test -p drive-abci lib tests (3,556 passing) and strategy tests with RUST_MIN_STACK=4194304 as CI runs them (104 passing), cargo test -p drive-proof-verifier (336 passing) and cargo test -p dash-sdk (recorded proof vectors included, all passing) for the GroveDB bump's verification changes, cargo check -p drive --no-default-features --features verify, cargo check -p wasm-drive-verify --target wasm32-unknown-unknown, cargo fmt --all.

Breaking Changes

None. The operations built, their order and their costs are unchanged at every protocol version.

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 added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed
  • If I added or changed GroveDB structure, I described it in the area's structure.rs, regenerated grovedb-structure.json, and checked the structure viewer link posted on this pull request

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Performance Improvements
    • Batch deletions, moves, and removals now avoid repeatedly copying earlier operations in large batches, reducing unnecessary work.
  • Compatibility
    • Tested stateful and stateless workflows preserve their results and generated operations.

The batch delete helpers copied every pending grove operation into a
fresh batch on each call so GroveDB's delete_operation_for_delete_internal
could account for them, which made building k deletes into one batch cost
O(k^2) copies. GroveDB reads only the pending operations at the deleted
tree's own path (path followed by key), and none when the element is known
not to be a tree; the up-tree variant reads one such path per level.

The helpers now hand GroveDB exactly those operations. The operations
built, their order and their costs are unchanged at every protocol
version; tests compare every helper against a verbatim copy of its old
implementation, and a test-only counter keeps the full copy out of the
per-delete path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added this to the v4.2.0 milestone Sep 25, 2026
@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Sep 25, 2026
@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

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

⚙️ Run configuration

Configuration used: Repository: dashpay/platform/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 38abc965-e677-4f95-b3e1-efee2aa3a39a

📥 Commits

Reviewing files that changed from the base of the PR and between 977b9d0 and fe25e36.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • Cargo.toml
  • packages/rs-drive/src/util/grove_operations/batch_delete/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/batch_delete_items_in_path_query/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/batch_delete_up_tree_while_empty/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/batch_move/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/batch_move_items_in_path_query/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/batch_remove_raw/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/pending_grove_operations/mod.rs
  • packages/rs-drive/src/util/grove_operations/pending_grove_operations/tests.rs
 ________________________________________________________________________
< This is like dependency injection, except the dependency is suffering. >
 ------------------------------------------------------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: dashpay/platform/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: baa0f96a-527b-4f2c-a041-9cd26716aa65

📥 Commits

Reviewing files that changed from the base of the PR and between 7829c84 and 977b9d0.

📒 Files selected for processing (10)
  • packages/rs-drive/src/fees/op.rs
  • packages/rs-drive/src/util/grove_operations/batch_delete/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/batch_delete_items_in_path_query/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/batch_delete_up_tree_while_empty/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/batch_move/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/batch_move_items_in_path_query/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/batch_remove_raw/v0/mod.rs
  • packages/rs-drive/src/util/grove_operations/mod.rs
  • packages/rs-drive/src/util/grove_operations/pending_grove_operations/mod.rs
  • packages/rs-drive/src/util/grove_operations/pending_grove_operations/tests.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

Stateful delete and move paths now pass GroveDB operations selected for each target instead of the full batch. New helpers select operations for individual deletes and delete-up-tree processing. Tests compare results and generated operations with previous implementations and track copied-operation counts.

Changes

Pending GroveDB delete operations

Layer / File(s) Summary
Select pending operations
packages/rs-drive/src/util/grove_operations/pending_grove_operations/*, packages/rs-drive/src/util/grove_operations/mod.rs
New helpers select regular and ephemeral GroveDB operations by target path or path prefix. Test-only tracking counts copied operations.
Use selected operations in delete and move paths
packages/rs-drive/src/util/grove_operations/batch_delete/..., packages/rs-drive/src/util/grove_operations/batch_delete_items_in_path_query/..., packages/rs-drive/src/util/grove_operations/batch_delete_up_tree_while_empty/..., packages/rs-drive/src/util/grove_operations/batch_move/..., packages/rs-drive/src/util/grove_operations/batch_move_items_in_path_query/..., packages/rs-drive/src/util/grove_operations/batch_remove_raw/...
Stateful delete and move paths pass selected pending operations to GroveDB. Raw removal inspects the first pending operation for the key and uses selected operations for stateful deletion.
Check compatibility and operation copies
packages/rs-drive/src/util/grove_operations/pending_grove_operations/tests.rs, packages/rs-drive/src/fees/op.rs
Tests compare results and generated operations with preserved implementations. Copy-count tests cover batch deletes and contested-poll cleanup; test-only instrumentation counts operations collected during batch conversion.

Priority: ➖ Normal

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

Change: Refactor

Suggested reviewers: shumkov

Merge Risk: ⚪ Minimal · up to 977b9

This change reduces copying when Drive builds batch deletes and moves. Tests cover a wide range of cases and show that the operations built and their costs match the previous behavior. No concrete correctness risk was found, and the change appears ready to merge.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 977b9

The change keeps the existing deletion interfaces and safeguards while reducing the operations copied into each batch. Incorrect filtering could affect tree deletion, but the changed paths preserve operation order and include comparisons with the prior behavior. Validation across supported versions remains worthwhile.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The material failure mode is an incorrect decision about a tree in Drive’s GroveDB-backed state. The inspected change adds no external authority path; the high-fanout fee-operation change records a copy count only in tests.

Trust Boundaries and Controls

  • observed — Drive passes the caller’s existing path, key, transaction, and restrictive delete options to GroveDB. The new helper filters already-pending Drive operations; it does not grant a caller a new deletion capability.

Resilience and Maintainability Implications

  • observed — The comparison suite retains a full-batch reference implementation, but the inspected comparison and copy-count helpers use the latest platform version. Their presence does not establish equivalence for every supported version.

Hardening Proposals

  • proposed — Validate the selector against GroveDB’s pending-operation reads at the pinned revision and compare generated operations across supported protocol versions, particularly for overlapping tree deletes and stop-height boundaries.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 49 functions across 10 files. 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 and concisely describes the primary change: improving Drive batch-delete performance by avoiding copies of the pending batch.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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.

@thepastaclaw

thepastaclaw commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

🕓 Queued for automated review — 3rd in line, estimated start in ~25 min (commit fe25e36)
Estimated review time once started: ~40 min (two-phase automated review; median of recent runs).

  • Request priority review — click to move this review to the front of the queue.

QuantumExplorer and others added 2 commits September 26, 2026 08:34
GroveDB dashpay/grovedb#995 lets delete_operation_for_delete_internal and
delete_operations_for_delete_up_tree_while_empty borrow the pending
operations and ask only for those at the deleted tree's own path. Bump
GroveDB to dce8252f and pass the batch's grove operations as they are,
dropping Drive's copy of GroveDB's selection rules. The operations built
and their costs are unchanged.

The old-copy comparison tests keep batch_delete, the up-tree chain and
batch_remove_raw; batch_move and the path-query helpers changed the same
way as batch_delete.

Co-Authored-By: Claude Opus 5.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 a876bc9 into v4.2-dev Sep 26, 2026
23 of 25 checks passed
@QuantumExplorer
QuantumExplorer deleted the claude/brave-nobel-8629f7 branch September 26, 2026 03:22
@github-actions github-actions Bot removed the waiting-bots Waiting for the review bots to report on this head label Sep 26, 2026
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