kernel: allow only one global logging connection #34775

Open
stickies-v wants to merge 4 commits from 2026-02/kernel-logging-global into master AGit
stickies-v commented 2026-03-09 08:35:36 +00:00 (Migrated from github.com)

Kernel logging is inherently global: KernelLogger is a process-wide
singleton, so every connection receives every log entry and shares the
minimum level. Multiple btck_LoggingConnection handles give the false
impression of independent loggers.

Limit btck_global_logging_connection_create to a single connection, so
that the globalness is expressed in that one function and the rest of
the interface can operate on the connection handle.

A single connection also makes it straightforward to invoke the callback
without holding the logger's mutex. Holding it serializes all logging
threads on user code, and deadlocks if anything on the callback's thread
logs, e.g. a garbage collector running finalizers that destroy kernel
objects.

Behaviour changes for consumers:

  • btck_logging_connection_create is renamed to
    btck_global_logging_connection_create, and fails if a connection
    already exists.
  • btck_logging_set_min_level becomes
    btck_logging_connection_set_min_level, and each new connection
    starts at Info.
  • The "Logger connected." Debug entry is removed, since it can no
    longer be delivered.
  • The callback can be invoked from multiple threads at the same time,
    so it must be thread-safe. Destroying the connection still waits for
    running invocations to return.
Kernel logging is inherently global: `KernelLogger` is a process-wide singleton, so every connection receives every log entry and shares the minimum level. Multiple `btck_LoggingConnection` handles give the false impression of independent loggers. Limit `btck_global_logging_connection_create` to a single connection, so that the globalness is expressed in that one function and the rest of the interface can operate on the connection handle. A single connection also makes it straightforward to invoke the callback without holding the logger's mutex. Holding it serializes all logging threads on user code, and deadlocks if anything on the callback's thread logs, e.g. a garbage collector running finalizers that destroy kernel objects. Behaviour changes for consumers: - `btck_logging_connection_create` is renamed to `btck_global_logging_connection_create`, and fails if a connection already exists. - `btck_logging_set_min_level` becomes `btck_logging_connection_set_min_level`, and each new connection starts at `Info`. - The "Logger connected." `Debug` entry is removed, since it can no longer be delivered. - The callback can be invoked from multiple threads at the same time, so it must be thread-safe. Destroying the connection still waits for running invocations to return.
DrahtBot commented 2026-03-09 08:36:14 +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
Approach ACK w0xlt

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:

  • #36820 (refactor: remove more dead code by fanquake)
  • #36768 (kernel: Dispatch log callbacks with btcsignals by ryanofsky)
  • #35355 (Use atomics for determining whether trace logging is enabled by ajtowns)
  • #34778 (logging: rewrite macros to enforce restrictions at compile-time, improve efficiency and usability by ryanofsky)
  • #33847 (kernel: Attach logging connections to contexts, per-connection log levels by ryanofsky)
  • #29256 (log, refactor: Allow log macros to accept context arguments 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.

LLM Linter (✨ experimental)

Possible places where comparison-specific test macros should replace generic comparisons:

  • src/test/kernel/test_kernel.cpp: BOOST_CHECK_THROW(Logger{...}, std::runtime_error) → Prefer BOOST_CHECK_EXCEPTION(..., std::runtime_error, HasReason{"A logging connection already exists"}) to check the specific failure message.

2026-11-03 14:52:41

<!--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/34775 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/34775.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/34775#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/34775#issuecomment-4022995511) | | Approach ACK | [w0xlt](https://github.com/bitcoin/bitcoin/pull/34775#issuecomment-4792069971) | 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: * [#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) * [#36768](https://github.com/bitcoin/bitcoin/pull/36768) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36768.svg"></sub> (kernel: Dispatch log callbacks with btcsignals by ryanofsky) * [#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) * [#34778](https://github.com/bitcoin/bitcoin/pull/34778) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/34778.svg"></sub> (logging: rewrite macros to enforce restrictions at compile-time, improve efficiency and usability by ryanofsky) * [#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) * [#29256](https://github.com/bitcoin/bitcoin/pull/29256) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/29256.svg"></sub> (log, refactor: Allow log macros to accept context arguments 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--> ### LLM Linter (✨ experimental) Possible places where comparison-specific test macros should replace generic comparisons: - `src/test/kernel/test_kernel.cpp`: `BOOST_CHECK_THROW(Logger{...}, std::runtime_error)` → Prefer `BOOST_CHECK_EXCEPTION(..., std::runtime_error, HasReason{"A logging connection already exists"})` to check the specific failure message. <sup>2026-11-03 14:52:41</sup>
sedited commented 2026-03-09 11:12:37 +00:00 (Migrated from github.com)

