Skip to content

kernel: allow only one global logging connection - #34775

Open
stickies-v wants to merge 4 commits into
bitcoin:masterfrom
stickies-v:2026-02/kernel-logging-global
Open

stickies-v wants to merge 4 commits into
bitcoin:masterfrom
stickies-v:2026-02/kernel-logging-global

Conversation

@stickies-v

@stickies-v stickies-v commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

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

DrahtBot commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

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

@sedited

sedited commented Mar 9, 2026

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor Author

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

ryanofsky commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

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 #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 #34374 (comment) 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

sedited commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

@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

Copy link
Copy Markdown
Contributor Author

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 #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.

Comment thread src/kernel/bitcoinkernel.cpp Outdated

KernelLogger& g_kernel_logger()
{
static KernelLogger* logger{new KernelLogger};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this have to be a raw pointer?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/test/kernel/test_kernel.cpp Resolved
Comment thread src/kernel/bitcoinkernel_wrapper.h Resolved
@w0xlt

w0xlt commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Approach ACK

@sedited

sedited commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

@stickies-v what is the status here?

@stickies-v

Copy link
Copy Markdown
Contributor Author

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

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.

@ryanofsky

Copy link
Copy Markdown
Contributor

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: #34775 (comment)

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.

@stickies-v
stickies-v force-pushed the 2026-02/kernel-logging-global branch from f40aeb1 to 70e1de6 Compare October 5, 2026 19:03
@stickies-v
stickies-v marked this pull request as draft October 5, 2026 19:04
@stickies-v stickies-v changed the title kernel: make logging callback global kernel: allow only one global logging connection Oct 5, 2026
@stickies-v

Copy link
Copy Markdown
Contributor Author

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.

MaybeLog() is the only caller of Log().
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.

Behaviour change: btck_logging_connection_create is renamed to
btck_global_logging_connection_create, and fails if a connection
already exists.
With only one connection, the logging interface can operate on the
connection handle instead of on global state.

Behaviour changes:
- btck_logging_set_min_level becomes
  btck_logging_connection_set_min_level.
- Each new connection starts at Info, instead of at the level of the
  previous connection.
- The "Logger connected." debug entry is removed, since it can no
  longer be delivered.
Holding m_mutex while running the callback 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 change: 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.

Update bitcoin-chainstate and the test logger to write each line in a
single call, so concurrent lines don't interleave.
@stickies-v
stickies-v force-pushed the 2026-02/kernel-logging-global branch from 9213290 to f4e0a6f Compare November 3, 2026 14:52
@stickies-v

Copy link
Copy Markdown
Contributor Author

Force-pushed to address merge conflict from #36584

@ryanofsky ryanofsky left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review f4e0a6f

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 #36768 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.

Edit: now points to #36768, which replaces #36766 and fixes the same deadlock using btcsignals. #36766 has a comparison of the two.

Comment on lines +966 to +967
* Stop logging and destroy the logging connection. Blocks until running
* invocations of its callback return, then destroys the user data.

@ryanofsky ryanofsky Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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.

ryanofsky added a commit to ryanofsky/bitcoin that referenced this pull request Nov 5, 2026
…e logger mutex

KernelLogger called log callbacks while holding its mutex, so a callback
that logged, or destroyed a kernel object that logs, deadlocked. A
garbage collector running finalizers inside a callback can trigger this
(bitcoin#34775 (comment)).

Deliver entries through a btcsignals::signal instead, which holds no lock
while callbacks run. The API is unchanged. Behavior changes:

- Callbacks can run on several threads at the same time, so they must be
  thread-safe.
- Callbacks may call kernel functions, including creating and destroying
  logging connections, their own included.
- Destroying a connection no longer waits for invocations already
  running on other threads. The user data is destroyed when the last one
  returns, as with other btcsignals users.

This is the follow-up suggested in
bitcoin#34374 (comment).

This change was written with Claude Opus 5.5.
ryanofsky added a commit to ryanofsky/bitcoin that referenced this pull request Nov 6, 2026
…e logger mutex

KernelLogger called log callbacks while holding its mutex, so a callback
that logged, or destroyed a kernel object that logs, deadlocked. A
garbage collector running finalizers inside a callback can trigger this
(bitcoin#34775 (comment)).

Deliver entries through a btcsignals::signal instead, which holds no lock
while callbacks run. The API is unchanged. Behavior changes:

- Callbacks can run on several threads at the same time, so they must be
  thread-safe.
- Callbacks may call kernel functions, including creating and destroying
  logging connections, their own included.
- Destroying a connection no longer waits for invocations already
  running on other threads. The user data is destroyed when the last one
  returns, as with other btcsignals users.

This is the follow-up suggested in
bitcoin#34374 (comment).

This change was written with Claude Opus 5.5.
nervana21 pushed a commit to nervana21/bitcoin that referenced this pull request Nov 26, 2026
Release KernelLogger::m_mutex while a log callback runs, so a callback
can log, or destroy kernel objects that log, without deadlocking.
Previously Log() held m_mutex across every callback, so an entry logged
from inside a callback waited for the mutex its own thread held. A
garbage collector running finalizers inside a callback triggers this: a
finalizer that destroys a chainstate manager flushes and logs, and the
process hangs. See
bitcoin#34775 (comment)
and bitcoin#34374 (comment).
Creating or destroying another connection from inside a callback hung
the same way.

Multiple connections and the API are unchanged. Log() walks the list
of callbacks holding m_mutex only to step to the next one, and each
callback has a count of running invocations. Destroying a connection
marks its callback removed so no new invocations start, waits for the
count to reach zero, and then destroys the callback and its user_data
outside m_mutex, so it still waits for invocations on other threads.
The count is only decremented and notified under m_mutex, and destroy
takes m_mutex again before freeing the callback, so Log() never touches
a freed callback. Destroying a connection from inside its own callback
would wait for itself, so it asserts instead.

Behavior change: callbacks can run on several threads at the same time
and must be thread-safe, and entries from different threads have no
global order. The header documents this and which kernel calls are
safe from inside a callback. bitcoin-chainstate and the test logger now
write each line in one call so concurrent lines don't interleave.

New test_kernel cases, which all hang without this change: a callback
that logs and destroys a chainstate manager and context, a callback
that destroys another connection, and destroying a connection while
invocations run on other threads.

This change was written with Claude Opus 5.5.
nervana21 pushed a commit to nervana21/bitcoin that referenced this pull request Nov 27, 2026
Release KernelLogger::m_mutex while a log callback runs, so a callback
can log, or destroy kernel objects that log, without deadlocking.
Previously Log() held m_mutex across every callback, so an entry logged
from inside a callback waited for the mutex its own thread held. A
garbage collector running finalizers inside a callback triggers this: a
finalizer that destroys a chainstate manager flushes and logs, and the
process hangs. See
bitcoin#34775 (comment)
and bitcoin#34374 (comment).
Creating or destroying another connection from inside a callback hung
the same way.

Multiple connections and the API are unchanged. Log() walks the list
of callbacks holding m_mutex only to step to the next one, and each
callback has a count of running invocations. Destroying a connection
marks its callback removed so no new invocations start, waits for the
count to reach zero, and then destroys the callback and its user_data
outside m_mutex, so it still waits for invocations on other threads.
The count is only decremented and notified under m_mutex, and destroy
takes m_mutex again before freeing the callback, so Log() never touches
a freed callback. Destroying a connection from inside its own callback
would wait for itself, so it asserts instead.

Behavior change: callbacks can run on several threads at the same time
and must be thread-safe, and entries from different threads have no
global order. The header documents this and which kernel calls are
safe from inside a callback. bitcoin-chainstate and the test logger now
write each line in one call so concurrent lines don't interleave.

New test_kernel cases, which all hang without this change: a callback
that logs and destroys a chainstate manager and context, a callback
that destroys another connection, and destroying a connection while
invocations run on other threads.

This change was written with Claude Opus 5.5.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: API Development

Development

Successfully merging this pull request may close these issues.

6 participants