Skip to content

fix(drive): make the data contract cache transaction-aware - #4755

Merged
QuantumExplorer merged 3 commits into
v4.2-devfrom
claude/data-contract-cache-race-ab3245
Sep 15, 2026
Merged

QuantumExplorer merged 3 commits into
v4.2-devfrom
claude/data-contract-cache-race-ab3245

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

Issue being fixed or feature implemented

Security review P1: block execution could validate and serialize against a stale committed data contract.

An ordinary contract update writes the new definition into the block transaction, and the ApplyContract finalization task then only evicted both caches. A concurrent committed-state query (what a public getDocuments request does on a validator; query workers share the Platform with consensus execution) could read committed state, still the pre-update contract, and put it back into the global cache. The block's next transactional read of that contract missed the block cache and fell back to the global cache, so a validator hit by such a query validated the rest of the block against the old contract while a cold validator read the new one from its transaction. With two sequential updates of one contract in a block, the raced validator rejected the second as a version mismatch (paid consensus error) and the cold one applied it; both outcomes are proposal-acceptable, so they produced different app hashes.

Two things are wider than the report stated:

  • The stale global entry outlived the block. Nothing re-fetched the contract at commit, so the node stayed divergent until that contract's next update.
  • Two pre-existing hazards sat in the same code: check_tx's fee re-insert wrote into the block cache from a non-consensus thread, and the block cache was promoted to the global cache inside finalize_block_proposal, before the GroveDB commit.

What was done?

DataContractCache (packages/rs-drive/src/cache/data_contract.rs) is now transaction-aware:

  • Modified-in-block set. Every rewrite of a contract through the block transaction marks it. A transactional read of a marked contract never falls back to the global cache; on a block-cache miss it goes to state through the transaction. This holds across block-cache eviction and rollback, and clear() keeps the marks so the mid-block schema-strip migration stays covered.
  • Committed generation. Committed-state readers snapshot a counter before reading state, and insert_committed drops the copy, inside moka's per-key compute closure, if a block was committed in between. This closes the descheduled-query straggler independently of contract version bumps, so it also covers same-version rewrites. insert is split into insert_block and insert_committed.
  • Refresh instead of evict. The finalization task is renamed RefreshDataContractCache and takes the batch's transaction; it calls refresh_data_contract_cache_from_state, which marks the contract and seeds the block cache with what the transaction holds. apply_drive_operations_v0 passes the caller's transaction (None when it committed its own) and runs no tasks for estimation-only batches. Without a transaction the refresh only evicts, as before.
  • Rollback. The proposer-side savepoint rollback in process_raw_state_transitions_v0 drops the rewritten contracts from the block cache, so the next read goes to the rolled-back transaction rather than to a phantom definition.
  • Promotion after commit. merge_and_clear_block_cache moves out of update_drive_cache_v0 into the finalize_block handler, after commit_transaction. It bumps the generation, removes global entries for rewritten contracts that are no longer in the block cache, then promotes.
  • check_tx never writes the cache. The cached-hit fee re-insert is gated on the same add_to_cache_if_pulled flag as the pull-insert, which ValidationMode::can_alter_cache() already sets to false for CheckTx and RecheckTx.
  • Both update_contract generations and the schema-strip migration mark the contracts they rewrite. The book chapter book/src/drive/finalize-tasks.md is updated.

Fees are unaffected: a cache hit seeded by the refresh bills the same OperationCost as the cold fetch it replaces (fetch_contract_v0 computes it with grovedb value caching disabled), which the existing should_always_have_then_same_cost test pins.

How Has This Been Tested?

New tests:

  • Cache unit tests: transactional reads do not fall back to the global cache for a rewritten contract; rollback drops rewritten entries and keeps the marks; merge promotes over the committed copy, removes the committed copy of a rewritten contract missing from the block cache, clears the marks, and advances the generation; a committed insert with a pre-promotion snapshot is dropped, including a same-version straggler that the version guard alone would let through.
  • Drive: the report's exact path through apply_drive_operations with ApplyContract, a committed query refilling the global cache, and the next transactional read resolving to the update with and without the seeded copy resident; estimation-only batches record nothing; refresh tests for marking, block-cache seeding, and the no-transaction eviction.
  • drive-abci: contract_cache_coherence: a raced validator (query between two sequential updates of one contract) and a quiet validator both accept the second update and compute the same root hash; a proposer-side rolled-back update leaves no phantom definition and the same update then applies cleanly on the rolled-back state. finalize_block handler: the block cache is promoted after a real commit and the marks are reset. update_drive_cache leaves the block cache alone.

Existing suites run green: run_block_proposal cache-ordering pins, check_tx, finalize_block handler (including the tolerated mainnet busy-commit branch), the shield savepoint test, perform_events_on_first_block_of_protocol_change, token config update, all data_contract_update tests, the drive util::batch tests, and the strategy tests run_chain_insert_one_new_identity_and_a_contract_with_updates, run_chain_contract_update_adds_required_field_mid_run, and run_chain_insert_one_new_identity_and_a_contract_with_bad_update. cargo clippy --tests is clean on drive and drive-abci.

