mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
RFC: Separate out runtime errors from BlockValidationState using util::Expected #35646
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!35646
Loading…
Reference in a new issue
No description provided.
Delete branch "2026-06-remove_enum_ie"
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?
BlockValidationStatecurrently carries two unrelated kinds of failure: consensus/policy invalidity which is the actual purpose and runtime errors via aM_ERRORmode inModeStateenum insideValidationStateclass. This PR removesM_ERRORand routes runtime errors throughutil::Expected<T, std::string>instead, making the two failure modes distinct.Motivation
BlockValidationStateexists to describe why a block or transaction is invalid. It holds a consensus/policy reject reason. A disk write or system runtime error is not that, yet it was folded into the same object as a third state i.e.M_ERROR.This conflation has two costs:
Wrong abstraction for non-validating functions.
FlushStateToDisk,DisconnectTip,ActivateBestChain,PreciousBlock, andInvalidateBlockdo no block validation, but each takes aBlockValidationStateout-param to report any runtime error.Three outcomes in one object. Functions that can both validate and hit a runtime error (
ConnectBlock,AcceptBlock,ProcessNewBlock) holds valid, invalid, and fatal into a singleBlockValidationState, forcing every caller to unwrap.As noted in the original discussion here:
And also discussion here to remove
M_ERRORvalue.BlockValidationStatefrom validation methods instead of boolean value.util::Expectedis a good option for this reason, it keeps the error handling in the same return value style (system/runtime errors andValidationStatefor consensus correctness) and separates-out runtime errors fromValidationState.Runtime errors could be signaled either by a return value or by throwing. This PR keeps them as return values as it's a minimal change.
M_ERRORwas already a return-value mechanism included inValidationStatewith consensus verdict. This PR doesn't open the exceptions vs returns question, it keeps the existing return-value style and just moves the fatal error into a proper Expected channel.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 named args for integral literals may be used (e.g.
func(x, /*named_arg=*/0)in C++, andfunc(x, named_arg=0)in Python):src/test/baseindex_tests.cpp:AcceptBlock(new_block, &new_block_index, true, nullptr, nullptr, true)src/test/blockfilter_index_tests.cpp:ProcessNewBlock(block, true, true, nullptr)(three occurrences)src/test/util/mining.cpp:ProcessNewBlock(block, true, true, &new_block)src/test/util/setup_common.cpp:ProcessNewBlock(shared_pblock, true, true, nullptr)src/test/validation_block_tests.cpp:ProcessNewBlock(block, true, true, &ignored)(two occurrences)src/test/validation_chainstate_tests.cpp:ProcessNewBlock(std::make_shared<CBlock>(block), true, true, nullptr)src/test/validation_chainstate_tests.cpp:AcceptBlock(pblockone, &pindex, true, nullptr, &newblock, true)2026-11-03 06:18:20
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased on master to resolve conflicts with #35621.
Adopted its "ignore the flush error" behavior in the new
util::ExpectedAPI by dropping the flush-error propagation fromAcceptBlock.Hmm, it could make sense to be more type-safe here, but looking at the code, there are places that flatten this back down to a boolean, so I wonder what the overall benefit is?
I think it could make sense to think whether any places that flatten this down again to a boolean need a different handling? If yes, fixing that handling should probably be done early in a pull request changing the behavior.
Moreover, I presume all of the runtime-errors are fatal, so I presume they must all call the fatal error function. Maybe this can be enforced at compile-time, so that all those fatal errors ensure that the fatal error function is called exactly once?
Concept ACK
The advantages of this change are:
At first it looked a bit strange that some errors (runtime errors) are treated as exceptional cases, while validation errors are treated as return values, as previously both were treated the same. However, this makes sense; validation status can be regarded as the non-exceptional output of the checker algotihms, while runtime errors are proper exceptional errors.
Some minor observations:
voidreturn value changes, then theBlockValidationStatechanges)CheckBlock,CheckBlockHeadercould be also be changed to the return-state pattern[[nodiscard]]could be added touched signatures, to reduce risk of ignored errors.statevariable is used, its scope could be reduced, or omitted entirely. Preferably error from a call should be handled right away, there is no need for method-wide state/error variable (left comments in a few places).Could get rid of this local variable if
CheckBlocksignature is also changed (to return state).The scope of this local var. could be reduced, or maybe omitted completely, if
CheckBlockHeadersignature is also changed.The scope of this local variable could be reduced.
You're right that the top-level callers collapses the result back to yes/no, wouldn't that be the right place for it to collapse? e.g.
ConnectBlock->ConnectTip->ActivateBestChainStep->ActivateBestChain, whereM_ERRORused to be insideValidationStatenext to consensus verdict and every caller had to unwrap to distinguish b/w consensus failure v/s fatal error.I've checked, every fatal error already fires at the origin(
FatalError()), so by the time it reaches the top-level caller, the node might be shutting down regardless of what the caller does with the string, none of the callers branch on fatal-vs-non-fatal; they just surface the message. If other reviewers also feels the same that the caller needs to programmatically tell the two apart, we could have a distinct type for fatal and non-fatal type.This is mostly true, except for
invalidateblock/reconsiderblockrpc whose error returns are non-fatal and fire nothing. I think we can get a compile-time guarantee for the functions where every error is fatal, by constructingFatalErrorlike below?I think this could be done in a follow-up to reduce the review burden here? #35570
same as above https://github.com/bitcoin/bitcoin/pull/35646#discussion_r3541844030
same as above https://github.com/bitcoin/bitcoin/pull/35646#discussion_r3541844030
Yeah, I am mostly wondering aloud. Because currently, your patch will map both to
RPC_INTERNAL_ERRORinGenerateBlock. However, ingenerateblock, they are mapped toRPC_INTERNAL_ERRORorRPC_VERIFY_ERROR. And insubmitblock, they are mapped to a new imaginary/undocumented?"validation-error"string?That doesn't seem consistent or worthwhile. I'd say:
🐙 This pull request conflicts with the target branch and needs rebase.
Thanks, I agree. I went with the first option. Fatal/system failures are now represented separately as
kernel::FatalErrorand propagated viautil::Expected, whileBlockValidationStatenow only represents valid vs. invalid consensus validation.Also, the existing RPC behavior is preserved.
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased to master.
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased on master
Ready for review.
ConceptACK
4b183f4e07Reviewed again, generally looks good.
I've left some comments; most are rather minor, but there are some that should be checked. Therefore not upgrading my Concept A to a proper acknowledgement as of now.
This PR is related to #35570 (of mine), and my assessment is that both PR's stand on their own, but, despite an overlap, they also complement each other.
I uphold my comment from last review:
Isn't this an API change technically? If so, consider a release note for it.
Nit: typo: occured -> occurred
It's not clear to me that this does not introduce new error reasons. I have the impression that the Error case previously resulted in "inconclusive" (but I'm not sure). If that's the case, this needs to be changed.
Note: pre-change error from
ActivateBestChainwas ignored.Technically, in this commit
BlockValidationStatecan still beError, so this error check should be kept, removed in the later commit.It's not clear to me that the checks for the returned
statecan be omitted.I think there is a behavior change here in case of Error: previously
BlockCheckedwas called, and now it isn't.It's unclear why the 'empty' CBlock parameter was removed (it's also unclear why it was there in the first place).
Nit: no need to touch this, but can stay.
It seems to me, that the
(blockPos.IsNull())branch with the specific error return should be kept.I think there is a behavior change here: in case of error from
AcceptBlockpreviouslyBlockCheckedwas called before return, now it's not.Why not keeping the
NONFATAL_UNREACHABLEchecks?bitcoinkernel hasn't released yet.
Hmm, this means no block data is supplied and read from disk. So a null shared ptr not empty CBlock. Will add a comment mentioning this.
🚧 At least one of the CI tasks failed.
Task
macOS-cross to arm64: https://github.com/bitcoin/bitcoin/actions/runs/35190448674/job/105101625071LLM reason (✨ experimental): CI failed due to a C++ build error:
Chainstate().InvalidateBlockis declared to take a singleCBlockIndex*argument, butwallet_tests.cppcalls it with two arguments.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.
Concept ACK the earlier push
4b183f4e07Extracting the error-part of
BlockValidationStateby usingutil::Expectedis a promising direction.As the PRs stand today, something like this should be merged before #35570 is considered.
This PR would make review easier if broken up into more commits so that the transforms are applied to one function at a time.
See my suggestions branch: https://github.com/hodlinator/bitcoin/tree/pr/35646_piecemeal
nit: Cleaner diff if we retain the optional ending comma:
Could put the contents of fatal_error.h inside notifications_interface.h since it's fairly tightly coupled with it?
nit: Could take as sink-argument and move-construct to avoid some copying/heap activity.
nanonit: More honest/direct name?
Might as well return
FlatFilePosinstead of keeping it as an out-parameter:Why do this roundabout error handling rather than checking the return value of
ProcessNewBlock()? Is it a way of preserving the internal error string instead of getting the replaced one?Agree, would keep it as:
These renames from
dummytostateseem net-negative.Seems like naming becomes worse here.
Would prefer adding the test together with the commit adding the
FatalErrortype since the test is so tightly coupled to the existence of the type.nanonit: While
util::Expecteddoes have aE&& error() &&-overload, I think it's less surprising to do:thread https://github.com/bitcoin/bitcoin/pull/35646#discussion_r3959411618:
Noticed this too.
In light of this I don't understand how you could A-C-K this? I guess you mean Concept A-C-K of this as an RFC. Seems potentially dangerous but I'm not super-familiar with the signals.
Edit 2026-09-22: My view of this changed somewhat during the review (https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4034759979, https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4028466459). Deferring to the notification system to report fatal errors seems promising.
nit: Slightly simpler?
Good catch! Missed this one. Although we have hit a fatal error, so not signalling
BlockCheckedmight be okay. Then again some subscriber ofBlockCheckedmight be checkingstatefor errors... but that would show up in this PR when we remove error support fromstate.nit: Technically this would be more correct:
Could shorten to:
Same below.
nit:
stateis not technically used after this if-block, but would still be more correct to assign to it.nit: I think this code is important enough to keep calling out control flow a bit clearer:
If the error is truly fatal, like the disk being unusable, should we still trigger signals like this one?
Maybe it's not worth changing the validation interface further than removing error from
BlockValidationState.Could add a separate
FatalErrorsignal if we really deem it worth handling?Makes me wish
BlockValidationStateinstead ofIsValid()+IsInvalid()+IsError()just had oneGetMode()which all consumers would put inswitchblocks with exhaustive cases so that we could refactor with higher confidence.@DrahtBot note: As I've noticed during the discussion with @hodlinator , my previous concept A was interpreted as a plain ack. I think this is because there was no space between the "Concept" and "A", and there was a following commit ID. This was against my intention. I edit it to reflect this (insert a space). I should have noticed this, my mistake. Screenshots follow.
Sure, fixed in
github.com/maflcko/DrahtBot@7554887cad. You can edit it back, if you want.That was fast, thanks! 🙏
Done.
Correct. That was leftover from when
ProcessNewBlock()returned only bool. Since it now returnsutil::Expected, we can useres.error().message()directly andremove sc->m_error.🚧 At least one of the CI tasks failed.
Task
test ancestor commits: https://github.com/bitcoin/bitcoin/actions/runs/35315445149/job/105651757101LLM reason (✨ experimental): CTest failed because the
miner_teststest suite failed (ctestreturned non-zero exit status 8).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.
Thanks for the review @hodlinator and @optout21, I have split the commits more for easier review and addressed other comments:
Added the move-only
kernel::FatalErrortype and co-located it with Notifications.Changed
FatalError::Raise()to take ownership of the translated message and move the original string into the error.Renamed
WithMessage()toReplaceMessage().Converted block storage, flushing, block connection, block acceptance, chain activation, invalidation, precious-block handling, and block
submission to propagate fatal failures through
util::Expected.Changed
FindUndoPos()to returnFlatFilePosdirectly instead of using an output parameter.Simplified
util::Expectedchecks with value_or(false) where appropriate.Preserved explicit validation-state checks where the returned
BlockValidationStateremains meaningful, including submitheader.Removed the obsolete validation-state error mode and the kernel
INTERNAL_ERRORmode.Kept
BlockCheckedfor ordinary validation results and handled fatal errors through the direct return value and fatalError notification.Addressed the behavior change where fatal
AcceptBlockfailures no longer emitBlockChecked, peer block-source cleanup now happens directly whenProcessNewBlock()returns a fatal error.Other nits and typos.
Reviewed
22af5819cd, looks good!Left some comments.
Nit:
res.error()could be also logged.Nit: 'res.error()` could be included in the log.
Should check that it has value, and it is Valid.
Why remove this
asserthere, if it was introduced earlier? I can't see any relevant change in this commit.Nit: This always returns Valid state, could be
return {}to better reflect that, and make less use of the localstatevariable.This looks correct, but it could be a bit simplified and kept more similar to the original, if using
!state.IsValid()as condition (it corresponds tostate.IsInvalid() || state.IsError()).Full code snippet:
I think setting of
stateto*resin case of Invalid (res && res.IsInvalid()) is missing here,stateis being used without being affected by theDisconnectTipcall.(I realize this finding becomes irrelevant in a later commit.)
This is the only place where
ActivateBestChainreturns false. Maybe this could be turned into a FatalError (in a new commit), as it isAssume'd already. Then the return value could be changed tovoidfrombool, and that would simplify call sites (there are duplicate branches for false and error).I think this line can stay untouched, with
ret.value_or(false).Nit: This if occurs in a few places, would it make sense to factor it out somewhere?
Might take a while until I'm able to do a full review but I see you've incorporated my feedback from https://github.com/bitcoin/bitcoin/pull/35646#pullrequestreview-5210572199, thanks!
re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4069900161:
That is only true as long as the logic above doesn't change. Seems safest to use
stateas long as it exists.re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4069993828:
Couldn't we just remove the check for
IsInvalid()once we remove the Error-mode?re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4070346105:
Yes, returning
FatalErrorrather thanfalsehere seems like it would decrease incidental complexity.re https://github.com/bitcoin/bitcoin/pull/35646#discussion_r4070085310:
state.Error()is removed in a later commit so I would defer considerations of factoring it out until later.That's true, but it could be improved by making
statean if-local in the block whereCheckBlockis called, and the declaration of method-localstatevariable could be moved further down. That way there would be no chance to represent an non-Valid state at this point. (My guiding principle here is to reduce the scope of variables.)I think this is still a valid concern (in
22af5819cd).The
reasoncan end up here e.g. with "Failed to write undo data." or "Failed to read block.". I think previously it could only assume "inconclusive".Could you unresolve this?
I think this still applies! (in commit
22af5819cd)Could you unresolve?
Agree we need to be careful around this but I think the current approach has promise. Should call out that
BlockCheckedis only called for Valid/Invalid blocks now in the PR description.Correct. Thanks.
Done, Thanks.
Hmm. I think this can be also be applied the same to the
fJustCheckearly return and the final return, since those are also always valid at that point (invalid states are returned earlier) ?Good catch, restructured to
!state.IsValid()with the nestedIsInvalid()check, keepingLogErroras in the original.Agreed, dropped the
IsInvalid()check in "consensus: removeValidationStateerror mode", since!IsValid()is equivalent once Error mode is gone.Good catch, that was unintentional.
Thanks, done.
Agree!
OK, I retract this, feel free to Resolve.
Hmm,
ProcessNewBlock()getsbg_chainfromHistoricalChainstate()undercs_main, then releases the lock before callingbg_chain->ActivateBestChain(). If anotherProcessNewBlock()caller (msghand,submitblockRPC, or theloadblkthread) is inside the background chainstate'sActivateBestChain()at that moment, it can reach the snapshot base block.MaybeValidateSnapshot()then setsm_target_utxohash, and the first thread hits this check as soon as it getsm_chainstate_mutex. That window is narrow but real, making it aFatalErrorwould shut down nodes, and also that behavior change doesn't belong in a refactor PR ?That seems to be the case: after the genesis block early return there is a large portion of code where validation checks are made, and
statemay be set to Invalid, without immediate return. But at the end, there is a return on Invalid. So by the time execution gets to thefJustCheckearly return,statemust be Valid. I would put anAssume(state.IsValid())there to show and enforce. The early return and the final return can be{}then.But on a second thought I lean to leaving as-is, seems a bit risky. With this change the scope of the
statelocal variable would not be reduces, so I don't think it's worth it.Thanks for review @optout21. Addressed comments:
FatalErrormessage in theFindUndoPosandFindNextBlockPosfailure logs. Restored theassert(!res->IsNull())that was unintentionally dropped in the AcceptBlock commit.{}instead ofstateon paths where the state is always valid.MaybeUpdateMempoolForReorg(...)line is now untouched and keepsret.value_or(false).IsInvalid()check beforeInvalidBlockFound()inConnectTip()I agree with the full motivation but disagree (NACK) conceptually with using
util::Expected/std::expected.std::expected-style error handling trades runtime efficiency for runtime deterministic performance, which is a valid trade-off for systems with hard-realtime-requirements. I explained it on multiple occasions that for Bitcoin, runtime efficiency is more important than runtime deterministic performance, because we need IBD to be as fast as possible and new blocks are added on an extremely irregular cadence (approximately ten minutes on average is about as far away from a hard realtime system as you can possibly imagine). Hence, for Bitcoin, throwing exceptions is the more appropriate mechanism for error handling.And you received pushback every single time (e.g. https://github.com/bitcoin/bitcoin/pull/36101): exceptions are hard-to-predict invisible control flow, which is why many newer languages are moving away from them and towards explicit, value-based error handling to minimize surprises.
You're presenting your opinion as facts here, ignoring the project's specific needs and history.
I'm glad you're worried about this, so are we, it's why we've been working on this for years, we still have many open PRs optimizing this, you can help by reviewing them. That's also a good way to familiarize yourself with the project.
No, in mission-critical applications exceptions are often forbidden for good reason: they're hard to predict in exceptional (pun intended) circumstances.
🐙 This pull request conflicts with the target branch and needs rebase.
@purpleKarrot I watched the talk you recommended by Khalil Estell. My impression was that [Ee]xpected performs poorly primarily when the involved types are large/complex. Types being able to be moved like the proposed
FatalErrorprobably helps.I think sacrificing a tiny bit of efficiency in exchange for making error handling explicit at each level is the prudent approach in this part of the code.
Thanks @purpleKarrot. I agree that IBD throughput matters and that exceptions might provide a cheaper success path. However, deterministic execution isn’t the reason for choosing
util::Expectedhere. Its other benefit is making the distinction between a validation result and an operational failure explicit in the function’s interface. That is also part of the motivation for std::expected.Apart from that there is also existing control flow to preserve. For example,
ActivateBestChainStep()updates the mempool after a failed connection or disconnection before propagating the failure. An exception based implementation could preserve this too, but would require deliberately arranging cleanup and catch boundaries, including at the kernel API. Keeping explicit propagation makes that separation a more easier to review change. Also opened a PR in benchcoin to check the IBD performance.Rebased onto master (
e8e7e91a11) and resolved conflicts with #35675.My point is that this distinction is not explicit enough when both are communicated over the same channel.
When block validation returns a success value and throws on exception, client code will look like this:
Operational failure will take neither of the two branches.
But when validate returns an expected object,
operator boolwill just tell whether a fatal error occurred. If user code uses conditions likeres && res->IsValid(), it is very dangerous to have anelsebranch, because it may lead to the same situation that caused the 2013 chain split.And furthermore: If functions returning expected are not marked
noexcept, all clients now have to deal with two error handling mechanisms. But if the function is markednoexcept, it will terminate when an actual exception is thrown.Contrarian views have the potential to advance things. I've considered your point of view from different sides (including discussions in #36101).
My personal conclusion is that in this particular instance (and probably in many others as well) returns are preferable over exceptions, because the latter is more brittle and error prone in face of future code changes. I say this considering the criticality of the validation code, and also the losly organized nature of the project.
Your objection did raise my awareness of the cost aspects of passing objects as return values (structs, Expected, string fields, movability, etc.), but I dismiss your performance degradation point as minor in comparison with the risks of future mishandled errors.
Triggered by the return-vs-throw discussion (@purpleKarrot), I've done some microbenchmarking of the different error styles. Styles compared:
bool, withBlockValidationStateas parameterstate = {})BlockValidationStateutil::Expected<BlockValidationState, kernel::FatalError>BlockValidationState(valid or invalid), throw on fatal errorutil::Expected<void, std::variant<BlockValidationState, kernel::FatalError>>For 1&2 it is assumed that state can represent Error as well (not the case in this PR any more, but was before)
The benchmark does 50M iterations of a method call, which itself calls into other methods, with branch-out factor of 2 for 2 levels (1+2+4 = 7 total calls).
Every 1000th call returns invalid, every 1000th (not the same ones) return Error, the rest of the calls (998) return success.
The benchmarks is available at: https://github.com/optout21/bitcoin/blob/error-style-bench/src/bench/validation_state_error_handling.cpp
Sample results below.
Some conclusions:
stateparameter is not touched at all in the success branch. However, this is not very clean, as state from different methods can get mixed or overwritten, and we aim to make this cleaner (this PR, #35570)util::Expectedis generally not slower than out-param style. In fact in some earlier iteration it was even faster than the plain return (analysis found that the differences are due to the specifics of compiler branch optimizations).BlockValidationStateobject in success case at all. This can be achieved e.g. by instead of:`util::Expected<BlockValidationState, kernel::FatalError>using:
util::Expected<void, util::Expected<BlockValidationState, kernel::FatalError>>or
util::Expected<void, std::variant<BlockValidationState, kernel::FatalError>>This way the success case is optimized, and this is confirmed by the benchmark. @yuvicc, give it a thought. However, I think it's a micro-optimization not worth doing.
Sample benchmark results
Now that the mode is only binary, maybe consider simplifying to a
bool?Concept ACK
I like the
util::Expecteddirection, as I also asked for it in my review on #35570, so consider this a supporting vote for it. I do not like exceptions, and this error handling is much easier to understand and follow.Since this PR and my own #36326 ("kernel: Use typed errors for fatal and flush error notifications") overlap, there are a couple of things I would like to mention.
Adding a new type to the kernel here feels from my pov out of scope for this PR, separate from what it sets out to fix (the tri-state in
BlockValidationState), since that is already achievable with plain strings. Adding a type is an improvement on top of that, not a requirement for it, and has more implications than what has been already discussed in this conversation: it pulls more core-owned dependencies into the kernel, which I think goes against the general direction of thelibbitcoinkernelproject, fixes the shape of the errors inside the kernel and also broadens kernel maintenance surface. The kernel is consensus-critical code, so the less responsibility it carries, the easier it is to maintain. Those feel like implications that deserve their own discussion. I have been exploring how to improve the error type and remove dependencies from the kernel for a few months now, until finally proposing #36326. My focus was extractingbilingual_strand improving the kernel API, unrelated to this PR's behavior, but our work ended up colliding.I think the two ideas are not in conflict, and can actually be combined: the typed
kernel::FatalErrorvariant from #36326 could be the payloadutil::Expectedcarries here instead of a wrapped-string. Notifying and building the message are already two separate steps in #36326:fatalError()fires right at the origin with the typed data, no string needed at that point, and the translated message gets built afterwards, downstream, on the node side. So swapping the payload would not delay or otherwise change when the fatal notification fires, only what it carries. Worth discussing which PR keeps which part before either one merges, since right now both definekernel::FatalErrorwith the same name, different responsibilities, and incompatible shapes.Thanks @optout21 for putting this together! I reproduced it locally ( with standalone at -O2, pinned core, GCC 14.2 / Clang 18.1). Results in ns per top-level call (7 nested calls):
benchmark results
| Style | GCC | Clang | |-----------------------------|------|-------| | 0 baseline | 10.4 | 10.6 | | 1a out-param | 24.9 | 29.2 | | 1b in-out | 11.9 | 11.5 | | 2 return state | 24.0 | 23.6 | | 3 Expected | 26.4 | 32.4 | | 4 return + throw | 33.8 | 39.7 | | 5 Expected | 16.7 | 20.4 |The ordering matches yours one. The main cost is building a
BlockValidationState(two std::strings) on the success path, not the return mechanism. Agree that style no. 5 isn't worth it now. Moving Invalid into the error channel alongside FatalError would also blur the separation this PR aims for.Thanks for looking into it! I think we are in agreement.
The result return is not the hot-path of the chain validation, over-optimization doesn't worth it.
Earlier concerns remain unresolved; see the full report for their current assessments.
🟠 Minor · Reorg disconnect flush failures no longer raise fatalError
Kernel clients that treat flush_error as non-fatal can miss the unrecoverable-error signal when a required reorg-disconnect flush fails.
Location:
src/validation.cpp:3288(head).🔵 Suggestion · Fatal-error callback comments omit flushError
ProcessNewBlock can return a FatalError after only flushError fires, contrary to comments that direct callers and kernel embedders solely to fatalError.
Location:
src/validation.h:1281(head).🔵 Suggestion · Fatal-submission tests miss submitblock's RPC error branch
The fixture only exercises BlockTemplateManager::SubmitBlock, so it does not protect submitblock's new RPC_VERIFY_ERROR result after a fatal failure, including one following a valid BlockChecked notification.
Location:
src/test/validation_block_tests.cpp:116(head).🔵 Suggestion · TestBlockValidity exposes an unreachable FatalError alternative
Keeping Expected for a currently impossible fatal outcome adds four unreachable caller branches and an unnecessary Mining::checkBlock error contract.
Location:
src/node/interfaces.cpp:1006(head).Review coverage was incomplete.
Reviewed:
ebe01e1c00fb· Full review report · Previous reportspermalink
🐙 This pull request conflicts with the target branch and needs rebase.
Can we please leave personal preference completely out of the discussion and make a decision based on technical merit? I have documented the risks of result-style error handling ("intermediate functions should not receive errors as values or through shared state that they can inspect, suppress, or turn into validation results. ... Each such handling point creates an opportunity for misuse") in https://github.com/bitcoin/bitcoin/pull/36101#issuecomment-6045777724 and made a direct connection to the 2013 chain split. As written there, I would welcome concrete technical arguments in favor of an alternative design. I hope we can reach consensus before more quality regressions are introduced into the codebase without a proper design goal.
@l0rinc, a 👎 is not what I consider a concrete technical argument.
What is the most catastrophic outcome we want to avoid?
I would suggest it's a runtime error influencing the consensus verdict. I agree with @purpleKarrot and @maflcko's earlier points that the current design still leaves room for this when results are flattened into a boolean, e.g.
bool ok{res && res->IsValid()}, where a fatal error silently becomes "invalid".@purpleKarrot I only meant to support the technical arguments already made in this thread, but I have looked into your objections and here is my reply.
I was not familiar with BIP50, but I took a look at the v0.7.2 code:
CDB::Readreturnedfalseboth for a missing key and for a BDB lock exhaustion, soFetchInputsreported a missing input and the block was marked invalid. The runtime error went through the same channel as the validation result.I do not think this example shows a problem with result-style error handling. The cause was that a runtime error and a validation result could not be told apart, not the mechanism used to return them. Today the coin lookup path is protected by
CCoinsViewErrorCatcher. However,M_ERRORstill keeps both outcomes in the same object and relies on every caller checkingIsError(). This PR separates invalid blocks from runtime errors even further, by giving each its own type.As @alexanderwiederin said, some callers still flatten the result into a bool, but none of them affect a consensus verdict. Where it matters, invalid blocks and runtime errors are already told apart: only invalid blocks are marked as such and only their peers are punished. The cases that flatten the result are in RPC, mining, the C API, or the block import loop, where it only updates a counter and a queue (LoadExternalBlockFile, his example).
The microbenchmarks by optout21, reproduced by yuvicc, show no performance cost for
util::Expectedcompared to throwing. On top of that, the error flow stays visible in each function signature, which makes it easier to follow and to maintain, as optout21, hodlinator, l0rinc and I also pointed out earlier in this thread.I understand your objection is really about the long-term shape of error handling in consensus code (#35904, #36101), but I do not think this PR needs to wait for that. That is a big (and controversial) decision that needs its own discussion, and this PR does not depend on it or commit to any direction. It only fixes a problem whose motivation you agreed with in your first comment, and there is no simple alternative to this PR (as mentioned in #35904, it would require a complex refactor as it not even decide that is the direction fo core). If a different approach is chosen in the future, changing this code then will take no more effort than changing the code as it is today. I think the net impact of this PR is positive in the short term, and neutral in case it is decided to change the approach in the future.
Thanks @arejula27, agreed that none of the current flattening sites affect the verdict.
My point is a bit stronger though: that property currently holds because reviewers checked each site, not because the interface enforces it.
I think #35646 and #36101 agree more than it seems: both say an invalid block is a result, not an error, and the 2013 split illustrates the failure both are guarding against. The disagreement for this PR is the mechanism for fatal errors.
I would suggest settling the mechanism discussion in #36101, which gives the project a consistent direction long term.
I've done another round of review (
7a6ced08c6), looks good. I was close to a-c-k-ing, but I found 2-3 potential behavior changes, and several nits. Happy to re-review once those are addressed.Include hygiene: Moving the implementation to the .cpp file could save an include here (
util/translation.h).Are we silently introducing new validation reason strings?
Nit: Reverse alphabetical order.
Unrelated change, omit it.
For robustness (against future changes)
return statewould be more appropriate here. If it's still Valid, it is the same as{}. If it's not Valid, it should have been checked already. If it's not valid and it has not been checked, that's a bug, and the value should not be swallowed.Applies for all the
return {}lines below.Nit:
this->could be dropped in the changed line.Nit:
this->could be dropped in the changed line.Behavior change: previously
BlockCheckedwas signaled uponError, now it isn't. Should be checked.This error branch should return (
return false), to prevent falling through to the Invalid case, which also does aFatalError.Important!
statehas to be set toErrorhere before returningfalse.Here an Error can cause a
falsereturn with a validstate!Nit:
return std::move(*res);Note:
stateis not used from here on, so this could be deleted. In fact, thestatelocal variable could be moved inside theforloop to reduce its scope.In the current version there is not way to trigger returning a
FatalError.ConnectBlock()is called withfJustCheck=true, which skips the merkle/witness checks that report corruption and skips writing undo data. I suggest changing the comment accordingly (but keeping theutil::Expectedreturn type).Why not
[[nodiscard]]here as on other methods? Also, the doc was not updated.ralph referenced this pull request2026-10-29 10:17:31 +00:00
Correct, nice catch. I think
reasonshould carry existing values (e.g.inconclusive) anddebugshould be carrying extra details?Rebased onto master (
ddea919649) and addressed review comments from @optout21.FatalError::RaiseFlush(). After the rebase, master's12f691cf28makesFlushStateToDisk()fail whenFlushChainstateBlockFile()fails. That path has already firedflushError(), notfatalError(). Wrapping it withRaise()would callAbortNode()a second time, and would report a flush failure as a different notification whose shutdown behavior depends onm_shutdown_on_fatal_error.Raise()/RaiseFlush()intokernel/notifications_interface.cppto drop theutil/translation.hinclude (comment).ConnectBlock()now returnsstateinstead of{}on success paths (comment).return std::move(*res);(comment).state = *res;inVerifyDB()and movedstateinto the loop (comment).TestBlockValidity()doc to say aFatalErroris currently never returned (comment).ActivateBestChainStep()now sets the Error state before returningfalse(comment).BlockCheckedfiring in the ConnectTip commit and moved its removal to theProcessNewBlock()commit, where it is documented ([comment](https://github.com/bitcoin/bitcoin/pull/35646#diDisconnectTip()fatal-error branch now returns instead of falling through to a secondFatalError([comment](https://github.com/bitcoin/bitcoin/pull/35646#di
InvalidateBlock()now sets the Error state instead of rlid state(comment).rpc/register.hinclude move[[nodiscard]]toProcessNewBlock()and updated(comment).reason = essage indebug`crACK
ebe01e1c00Continued the code review. I have not identified any serious issues, left 2 non-blocking comments.
Thanks for incorporating my earlier comments!
In case of error,
res.error().message()could be included in the error message.Even though currently this
assertis guaranteed to not be hit, anAssume()instead ofassertwould be more appropriate.🐙 This pull request conflicts with the target branch and needs rebase.