mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
kernel: allow only one global logging connection #34775
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!34775
Loading…
Reference in a new issue
No description provided.
Delete branch "2026-02/kernel-logging-global"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Kernel logging is inherently global:
KernelLoggeris a process-widesingleton, so every connection receives every log entry and shares the
minimum level. Multiple
btck_LoggingConnectionhandles give the falseimpression of independent loggers.
Limit
btck_global_logging_connection_createto a single connection, sothat 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_createis renamed tobtck_global_logging_connection_create, and fails if a connectionalready exists.
btck_logging_set_min_levelbecomesbtck_logging_connection_set_min_level, and each new connectionstarts at
Info.Debugentry is removed, since it can nolonger be delivered.
so it must be thread-safe. Destroying the connection still waits for
running invocations to return.
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
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)→ PreferBOOST_CHECK_EXCEPTION(..., std::runtime_error, HasReason{"A logging connection already exists"})to check the specific failure message.2026-11-03 14:52:41
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
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.
Forcing the user to use globals if they need state seems unnecessary, when using
user_datais I think a well-established pattern in C APIs? Unless I'm misunderstanding your suggested approach?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.
@stickies-v I'm not sure how we should proceed here. Are you still looking for review here, or should we work towards #34374?
My apologies for not responding earlier @ryanofsky
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.
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.
These changes are orthogonal to #34374 (they both use a
KernelLoggerclass, but that's an implementation detail). So yes, I'm still looking for review here.Does this have to be a raw pointer?
How about calling this
logging_reset_callbackand removing the argument?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?
Approach ACK
Yes, any test that installs the global logging callback now needs to clear it before returning to prevent state leakage into later tests.
logging_testsalready does this, sobtck_chainman_testswould need to do the same.I think the C++ wrapper could retain RAII while still exposing a single global logging callback.
@stickies-v what is the status here?
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_datarefers 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.Force-pushed to rebase onto latest master, and to:
Loggerin the C++ wrapper instead of free functionsMy 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.
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
Loggerclass 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 agree, but this is no longer relevant in the latest version as per https://github.com/bitcoin/bitcoin/pull/34775#discussion_r4036445255.
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_LoggingConnectiongives a false impression of independent loggers becauseLogInstance()is a process-wide singleton and all logging configuration is global. After #34374, the kernel doesn't useLogInstance()at all.KernelLoggeralready supports multiple callbacks, each with its ownuser_dataand 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_leveltake abtck_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 soShouldDebugLogstays 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_callbackgets 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.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 reportspermalink
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/37360665164/job/111934165167LLM 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.
Force-pushed to change the approach to still let the user manage
btck_LoggingConnection*lifetimes, but enforce that only a singlebtck_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?
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
MaybeLogfunction which didn't really make sense anymore, asLoghas to be conditional anyway.I've updated the PR description with the new approach. This PR is now ready for review.
🐙 This pull request conflicts with the target branch and needs rebase.
Force-pushed to address merge conflict from #36584
Code review
f4e0a6faf7Concept 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_LoggingConnectionwith 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.
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:
cs_main.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.