Breaking Changes

None. The change alters node-local caching only; the state a block evaluates to is what a cold node already computed.

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

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved data contract cache consistency during updates, rollbacks, migrations, and concurrent reads.
    • Prevented uncommitted contract definitions from being exposed to committed-state readers.
    • Ensured cache refresh tasks run only for applied operations, not estimation-only requests.
    • Improved handling of stale cache entries and committed-state reads after block finalization.
  • Tests

    • Added coverage for transactional isolation, rollback behavior, concurrent reads, cache promotion, and generation changes.

An ordinary contract update wrote the new definition into the block
transaction and then only evicted both caches. A concurrent committed-state
query (what getDocuments does on a validator) could put the committed,
pre-update definition back into the global cache, and the block's next
transactional read of that contract fell back to it. A validator hit by such
a query validated later transitions against the old contract while a cold
validator read the new one from its transaction, so the two produced
different app hashes. The stale global entry also outlived the block, since
nothing re-fetched the contract at commit.

The cache now records which contracts the block transaction rewrote, and a
transactional read of one of them never falls back to the global cache. The
ApplyContract finalization task re-seeds the block cache from transactional
state instead of evicting, taking the batch's transaction to do so, and the
proposer-side savepoint rollback drops the rewritten contracts from the block
cache. Committed-state inserts carry a generation snapshot taken before the
read and are dropped if a block committed in between, which closes the
descheduled-query straggler independently of version bumps. Promotion of the
block cache moves out of update_drive_cache into the finalize_block handler,
after the GroveDB commit, and check_tx no longer writes to any cache through
the fee re-insert path.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@github-actions github-actions Bot added this to the v4.2.0 milestone Sep 14, 2026
@github-actions

github-actions Bot commented Sep 14, 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-09-15T00:00:25.517Z

@coderabbitai

coderabbitai Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: b7017fca-349e-48ba-a664-07bd70b7df2b

📥 Commits

Reviewing files that changed from the base of the PR and between 585db3e and 45d6b72.

📒 Files selected for processing (17)
  • book/src/drive/finalize-tasks.md
  • packages/rs-drive-abci/src/abci/handler/finalize_block.rs
  • packages/rs-drive-abci/src/execution/platform_events/block_end/update_drive_cache/v0/mod.rs
  • packages/rs-drive-abci/src/execution/platform_events/protocol_upgrade/perform_events_on_first_block_of_protocol_change/v0/mod.rs
  • packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/process_raw_state_transitions/v0/mod.rs
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/mod.rs
  • packages/rs-drive/src/cache/data_contract.rs
  • packages/rs-drive/src/cache/mod.rs
  • packages/rs-drive/src/drive/contract/get_fetch/get_contract_with_fetch_info/mod.rs
  • packages/rs-drive/src/drive/contract/get_fetch/get_contract_with_fetch_info/v0/mod.rs
  • packages/rs-drive/src/drive/contract/migration/strip_unknown_document_schema_properties.rs
  • packages/rs-drive/src/drive/contract/refresh_cache/mod.rs
  • packages/rs-drive/src/drive/contract/update/update_contract/v0/mod.rs
  • packages/rs-drive/src/drive/contract/update/update_contract/v1/mod.rs
  • packages/rs-drive/src/util/batch/drive_op_batch/contract.rs
  • packages/rs-drive/src/util/batch/drive_op_batch/drive_methods/apply_drive_operations/v0/mod.rs
  • packages/rs-drive/src/util/batch/drive_op_batch/finalize_task.rs

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The PR separates block and committed data-contract cache state. It refreshes rewritten contracts through transactions, defers promotion until after commit, tracks committed generations, and adds rollback, estimation, concurrency, and validator-consistency coverage.

Changes

Data Contract Cache Coherence

