mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 11:50:39 +00:00
WIP: coins: prevent DB resize from invalidating cursors #35744
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35744
Loading…
Reference in a new issue
No description provided.
Delete branch "l0rinc/coins-cursor-resize-lifetime"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem:
gettxoutsetinfo,scantxoutset, anddumptxoutsetretain LevelDB iterators after releasingcs_main.While those iterators are live, AssumeUTXO cache rebalancing can call
ResizeCache(), replacem_db, and cause LevelDB to abort.The issue was reported during review of #35465.
Fix: Each cursor holds a shared lock on
m_db_mutexfor its lifetime.Compaction takes the same shared lock, allowing it to run alongside cursors.
ResizeCache()takes the lock exclusively and waits for both before replacingm_db.Checked shared-lock wrappers and non-LIFO lock tracking preserve Core's locking diagnostics, including for the existing signature-cache and parallel cuckoo-cache users migrated in this series.
Risk:
ResizeCache()holdscs_mainwhile it waits, so a long-running UTXO scan can stall validation, message processing, and RPCs that need that lock during cache rebalancing.Current callers destroy cursors on the thread that created them. A cursor holder must not acquire
cs_mainunless it already holds it.This is a concrete example of the lifetime interactions created by rebalancing the snapshot and background chainstates, as discussed in #35054.
The fix protects the current lifecycle and can be reviewed independently of the discussion about making snapshot trust explicit and simplifying background validation in #32377.
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
-Wunusedby fanquake)If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.
Thanks for tackling this.
I'm not sure about this approach with an atomic counter though. Would it make sense to instead have a shared mutex that would allow multiple consumers to take a read lock along with the cursor, which are then released in the destructor? Then only
ResizeCachetakes an exclusive lock? Just brainstorming here.Thanks, I already investigated this, but the warnings and LLM reviews scared me off because it seems to force cursors to be destroyed on the thread that created them:
unlock_shared()requires the calling thread to hold the shared lock. Current callers seem to satisfy that, though, so maybe it is fine.I also found that
std::shared_mutexmay lose some of Core's lock checking: this Godbolt recreates it, which still warns inside astd::unique_lock<std::shared_mutex>, and my localDEBUG_LOCKORDERprobe did not see the lock.What do you think?
Iterators alone are not thread-safe though, so we should not be passing them to other threads. I think in this case it should be fine.
Do we need this here? We do use a
shared_mutexalready inSignatureCachewithout any of the lock checking machinery.Thanks, took your suggestions, @andrewtoth.
I reworked the fix around it and split the series into a characterization test, a commit that makes
ResizeCache()wait for live cursors, and a follow-up that lets cursors remain live during compaction.Let me know if you think it's better this way.
Should we add
AssertLockHeld(::cs_main);here?Thanks, I do like this better.
What do you think of adding shared locking to our lock checking machinery?
Since we now take a shared lock while inside a separate lock which is released while the shared lock continues to be held, it would require us to make a modification to make sure we're popping the correct lock being released. This would let us catch issues with DEBUG_LOCKORDER.
Something like this?
Thanks, I implemented both suggestions and pushed the reworked series.
The rework is quite heavy and needs a thorough review, but I think I managed to split it into reviewable logical chunks: common lock acquisition, checked shared-lock support, non-LIFO lock tracking, migration of
SignatureCacheand the parallel cuckoo-cache test, then characterization and fixes for cursor lifetime during resize, destruction, and compaction.ResizeCache()now assertscs_main, cursors and compaction holdm_db_mutexshared, while resize takes it exclusively.Edit: looks like a member mutex cannot guard its own destruction - TSAN should be fixed.
🚧 At least one of the CI tasks failed.
Task
TSan: https://github.com/bitcoin/bitcoin/actions/runs/30319724201/job/90152871691LLM reason (✨ experimental): CI failed because ThreadSanitizer reported a data race (in
pthread_cond_destroy) causing thecoins_testsCTest to fail.Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
Concept ACK
Base:
7988380da987c0b860885853ace8149b84ac2ee8Head:
99b9c21e404032fc4df3f418fd8aa21cde27fb3dDesign and approach
Should resize hold cs_main while waiting indefinitely for a cursor? (src/txdb.cpp:79, head)
Resize waits for an exclusive lock under cs_main, while a cursor holds its shared lock through its caller's work. Besides long UTXO scans, dumptxoutset can write to a FIFO while the cursor remains alive. If a connected reader stops draining, the write can block indefinitely, preventing periodic interruption checks and keeping cs_main unavailable. Should cache rebalancing make cs_main availability depend on such output? If not, a deferrable resize or different FIFO strategy could preserve DB lifetime safety. Spooling a snapshot could require space for the full output and would change the streaming tradeoff.
💡 Suggestion
Release the scan cursor before building scantxoutset results (src/txdb.cpp:247, head)
The cursor holds its shared lock for its lifetime. In scantxoutset, FindScriptPubKey is the last cursor use, but the cursor remains alive while matching coins are formatted into the response. Reset it after the scan to preserve the results while allowing a waiting resize to proceed before JSON construction.
Synchronize the resize test on an actual lock wait (src/test/coins_tests.cpp:1080, head)
The latch is released immediately before db.ResizeCache(), so wait_for(100ms) may time out because the async thread was descheduled before calling ResizeCache(). The test can therefore pass without proving the resize waited for the cursor. Add a synchronization point showing that resize reached the m_db_mutex acquisition, such as a narrow test hook or observable contention signal, before asserting that it remains blocked.
Account for destructor access to the cs_main-guarded future (src/txdb.h:45, head)
GUARDED_BY(cs_main) requires the analyzer to see the guard at each access, but CCoinsViewDB::~CCoinsViewDB reads and waits on m_compaction without acquiring cs_main. Lifecycle exclusivity may make this safe at runtime, but the annotation does not express that. Use a narrowly documented thread-safety-analysis exemption for the destructor or a synchronization model that also covers destruction, so the new guard does not leave analyzer diagnostics at these accesses.
Review coverage was incomplete. The adversarial review had incomplete evidence. The adversarial_glm review had incomplete evidence.
Full review report
Drafting after https://github.com/bitcoin/bitcoin/issues/32377
I closed it because I think we should remove the multiple-chainstate design behind these problems instead of adding workaround after workaround, see https://github.com/bitcoin/bitcoin/issues/36499