kernel: Dispatch log callbacks with btcsignals #36768

Open
ryanofsky wants to merge 3 commits from pr/logsig into master AGit
ryanofsky commented 2026-11-05 03:19:25 +00:00 (Migrated from github.com)

Problem: A kernel application whose log callback logs, or destroys a kernel object, hangs. The common way to hit this is a garbage-collected language binding: Python's garbage collector can run finalizers inside the callback, and a finalizer that destroys a chainstate manager flushes and logs (https://github.com/bitcoin/bitcoin/pull/34775#issuecomment-6278257737, https://github.com/bitcoin/bitcoin/pull/34374#discussion_r4030551866). The cause is that the kernel calls log callbacks while holding the logger's mutex, so any logging from inside a callback blocks on a mutex its own thread already holds. The problem is not new and has existed since logging callbacks were introduced in #30595.

Solution: This PR delivers log entries through btcsignals::signal, which calls callbacks without holding any lock, replacing the kernel's own callback list and custom dispatching mechanism.

The change is a usability improvement and a bugfix because with it applications no longer need to reason about deadlocks and blocking behavior from a mutex they can't see. However, they may need to be updated to deal with log callbacks that are no longer serialized and connection functions that no longer block. Compatibility details are in the commit message.

The main code change is in src/kernel/bitcoinkernel.cpp (+42/-77) accompanied by header docs and new test_kernel cases, which hang without the fix. There is also a commit switching btcsignals.h to use StdMutex instead of Mutex so it is safe to use in logging callbacks.

This is an alternative to the last commit of #34775, which fixes the same deadlock but only after limiting the process to one logging connection, and still hangs if a callback destroys the connection.

**Problem:** A kernel application whose log callback logs, or destroys a kernel object, hangs. The common way to hit this is a garbage-collected language binding: Python's garbage collector can run finalizers inside the callback, and a finalizer that destroys a chainstate manager flushes and logs (https://github.com/bitcoin/bitcoin/pull/34775#issuecomment-6278257737, https://github.com/bitcoin/bitcoin/pull/34374#discussion_r4030551866). The cause is that the kernel calls log callbacks while holding the logger's mutex, so any logging from inside a callback blocks on a mutex its own thread already holds. The problem is not new and has existed since logging callbacks were introduced in #30595. **Solution:** This PR delivers log entries through `btcsignals::signal`, which calls callbacks without holding any lock, replacing the kernel's own callback list and custom dispatching mechanism. The change is a usability improvement and a bugfix because with it applications no longer need to reason about deadlocks and blocking behavior from a mutex they can't see. However, they may need to be updated to deal with log callbacks that are no longer serialized and connection functions that no longer block. Compatibility details are in the commit message. The main code change is in `src/kernel/bitcoinkernel.cpp` (+42/-77) accompanied by header docs and new test_kernel cases, which hang without the fix. There is also a commit switching `btcsignals.h` to use `StdMutex` instead of `Mutex` so it is safe to use in logging callbacks. This is an alternative to the last commit of #34775, which fixes the same deadlock but only after limiting the process to one logging connection, and still hangs if a callback destroys the connection.
First-time contributor

1 additional verified finding in the full report.

Earlier concerns remain unresolved; see the full report for their current assessments.

🟠 Minor · Concurrent pruning can destroy logging user data under the signal mutex

Concurrent connection creation and destruction can run an existing subscriber's cleanup under the signal mutex, hanging if that cleanup reconnects or emits an enabled log entry while another subscriber remains.

Location: src/kernel/bitcoinkernel.cpp:519 (head).

🟠 Minor · A throwing connection diagnostic leaks the registered subscriber

With Debug or Trace delivery enabled, an allocation failure in the post-registration diagnostic returns null without deleting the connection, leaving its callback registered and violating the user-data cleanup guarantee.

Location: src/kernel/bitcoinkernel.cpp:955 (head).

🟠 Minor · Callback contract overlooks same-thread kernel lock reentry

Callbacks still run while non-recursive kernel locks are held, so the new permission to call kernel functions needs same-thread restrictions as well as the cross-thread warning.

Location: src/kernel/bitcoinkernel.h:411 (head).

🔵 Suggestion · Thread-safety guidance omits same-thread callback reentry

An enabled entry emitted inside a callback synchronously invokes that callback again, so a thread-safe implementation can still deadlock on its own non-recursive lock.

Location: src/kernel/bitcoinkernel_wrapper.h:1060 (head).

🔵 Suggestion · Concurrency test misses destruction between the two returns

