Repository navigation
fix(drive): make the data contract cache transaction-aware - #4755
Conversation
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]>
|
📖 Book Preview built successfully. Download the preview from the workflow artifacts. Updated at 2026-09-15T00:00:25.517Z |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (17)
Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe 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. ChangesData Contract Cache Coherence
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
Merge Risk: ⚪ Minimal · up to 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)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
|
🕓 Queued for automated review — 8th in line, estimated start in ~20 min (commit 45d6b72)
|
Codecov Report❌ Patch coverage is
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
🚀 New features to boost your workflow:
|
…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]>
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]>
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
ApplyContractfinalization task then only evicted both caches. A concurrent committed-state query (what a publicgetDocumentsrequest does on a validator; query workers share thePlatformwith 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:
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 insidefinalize_block_proposal, before the GroveDB commit.What was done?
DataContractCache(packages/rs-drive/src/cache/data_contract.rs) is now transaction-aware:clear()keeps the marks so the mid-block schema-strip migration stays covered.insert_committeddrops 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.insertis split intoinsert_blockandinsert_committed.RefreshDataContractCacheand takes the batch's transaction; it callsrefresh_data_contract_cache_from_state, which marks the contract and seeds the block cache with what the transaction holds.apply_drive_operations_v0passes the caller's transaction (Nonewhen it committed its own) and runs no tasks for estimation-only batches. Without a transaction the refresh only evicts, as before.process_raw_state_transitions_v0drops the rewritten contracts from the block cache, so the next read goes to the rolled-back transaction rather than to a phantom definition.merge_and_clear_block_cachemoves out ofupdate_drive_cache_v0into thefinalize_blockhandler, aftercommit_transaction. It bumps the generation, removes global entries for rewritten contracts that are no longer in the block cache, then promotes.add_to_cache_if_pulledflag as the pull-insert, whichValidationMode::can_alter_cache()already sets tofalseforCheckTxandRecheckTx.update_contractgenerations and the schema-strip migration mark the contracts they rewrite. The book chapterbook/src/drive/finalize-tasks.mdis updated.Fees are unaffected: a cache hit seeded by the refresh bills the same
OperationCostas the cold fetch it replaces (fetch_contract_v0computes it with grovedb value caching disabled), which the existingshould_always_have_then_same_costtest pins.How Has This Been Tested?
New tests:
apply_drive_operationswithApplyContract, 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.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_blockhandler: the block cache is promoted after a real commit and the marks are reset.update_drive_cacheleaves the block cache alone.Existing suites run green:
run_block_proposalcache-ordering pins,check_tx,finalize_blockhandler (including the tolerated mainnet busy-commit branch), the shield savepoint test,perform_events_on_first_block_of_protocol_change, token config update, alldata_contract_updatetests, the driveutil::batchtests, and the strategy testsrun_chain_insert_one_new_identity_and_a_contract_with_updates,run_chain_contract_update_adds_required_field_mid_run, andrun_chain_insert_one_new_identity_and_a_contract_with_bad_update.cargo clippy --testsis clean ondriveanddrive-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:
For repository code-owners and collaborators only
🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Tests