WIP: coins: prevent DB resize from invalidating cursors #35744

Closed
l0rinc wants to merge 7 commits from l0rinc/coins-cursor-resize-lifetime into master AGit
l0rinc commented 2026-07-17 22:25:59 +00:00 (Migrated from github.com)

Problem: gettxoutsetinfo, scantxoutset, and dumptxoutset retain LevelDB iterators after releasing cs_main.
While those iterators are live, AssumeUTXO cache rebalancing can call ResizeCache(), replace m_db, and cause LevelDB to abort.
The issue was reported during review of #35465.

Fix: Each cursor holds a shared lock on m_db_mutex for its lifetime.
Compaction takes the same shared lock, allowing it to run alongside cursors.
ResizeCache() takes the lock exclusively and waits for both before replacing m_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() holds cs_main while 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_main unless 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.

**Problem:** `gettxoutsetinfo`, `scantxoutset`, and `dumptxoutset` retain LevelDB iterators after releasing `cs_main`. While those iterators are live, AssumeUTXO cache rebalancing can call `ResizeCache()`, replace `m_db`, and cause LevelDB to abort. The issue was [reported during review of #35465](https://github.com/bitcoin/bitcoin/pull/35465#discussion_r3428902672). **Fix:** Each cursor holds a shared lock on `m_db_mutex` for its lifetime. Compaction takes the same shared lock, allowing it to run alongside cursors. `ResizeCache()` takes the lock exclusively and waits for both before replacing `m_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()` holds `cs_main` while 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_main` unless 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](https://github.com/bitcoin/bitcoin/pull/35054#issuecomment-4488453829). 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](https://github.com/bitcoin/bitcoin/issues/32377).
DrahtBot commented 2026-07-17 22:26:06 +00:00 (Migrated from github.com)

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.

Type Reviewers
Concept ACK sedited

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:

  • #36395 (script: clarify implicit signature-cache input requirements by l0rinc)
  • #36167 ([RFC] Enable -Wunused by fanquake)
  • #35911 (Warn on and add missing noreturn by fanquake)
  • #35713 (Remove boost as a unit test runner by rustaceanrob)
  • #29491 ([EXPERIMENTAL] Schnorr batch verification for blocks by fjahr)

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/35744 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35744.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35744#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [sedited](https://github.com/bitcoin/bitcoin/pull/35744#issuecomment-5588425476) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36395](https://github.com/bitcoin/bitcoin/pull/36395) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36395.svg"></sub> (script: clarify implicit signature-cache input requirements by l0rinc) * [#36167](https://github.com/bitcoin/bitcoin/pull/36167) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36167.svg"></sub> ([RFC] Enable `-Wunused` by fanquake) * [#35911](https://github.com/bitcoin/bitcoin/pull/35911) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35911.svg"></sub> (Warn on and add missing [[noreturn]] by fanquake) * [#35713](https://github.com/bitcoin/bitcoin/pull/35713) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35713.svg"></sub> (Remove boost as a unit test runner by rustaceanrob) * [#29491](https://github.com/bitcoin/bitcoin/pull/29491) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/29491.svg"></sub> ([EXPERIMENTAL] Schnorr batch verification for blocks by fjahr) 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. <!--5faf32d7da4f0f540f40219e4f7537a3-->
andrewtoth (Migrated from github.com) reviewed 2026-07-18 02:31:03 +00:00
andrewtoth (Migrated from github.com) commented 2026-07-18 02:31:03 +00:00

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 ResizeCache takes an exclusive lock? Just brainstorming here.

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 `ResizeCache` takes an exclusive lock? Just brainstorming here.
l0rinc (Migrated from github.com) reviewed 2026-07-18 04:45:24 +00:00
l0rinc (Migrated from github.com) commented 2026-07-18 04:45:24 +00:00

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_mutex may lose some of Core's lock checking: this Godbolt recreates it, which still warns inside a std::unique_lock<std::shared_mutex>, and my local DEBUG_LOCKORDER probe did not see the lock.
What do you think?

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](https://eel.is/c++draft/thread.sharedmutex.requirements#12). Current callers seem to satisfy that, though, so maybe it is fine. I also found that `std::shared_mutex` may lose some of Core's lock checking: [this Godbolt recreates it](https://godbolt.org/z/3q94MYEsb), which still warns inside a `std::unique_lock<std::shared_mutex>`, and my local `DEBUG_LOCKORDER` probe did not see the lock. What do you think?
andrewtoth (Migrated from github.com) reviewed 2026-07-18 21:41:04 +00:00
andrewtoth (Migrated from github.com) commented 2026-07-18 21:41:04 +00:00

it seems to force cursors to be destroyed on the thread that created them

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.

std::shared_mutex may lose some of Core's lock checking

Do we need this here? We do use a shared_mutex already in SignatureCache without any of the lock checking machinery.

> it seems to force cursors to be destroyed on the thread that created them [Iterators alone are not thread-safe](https://github.com/bitcoin-core/leveldb-subtree/blob/bitcoin-fork/doc/index.md#concurrency) though, so we should not be passing them to other threads. I think in this case it should be fine. > `std::shared_mutex` may lose some of Core's lock checking Do we need this here? We do use a `shared_mutex` already in `SignatureCache` without any of the lock checking machinery.
l0rinc commented 2026-07-25 05:28:02 +00:00 (Migrated from github.com)

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.

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.
andrewtoth (Migrated from github.com) reviewed 2026-07-26 18:02:18 +00:00
andrewtoth (Migrated from github.com) commented 2026-07-26 18:02:18 +00:00

Should we add AssertLockHeld(::cs_main); here?

Should we add `AssertLockHeld(::cs_main);` here?
andrewtoth commented 2026-07-26 18:30:29 +00:00 (Migrated from github.com)

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?
diff --git a/src/sync.cpp b/src/sync.cpp
index 6d740866d4..838f420c96 100644
--- a/src/sync.cpp
+++ b/src/sync.cpp
@@ -14,6 +14,7 @@
 #include <map>
 #include <mutex>
 #include <set>
+#include <shared_mutex>
 #include <system_error>
 #include <thread>
 #include <type_traits>
@@ -31,6 +32,7 @@ void ContendedLock(std::string_view name, std::string_view file, int nLine, Lock
 }
 template void ContendedLock(std::string_view name, std::string_view file, int nLine, std::unique_lock<std::mutex>& lock);
 template void ContendedLock(std::string_view name, std::string_view file, int nLine, std::unique_lock<std::recursive_mutex>& lock);
+template void ContendedLock(std::string_view name, std::string_view file, int nLine, std::unique_lock<std::shared_mutex>& lock);
 
 #endif
 
@@ -75,7 +77,7 @@ private:
     bool fTry;
     std::string mutexName;
     std::string sourceFile;
-    const std::string m_thread_name;
+    std::string m_thread_name;
     int sourceLine;
 };
 
@@ -204,13 +206,20 @@ static void push_lock(MutexType* c, const CLockLocation& locklocation)
     }
 }
 
