Skip to content

fix(drive)!: write no entry in an expired time range bucket on insert (PV15) - #5877

Merged
QuantumExplorer merged 3 commits into
v5.1-devfrom
fix/time-range-insert-live-buckets
Nov 12, 2026
Merged

QuantumExplorer merged 3 commits into
v5.1-devfrom
fix/time-range-insert-live-buckets

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

Basic explanation

What this does: Some indexes sort documents into time windows ("buckets") and throw a whole window away once it is old enough. From protocol version 15, when a document is inserted late (after one of its windows has already expired), it is no longer written into the expired window. Only the windows that are still live get an entry.

Value: An expired window is now never written again after it has been thrown away, so its storage is always reclaimed at the end of the block instead of lingering until a later write cleans it up again. Inserts and updates now follow the same rule, which the code and the book already stated as an invariant.

Risks: Low. The only insert whose timestamp is older than the block is the winner of a contest, awarded with the $createdAt it was submitted with; every other created document has the block's time and is unaffected. The change is consensus-relevant, so it is a new generation selected by protocol version 15 only. Protocol version 14 replays exactly as before.

Issue being fixed or feature implemented

A document's entries under a timeRange index with a ttl live in the buckets its timestamp falls in. Every write first drops the buckets that have expired at the block time, then queues its own changes.

An update leaves a document out of a bucket that has expired. An insert did not filter, on the reasoning that a created document's timestamp is the block's. That holds for a create, but not for every insert: the winner of a contest is inserted when the contest ends, with the $createdAt it was submitted with. If the contest outlasts the index's ttl, the award writes the winner into a bucket that has expired, possibly one the same write has just dropped.

A bucket dropped and written again in the same block keeps its dropped storage: the end-of-block reclaim skips a path that is live again. The rows stay until a later write to the document type drops the bucket once more. Nothing fails and every node does the same thing, but the storage is not reclaimed when it should be.