While I do believe contextualized logging would be a natural fit for the kernel interface, it seems there is currently (in my view) too little demand for the scope of changes necessary.

It really isn't a feature/issue that is sorely missed for the foreseeable future in the kernel library. There are a few applications where it would be a nice to have. Logs coming from different sources, for example in the units tests, can be a little confusing sometimes, but even that has been manageable, and I don't think I've heard many complain about that.

Not having separate connections seems simpler. Clients of the library can still multiplex the single callback on their side in whatever fashion they wish to. There are many other (and more interesting problems imo) to be working on, so this seems like the pragmatic thing to do for now.

Concept ACK

> While I do believe contextualized logging would be a natural fit for the kernel interface, it seems there is currently (in my view) too little demand for the scope of changes necessary. It really isn't a feature/issue that is sorely missed for the foreseeable future in the kernel library. There are a few applications where it would be a nice to have. Logs coming from different sources, for example in the units tests, can be a little confusing sometimes, but even that has been manageable, and I don't think I've heard many complain about that. Not having separate connections seems simpler. Clients of the library can still multiplex the single callback on their side in whatever fashion they wish to. There are many other (and more interesting problems imo) to be working on, so this seems like the pragmatic thing to do for now. Concept ACK
purpleKarrot commented 2026-03-09 13:12:49 +00:00 (Migrated from github.com)

I would go a step further. Since the log function is global, there is no need for local user data. It can be a simple function pointer, even in the C++ wrapper.

I would go a step further. Since the log function is global, there is no need for local user data. It can be a simple function pointer, even in the C++ wrapper.
stickies-v commented 2026-03-09 14:35:51 +00:00 (Migrated from github.com)

Since the log function is global, there is no need for local user data.

Forcing the user to use globals if they need state seems unnecessary, when using user_data is I think a well-established pattern in C APIs? Unless I'm misunderstanding your suggested approach?

> Since the log function is global, there is no need for local user data. Forcing the user to use globals if they need state seems unnecessary, when using `user_data` is I think a well-established pattern in C APIs? Unless I'm misunderstanding your suggested approach?
ryanofsky commented 2026-03-09 15:09:15 +00:00 (Migrated from github.com)

I think it would be a mistake to limit functionality of the logging/debuging/tracing API prematurely, in a way that seems difficult to reverse and does not seem to provide a noticeable simplification (possible I missed it, I have not reviewed the code much yet!). Anyway I have many more thoughts on this topic and can post them later.

One thing I did want to say is I don't think https://github.com/bitcoin/bitcoin/pull/30342 is the only alternative to this and other approaches should be possible. Also I am actively working on #30342, and will push a significant update to it today or tomorrow. So if there are problems with that approach, I would like to at least try to pin them down and address them.

My preference in terms of review & development effort would be to undraft your other PR #34374. I rebased that PR recently https://github.com/bitcoin/bitcoin/pull/34374#issuecomment-4012333941 and think is ready for review, and that it makes improvements that should have many more benefits to applications than this PR. Personally, I would like to review it and see it merged ASAP.

I think it would be a mistake to limit functionality of the logging/debuging/tracing API prematurely, in a way that seems difficult to reverse and does not seem to provide a noticeable simplification (possible I missed it, I have not reviewed the code much yet!). Anyway I have many more thoughts on this topic and can post them later. One thing I did want to say is I don't think https://github.com/bitcoin/bitcoin/pull/30342 is the only alternative to this and other approaches should be possible. Also I am actively working on #30342, and will push a significant update to it today or tomorrow. So if there are problems with that approach, I would like to at least try to pin them down and address them. My preference in terms of review & development effort would be to undraft your other PR #34374. I rebased that PR recently https://github.com/bitcoin/bitcoin/pull/34374#issuecomment-4012333941 and think is ready for review, and that it makes improvements that should have many more benefits to applications than this PR. Personally, I would like to review it and see it merged ASAP.
sedited commented 2026-06-04 20:16:16 +00:00 (Migrated from github.com)

@stickies-v I'm not sure how we should proceed here. Are you still looking for review here, or should we work towards #34374?

@stickies-v I'm not sure how we should proceed here. Are you still looking for review here, or should we work towards #34374?
stickies-v commented 2026-06-05 20:22:33 +00:00 (Migrated from github.com)