-static void pop_lock()
+static void pop_lock(void* cs)
 {
     LockData& lockdata = GetLockData();
     STDLOCK(lockdata.dd_mutex);
 
     LockStack& lock_stack = lockdata.m_lock_stacks[std::this_thread::get_id()];
-    lock_stack.pop_back();
+    // Erase the most recent entry for this mutex rather than popping the back:
+    // locks that outlive their creating scope may be released out of LIFO order.
+    for (auto it = lock_stack.rbegin(); it != lock_stack.rend(); ++it) {
+        if (it->first == cs) {
+            lock_stack.erase(std::next(it).base());
+            break;
+        }
+    }
     if (lock_stack.empty()) {
         lockdata.m_lock_stacks.erase(std::this_thread::get_id());
     }
@@ -223,6 +232,7 @@ void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexTyp
 }
 template void EnterCritical(const char*, const char*, int, std::mutex*, bool);
 template void EnterCritical(const char*, const char*, int, std::recursive_mutex*, bool);
+template void EnterCritical(const char*, const char*, int, std::shared_mutex*, bool);
 
 void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line)
 {
@@ -250,9 +260,9 @@ void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, c
     throw std::logic_error(strprintf("%s was not most recent critical section locked", guardname));
 }
 
-void LeaveCritical()
+void LeaveCritical(void* cs)
 {
-    pop_lock();
+    pop_lock(cs);
 }
 
 static std::string LocksHeld()
diff --git a/src/sync.h b/src/sync.h
index 28bc78e911..fcb870ecaf 100644
--- a/src/sync.h
+++ b/src/sync.h
@@ -14,6 +14,7 @@
 #include <cassert>
 #include <condition_variable>
 #include <mutex>