logging_callback_concurrency_tests never checks that user data remains alive after one disconnected invocation returns while the other is still running.

Location: src/test/kernel/test_kernel.cpp:940 (head).

🔵 Suggestion · Test-only warning downgrade applies to all C++ targets

The i686 and Alpine additions downgrade maybe-uninitialized warnings for all configured C++ targets, although the stated trigger is confined to test_kernel.cpp.

Location: ci/test/00_setup_env_i686.sh:19 (head).

Review coverage was incomplete.


Reviewed: a9f467e8dfea · Full review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:055d1cd96b176486294e0a3d052a7e506a00c1f0c7c35fbf579b09cfe6d615cd:237cc81563f53f26a84ba90acce49f0597b0e28b0a77aa425401db6e90431c0b --> <!-- ralph-base:5bf3bc5e263407a252c14a17afe04fc3bf24a889 --> <!-- ralph-head:a9f467e8dfeafc137cb2a565fd37d555e24e3136 --> <!-- ralph-case:ed41f0e8c60a3d5b315750e27c3a12d033dcfce78d8b8b7ddb5d6d9f966d122a --> [1 additional verified finding in the full report](<https://review.fish.foo/traces/36768-a9f467e8dfeafc137cb2a565fd37d555e24e3136-2342-3.html>). Earlier concerns remain unresolved; see the full report for their current assessments. **🟠 Minor · Concurrent pruning can destroy logging user data under the signal mutex** Concurrent connection creation and destruction can run an existing subscriber's cleanup under the signal mutex, hanging if that cleanup reconnects or emits an enabled log entry while another subscriber remains. Location: [`src/kernel/bitcoinkernel.cpp:519`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a9f467e8dfeafc137cb2a565fd37d555e24e3136/src/kernel/bitcoinkernel.cpp#L519>) (head). **🟠 Minor · A throwing connection diagnostic leaks the registered subscriber** With Debug or Trace delivery enabled, an allocation failure in the post-registration diagnostic returns null without deleting the connection, leaving its callback registered and violating the user-data cleanup guarantee. Location: [`src/kernel/bitcoinkernel.cpp:955`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a9f467e8dfeafc137cb2a565fd37d555e24e3136/src/kernel/bitcoinkernel.cpp#L955>) (head). **🟠 Minor · Callback contract overlooks same-thread kernel lock reentry** Callbacks still run while non-recursive kernel locks are held, so the new permission to call kernel functions needs same-thread restrictions as well as the cross-thread warning. Location: [`src/kernel/bitcoinkernel.h:411`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a9f467e8dfeafc137cb2a565fd37d555e24e3136/src/kernel/bitcoinkernel.h#L411>) (head). **🔵 Suggestion · Thread-safety guidance omits same-thread callback reentry** An enabled entry emitted inside a callback synchronously invokes that callback again, so a thread-safe implementation can still deadlock on its own non-recursive lock. Location: [`src/kernel/bitcoinkernel_wrapper.h:1060`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a9f467e8dfeafc137cb2a565fd37d555e24e3136/src/kernel/bitcoinkernel_wrapper.h#L1060>) (head). **🔵 Suggestion · Concurrency test misses destruction between the two returns** `logging_callback_concurrency_tests` never checks that user data remains alive after one disconnected invocation returns while the other is still running. Location: [`src/test/kernel/test_kernel.cpp:940`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a9f467e8dfeafc137cb2a565fd37d555e24e3136/src/test/kernel/test_kernel.cpp#L940>) (head). **🔵 Suggestion · Test-only warning downgrade applies to all C++ targets** The i686 and Alpine additions downgrade maybe-uninitialized warnings for all configured C++ targets, although the stated trigger is confined to `test_kernel.cpp`. Location: [`ci/test/00_setup_env_i686.sh:19`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a9f467e8dfeafc137cb2a565fd37d555e24e3136/ci/test/00_setup_env_i686.sh#L19>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`a9f467e8dfea`](<https://git.fish.foo/bitcoin/bitcoin/commit/a9f467e8dfeafc137cb2a565fd37d555e24e3136>) · [Full review report](<https://review.fish.foo/traces/36768-a9f467e8dfeafc137cb2a565fd37d555e24e3136-2342-3.html>) · [Previous reports](<https://review.fish.foo/traces/36768/>) [permalink](<https://review.fish.foo/traces/36768-a9f467e8dfeafc137cb2a565fd37d555e24e3136-2342-3.html>)
ryanofsky commented 2026-11-05 03:55:35 +00:00 (Migrated from github.com)
<!-- begin push-2 --> Updated 7a5e5b0a4998d79710a1c0babae9e66dac123f0e -> 25eff90bfd61d1dac76627f8b0eda96c23be8973 ([`pr/logsig.1`](https://github.com/ryanofsky/bitcoin/commits/pr/logsig.1) -> [`pr/logsig.2`](https://github.com/ryanofsky/bitcoin/commits/pr/logsig.2), [compare](https://github.com/ryanofsky/bitcoin/compare/pr/logsig.1..pr/logsig.2))<!-- end --> Add a commit disabling -Werror for a GCC 15 -Wmaybe-uninitialized false positive in the new test_kernel test, as the armhf task already does https://github.com/bitcoin/bitcoin/actions/runs/41960869850/job/127026663042 https://github.com/bitcoin/bitcoin/actions/runs/41960869850/job/127026663160
nervana21 commented 2026-11-06 02:57:55 +00:00 (Migrated from github.com)

Approach ACK

Approach ACK
DrahtBot commented 2026-11-06 02:57:58 +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
Approach ACK nervana21

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:

  • #36909 (kernel: make btck_witness_stack_get_item_at O(1) by pzafonte)
  • #36820 (refactor: remove more dead code by fanquake)
  • #35355 (Use atomics for determining whether trace logging is enabled by ajtowns)
  • #34775 (kernel: allow only one global logging connection by stickies-v)
  • #33847 (kernel: Attach logging connections to contexts, per-connection log levels by ryanofsky)

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/36768 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36768.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36768#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 | | ---- | --------- | | Approach ACK | [nervana21](https://github.com/bitcoin/bitcoin/pull/36768#issuecomment-6675633257) | 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: * [#36909](https://github.com/bitcoin/bitcoin/pull/36909) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36909.svg"></sub> (kernel: make btck_witness_stack_get_item_at O(1) by pzafonte) * [#36820](https://github.com/bitcoin/bitcoin/pull/36820) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36820.svg"></sub> (refactor: remove more dead code by fanquake) * [#35355](https://github.com/bitcoin/bitcoin/pull/35355) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35355.svg"></sub> (Use atomics for determining whether trace logging is enabled by ajtowns) * [#34775](https://github.com/bitcoin/bitcoin/pull/34775) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34775.svg"></sub> (kernel: allow only one global logging connection by stickies-v) * [#33847](https://github.com/bitcoin/bitcoin/pull/33847) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/33847.svg"></sub> (kernel: Attach logging connections to contexts, per-connection log levels by ryanofsky) 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-->
maflcko (Migrated from github.com) reviewed 2026-11-06 08:33:48 +00:00
maflcko (Migrated from github.com) commented 2026-11-06 08:32:26 +00:00

nit: could use a trailing comment # for std::optional::emplace in test_kernel.cpp (or so), and put this in the first line to minimize the diff churn and conflicts with other ci pulls?

nit: could use a trailing comment `# for std::optional::emplace in test_kernel.cpp` (or so), and put this in the first line to minimize the diff churn and conflicts with other ci pulls?
maflcko (Migrated from github.com) commented 2026-11-06 08:33:30 +00:00

unrelated-nit: Obviously doesn't matter, but in theory this should use a hard-coded type in TicksSinceEpoch, not a silently fluent type.

unrelated-nit: Obviously doesn't matter, but in theory this should use a hard-coded type in TicksSinceEpoch, not a silently fluent type.
ryanofsky (Migrated from github.com) reviewed 2026-11-06 23:10:22 +00:00
ryanofsky (Migrated from github.com) left a comment

Updated 25eff90bfd -> a9f467e8df (pr/logsig.2 -> pr/logsig.3, compare) with maflcko's suggestions: put the CI flag first with a comment saying what it is for, and print the log timestamp with an explicit nanoseconds unit

<!-- begin push-3 --> Updated 25eff90bfd61d1dac76627f8b0eda96c23be8973 -> a9f467e8dfeafc137cb2a565fd37d555e24e3136 ([`pr/logsig.2`](https://github.com/ryanofsky/bitcoin/commits/pr/logsig.2) -> [`pr/logsig.3`](https://github.com/ryanofsky/bitcoin/commits/pr/logsig.3), [compare](https://github.com/ryanofsky/bitcoin/compare/pr/logsig.2..pr/logsig.3))<!-- end --> with maflcko's suggestions: put the CI flag first with a comment saying what it is for, and print the log timestamp with an explicit nanoseconds unit
ryanofsky (Migrated from github.com) commented 2026-11-06 23:07:40 +00:00

re: https://github.com/bitcoin/bitcoin/pull/36768#discussion_r4490493347

Thanks, moved it to the first line with a trailing comment, in the Alpine musl task too.

re: https://github.com/bitcoin/bitcoin/pull/36768#discussion_r4490493347 Thanks, moved it to the first line with a trailing comment, in the Alpine musl task too.
ryanofsky (Migrated from github.com) commented 2026-11-06 23:07:41 +00:00

re: https://github.com/bitcoin/bitcoin/pull/36768#discussion_r4490500702

in theory this should use a hard-coded type in TicksSinceEpoch, not a silently fluent type.

Good point, changed it to std::chrono::nanoseconds{entry.Timestamp().time_since_epoch()}.count(), so a change to the timestamp type would fail to compile instead of silently changing the unit. I used std::chrono instead of TicksSinceEpoch because bitcoin-chainstate is there to show what an external c++ program using the kernel library needs, so it shouldn't depend on internal util/ helpers.

re: https://github.com/bitcoin/bitcoin/pull/36768#discussion_r4490500702 > in theory this should use a hard-coded type in TicksSinceEpoch, not a silently fluent type. Good point, changed it to `std::chrono::nanoseconds{entry.Timestamp().time_since_epoch()}.count()`, so a change to the timestamp type would fail to compile instead of silently changing the unit. I used `std::chrono` instead of `TicksSinceEpoch` because bitcoin-chainstate is there to show what an external c++ program using the kernel library needs, so it shouldn't depend on internal util/ helpers.
nervana21 (Migrated from github.com) reviewed 2026-11-13 17:18:18 +00:00
nervana21 (Migrated from github.com) left a comment

I've tested and reviewed the code and it lgtm. I've left a suggestion to improve a unit test

I've tested and reviewed the code and it lgtm. I've left a suggestion to improve a unit test
nervana21 (Migrated from github.com) reviewed 2026-11-13 17:18:54 +00:00
nervana21 (Migrated from github.com) commented 2026-11-13 17:18:55 +00:00

a9f467e8df: kernel: Dispatch log callbacks with btcsignals so they run without the logger mutex

This test does not yet test that after multiple threads enter the callback and after 1 of them (but not all of them) returns, the object persists. Below is one way to test the desired logic.

Diff
diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp
--- a/src/test/kernel/test_kernel.cpp
+++ b/src/test/kernel/test_kernel.cpp
@@ -896,24 +896,32 @@ BOOST_AUTO_TEST_CASE(logging_callback_destroy_outer_tests)
     BOOST_CHECK_EQUAL(inner_entries, 2);
 }
 
-//! Counts invocations of LogMessage(), and blocks each one until released, so that a test controls
-//! when invocations return.
+//! Counts invocations of LogMessage(), and blocks each one on its own release gate, so that a test
+//! can let them return one at a time.
 class BlockingLog
 {
     std::atomic<int>& m_entered;
-    std::atomic<bool>& m_released;
+    std::atomic<bool>& m_released_a;
+    std::atomic<bool>& m_released_b;
+    std::atomic<int>& m_returned;
     std::atomic<bool>& m_destroyed;
+    std::atomic<int> m_next{0};
 
 public:
-    BlockingLog(std::atomic<int>& entered, std::atomic<bool>& released, std::atomic<bool>& destroyed)
-        : m_entered{entered}, m_released{released}, m_destroyed{destroyed} {}
+    BlockingLog(std::atomic<int>& entered, std::atomic<bool>& released_a, std::atomic<bool>& released_b,
+                std::atomic<int>& returned, std::atomic<bool>& destroyed)
+        : m_entered{entered}, m_released_a{released_a}, m_released_b{released_b}, m_returned{returned},
+          m_destroyed{destroyed} {}
     ~BlockingLog() { m_destroyed = true; }
 
     void LogMessage(const LogEntry&)
     {
+        const int slot{m_next.fetch_add(1)};
         ++m_entered;
         m_entered.notify_all();
-        m_released.wait(false);
+        (slot == 0 ? m_released_a : m_released_b).wait(false);
+        ++m_returned;
+        m_returned.notify_all();
     }
 };
 
@@ -922,10 +930,12 @@ public:
 BOOST_AUTO_TEST_CASE(logging_callback_concurrency_tests)
 {
     std::atomic<int> entered{0};
-    std::atomic<bool> released{false};
+    std::atomic<bool> released_a{false};
+    std::atomic<bool> released_b{false};
+    std::atomic<int> returned{0};
     std::atomic<bool> destroyed{false};
     std::optional<Logger<BlockingLog>> logger;
-    logger.emplace(std::make_unique<BlockingLog>(entered, released, destroyed));
+    logger.emplace(std::make_unique<BlockingLog>(entered, released_a, released_b, returned, destroyed));
 
     const auto log_info{[] { ChainParams params{hex_string_to_byte_vec("51")}; }};
     std::thread log_1{log_info};
@@ -937,8 +947,15 @@ BOOST_AUTO_TEST_CASE(logging_callback_concurrency_tests)
     logger.reset();
     BOOST_CHECK(!destroyed);
 
-    released = true;
-    released.notify_all();
+    released_a = true;
+    released_a.notify_all();
+    for (int n; (n = returned) < 1;) {
+        returned.wait(n);
+    }
+    BOOST_CHECK(!destroyed);
+
+    released_b = true;
+    released_b.notify_all();
     log_1.join();
     log_2.join();
     BOOST_CHECK(destroyed);
a9f467e8dfeafc137cb2a565fd37d555e24e3136: kernel: Dispatch log callbacks with btcsignals so they run without the logger mutex This test does not yet test that after multiple threads enter the callback and after 1 of them (but not **all** of them) returns, the object persists. Below is one way to test the desired logic. <details> <summary>Diff</summary> ```diff diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp --- a/src/test/kernel/test_kernel.cpp +++ b/src/test/kernel/test_kernel.cpp @@ -896,24 +896,32 @@ BOOST_AUTO_TEST_CASE(logging_callback_destroy_outer_tests) BOOST_CHECK_EQUAL(inner_entries, 2); } -//! Counts invocations of LogMessage(), and blocks each one until released, so that a test controls -//! when invocations return. +//! Counts invocations of LogMessage(), and blocks each one on its own release gate, so that a test +//! can let them return one at a time. class BlockingLog { std::atomic<int>& m_entered; - std::atomic<bool>& m_released; + std::atomic<bool>& m_released_a; + std::atomic<bool>& m_released_b; + std::atomic<int>& m_returned; std::atomic<bool>& m_destroyed; + std::atomic<int> m_next{0}; public: - BlockingLog(std::atomic<int>& entered, std::atomic<bool>& released, std::atomic<bool>& destroyed) - : m_entered{entered}, m_released{released}, m_destroyed{destroyed} {} + BlockingLog(std::atomic<int>& entered, std::atomic<bool>& released_a, std::atomic<bool>& released_b, + std::atomic<int>& returned, std::atomic<bool>& destroyed) + : m_entered{entered}, m_released_a{released_a}, m_released_b{released_b}, m_returned{returned}, + m_destroyed{destroyed} {} ~BlockingLog() { m_destroyed = true; } void LogMessage(const LogEntry&) { + const int slot{m_next.fetch_add(1)}; ++m_entered; m_entered.notify_all(); - m_released.wait(false); + (slot == 0 ? m_released_a : m_released_b).wait(false); + ++m_returned; + m_returned.notify_all(); } }; @@ -922,10 +930,12 @@ public: BOOST_AUTO_TEST_CASE(logging_callback_concurrency_tests) { std::atomic<int> entered{0}; - std::atomic<bool> released{false}; + std::atomic<bool> released_a{false}; + std::atomic<bool> released_b{false}; + std::atomic<int> returned{0}; std::atomic<bool> destroyed{false}; std::optional<Logger<BlockingLog>> logger; - logger.emplace(std::make_unique<BlockingLog>(entered, released, destroyed)); + logger.emplace(std::make_unique<BlockingLog>(entered, released_a, released_b, returned, destroyed)); const auto log_info{[] { ChainParams params{hex_string_to_byte_vec("51")}; }}; std::thread log_1{log_info}; @@ -937,8 +947,15 @@ BOOST_AUTO_TEST_CASE(logging_callback_concurrency_tests) logger.reset(); BOOST_CHECK(!destroyed); - released = true; - released.notify_all(); + released_a = true; + released_a.notify_all(); + for (int n; (n = returned) < 1;) { + returned.wait(n); + } + BOOST_CHECK(!destroyed); + + released_b = true; + released_b.notify_all(); log_1.join(); log_2.join(); BOOST_CHECK(destroyed); ``` </details>
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!36768
No description provided.