Layer / File(s) Summary
Cache state and generation handling
packages/rs-drive/src/cache/*
DataContractCache tracks modified contracts and committed generations. Separate APIs manage block entries, committed entries, rewrites, rollback cleanup, and promotion.
Transactional refresh and generation-aware reads
packages/rs-drive/src/drive/contract/get_fetch/*, packages/rs-drive/src/drive/contract/refresh_cache/*, packages/rs-drive/src/drive/contract/update/*
Transactional reads use block-cache entries for modified contracts. Committed reads validate generation snapshots. Refresh and update paths use the new cache APIs.
Refresh finalization task wiring
packages/rs-drive/src/util/batch/drive_op_batch/*, book/src/drive/finalize-tasks.md
The finalization task now refreshes contracts through Drive::refresh_data_contract_cache_from_state. Tasks receive the caller transaction and run only after apply, not during estimation.
Post-commit promotion and rollback cleanup
packages/rs-drive-abci/src/abci/handler/finalize_block.rs, packages/rs-drive-abci/src/execution/platform_events/*, packages/rs-drive/src/drive/contract/migration/*
finalize_block promotes the block cache after commit. Earlier block-end processing leaves data-contract entries unchanged. Rollback and migration paths update modified-contract markers.
Cache-coherence integration validation
packages/rs-drive-abci/src/execution/validation/*, packages/rs-drive/src/drive/contract/get_fetch/get_contract_with_fetch_info/*
Tests cover concurrent committed reads, validator root consistency, rollback recovery, and the absence of cache rewrites during estimation.

Priority: ➖ Normal

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

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant DriveOperation
  participant DataContractCache
  participant finalize_block
  participant CommittedReader
  DriveOperation->>DataContractCache: refresh rewritten contract through caller transaction
  CommittedReader->>DataContractCache: read committed state with generation snapshot
  finalize_block->>DataContractCache: promote block cache after commit
  DataContractCache-->>CommittedReader: serve promoted contract at current generation
Loading

Merge Risk: ⚪ Minimal · up to 45d6b

The transaction-aware cache paths include rollback, post-commit promotion, generation checks, and focused integration coverage, with no actionable merge-blocking issue identified.

🚥 Pre-merge checks | ✅ 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: making the data contract cache transaction-aware to prevent stale cache reads during transaction processing.
Docstring Coverage ✅ Passed Docstring coverage is 92.11% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 76 functions across 16 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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/data-contract-cache-race-ab3245

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 14, 2026 •

Copy link
Copy Markdown
Collaborator

🕓 Queued for automated review — 8th in line, estimated start in ~20 min (commit 45d6b72)
Estimated review time once started: ~5 min (two-phase automated review; median of recent runs).

  • Request priority review — tick this box and the review moves to the front of the queue.

@codecov

codecov Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.67069% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.52%. Comparing base (4bb2b3e) to head (45d6b72).
⚠️ Report is 3 commits behind head on v4.2-dev.

Files with missing lines Patch % Lines
...tion/state_transitions/data_contract_update/mod.rs 99.02% 2 Missing ⚠️
...rc/drive/contract/update/update_contract/v0/mod.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##           v4.2-dev    #4755      +/-   ##
============================================
+ Coverage     87.32%   87.52%   +0.19%     
============================================
  Files          2827     2827              
  Lines        371564   372480     +916     
============================================
+ Hits         324476   326007    +1531     
+ Misses        47088    46473     -615     
Components Coverage Δ
dpp 88.97% <ø> (+0.08%) ⬆️
drive 86.58% <99.84%> (+0.09%) ⬆️
drive-abci 89.04% <99.27%> (+0.49%) ⬆️
sdk ∅ <ø> (∅)
dapi-client ∅ <ø> (∅)
platform-version ∅ <ø> (∅)
platform-value 92.92% <ø> (ø)
platform-wallet ∅ <ø> (∅)
drive-proof-verifier 40.73% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

QuantumExplorer and others added 2 commits September 15, 2026 06:26
…acts as modified in the block

The strip migration rewrites contracts in place through the block transaction
and then clears both caches. The mark is what keeps a transactional read of
such a contract from falling back to a copy a concurrent committed-state
query puts into the global cache before the block commits; assert it in the
migration test that exercises the rewrite branch.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ed inserts

moka's plain insert and remove do not take the per-key lock that the entry
API's compute path holds, so a committed-state reader whose insert had
already passed its generation check could pause, let the block's promotion
write the rewritten contract with a plain insert, and then land the
pre-block copy on top of it. The next block would read that copy. Every
global-cache write the promotion makes now goes through the same per-key
compute lock, so an approved insert finishes before the promotion touches
the key and is overwritten, and one that reaches the lock afterwards sees
the new generation and inserts nothing. Two tests pause a committed insert
inside its compute closure while the promotion runs; both fail against the
plain writes.

A contract rewrite made outside any block transaction is a commit too:
replace_committed advances the generation and applies the eviction or the
replacement through the same lock, so a reader that read the pre-write
contract cannot put it back. The transactionless refresh and update paths
use it.

Co-Authored-By: Claude Fable 5.1 <[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 59afddc into v4.2-dev Sep 15, 2026
19 of 20 checks passed
@QuantumExplorer
QuantumExplorer deleted the claude/data-contract-cache-race-ab3245 branch September 15, 2026 00:07
QuantumExplorer added a commit that referenced this pull request Sep 15, 2026
v4.3-dev was fast-forwarded to v4.2-dev's tip (cb6514e). The only conflict
was in the data contract update test module, where this branch adds the delta
processing test and the base adds the contract cache coherence tests (#4755);
both are kept.

Co-Authored-By: Claude Fable 5.1 <[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