What was done?

  • add_indices_for_top_index_level_for_contract_operations 3: generation 2 plus one step. Under a time range level with a ttl, the insert's bucket keys go through live_time_range_index_keys, which keeps the buckets that have not expired at the block time. An estimate keeps every bucket: the filter applies only when the insert is applied, so every estimate equals generation 2's. An update is estimated as an insert of the new version with the real document, and its execution can still remove the stored version's entries from an expired bucket the drain has not dropped yet, so the dry run stays the upper bound.
  • live_time_range_index_keys sits in time_range_ttl.rs next to live_time_range_entry_keys (the update's filter) and uses the same expiry_horizon_ms, so expiry is still defined once.
  • DRIVE_DOCUMENT_METHOD_VERSIONS_V5 (protocol version 15's table) selects generation 3. Protocol version 15 note 36 and Drive version 10's notes describe it.
  • document_create_cost accepts generation 2 or 3 of the walker: they differ only for a document whose buckets have expired, which a document created now has none of.
  • The module documentation of time_range_ttl.rs and the book chapter on time range indexes state the rule for inserts and from which protocol version it holds.

Example

A contested type with this index (ten minute buckets that expire ten minutes after they start):

{
  "name": "recentInParent",
  "properties": [{ "$createdAt": "asc" }, { "normalizedParentDomainName": "asc" }],
  "timeRange": { "on": "$createdAt", "range": 600, "step": 600, "ttl": 600 }
}

A contender submits a document at 10 s into a bucket. Another document is created in the same bucket a minute later. The contest ends days later and the contender wins.

Before (protocol version 14):

award block:   drop the expired bucket, then insert the winner's entry into it again
end of block:  reclaim report: skipped_live 4   (the bucket's dropped storage is kept)

After (protocol version 15):

award block:   drop the expired bucket, the winner gets no entry in it
end of block:  reclaim report: skipped_live 0, reclaimed_records > 0

The winner's document itself is stored and found through every other index either way.

In-place changes to shipped generations

None. Generation 2 of the walker is untouched and protocol version 14's table still selects it. The table amended is DRIVE_DOCUMENT_METHOD_VERSIONS_V5, which only the unreleased protocol version 15 selects. document_create_cost is a client-side estimate, not a block-execution path, and its accepted list only grows.

How Has This Been Tested?

  • v3/tests.rs in Drive (5 tests): no entry in an expired bucket and everything dropped is reclaimed; protocol version 14 still writes every bucket; with overlapping buckets the live one keeps its entry; a late-inserted document is deleted while an expired bucket still stands, without touching another document's entry; an update estimated while an expired bucket stands equals generation 2's estimate and covers the applied update, which removes the stored entry from that bucket. With the filter applied to estimates too, the estimate's processing fee drops from 17,394,110 to 7,362,600.
  • should_award_a_winner_whose_time_range_bucket_has_expired in drive-abci runs the real path: a contest on a type with the index above, ended through check_for_ended_vote_polls. With the table set back to generation 2 it fails with skipped_live 4 instead of 0.
  • Ran cargo test -p drive --lib -- time_range document::cost add_indices_for_top_index_level (74 passed), cargo test -p drive-abci --lib no_locking_contest_tests (16 passed), cargo test -p platform-version, and cargo clippy -p drive -p platform-version --all-features --all-targets -- -D warnings. The full suites were left to CI.

Breaking Changes

Consensus change at protocol version 15: the winner of a contest whose time range buckets have expired gets no entry in them, so the award block's state and fees differ from what protocol version 14 produces for the same input. Blocks committed under protocol version 14 replay unchanged.

Checklist:

  • I have performed a self-review of my own code
  • My Rust, FFI, WASM, Swift or Kotlin changes follow the coding conventions
  • 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
  • If I added or changed a system contract's document schemas, I checked the contract 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

PR Hygiene · 906662f

  • Bots — 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

  • Behavior Changes
    • From protocol version 15, document inserts no longer create entries in time-range index buckets that have expired at insertion time. Live buckets continue to receive entries.
    • Contest winners can still be recorded after their submitted time window expires, without writing to the expired bucket.
    • Protocol version 14 retains its previous behavior and writes entries to all buckets.
  • Bug Fixes
    • Expired buckets can be reclaimed during insertion without skipping records in live buckets.
  • Documentation
    • Clarified how expired time-range buckets are handled for document inserts and contest resolution.

… (PV15)

A document's entries under a time range index with a ttl live in the buckets its timestamp falls in. An update already left a document out of a bucket that had expired. An insert did not, because a created document's timestamp is the block's. The winner of a contest is inserted when the contest ends, with the $createdAt it was submitted with, so the award wrote it into a bucket that had expired, and that the same write may just have dropped: the dropped bucket's storage was then never reclaimed until a later write dropped it again.

add_indices_for_top_index_level_for_contract_operations 3, selected by protocol version 15 only, filters the insert's bucket keys by the block time as the update does. Protocol version 14 keeps generation 2. document_create_cost accepts either generation: a document created now has no expired bucket.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@github-actions github-actions Bot added this to the v5.1.0 milestone Nov 11, 2026
@coderabbitai

coderabbitai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Protocol version 15 adds a version 3 document-insert method that skips expired time-range index buckets. The change updates version selection, documents the behavior, and adds tests for inserts, deletes, and contest resolution.

Changes: TTL Time-Range Index Inserts

Layer / File(s) Summary
Versioned insert filtering
packages/rs-drive/src/drive/document/time_range_ttl.rs, packages/rs-drive/src/drive/document/insert/add_indices_for_top_index_level_for_contract_operations/..., packages/rs-drive/src/drive/document/cost/mod.rs, packages/rs-platform-version/src/version/drive_versions/drive_document_method_versions/v5.rs, packages/rs-platform-version/src/version/drive_versions/v10.rs, packages/rs-platform-version/src/version/v15.rs, book/src/drive/time-range-ttl.md
Version 3 filters time-range keys using block time and routes TTL-backed operations as ephemeral operations. Protocol-version selection and documentation describe this behavior.
Expired-bucket behavior tests
packages/rs-drive/src/drive/document/insert/add_indices_for_top_index_level_for_contract_operations/v3/tests.rs, packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/masternode_vote/no_locking_contest_tests.rs
Tests cover expired and live buckets, version 14 behavior, deletion and update estimates when an expired bucket remains, and contest resolution after bucket expiry.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Drive
  participant InsertV3 as Version 3 insert method
  participant KeyFilter as live_time_range_index_keys
  participant Operations as TTL operation collection
  Drive->>InsertV3: Dispatch version 3 with block_time_ms
  InsertV3->>KeyFilter: Filter generated time-range keys
  KeyFilter-->>InsertV3: Return keys for execution and estimation
  InsertV3->>Operations: Append TTL-backed operations as ephemeral
Loading

Suggested reviewers: thepastaclaw, shumkov

Merge Risk: Minimal · up to 98e0b

Protocol version 15 inserts skip expired time-range buckets, and version 14 behavior is unchanged. No concrete merge-blocking risk was found in the supplied changes. This is a consensus change that CI should confirm.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: inserts under protocol version 15 no longer write entries into expired time-range index buckets. The changeset implements this through a new v3 insert method, a PV15 m…
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.
Full details: Title check

Explanation

The title names the main change: inserts under protocol version 15 no longer write entries into expired time-range index buckets. The changeset implements this through a new v3 insert method, a PV15 method-table update, an insert-time expiry filter, tests, and documentation. The conventional-commit prefix and the (PV15) tag give the scope and version. The title is 76 characters, which is within a normal range.

Finishing Touches

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

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 01acbe3 and 98e0bf0.

Files selected for processing: 3

  • packages/rs-drive/src/drive/document/insert/add_indices_for_top_index_level_for_contract_operations/v3/mod.rs
  • packages/rs-drive/src/drive/document/insert/add_indices_for_top_index_level_for_contract_operations/v3/tests.rs
  • packages/rs-drive/src/drive/document/time_range_ttl.rs
Files skipped from review as they are similar to previous changes: 1

  • packages/rs-drive/src/drive/document/time_range_ttl.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.

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — 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 Nov 11, 2026
@thepastaclaw

thepastaclaw commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Final review complete — no blockers (commit 906662f) · triage: normal

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

📖 Book Preview built successfully.

Download the preview from the workflow artifacts.
To view locally: download the artifact, unzip, and open index.html.

Updated at 2026-11-12T07:39:36.953Z

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final validation — Phase 1 + Phase 2

The stateful insertion fix is correctly isolated to PV15, but its expiry filter also removes cost coverage from concrete-document update estimates, leaving one blocking fee-estimation regression. Static verification covered head 01acbe3; no local builds or tests were run. Current CI reports passing Rust, wasm32, Swift, Kotlin, and all four JS test jobs, with only review/hygiene checks pending.

🔴 1 blocking

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 6: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.1-sol (effort low) — This is a large, intricate change to consensus-relevant document indexing and storage behavior, including protocol-version dispatch and historical generation preservation in the insert path.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Single stage: Phase 1 and Phase 2 reviewed this head side by side, with no blocker gate between them (triage tier)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — platform-versioning (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `packages/rs-drive/src/drive/document/insert/add_indices_for_top_index_level_for_contract_operations/v3/mod.rs`:
- [BLOCKING] packages/rs-drive/src/drive/document/insert/add_indices_for_top_index_level_for_contract_operations/v3/mod.rs:299-307: Preserve expired bucket costs when estimating an update
  Estimation does not always use size-only keys. `DocumentInfo::get_raw_for_document_type` returns concrete `Key` values for owned and borrowed documents, and `update_document_for_contract_operations_v1_body` forwards those documents unchanged to `estimate_document_change_as_insert_operations_v1`. PV15's update generation 2 delegates to that same body, so this filter also removes expired buckets from real-document update estimates.

  When bounded drainage leaves an expired bucket and the document's entry standing, actual execution still removes that entry through `update_fanned_out_index_for_contract_operations_v1`. Those removals enter the billed ephemeral operations, unlike unbilled drainage. The estimate can therefore contain no operations for the TTL index while execution performs billed removals, losing the upper-bound coverage required by fee validation. The `KeySize` bypass is not an estimation-mode guard. Apply this filter only when `estimated_costs_only_with_layer_info` is `None`, and add a paired estimate-versus-apply regression for a real-document update whose expired entries survive the drainage budget.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them.
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 Nov 11, 2026
An update is estimated as an insert of the new version with the real
document, so the insert walker's keys are concrete on that path, not
sizes. Generation 3 filtered them by the block time there too, and an
update's estimate lost the entries of an expired bucket while its
execution still removes the stored version's entries from that bucket
when the drain has not dropped it yet. The filter now applies only when
the insert is applied, so every estimate of generation 3 equals
generation 2's, as the removal walkers' estimates keep every key.

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

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

The base took protocol version 15 note 35 for composite document history,
so the time range insert note is 36. Its add_indices_for_top_index_level
line joins the base's insert table, next to add_document_to_primary_storage 1.

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

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — 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 waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 12, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review — Final validation — Phase 1 + Phase 2

Verified the complete diff at 906662f: expired-bucket filtering is confined to applied inserts under PV15, estimates retain generation 2's bucket operations, and historical implementations remain unchanged. No actionable in-scope findings remain. This was a static review; current CI reports successful Rust workspace and wasm32 tests with no failed code checks, while PastaClaw review and PR Hygiene remain pending.

🔴 0 blocking | 🟡 0 suggestion(s) | 💬 0 nitpick(s)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 6: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); reviewer 8: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 9: gpt-6.1-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 10: gpt-6.1-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 11: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); reviewer 12: gpt-6.1-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.1-sol (effort low) — The consensus-relevant change in add_indices_for_top_index_level_for_contract_operations_v3 is a contained bucket-filtering addition to the existing walker, with most added lines copying the prior generation or providing tests, rather than a large or intricate behavioral change.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • Fresh final gate: an independent Phase-2 review ran after iterative findings were reconciled
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.1-sol — security-auditor (completed, effort high); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

No unresolved findings remain from the prior review on this head.

@github-actions

Copy link
Copy Markdown
Contributor

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 Nov 12, 2026
@QuantumExplorer
QuantumExplorer merged commit 1f36c10 into v5.1-dev Nov 12, 2026
33 of 34 checks passed
@QuantumExplorer
QuantumExplorer deleted the fix/time-range-insert-live-buckets branch November 12, 2026 09:39
QuantumExplorer added a commit that referenced this pull request Nov 12, 2026
…roposal-contract-1db678

Brings in v5.1-dev at 1f36c10: an insert writes no entry in an expired
time range bucket (#5877), which took protocol version 15 note 36.

The one conflict is the note list: the base's note stays 36 and this branch's
"A contest among documents" becomes 37. No root pin, fee pin or stored
contract fixture line changes.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
QuantumExplorer added a commit that referenced this pull request Nov 12, 2026
…ecision-proposal-description-reference

Brings in v5.1-dev at 1f36c10: an insert writes no entry in an expired
time range bucket (#5877), which took protocol version 15 note 36, so the
multiple choice proposals branch's "A contest among documents" is 37. The
merge is clean and no root pin, fee pin or stored contract fixture line
changes.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
QuantumExplorer added a commit that referenced this pull request Nov 12, 2026
The protocol version 15 notes of #4652, #5877 and #5848 took 35 to 37;
the pattern bound's note is now 38.

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