My apologies for not responding earlier @ryanofsky

in a way that seems difficult to reverse

It's a +76/-72 diff, I don't think this will be particularly hard to reverse? If you're talking about breaking the interface: it is unversioned and we're quite explicit about breaking it when we want to, so I don't think that's a concern either. Of course, we shouldn't merge this when it seems like there is strong conceptual support for an alternative.

and does not seem to provide a noticeable simplification

I think having an interface that looks like it makes sense to have multiple logging connections, when it actually doesn't is unnecessarily confusing. While having documentation is good, having a self-explanatory interface is better.

Generally, I don't think this PR should or will prevent future changes that improve contextualized logging. It just seems to me like there currently isn't a lot of support for those improvements, so I think it's better to clean up the interface since that's such a straightforward change. I'm not opposed to contextualized logging, but I won't be reviewing it myself as I think it's currently not worth the effort.

Are you still looking for review here, or should we work towards https://github.com/bitcoin/bitcoin/pull/34374?

These changes are orthogonal to #34374 (they both use a KernelLogger class, but that's an implementation detail). So yes, I'm still looking for review here.

My apologies for not responding earlier @ryanofsky > in a way that seems difficult to reverse It's a +76/-72 diff, I don't think this will be particularly hard to reverse? If you're talking about breaking the interface: it is unversioned and we're quite explicit about breaking it when we want to, so I don't think that's a concern either. Of course, we shouldn't merge this when it seems like there is strong conceptual support for an alternative. > and does not seem to provide a noticeable simplification I think having an interface that looks like it makes sense to have multiple logging connections, when it actually doesn't is unnecessarily confusing. While having documentation is good, having a self-explanatory interface is better. Generally, I don't think this PR should or will prevent future changes that improve contextualized logging. It just seems to me like there currently isn't a lot of support for those improvements, so I think it's better to clean up the interface since that's such a straightforward change. I'm not opposed to contextualized logging, but I won't be reviewing it myself as I think it's currently not worth the effort. > Are you still looking for review here, or should we work towards https://github.com/bitcoin/bitcoin/pull/34374? These changes are orthogonal to #34374 (they both use a `KernelLogger` class, but that's an implementation detail). So yes, I'm still looking for review here.
sedited (Migrated from github.com) reviewed 2026-06-11 12:06:24 +00:00
sedited (Migrated from github.com) commented 2026-06-11 11:56:50 +00:00

Does this have to be a raw pointer?

Does this have to be a raw pointer?
sedited (Migrated from github.com) commented 2026-06-11 12:05:50 +00:00

How about calling this logging_reset_callback and removing the argument?

How about calling this `logging_reset_callback` and removing the argument?
sedited (Migrated from github.com) commented 2026-06-11 12:03:24 +00:00

I think this shows the downside of exposing a global function for this: Even though this function is scoped to this test, it now enables logging for all the the other unit tests too. Maybe add another call to set the callback to null at the end of the test?

I think this shows the downside of exposing a global function for this: Even though this function is scoped to this test, it now enables logging for all the the other unit tests too. Maybe add another call to set the callback to null at the end of the test?
w0xlt commented 2026-06-24 17:41:45 +00:00 (Migrated from github.com)

Approach ACK

Approach ACK
w0xlt (Migrated from github.com) reviewed 2026-07-16 00:08:03 +00:00
w0xlt (Migrated from github.com) commented 2026-07-16 00:08:03 +00:00

Yes, any test that installs the global logging callback now needs to clear it before returning to prevent state leakage into later tests.
logging_tests already does this, so btck_chainman_tests would need to do the same.

diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp
index cfd02ea495..1413d5be22 100644
--- a/src/test/kernel/test_kernel.cpp
+++ b/src/test/kernel/test_kernel.cpp
@@ -758,6 +758,7 @@ BOOST_AUTO_TEST_CASE(btck_chainman_tests)
     BOOST_CHECK(chainman_opts.SetWipeDbs(/*wipe_block_tree=*/false, /*wipe_chainstate=*/true));
     BOOST_CHECK(chainman_opts.SetWipeDbs(/*wipe_block_tree=*/false, /*wipe_chainstate=*/false));
     ChainMan chainman{context, chainman_opts};