+#include <shared_mutex>
 #include <string>
 #include <thread>
 
@@ -47,7 +48,7 @@ TRY_LOCK(mutex, name);
 #ifdef DEBUG_LOCKORDER
 template <typename MutexType>
 void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false);
-void LeaveCritical();
+void LeaveCritical(void* cs);
 void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line);
 template <typename MutexType>
 void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs);
@@ -65,7 +66,7 @@ extern bool g_debug_lockorder_abort;
 #else
 template <typename MutexType>
 inline void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false) {}
-inline void LeaveCritical() {}
+inline void LeaveCritical(void* cs) {}
 inline void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line) {}
 template <typename MutexType>
 inline void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs) {}
@@ -113,6 +114,7 @@ public:
     }
 
     using unique_lock = std::unique_lock<PARENT>;
+    using shared_lock = std::shared_lock<PARENT>;
 #ifdef __clang__
     //! For negative capabilities in the Clang Thread Safety Analysis.
     //! A negative requirement uses the EXCLUSIVE_LOCKS_REQUIRED attribute, in conjunction
@@ -130,6 +132,9 @@ using RecursiveMutex = AnnotatedMixin<std::recursive_mutex>;
 /** Wrapped mutex: supports waiting but not recursive locking */
 using Mutex = AnnotatedMixin<std::mutex>;
 
