Skip to content

perf!: borrow the pending batch when building delete operations - #995

Merged
QuantumExplorer merged 3 commits into
developfrom
perf/delete-borrows-pending-batch
Sep 26, 2026
Merged

QuantumExplorer merged 3 commits into
developfrom
perf/delete-borrows-pending-batch

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Issue being fixed or feature implemented

delete_operation_for_delete_internal and delete_operations_for_delete_up_tree_while_empty take the operations already pending in the batch being built, so a delete can account for them: a tree whose children the batch already deletes counts as empty, and a tree the batch writes into does not. They took those operations as &[QualifiedGroveDbOp] and an owned Vec<QualifiedGroveDbOp>.

A caller that keeps its batch in its own operation type has no such slice to hand over, so it has to copy the whole pending batch, element values included, on every delete it builds. Building k deletes into one batch then costs O(k^2) copies, although GroveDB reads none of them unless the deleted element is a tree, and then only those at that tree's own path. Dash Platform's Drive keeps its batch as LowLevelDriveOperations and did exactly this: building about 400 deletes into one batch took 21 ms and about 4,000 took 1.9 s, almost all of it copying. dashpay/platform#5004 works around it on the Drive side by copying only the operations it knows GroveDB reads, which means Drive has to mirror GroveDB's selection rules.

Review of this PR also found that the builder counts a pending DeleteTree with SubelementsDeletionBehavior::Skip as removing its child. The apply path drops such a delete when the child is not empty, so a parent emptied only by it is built as DeleteTree(DontCheckWithNoCleanup) and deleted without cleanup over the child it keeps. Reproduced: the parent element is gone, its Merk still holds child, child still holds its item, and verify_grovedb reports nothing.

What was done?

Pending operations are asked for by path. Both builders take current_batch_operations: impl PendingOperations<'a>, a new trait with one method, at_path(&self, path) -> impl Iterator<Item = &'a QualifiedGroveDbOp>. A builder asks it only when the deleted element is a tree, and only for that tree's own path; an up-tree chain asks once per tree it climbs through.

  • Every IntoIterator<Item = &QualifiedGroveDbOp> + Clone implements it by scanning: a slice, &Vec, ops.iter(), or an adapter over the caller's own operation type (ops.iter().filter_map(CallerOp::grove_op)).
  • A caller with a large batch can implement it over an index of its batch by path (on a reference to the index), so each question costs only the operations at that path instead of a scan of the whole batch. This works from a downstream crate, which I checked.

Up-tree chain. Each level gets the key the level below deleted, the only one of the chain's own deletes at that tree's path, instead of re-reading all of them. The chain collects its deletes once. add_delete_operations_for_delete_up_tree_while_empty keeps its signature and appends the chain's deletes to the caller's Vec once every level is built. On an error it leaves the Vec as it was; before, it kept the deletes built below the failing level.

Skip deletes, gated to GROVE_V4. The builder moves to operations/delete/delete_operation_for_delete_internal/{mod.rs,v0.rs,v1.rs} (slot delete.delete_operation_for_delete_internal, V4 = 1).

  • v1 counts only the deletes GroveOp::always_removes_its_key accepts, so a pending Skip delete leaves its child counted as present.
  • The batch pre-scan's two emptiness arms use the same rule, now shared through QualifiedGroveDbOp::key_always_removed_at. The refactor leaves their behaviour unchanged.
  • v0 keeps the old rule for GROVE_V1..V3. Excluding the Skip key changes the is_empty_tree_except walk and so the cost, which is why it is gated.

Also: deleted keys are collected only for Merk trees, and the builder re-checks each returned operation's path, so an index that returns more than it was asked cannot change the result.

How Has This Been Tested?

