mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 14:11:39 +00:00
kernel: Use typed errors for fatal and flush error notifications #36326
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!36326
Loading…
Reference in a new issue
No description provided.
Delete branch "kernel-notifications-error-variant"
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?
Part of the libbitcoinkernel project (tracking issue #27587 ), specifically the "Remove translation.h usage from the kernel" item.
kernel::Notifications::fatalError()andflushError()take abilingual_str, which pullsutil/translation.hand the application-levelG_TRANSLATION_FUNinto the kernel library, and translation is an application concern rather than a consensus one. The same interface already shows the way out:warningSet()takes akernel::Warningenum, and the node turns it into a translated string innode/kernel_notifications.cpp.Along with removing the dependency, another goal here is separating responsibilities, because the goals of error handling and error reporting are different: presenting an error to a user is an application concern, not something
libbitcoinkernelitself should own. The error is structured on both sides: in C++ as the fullkernel::FatalErrorvariant, and in the C API as its numeric value. With the current changes the C side only carries half of that structure today though, the dynamic fields (a block hash, a path, an exception'swhat()) do not cross the C API yet, even though ideally they should.This PR does the same for the two error notifications. A new
src/kernel/error.hdefineskernel::FlushErroras a plain enum andkernel::FatalErroras astd::variantwith one struct per error, whose fields carry the context the message needs: a block hash, a path, thewhat()of a caught exception, block heights. It holds types and nothing else, so every message is now built on the node side. The exception isFatalErrorString()invalidation.cpp, because a fatal error raised during validation also fails the block throughBlockValidationState::Error(), which takes the reason as a plain string right there, andfatalError()returns void, so the node has no way to put its message into that state. A follow-up could store the typed error in the state instead and let the node create the string message.This does not remove the kernel's dependency on
util/translation.h, it is just a step. The other two notifications,progress()andwarningSet(), still take abilingual_str, andbitcoinkernel.cpp,checks.cpp,node/chainstate.cpp,txmempool.cppandvalidation.cppstill include the header.There is one behavior change to mention here. The two C API callbacks lose their
messageparameter, so they now carry only the error code, the same pattern thatbtck_BlockValidationResultalready uses.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:
-Wunusedby fanquake)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.
Concept ACK :)
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/36001208610/job/107638021690LLM reason (✨ experimental): CI failed because IWYU detected missing/incorrect includes and generated changes (“Failure generated from IWYU”).
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.
Interesting. I didn't know this was a goal. Has this been discussed somewhere? Do we want to have no ability for the kernel to show detailed translated messages when something fails in the kernel, like "Bad undo data in block {hash} height {height} file {filename}" (to pick a random example)? Is this because we want (1) all kernel messages to be untranslated? Or (2) all messages that are translated to be represented as structs and enums in the kernel and made into strings by applications? Or some combination of these approaches?
I do think these approaches are reasonable, but they do come with costs. Approach (1) makes harder to write polished applications that are localized and do not require english. Approach (2) is costly to developers and users because it either results in vague messages that do not include important details necessary to understand, or it requires complicated structural representations of exceptional conditions and statuses in code.
IMO, util/translation.h is a low overhead way to provide helpful error and status messages that can be easily translated as needed. I don't see significant benefits to removing it and don't think it should be a goal to remove.
Which is not to say that providing structural error information is not useful at all. Right now we do not provide enough structural error information and should provide more. But it is also possible to take things too far and add too much structure. We should not be creating a situation where calling any kernel API means needing to handle a half-dozen error codes, when a simple error status and a translated string would be easier to handle in code and provide more detailed and helpful information to users.
@ryanofsky thanks for sharing your opinion!
I don't know if this has been discussed in more depth than the checklist item in #27587 from i took inspiration. @sedited might be able to answer that better. If more discussion is needed, we can keep it here on the PR, or I (or someone else, not sure about the process) can start a thread on the mailing list, whatever works best.
Given the two directions you describe, I was thinking on the 2 when writing the PR.
I think this is less about the dependency itself (despite removing it is a nice win for me),
util/translation.his small, as you say, and more about scope: should the kernel be responsible for producing user-facing output messages at all? The way I see thelibbitcoinkernelproject (which can be wrong or misunderstood), it is not a module of Core, but a library that uses Core's consensus code and can be used anywhere else, to build any application that needs consensus, not only a node that writes to debug.log. Bark, for example, uses therust-bitcoinkernelbindings in their test suite (see this tweet), and that kind of consumer is exactly the case where a fixed string is not the right fit. Handing back a string (and I mean any fixed string, not just abilingual_str) is already an application-level decision (how to log, how to present in a GUI), and the kernel should not be the one making it, it forces the clients to parser the message in case they want to handle it. It also limits the library's own clients: if the kernel ships an already-written message, it pushes the consumer toward the kernel's wording instead of whatever the application wants to say. A structured type does not have that problem, the consumer decides all of it.On the complexity you are worried about: this set is small and closed. There are 18 cases in total right now, 16
FatalErrorvariants plus 2FlushErrorones, and I do not expect it to grow, these are internal validation/IO failure modes, not an open API surface. It already shrank by one in this branch (FailedToStartIndexes, dropped because it was unreachable from any real kernel consumer).On your example, "Bad undo data in block {hash} height {height} file {filename}", option (2) does not have to produce a vaguer message.
AssumeutxoDataNotFound/SnapshotValidationFailedand similar carry the typed fields needed (a block hash, heights, a path), and the node still builds that exact detailed, translated message (seeFatalErrorMessageinkernel_notifications.cpp), nothing is lost. It is true that right now the C API loses that message: it only hands back the numeric code. I was thinking about sending the dynamic part of the error the same way I do for the enum itself, maybe through a union (instead of a variant), but that might push manual maintenance work onto the bindings (that is the reason I did not do it in the first approach, worth a discussion).On "calling any kernel API means needing to handle a half-dozen error codes": I see that as a positive. Handling the error would be the application's responsibility, and I think that is what lets the kernel stay smaller and closer to consensus, further away from logging or presenting errors. The C API just hands back the numeric code (
btck_FatalError); no message is exposed, only the code, the same precedentbtck_BlockValidationResultalready set. Building anything out of it is entirely up to the consumer. The node (in this repo) is the application that wants the full detailed message, so it is the one place doing an exhaustivestd::visitover all the variants (other consumers are free not to be that exhaustive).All of the above is just my own opinion. As a fairly recent contributor, I am not trying to impose any of this, just making proposals I am happy to change and discuss.
Thanks, and I want apologize because my last comment was just based on an initial reaction and not very constructive.
I do agree with the direction of the PR and approach of adding structured error types in a src/kernel/error.h file. Right now kernel functions don't return enough structured error information and they should return more.
I just want to caution against trying to use types intended for error handling for error reporting as well, because the goals of error handling and error reporting are different. For error handling you generally want fewer branching cases to avoid code complexity and bugs, while for error reporting you usually want more detail. I was also just surprised to see the goal of removing the translation header because it is so small and it was unclear what benefits that removal would bring.
Overall direction of the PR seems good, but would maybe just want to clarify the goals a little more. I think there are a number of problems worth addressing in the error handling area, the main ones being that errors are returned by callback instead of return value, which makes them difficult to handle, and that we don't have good error type, and to extend we do there is no type safety so a function that can actually only return 3 errors looks like it returns 15 errors and caller have to deal with unnecessary ambiguity and mess.
But looking at actual changes in this PR they seem reasonable, and like something that could be built on to fix other problems. The one thing I would change is that it seems like btck_NotifyFatalError and btck_NotifyFlushError are losing all details about errors that occur because messages are being replaced by codes. This seems like it could cause real harm to kernel applications because there could be no clean way to extract and present error information to users. But could be fixed by keeping the error messages and adding the codes instead of replacing the messages with codes
Appreciate that, @ryanofsky. I have updated the PR description, hope it is what you wanted.
I would also like to recommend reviewers take a look at #35646 (I just left a review there): although DrahtBot does not flag it as a conflict, both PRs define a
kernel::FatalErrortype with the same name but different goal and the main purpose of the PR is other.Could turn into draft while CI is red?
Base:
aa76bd266df9742a266d52e0e5da8dbf033658f6Head:
8a5934f7d28204270c56f445519c6f66259c1df8Findings
[Minor] Preserve snapshot-validation details in the kernel log
The kernel log no longer records why snapshot validation failed or the heights involved, particularly affecting libbitcoinkernel users.
Explanation and suggested change
Previously, the kernel logged the full snapshot-validation message, including the reset from
height_fromtoheight_to. It now logs only that it is deleting the snapshot, reverting to the validated chain, and stopping the node; the heights are available only inkernel::SnapshotValidationFailed. bitcoind still records node-rendered text throughAbortNodeandInitError, but a libbitcoinkernel consumer gets onlySNAPSHOT_VALIDATION_FAILEDand no details in its log callback. Add an untranslated kernel log line that records the height range. Also update theInvalidateCoinsDBOnDisk()comment saying the user is instructed inMaybeValidateSnapshot(), since the instruction now comes from the node's message.Location:
src/validation.cpp:6025(head).Previous reports
First reported at
8a5934f7d28204270c56f445519c6f66259c1df8. Last checked at8a5934f7d28204270c56f445519c6f66259c1df8.[Suggestion] Make fatal-error rendering exhaustive
Current callers are covered, but a future fatal error could compile and silently produce an empty reject reason.
Explanation and suggested change
FatalError()accepts anykernel::FatalErrorand passesFatalErrorString(error)tostate.Error(). The string function checks eight alternatives, then returns an empty string. All current state-setting callers use one of those alternatives, so this does not affect them. But a future caller could pass another variant, such asBlockWriteFailed, and silently set an empty reject reason shown bysubmitblockorsubmitheader; the hand-maintained test list would not catch it. Narrow the parameter to a variant containing only state-reported errors and render it with an exhaustivestd::visit.Location:
src/validation.cpp:2147(head).Design and approach
[Minor] Preserve dynamic fatal-error details for C API consumers
C API callbacks lose error messages, and several errors' details are not logged elsewhere, leaving consumers without information to diagnose them.
Explanation and suggested change
fatalError()forwards only the error category to the C callback. Although the fields do not cross the C API, several errors are also not logged before notification: the external block-file exception text, the chainstate name and validation reason inActivateBestChainsFailed, and the block hash inAssumeutxoDataNotFound. A caller ofbtck_chainstate_manager_import_blocksthat encounters an I/O or activation failure therefore sees only a category, with no details in its log callback. Until the C API carries these fields, log the variants' dynamic details in the btck adapter'sfatalError()or at the raise sites, using untranslated messages to avoid a translation dependency.Location:
src/kernel/bitcoinkernel.cpp:368(head).Previous reports
Previous reports of the same concern:
1d66b88dcd0f4608ea151d306547f41a56f29d26. Last checked at8a5934f7d28204270c56f445519c6f66259c1df8. The author plans to address this separately. Author reply 2026-09-25T15:32:32Z8a5934f7d28204270c56f445519c6f66259c1df8. Last checked at8a5934f7d28204270c56f445519c6f66259c1df8. The author plans to address this separately. Author reply 2026-09-25T15:32:32ZPreviously reported concerns remain unresolved: 1 minor.
Previous findings
[Minor · still present] Cast error codes to an integer before printing
The demo and test harness print control characters instead of readable fatal and flush error codes.
The error enums have
uint8_tunderlying types, so streaming their underlying values selects theunsigned charoverload and prints characters rather than numbers. For example,DISK_SPACE_TOO_LOWprints BEL instead of7, while flush errors print NUL or SOH. This makes the diagnostic output uninformative. Cast tounsigned intbefore streaming in all four handlers, including the matching handlers insrc/test/kernel/test_kernel.cpp.Location:
src/bitcoin-chainstate.cpp:143(head).Previous reports of the same concern:
1d66b88dcd0f4608ea151d306547f41a56f29d26. Last checked at8a5934f7d28204270c56f445519c6f66259c1df8.8a5934f7d28204270c56f445519c6f66259c1df8. Last checked at8a5934f7d28204270c56f445519c6f66259c1df8.Review coverage was incomplete.
Review limitations
Review tier: sensitive
Full review report
🐙 This pull request conflicts with the target branch and needs rebase.
Concept ACK
I haven’t looked into this in depth yet. I’ll try to review it more closely alongside https://github.com/bitcoin/bitcoin/pull/35646. Meanwhile, I've left some nits.
can be marked
constexpr& namedto_btckto match naming convention?Same here! See comment
I think with this change this method reduces each variant to an error code losing the error details (block hash, paths, snapshot recovery info). For e.g.
SystemErrorWhileSavingBlocknow reports onlySYSTEM_ERROR_WHILE_SAVING_BLOCKconsumers cannot reconstruct the underlying cause from the callback.Maybe exposing through some error object could be a way, not sure though!
af5ed188f1commit message can be more descriptive.should come before
key_io_tests.cpp?This can now return an empty string if the variant isn’t one of the listed types, which wasn’t possible before. In practice, though, every caller passes one of the listed types.
FatalErrorString in src/validation.cpp returns {} for the eight variants that are only routed through Notifications::fatalError(). Having an Assume(false) before the fallthrough return {}; would catch any accidental use of those variants in FatalError(notifications, state, ...) in debug builds, preventing BlockValidationState::Error() from silently absorbing an empty reject reason.
For btck_NotifyFatalError, passing both the code and the formatted message would mirror btck_NotifyWarningSet, which already supplies both btck_Warning warning and (const char* message, size_t message_len). That preserves programmatic dispatch for C consumers without dropping dynamic details like paths or block hashes.
Concept ACK and code reviewed
8a5934f7d2commit by commit.Also the heights are also gone from the kernel's log. Because
cdd4757drops the[snapshot] !!!LogError inhandle_invalid_snapshotso then after a hash mismatch C API users can't get either height from the callback or the log.Could the kernel keep a plain log line with them? Something like
LogError("[snapshot] validation failed, resetting chain height from %d to %d", ...), similar to theassumeutxo data not found for height (%d)warning just below. Which would be diagnostic rather than user-facing, so it shouldn't need_().To check, I added
ASSERT_DEBUG_LOG("[snapshot] !!!")tochainstatemanager_snapshot_completion_hash_mismatch. The test passes onf739c78and54bc6a5and fails on8a5934f.Could
6daa91cand the init.cpp change here go beforeaf5ed18? ThenFailedToStartIndexesis never added and codes 9 to 16 keep their values, as the "appended, never inserted" doc comment fromcdd4757says.8a5934fcould likewise be folded intocdd4757, since it restores the translation thatcdd4757drops from the rename message.nit: If you keep this commit: the message says init calls
AbortNode()directly, but it goes throughKernelNotifications::abort().Genuinely curious, would it make sense to add a test_kernel case for it? Destroying the chainman triggers a flush, and replacing
blocks/blk00000.dat(orrev00000.dat) with a directory is enough to make that flush fail. I ran it on8a5934fand the handler gotBLOCK_FILE_FLUSH_FAILED(0) andUNDO_FILE_FLUSH_FAILED(1).test_kernel.cpp diff