+/** Wrapped shared mutex: supports read locking via SharedLock and exclusive locking via LOCK */
+using SharedMutex = AnnotatedMixin<std::shared_mutex>;
+
 /** Different type to mark Mutex at global scope
  *
  * Thread safety analysis can't handle negative assertions about mutexes
@@ -173,7 +178,7 @@ private:
         if (Base::try_lock()) {
             return true;
         }
-        LeaveCritical();
+        LeaveCritical(Base::mutex());
         return false;
     }
 
@@ -200,7 +205,7 @@ public:
     ~UniqueLock() UNLOCK_FUNCTION()
     {
         if (Base::owns_lock())
-            LeaveCritical();
+            LeaveCritical(Base::mutex());
     }
 
     operator bool()
@@ -224,7 +229,7 @@ public:
 
             CheckLastCritical((void*)lock.mutex(), lockname, _guardname, _file, _line);
             lock.unlock();
-            LeaveCritical();
+            LeaveCritical(lock.mutex());
             lock.swap(templock);
         }
 
@@ -253,6 +258,34 @@ public:
 // the sake of thread-safety analysis, but it is not actually used otherwise.
 #define REVERSE_LOCK(g, cs) typename std::decay<decltype(g)>::type::reverse_lock BITCOIN_UNIQUE_NAME(revlock)(g, cs, #cs, __FILE__, __LINE__)
 
+/**
+ * An RAII shared (read) lock for SharedMutex that registers with the
+ * DEBUG_LOCKORDER checker. Unlike LOCK(), an instance may outlive the scope
+ * that created it, but it must be destroyed on the thread that created it.
+ */
+template <typename MutexType>
+class SharedLock : public MutexType::shared_lock
+{
+    using Base = typename MutexType::shared_lock;
+
+public:
+    SharedLock(MutexType& mutex, const char* name, const char* file, int line)
+        : Base{mutex, std::defer_lock}
+    {
+        EnterCritical(name, file, line, Base::mutex());
+        Base::lock();
+    }
+
+    SharedLock(SharedLock&&) = default;
+
+    ~SharedLock()
+    {
+        if (Base::owns_lock()) LeaveCritical(Base::mutex());
+    }
+};
+
+#define READ_LOCK(cs) SharedLock BITCOIN_UNIQUE_NAME(sharedlock)(cs, #cs, __FILE__, __LINE__)
+
 // When locking a Mutex, require negative capability to ensure the lock
 // is not already held
 inline Mutex& MaybeCheckNotHeld(Mutex& cs) EXCLUSIVE_LOCKS_REQUIRED(!cs) LOCK_RETURNED(cs) { return cs; }

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. <details> <summary>Something like this?</summary> ```diff diff --git a/src/sync.cpp b/src/sync.cpp index 6d740866d4..838f420c96 100644 --- a/src/sync.cpp +++ b/src/sync.cpp @@ -14,6 +14,7 @@ #include <map> #include <mutex> #include <set> +#include <shared_mutex> #include <system_error> #include <thread> #include <type_traits> @@ -31,6 +32,7 @@ void ContendedLock(std::string_view name, std::string_view file, int nLine, Lock } template void ContendedLock(std::string_view name, std::string_view file, int nLine, std::unique_lock<std::mutex>& lock); template void ContendedLock(std::string_view name, std::string_view file, int nLine, std::unique_lock<std::recursive_mutex>& lock); +template void ContendedLock(std::string_view name, std::string_view file, int nLine, std::unique_lock<std::shared_mutex>& lock); #endif @@ -75,7 +77,7 @@ private: bool fTry; std::string mutexName; std::string sourceFile; - const std::string m_thread_name; + std::string m_thread_name; int sourceLine; }; @@ -204,13 +206,20 @@ static void push_lock(MutexType* c, const CLockLocation& locklocation) } } -static void pop_lock() +static void pop_lock(void* cs) { LockData& lockdata = GetLockData(); STDLOCK(lockdata.dd_mutex); LockStack& lock_stack = lockdata.m_lock_stacks[std::this_thread::get_id()]; - lock_stack.pop_back(); + // Erase the most recent entry for this mutex rather than popping the back: + // locks that outlive their creating scope may be released out of LIFO order. + for (auto it = lock_stack.rbegin(); it != lock_stack.rend(); ++it) { + if (it->first == cs) { + lock_stack.erase(std::next(it).base()); + break; + } + } if (lock_stack.empty()) { lockdata.m_lock_stacks.erase(std::this_thread::get_id()); } @@ -223,6 +232,7 @@ void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexTyp } template void EnterCritical(const char*, const char*, int, std::mutex*, bool); template void EnterCritical(const char*, const char*, int, std::recursive_mutex*, bool); +template void EnterCritical(const char*, const char*, int, std::shared_mutex*, bool); void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line) { @@ -250,9 +260,9 @@ void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, c throw std::logic_error(strprintf("%s was not most recent critical section locked", guardname)); } -void LeaveCritical() +void LeaveCritical(void* cs) { - pop_lock(); + pop_lock(cs); } static std::string LocksHeld() diff --git a/src/sync.h b/src/sync.h index 28bc78e911..fcb870ecaf 100644 --- a/src/sync.h +++ b/src/sync.h @@ -14,6 +14,7 @@ #include <cassert> #include <condition_variable> #include <mutex> +#include <shared_mutex> #include <string> #include <thread> @@ -47,7 +48,7 @@ TRY_LOCK(mutex, name); #ifdef DEBUG_LOCKORDER template <typename MutexType> void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false); -void LeaveCritical(); +void LeaveCritical(void* cs); void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line); template <typename MutexType> void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs); @@ -65,7 +66,7 @@ extern bool g_debug_lockorder_abort; #else template <typename MutexType> inline void EnterCritical(const char* pszName, const char* pszFile, int nLine, MutexType* cs, bool fTry = false) {} -inline void LeaveCritical() {} +inline void LeaveCritical(void* cs) {} inline void CheckLastCritical(void* cs, std::string& lockname, const char* guardname, const char* file, int line) {} template <typename MutexType> inline void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, MutexType* cs) EXCLUSIVE_LOCKS_REQUIRED(cs) {} @@ -113,6 +114,7 @@ public: } using unique_lock = std::unique_lock<PARENT>; + using shared_lock = std::shared_lock<PARENT>; #ifdef __clang__ //! For negative capabilities in the Clang Thread Safety Analysis. //! A negative requirement uses the EXCLUSIVE_LOCKS_REQUIRED attribute, in conjunction @@ -130,6 +132,9 @@ using RecursiveMutex = AnnotatedMixin<std::recursive_mutex>; /** Wrapped mutex: supports waiting but not recursive locking */ using Mutex = AnnotatedMixin<std::mutex>; +/** Wrapped shared mutex: supports read locking via SharedLock and exclusive locking via LOCK */ +using SharedMutex = AnnotatedMixin<std::shared_mutex>; + /** Different type to mark Mutex at global scope * * Thread safety analysis can't handle negative assertions about mutexes @@ -173,7 +178,7 @@ private: if (Base::try_lock()) { return true; } - LeaveCritical(); + LeaveCritical(Base::mutex()); return false; } @@ -200,7 +205,7 @@ public: ~UniqueLock() UNLOCK_FUNCTION() { if (Base::owns_lock()) - LeaveCritical(); + LeaveCritical(Base::mutex()); } operator bool() @@ -224,7 +229,7 @@ public: CheckLastCritical((void*)lock.mutex(), lockname, _guardname, _file, _line); lock.unlock(); - LeaveCritical(); + LeaveCritical(lock.mutex()); lock.swap(templock); } @@ -253,6 +258,34 @@ public: // the sake of thread-safety analysis, but it is not actually used otherwise. #define REVERSE_LOCK(g, cs) typename std::decay<decltype(g)>::type::reverse_lock BITCOIN_UNIQUE_NAME(revlock)(g, cs, #cs, __FILE__, __LINE__) +/** + * An RAII shared (read) lock for SharedMutex that registers with the + * DEBUG_LOCKORDER checker. Unlike LOCK(), an instance may outlive the scope + * that created it, but it must be destroyed on the thread that created it. + */ +template <typename MutexType> +class SharedLock : public MutexType::shared_lock +{ + using Base = typename MutexType::shared_lock; + +public: + SharedLock(MutexType& mutex, const char* name, const char* file, int line) + : Base{mutex, std::defer_lock} + { + EnterCritical(name, file, line, Base::mutex()); + Base::lock(); + } + + SharedLock(SharedLock&&) = default; + + ~SharedLock() + { + if (Base::owns_lock()) LeaveCritical(Base::mutex()); + } +}; + +#define READ_LOCK(cs) SharedLock BITCOIN_UNIQUE_NAME(sharedlock)(cs, #cs, __FILE__, __LINE__) + // When locking a Mutex, require negative capability to ensure the lock // is not already held inline Mutex& MaybeCheckNotHeld(Mutex& cs) EXCLUSIVE_LOCKS_REQUIRED(!cs) LOCK_RETURNED(cs) { return cs; } ``` </details>
l0rinc commented 2026-07-28 01:27:40 +00:00 (Migrated from github.com)

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 SignatureCache and the parallel cuckoo-cache test, then characterization and fixes for cursor lifetime during resize, destruction, and compaction.