grovedb/src/tests/delete_pending_operations_tests.rs, every test at both GROVE_V3 and the latest version. Each result is built three ways (slice, adapter over a caller's own op type, index by path), and for the up-tree builder a fourth way through the &mut Vec form. All must agree.

  • Costs are pinned to the values develop charges, recorded by running develop's builders on the same fixtures: tree emptied by pending deletes, one child deleted, deletes at other paths, a write into an empty tree, a non-tree delete with and without a hint, the up-tree climb, and the cases below.
  • A non-tree delete never reads the pending operations or asks the index. A tree delete asks only for its own path. An up-tree chain asks only for the trees it climbs through.
  • An empty MMR tree with a pending append counts as non-empty; a pending delete at its path changes nothing.
  • A pending Skip delete of a non-empty child is counted on V3 (the old build and cost are pinned) and not on V4, where the result and cost match having nothing pending. A pending Error delete counts on both.
  • A pending write into a tree higher up stops the climb.
  • A failing chain leaves the caller's Vec unchanged.
  • Mutation checks, each failing a new test: hiding the caller's operations above the first level; dropping the key deleted at the level below; counting Skip deletes in v1; appending to the Vec on error.
  • cargo test -p grovedb --all-features (3,547 unit tests, the integration tests and doctests, all passing) and cargo test -p grovedb-version.
  • cargo clippy --workspace --exclude grovedb-bincode --exclude grovedb-bincode-derive --all-features --no-deps -- -D warnings, plus cargo clippy -p grovedb --all-features --all-targets with no lints in the files this touches.
  • cargo check --workspace --exclude grovedb-bincode --exclude grovedb-bincode-derive --all-features --all-targets, cargo check -p grovedb --no-default-features --features verify, cargo doc -p grovedb --all-features --no-deps (no warnings in touched files), cargo fmt --all -- --check.

Breaking Changes

  • Source. The pending-operations parameter of both builders is impl PendingOperations<'a>.
    • These still compile: &[], &ops for a Vec or slice ops, ops.iter(), vec![], and adapters over the caller's own operations.
    • The argument no longer deref-coerces, so a &mut Vec, &&Vec, &Box<[_]> or &Arc<Vec<_>> is passed as ops.iter().
    • An owned Vec<QualifiedGroveDbOp> for the up-tree builder is passed as &ops or ops.iter().
  • Behaviour, GROVE_V4 only. A pending DeleteTree with SubelementsDeletionBehavior::Skip no longer counts as removing its child, which changes the result and the cost of the emptiness check for such batches. GROVE_V1..V3 are unchanged.
  • add_delete_operations_for_delete_up_tree_while_empty leaves the caller's Vec as it was on an error.
  • No stored data or proof changes.

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 · c70dadd

  • Bots — coderabbitai not yet · thepastaclaw not yet — /skip-bots proceeds without the ones not yet reported
  • Self-review — post /self-reviewed once the bots are done
  • Within your 5 open PRs
  • Build running
  • Approvals — you own every area touched; none needed

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

Summary by CodeRabbit

  • Bug Fixes
    • Tree deletions now account for pending child deletes and writes when checking whether a tree is empty. This also supports deleting empty ancestor trees while preserving the resulting delete operations and costs.
  • Refactor
    • Delete-operation processing can read pending operations by reference, while existing mutable-vector workflows for building ancestor deletes remain available.

QuantumExplorer and others added 2 commits September 26, 2026 06:40
delete_operation_for_delete_internal and
delete_operations_for_delete_up_tree_while_empty took the operations
already pending in the batch as a slice and an owned Vec. A caller that
keeps its batch in its own operation type had to copy the whole batch for
every delete it built, so building k deletes into one batch cost O(k^2)
copies, although GroveDB reads none of them unless the deleted element is
a tree, and then only those at that tree's own path.

Both now take the pending operations by reference as an IntoIterator of
&QualifiedGroveDbOp (also Clone for the up-tree builder, whose levels each
read them). The single-delete builder reads them in one pass and only in
the tree branch. The operations built and their costs are unchanged.
add_delete_operations_for_delete_up_tree_while_empty keeps its signature.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 0abf866a-2c62-4fac-bd26-08afaea3339e

📥 Commits

Reviewing files that changed from the base of the PR and between 709fdba and 128fbd0.

📒 Files selected for processing (5)
  • CHANGELOG.md
  • grovedb/src/operations/delete/delete_up_tree.rs
  • grovedb/src/operations/delete/mod.rs
  • grovedb/src/tests/delete_pending_operations_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

Delete-operation APIs now accept borrowed pending-operation iterators. Tree deletion scans operations at the target path once. Recursive up-tree deletion carries generated deletes separately. Tests compare borrowed inputs with slice and mutable-vector forms.

Changes

Delete operation generation

Layer / File(s) Summary
Borrowed operations in tree-delete checks
CHANGELOG.md, grovedb/src/operations/delete/mod.rs, grovedb/src/tests/delete_pending_operations_tests.rs, grovedb/src/tests/mod.rs
The internal delete method accepts borrowed pending operations and scans them at the target path to collect delete keys and detect writes. Tests cover iterator consumption, tree emptiness, errors for remaining children or pending writes, and result and cost comparisons.
Recursive up-tree delete generation
grovedb/src/operations/delete/delete_up_tree.rs, grovedb/src/tests/delete_pending_operations_tests.rs
The up-tree builder accepts a cloneable iterator of borrowed operations and accumulates generated deletes separately during recursion. Tests check delete order, results and costs, and appending generated deletes to a mutable vector.

Priority: ⬇️ Low

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

Change: Refactor

Merge Risk: ⚪ Minimal · up to 128fb

The reviewed delete-generation changes preserve the examined behavior, with no identified issue requiring a fix before merge.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 128fb

The reviewed delete paths retain their tree-emptiness checks and operation-application boundary, and no introduced security failure was established. Risk remains because the change also affects backward-reference handling across batch operations, whose end-to-end behavior was not fully covered.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The directly evidenced deletion scope is a caller-selected GroveDB path and potentially its ancestor chain. Backward-reference maintenance may affect referring entries elsewhere in the database; the available evidence does not establish a tenant or service boundary.

Trust Boundaries and Controls

  • observed — Callers supply the path, options, and pending operations. The internal generator rejects root-leaf deletion, optionally validates the subtree path, and applies its tree-emptiness and non-empty-tree options before producing an operation. Borrowing does not itself grant delete authority.
  • observed — DontCheck is a caller declaration, not an independent proof about descendants. The source documents refusal when a directly observed value participates in backward references, but describes recursive subtree removal as trusting the declaration about its contents.

Resilience and Maintainability Implications

  • inferred — The comparison of recursive builders supports preservation of child-to-parent ordering and ordinary error-path batch mutation. It does not establish the backward-reference control's behavior across every batch preparation, commit, and recovery path.

Hardening Proposals

  • proposed — Before exposing DontCheck to less-trusted callers, establish who may make that declaration and verify descendant checks, atomic failure, and recovery behavior for recursive removals containing backward-reference participants.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 81.25% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 4 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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: borrowing pending batch operations while building delete operations.
✨ 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.

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

thepastaclaw commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

🕓 Queued for automated review — 4th in line, estimated start in ~25 min (commit c70dadd)
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.

@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.16393% with 36 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.10%. Comparing base (7797e2d) to head (c70dadd).
⚠️ Report is 4 commits behind head on develop.

Files with missing lines Patch % Lines
.../delete/delete_operation_for_delete_internal/v0.rs 84.46% 16 Missing ⚠️
.../delete/delete_operation_for_delete_internal/v1.rs 89.62% 11 Missing ⚠️
...delete/delete_operation_for_delete_internal/mod.rs 86.76% 9 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff            @@
##           develop     #995    +/-   ##
=========================================
  Coverage    93.09%   93.10%            
=========================================
  Files          332      336     +4     
  Lines       105213   105421   +208     
=========================================
+ Hits         97950    98153   +203     
- Misses        7263     7268     +5     
Components Coverage Δ
grovedb-core 91.48% <90.16%> (+0.03%) ⬆️
merk 94.03% <ø> (-0.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.

…ending batch

Review follow-ups on the pending-batch borrow.

The delete builder counted a pending DeleteTree with
SubelementsDeletionBehavior::Skip as removing its child. The apply path
drops such a delete when the child is not empty, so a parent emptied only
by it was built as DeleteTree(DontCheckWithNoCleanup) and deleted without
cleanup over the child it kept, orphaning the child and its contents with
verify_grovedb reporting nothing. From GROVE_V4 (slot
delete.delete_operation_for_delete_internal = 1) the builder counts only
the deletes GroveOp::always_removes_its_key accepts, the rule the batch
pre-scan now shares through QualifiedGroveDbOp::key_always_removed_at.
The builder moves to delete_operation_for_delete_internal/{mod,v0,v1}.rs;
v0 keeps the old rule for GROVE_V1..V3.

The builders take `impl PendingOperations` and ask it for the operations
at one path, the deleted tree's own. Every IntoIterator<Item =
&QualifiedGroveDbOp> + Clone implements it by scanning, as before, and a
caller with a large batch can implement it over an index by path so a
question costs only the operations there. The up-tree chain passes each
level the key the level below deleted instead of re-reading all of its
deletes, collects its deletes once, and
add_delete_operations_for_delete_up_tree_while_empty appends them to the
caller's Vec only when every level is built. Deleted keys are collected
only for Merk trees.

Operations and costs are unchanged apart from the V4 rule: the tests pin
the costs develop charges, at GROVE_V3 and the latest version, and cover
an index by path, non-Merk trees, the Skip rule on both versions, a write
higher up stopping the climb, and the Vec left as it was on an error.

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.

Approved

@QuantumExplorer
QuantumExplorer merged commit dce8252 into develop Sep 26, 2026
12 of 13 checks passed
@QuantumExplorer
QuantumExplorer deleted the perf/delete-borrows-pending-batch branch September 26, 2026 00:35
QuantumExplorer added a commit to dashpay/platform that referenced this pull request Sep 26, 2026
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]>
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