+    logging_set_callback(nullptr);
 }
 
 std::unique_ptr<ChainMan> create_chainman(TestDirectory& test_directory,
Yes, any test that installs the global logging callback now needs to clear it before returning to prevent state leakage into later tests. `logging_tests` already does this, so `btck_chainman_tests` would need to do the same. ```diff diff --git a/src/test/kernel/test_kernel.cpp b/src/test/kernel/test_kernel.cpp index cfd02ea495..1413d5be22 100644 --- a/src/test/kernel/test_kernel.cpp +++ b/src/test/kernel/test_kernel.cpp @@ -758,6 +758,7 @@ BOOST_AUTO_TEST_CASE(btck_chainman_tests) BOOST_CHECK(chainman_opts.SetWipeDbs(/*wipe_block_tree=*/false, /*wipe_chainstate=*/true)); BOOST_CHECK(chainman_opts.SetWipeDbs(/*wipe_block_tree=*/false, /*wipe_chainstate=*/false)); ChainMan chainman{context, chainman_opts}; + logging_set_callback(nullptr); } std::unique_ptr<ChainMan> create_chainman(TestDirectory& test_directory, ```
w0xlt (Migrated from github.com) reviewed 2026-07-16 00:22:06 +00:00
w0xlt (Migrated from github.com) commented 2026-07-16 00:22:06 +00:00

I think the C++ wrapper could retain RAII while still exposing a single global logging callback.

I think the C++ wrapper could retain RAII while still exposing a single global logging callback.
sedited commented 2026-08-27 11:04:39 +00:00 (Migrated from github.com)

@stickies-v what is the status here?

@stickies-v what is the status here?
stickies-v (Migrated from github.com) reviewed 2026-09-16 06:39:41 +00:00
stickies-v (Migrated from github.com) commented 2026-09-16 06:39:41 +00:00

I think so, to avoid running consumer code from static destructors. The order of destruction of static objects is undefined, so a plain static would run the consumer's destroy callback at some point during process teardown that they can't control, e.g. after objects their user_data refers to are already destroyed, or after a language runtime like Python has shut down. It's more important for #34374, where we also want to avoid log statements referencing a logger that's already destroyed, but it seems sensible to leak it here too.

I think so, to avoid running consumer code from static destructors. The order of destruction of static objects is undefined, so a plain static would run the consumer's destroy callback at some point during process teardown that they can't control, e.g. after objects their `user_data` refers to are already destroyed, or after a language runtime like Python has shut down. It's more important for #34374, where we also want to avoid log statements referencing a logger that's already destroyed, but it seems sensible to leak it here too.
stickies-v commented 2026-09-17 11:43:55 +00:00 (Migrated from github.com)

Force-pushed to rebase onto latest master, and to:

  • address @w0xlt's suggestion to have an RAII Logger in the C++ wrapper instead of free functions
  • align naming etc better with the updated approach in #34374

My apologies for once again a slow follow-up here. I wanted to first figure out my approach in #34374, and that took me much longer than I had anticipated.

Force-pushed to rebase onto latest master, and to: - address @w0xlt's [suggestion](https://github.com/bitcoin/bitcoin/pull/34775#discussion_r3591661659) to have an RAII `Logger` in the C++ wrapper instead of free functions - align naming etc better with the updated approach in #34374 My apologies for once again a slow follow-up here. I wanted to first figure out my approach in #34374, and that took me much longer than I had anticipated.
stickies-v (Migrated from github.com) reviewed 2026-09-17 11:46:08 +00:00
stickies-v (Migrated from github.com) commented 2026-09-17 11:46:08 +00:00

I think the C++ wrapper could retain RAII while still exposing a single global logging callback.

Yeah, this seems like the most elegant approach to me. In fact, I think it makes sense to not expose the free logging functions at all in the wrapper. The Logger class should offer all required functionality, in a way that is much harder to abuse.

Thank you both for your ideas and suggestions. I've updated the PR with this approach.

> I think the C++ wrapper could retain RAII while still exposing a single global logging callback. Yeah, this seems like the most elegant approach to me. In fact, I think it makes sense to not expose the free logging functions at all in the wrapper. The `Logger` class should offer all required functionality, in a way that is much harder to abuse. Thank you both for your ideas and suggestions. I've updated the PR with this approach.
stickies-v (Migrated from github.com) reviewed 2026-09-17 11:46:35 +00:00
stickies-v (Migrated from github.com) commented 2026-09-17 11:46:35 +00:00
I agree, but this is no longer relevant in the latest version as per https://github.com/bitcoin/bitcoin/pull/34775#discussion_r4036445255.
ryanofsky commented 2026-09-25 05:52:24 +00:00 (Migrated from github.com)

Sorry for going quiet here again, and thanks for the update and earlier reply.

I just ACKed #34374, and I think it changes the picture for this PR. The description says btck_LoggingConnection gives a false impression of independent loggers because LogInstance() is a process-wide singleton and all logging configuration is global. After #34374, the kernel doesn't use LogInstance() at all. KernelLogger already supports multiple callbacks, each with its own user_data and lifetime, registered and removed under a mutex, and the only shared setting left is the minimum level.

So instead of removing the connection handle, I'd suggest going the other way: have btck_logging_set_min_level take a btck_LoggingConnection* and filter per connection. It is a small change on top of #34374: store the level on each callback, and keep the atomic as the lowest level across callbacks so ShouldDebugLog stays cheap. After that, connections really are independent in everything a caller can configure, and the confusion this PR fixes goes away without introducing a process-wide callback that separate components in one process would have to coordinate over. I rebased #33847 onto #34374 to do this, which makes it much smaller than the original version.

re: https://github.com/bitcoin/bitcoin/pull/34775#issuecomment-4635220722

On reversibility: I agree the diff here is small. My concern is difficultly of updating code written against the API rather than the diff. Code that calls a global set_callback gets no connection object, so going back to connections later means restructuring callers, not just the library, because caller need to track the pointer and pass it to all sites that may need it. In the case of language bindings this could mean a coordinated rollout with bindings first needing to expose connection pointers, and then applications updated to start using them. Udates within applications could be nontrivial as well. Happy to go into this more, but hopefully #33847 shows how these problems can be easily avoided with small tweaks to the connection API making it flexible and future proof. I believe it is a better long term and short term approach.

Sorry for going quiet here again, and thanks for the update and earlier reply. I just ACKed #34374, and I think it changes the picture for this PR. The description says `btck_LoggingConnection` gives a false impression of independent loggers because `LogInstance()` is a process-wide singleton and all logging configuration is global. After #34374, the kernel doesn't use `LogInstance()` at all. `KernelLogger` already supports multiple callbacks, each with its own `user_data` and lifetime, registered and removed under a mutex, and the only shared setting left is the minimum level. So instead of removing the connection handle, I'd suggest going the other way: have `btck_logging_set_min_level` take a `btck_LoggingConnection*` and filter per connection. It is a small change on top of #34374: store the level on each callback, and keep the atomic as the lowest level across callbacks so `ShouldDebugLog` stays cheap. After that, connections really are independent in everything a caller can configure, and the confusion this PR fixes goes away without introducing a process-wide callback that separate components in one process would have to coordinate over. I rebased #33847 onto #34374 to do this, which makes it much smaller than the original version. re: https://github.com/bitcoin/bitcoin/pull/34775#issuecomment-4635220722 On reversibility: I agree the diff here is small. My concern is difficultly of updating code written against the API rather than the diff. Code that calls a global `set_callback` gets no connection object, so going back to connections later means restructuring callers, not just the library, because caller need to track the pointer and pass it to all sites that may need it. In the case of language bindings this could mean a coordinated rollout with bindings first needing to expose connection pointers, and then applications updated to start using them. Udates within applications could be nontrivial as well. Happy to go into this more, but hopefully #33847 shows how these problems can be easily avoided with small tweaks to the connection API making it flexible and future proof. I believe it is a better long term and short term approach.
First-time contributor

1 additional verified finding in the full report.

🟠 Minor · Keep registration unavailable until old user data is destroyed

UnregisterCallback (bitcoinkernel.cpp:609-610) clears m_callback before ~CallbackHandle destroys the old Callback and user_data. A concurrent create can succeed, and its callback can run, while the old destroy callback is still executing. This needs concurrent create/destroy, and no such caller was identified.

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

🔵 Suggestion · Callback contract still excludes the motivating finalizer case

Finalizer-driven kernel calls remain forbidden, while same-thread callback re-entry is undocumented and requires more than thread safety if that use is intended to work.

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

🔵 Suggestion · Concurrency test hangs instead of reporting serialized callbacks

If callbacks become serialized again or the signet Info entry stops being emitted, the test cannot reach its assertions or cleanup and relies on an outer timeout.

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

🔵 Suggestion · Teardown coverage misses the last running callback

The test releases both callbacks together, so it can miss destruction of user_data after only one invocation returns.

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

🔵 Suggestion · A single std::cout insertion does not guarantee whole log lines

Formatting each line first reduces interleaving but does not portably prevent it in the demo and test loggers, contrary to their comments.

Location: src/bitcoin-chainstate.cpp:57 (head).

🔵 Suggestion · Above-Info filtering is untested through the connection setter

The new connection setter is tested only with DEBUG_LEVEL, so filtering of unconditional Info entries is untested.

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

Review coverage was incomplete.


Reviewed: f4e0a6faf76d · Full review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:965af1044d9e41839565702e4d9bd0a751eda81f6e8b6402747fa296ef84ebea:7efd3c3ba41667382004cfa7a7db56605da7d8f9b7ab69bc483f27117390ba48 --> <!-- ralph-base:f5e10868da4442cee68e117f259880753b36d86c --> <!-- ralph-head:f4e0a6faf76dafe13b474a006fac57dfb4ebec75 --> <!-- ralph-case:1af68f721ba5b6b382ddb71c5fff9496853d6072e7f459fea63603c4c15730e4 --> [1 additional verified finding in the full report](<https://review.fish.foo/traces/34775-f4e0a6faf76dafe13b474a006fac57dfb4ebec75-2060-8.html>). **🟠 Minor · Keep registration unavailable until old user data is destroyed** UnregisterCallback (bitcoinkernel.cpp:609-610) clears m_callback before ~CallbackHandle destroys the old Callback and user_data. A concurrent create can succeed, and its callback can run, while the old destroy callback is still executing. This needs concurrent create/destroy, and no such caller was identified. Location: [`src/kernel/bitcoinkernel.cpp:598`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/f4e0a6faf76dafe13b474a006fac57dfb4ebec75/src/kernel/bitcoinkernel.cpp#L598>) (head). **🔵 Suggestion · Callback contract still excludes the motivating finalizer case** Finalizer-driven kernel calls remain forbidden, while same-thread callback re-entry is undocumented and requires more than thread safety if that use is intended to work. Location: [`src/kernel/bitcoinkernel.h:411`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/f4e0a6faf76dafe13b474a006fac57dfb4ebec75/src/kernel/bitcoinkernel.h#L411>) (head). **🔵 Suggestion · Concurrency test hangs instead of reporting serialized callbacks** If callbacks become serialized again or the signet Info entry stops being emitted, the test cannot reach its assertions or cleanup and relies on an outer timeout. Location: [`src/test/kernel/test_kernel.cpp:810`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/f4e0a6faf76dafe13b474a006fac57dfb4ebec75/src/test/kernel/test_kernel.cpp#L810>) (head). **🔵 Suggestion · Teardown coverage misses the last running callback** The test releases both callbacks together, so it can miss destruction of user_data after only one invocation returns. Location: [`src/test/kernel/test_kernel.cpp:818`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/f4e0a6faf76dafe13b474a006fac57dfb4ebec75/src/test/kernel/test_kernel.cpp#L818>) (head). **🔵 Suggestion · A single std::cout insertion does not guarantee whole log lines** Formatting each line first reduces interleaving but does not portably prevent it in the demo and test loggers, contrary to their comments. Location: [`src/bitcoin-chainstate.cpp:57`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/f4e0a6faf76dafe13b474a006fac57dfb4ebec75/src/bitcoin-chainstate.cpp#L57>) (head). **🔵 Suggestion · Above-Info filtering is untested through the connection setter** The new connection setter is tested only with DEBUG_LEVEL, so filtering of unconditional Info entries is untested. Location: [`src/test/kernel/test_kernel.cpp:749`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/f4e0a6faf76dafe13b474a006fac57dfb4ebec75/src/test/kernel/test_kernel.cpp#L749>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`f4e0a6faf76d`](<https://git.fish.foo/bitcoin/bitcoin/commit/f4e0a6faf76dafe13b474a006fac57dfb4ebec75>) · [Full review report](<https://review.fish.foo/traces/34775-f4e0a6faf76dafe13b474a006fac57dfb4ebec75-2060-8.html>) · [Previous reports](<https://review.fish.foo/traces/34775/>) [permalink](<https://review.fish.foo/traces/34775-f4e0a6faf76dafe13b474a006fac57dfb4ebec75-2060-8.html>)
DrahtBot commented 2026-10-05 20:05:34 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/37360665164/job/111934165167
LLM reason (✨ experimental): CI failed because IWYU modified src/kernel/bitcoinkernel.cpp, leaving a diff that caused the include-check 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 `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/37360665164/job/111934165167</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU modified `src/kernel/bitcoinkernel.cpp`, leaving a diff that caused the include-check 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>
stickies-v commented 2026-10-05 20:19:53 +00:00 (Migrated from github.com)

Force-pushed to change the approach to still let the user manage btck_LoggingConnection* lifetimes, but enforce that only a single btck_LoggingConnection* can exist at any given time (see updated PR description). This keeps the logging interface scoped while still naturally representing that currently we only support a single, global logging connection. I've rebased it on top of #34374, and will keep this as draft until that's merged. #34374 offers many more practical benefits and seems to have more consensus, so prioritizing that makes sense I think.

@ryanofsky: I believe this new approach addresses your concern about callers having to restructure if logging is contextualized later, because the connection handle is kept. I don't think allowing multiple connections or setting a connection per context makes sense until #30342 is merged, so I'm leaving that out of scope for here. We can discuss those changes on the relevant PRs?

Force-pushed to change the approach to still let the user manage `btck_LoggingConnection*` lifetimes, but enforce that only a single `btck_LoggingConnection*` can exist at any given time (see updated PR description). This keeps the logging interface scoped while still naturally representing that currently we only support a single, global logging connection. I've rebased it on top of #34374, and will keep this as draft until that's merged. #34374 offers many more practical benefits and seems to have more consensus, so prioritizing that makes sense I think. @ryanofsky: I believe this new approach addresses [your concern](https://github.com/bitcoin/bitcoin/pull/34775#issuecomment-5827538937) about callers having to restructure if logging is contextualized later, because the connection handle is kept. I don't think allowing multiple connections or setting a connection per context makes sense until #30342 is merged, so I'm leaving that out of scope for here. We can discuss those changes on the relevant PRs?
stickies-v commented 2026-10-19 21:55:48 +00:00 (Migrated from github.com)

While working on updating the Python language bindings, I noticed that Python's garbage collection can cause deadlocks even when the logging callback itself wouldn't have caused any deadlocks, because the GC can run finalizers inside the callback, and the (usually *_destroy) kernel calls they make log on the same thread. @w0xlt already raised concerns about this too, e.g. here and here.

Having a single callback (or one per context, cfr #30342) makes it a lot easier to invoke the callback without holding a lock, so I decided to include that change in this PR too. It comes with the side-effect that log callback invocations are no longer serialized, and callbacks must be thread-safe.

Restructured the commits a bit for reviewability, and also dropped the MaybeLog function which didn't really make sense anymore, as Log has to be conditional anyway.

I've updated the PR description with the new approach. This PR is now ready for review.

While working on updating the Python language bindings, I noticed that Python's garbage collection can cause deadlocks even when the logging callback itself wouldn't have caused any deadlocks, because the GC can run finalizers inside the callback, and the (usually `*_destroy`) kernel calls they make log on the same thread. @w0xlt already raised concerns about this too, e.g. [here](https://github.com/bitcoin/bitcoin/pull/36197#issuecomment-5685155418) and [here](https://github.com/bitcoin/bitcoin/pull/34374#discussion_r4030551866). Having a single callback (or one per context, cfr #30342) makes it a lot easier to invoke the callback without holding a lock, so I decided to include that change in this PR too. It comes with the side-effect that log callback invocations are no longer serialized, and callbacks must be thread-safe. Restructured the commits a bit for reviewability, and also dropped the `MaybeLog` function which didn't really make sense anymore, as `Log` has to be conditional anyway. I've updated the PR description with the new approach. This PR is now ready for review.
DrahtBot commented 2026-11-03 14:29:43 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
stickies-v commented 2026-11-03 14:52:58 +00:00 (Migrated from github.com)

Force-pushed to address merge conflict from #36584

Force-pushed to address merge conflict from #36584
ryanofsky (Migrated from github.com) reviewed 2026-11-04 22:37:41 +00:00
ryanofsky (Migrated from github.com) left a comment

Code review f4e0a6faf7

Concept ACK on calling the callback without holding the lock. I reviewed all the code here, and since the deadlock fix doesn't depend on the rest of the PR, I opened #36766 with just that fix for the current multi-connection logger, with no API change. The fix doesn't depend on having a single connection, so I'm hoping it can go in separately and this PR can rebase on it. That would let us make progress where we agree while we work out the rest.

Thanks for reworking the API. The first version replaced btck_LoggingConnection with a single global callback, so keeping the connection handle with a level setter that takes it is a real improvement: callers hold a connection and pass it where it's needed, they can't interfere with each other's callbacks, and they track what they own.

Where I'm still stuck is not requiring clients to attach a connection to what it should receive entries from. I think we've been talking past each other, so let me put my side as a concrete outcome. If a client is written assuming one global connection receives every entry, and we later add per-context logging and narrow what the global connection receives, that client has to be restructured to get a connection to every place it creates a context, possibly across package and language boundaries for bindings. If clients attach connections from the start, the same client code keeps working when better logging features arrive, and we don't need errors like "A logging connection already exists".

I understand the reasons given so far as "logging is inherently global" and avoiding a false impression of independent loggers, but I haven't been able to turn them into a concrete outcome like that. Is there a case where requiring clients to attach connections leads to a problem for a client, or for us? If you can describe one, I think that's what would let us find an API that satisfies both. This PR and #33847 have been getting closer to each other, so I'm hopeful we can get there.

Code review f4e0a6faf76dafe13b474a006fac57dfb4ebec75 Concept ACK on calling the callback without holding the lock. I reviewed all the code here, and since the deadlock fix doesn't depend on the rest of the PR, I opened #36766 with just that fix for the current multi-connection logger, with no API change. The fix doesn't depend on having a single connection, so I'm hoping it can go in separately and this PR can rebase on it. That would let us make progress where we agree while we work out the rest. Thanks for reworking the API. The first version replaced `btck_LoggingConnection` with a single global callback, so keeping the connection handle with a level setter that takes it is a real improvement: callers hold a connection and pass it where it's needed, they can't interfere with each other's callbacks, and they track what they own. Where I'm still stuck is not requiring clients to attach a connection to what it should receive entries from. I think we've been talking past each other, so let me put my side as a concrete outcome. If a client is written assuming one global connection receives every entry, and we later add per-context logging and narrow what the global connection receives, that client has to be restructured to get a connection to every place it creates a context, possibly across package and language boundaries for bindings. If clients attach connections from the start, the same client code keeps working when better logging features arrive, and we don't need errors like "A logging connection already exists". I understand the reasons given so far as "logging is inherently global" and avoiding a false impression of independent loggers, but I haven't been able to turn them into a concrete outcome like that. Is there a case where requiring clients to attach connections leads to a problem for a client, or for us? If you can describe one, I think that's what would let us find an API that satisfies both. This PR and #33847 have been getting closer to each other, so I'm hopeful we can get there.
ryanofsky (Migrated from github.com) commented 2026-11-04 20:57:22 +00:00

In commit "kernel: invoke the logging callback without holding the lock" (f4e0a6faf7)

Reviewing this commit I found a few things, which #36768 handles, in case they're useful:

  • A callback that destroys its own connection now hangs, because destroy waits for running invocations, including the one it's called from. At Debug level the "Logger disconnecting." entry reaches the callback first, so it recurses. I checked both with a scratch test. In #36768, destroying a connection doesn't wait for a running call, so a callback can destroy any connection, including its own.
  • With the lock gone, "must not call any other kernel API function" is stricter than needed, and the GC case depends on more being allowed (a finalizer destroying kernel objects, which logs). #36768 documents what's safe, that entries from different threads have no order, and that a callback shouldn't wait on threads that may hold internal locks like cs_main.
  • Nothing tests logging from inside a callback, the deadlock this fixes. #36768 adds that test, which hangs before the fix.

If you'd rather keep the fix in this PR, we can bring these changes over, but would like try to unbundle separate issues.

Edit: now points to #36768, which replaces #36766.

In commit "kernel: invoke the logging callback without holding the lock" (f4e0a6faf76dafe13b474a006fac57dfb4ebec75) Reviewing this commit I found a few things, which #36768 handles, in case they're useful: - A callback that destroys its own connection now hangs, because destroy waits for running invocations, including the one it's called from. At Debug level the "Logger disconnecting." entry reaches the callback first, so it recurses. I checked both with a scratch test. In [#36768](https://github.com/bitcoin/bitcoin/pull/36768), destroying a connection doesn't wait for a running call, so a callback can destroy any connection, including its own. - With the lock gone, "must not call any other kernel API function" is stricter than needed, and the GC case depends on more being allowed (a finalizer destroying kernel objects, which logs). [#36768](https://github.com/bitcoin/bitcoin/pull/36768) documents what's safe, that entries from different threads have no order, and that a callback shouldn't wait on threads that may hold internal locks like `cs_main`. - Nothing tests logging from inside a callback, the deadlock this fixes. [#36768](https://github.com/bitcoin/bitcoin/pull/36768) adds that test, which hangs before the fix. If you'd rather keep the fix in this PR, we can bring these changes over, but would like try to unbundle separate issues. _Edit: now points to #36768, which replaces #36766._
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!34775
No description provided.