ResizeCache() now asserts cs_main, cursors and compaction hold m_db_mutex shared, while resize takes it exclusively.

Edit: looks like a member mutex cannot guard its own destruction - TSAN should be fixed.

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 `SignatureCache` and the parallel cuckoo-cache test, then characterization and fixes for cursor lifetime during resize, destruction, and compaction. `ResizeCache()` now asserts `cs_main`, cursors and compaction hold `m_db_mutex` shared, while resize takes it exclusively. Edit: looks like a member mutex cannot guard its own destruction - TSAN should be fixed.
DrahtBot commented 2026-07-28 02:19:00 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task TSan: https://github.com/bitcoin/bitcoin/actions/runs/30319724201/job/90152871691
LLM reason (✨ experimental): CI failed because ThreadSanitizer reported a data race (in pthread_cond_destroy) causing the coins_tests CTest 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `TSan`: https://github.com/bitcoin/bitcoin/actions/runs/30319724201/job/90152871691</sub> <sub>LLM reason (✨ experimental): CI failed because **ThreadSanitizer reported a data race** (in `pthread_cond_destroy`) causing the **`coins_tests`** CTest to fail.</sub> <details><summary>Hints</summary> 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. </details>
sedited commented 2026-09-08 16:25:47 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
First-time contributor

Base: 7988380da987c0b860885853ace8149b84ac2ee8
Head: 99b9c21e404032fc4df3f418fd8aa21cde27fb3d

Design 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

<!-- forgejo-review-bot:bitcoin/bitcoin --> Base: `7988380da987c0b860885853ace8149b84ac2ee8` Head: `99b9c21e404032fc4df3f418fd8aa21cde27fb3d` ##### Design 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](<https://review.fish.foo/traces/35744-99b9c21e404032fc4df3f418fd8aa21cde27fb3d-202-2.html>)
l0rinc commented 2026-10-10 10:43:23 +00:00 (Migrated from github.com)
Drafting after https://github.com/bitcoin/bitcoin/issues/32377
l0rinc commented 2026-10-11 09:31:29 +00:00 (Migrated from github.com)

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

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
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!35744
No description provided.