mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 12:20:38 +00:00
validation: return block-file flush errors #35714
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!35714
Loading…
Reference in a new issue
No description provided.
Delete branch "l0rinc/flush-state-failure-boundary"
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?
Problem: When flushing block or undo data fails,
FlushStateToDisk()still writes block-index metadata and coins data, then advancesm_last_flushed_block.With a separate
-blocksdir, persistent failures there can leave metadata referring to block data that is not durable even when chainstate writes succeed.Fix: Return the flush error before those writes, leaving the last-flushed marker and on-disk coins tip unchanged in the failing call.
Later flushes can retry and write if they succeed, including during shutdown.
ConnectTip()andDisconnectTip()propagate the error before updating the chain tip, after applying the coins changes in memory.History:
m_last_flushed_blockto prevent persistent indexes from advancing past flushed chainstate. This fix keeps it at the last successful flush.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.
Concept ACK
I still have to dig into the code and the implications of this change (just did a quick review), but in the meantime: would it be worth adding a test case for the undo-file failure path as well? both the commit message and the error string mention block or undo files, but the test only injects a failure on blk*.dat.
Good question, thanks -
FlushBlockFile()returns false for either block or undo flush failures, see:github.com/bitcoin/bitcoin@e1a337ee96/src/node/blockstorage.cpp (L774-L786)Since this PR only changes how that shared result is handled, testing both failure sources separately would fit better in a lower-level
BlockManagertest.ACK
e1a337ee96This is a small change, closing a gap discussed at #34897 I built it and tested it locally. I tryied to play around it and I did not find anything wrong.
One small, non-blocking point: the comment
// FlushChainstateBlockFile() already emitted the flush-error notification.describes an invariant, but nothing checks it . It is true today only because everyfalsepath insideFlushBlockFile()/FlushUndoFile()callsflushError()first. Would be correct adding an assume to verify this behaviour is keep it in the future?:Also, I want to ask about something I found while testing, not sure if it is related to this PR.
FlushStateToDisk()does not check if shutdown was already requested before it starts. I wrote a test where a first flush fails and requests shutdown, then I fix the file and callFlushStateToDisk()again: it succeeds andm_last_flushed_blockmoves forward, even though shutdown was already requested before this second call. Is this expected? I think it may be needed for the final flush inShutdown()(init.cpp), but I am not 100% sure, so I wanted to ask before assuming it is fineI opened a follow-up PR https://github.com/bitcoin/bitcoin/pull/35731 i did while reviewing the PR with the intention to group this notify +
state.Error()behaviour into one helper, (making the invariant of the comment harder) and add more low-level tests like the ones you mentioned above.nit in
0f04fbee2f: The&&make this a bit harder to read and violate https://github.com/bitcoin/bitcoin/pull/35729It would be good to discuss the real-world consequences of this change a bit more:
As far as I understand one reason for the status quo is that even if an error would occur, and the data is not durable, there is a good chance of the fsync being done by the OS eventually if the failure is temporary - data is not necessarily lost, so we might as well flush the other state to avoid having to re-do the syncing. If the failure was permanent, the other write operations (chainstate etc.) would likely fail as well, so nothing gets out of sync in that scenario either.
However, one point for this change is that block data is often stored separately (
-blocksdiroption). In this case, it is quite possible that actually corruption occurs if theblocksdirfsync fails permanently, but flushes of the chainstate etc. all succeed, andBLOCK_HAVE_DATAis set in the blocktree db, while the actual block data is missing.So I am Concept ACK
flushedis tied to thestatebeing invalid, it makes more sense to test them in groups, see https://github.com/bitcoin/bitcoin/pull/35729#pullrequestreview-4715961548If you insist I can remove the
statevalidation here.Concept ACK (
e1a337ee96)The change is within
FlushStateToDisk, and changes how an error fromFlushChainstateBlockFileis handled -- ignored previously, returned upwards with the change.Build & unit tests verfied locally.
The effectiveness of the new test (i.e., it catches the error) is checked by manually reverting the change.
Analyis of call pattern of
FlushChainstateBlockFile: directly called in only one place, the one affected in this change.Indirectly it is used in several usecases:
It's hard to conceptually assess the high-level effects in all the use cases.
Reviewing the steps excluded with the early exit, the update of the
m_next_writeseems uneqivocal, it may have unintended consequences (left comment).LGTM, left some comments.
Unit test observation: Running all 781 unit tests, they all pass, but a single output line is printed on the output:
Error: A fatal internal error occurred, see debug.log for details: Flushing block file to disk failed. This is likely the result of an I/O error.This is noted as this is the only stdout printout from the whole unit test suite. It is emitted from the new unit test (
chainstate_flush_failure_boundary-> 2ns call toFlushStateToDisk->FlushChainstateBlockFile->FlushBlockFile.)Any chance to suppress this?
Why not simply
BOOST_CHECK(flushed); BOOST_CHECK(state.IsValid());?With this early exit, the update of
m_next_writebelow is also skipped. It looks like that may cause some unwanted side-effects, so maybe it should be kept (e.g. by storing the return value, skipping the steps to be skipped, and keeping theif (should_write || m_next_write == ...block).Why is the
LogWarningremoved? I could not convince myself that thefatalError()/state.Error()calls include the same logging. Is it possible to preserve the log line?At first I though that the added comments refers to the reason of removal of
LogWarning, but then I realized it explains the usage ofstate.Error()instead ofFatalError().Regarding the comment,
FlushChainstateBlockFileindeed callsKernelNotifications::flushErrorwhenever it returnsfalse, but this is handled across two levels (FlushUndoFile), which is a bit too brittle.Thanks for the review, took me a bit longer to react, I'm juggling a few open ones...
Good point, added
ASSERT_DEBUG_LOG, which suppresses the expected output and verifies the lower-level error message. It fixes it for me, can you please check it? Added you as coauthor.Yes, I could also do that, but that would assume that I find it likely that they will fail independently, and since I don't, I consider it just noise.
I don't think
m_next_writeshould advance after a failed write: the timer update was deliberately moved after the chainstate write in #30611. The lower layer has already requested shutdown, and the finalFORCE_FLUSHduring shutdown does not depend on the periodic deadline.The lower layer already reports the specific failure through
flushError()before returningfalse, so restoring this generic warning would duplicate the error. I clarified the comment to make that explicit, let me know if it helps.not important, but it looks like https://github.com/bitcoin/bitcoin/pull/35729 was merged, so it could make sense to follow the style used in
src/test/coinscachepair_tests.cpp. Or, if you really want to group them, wrap them in another pair of(). I just mention it to avoid a silent merge conflict with https://github.com/bitcoin/bitcoin/pull/35713 and avoid having to touch this line again after merge.I gave this exact line as a concrete example for why we shouldn't just blindly split these conditions https://github.com/bitcoin/bitcoin/pull/35729#pullrequestreview-4715961548
Why not fix https://github.com/bitcoin/bitcoin/pull/35713 instead?
Verified, no more output produced, thanks!
I see your argument about how unrolling is sub-optimal, but it's a weak one for me.
If you insist, the proper solution may be to create a new macro with 2 (or N) conditions,
BOOST_CHECK_ALL, that evaluates the conditions, and if one fails, prints the values of all. After moving away from BOOST it would be easy to add such a macro.Thanks, it makes sense.
Very good, thanks.
ACK
c42d7fe1cfConcluding my previous review. Reviewed, built and unit-tested locally. Also verified that without the behavior change, the new test fails.
1 minor finding · 3 previous findings
🟠 Minor
Flush failure leaves the coins tip ahead of the active chain
Location:
src/validation.cpp:2784(head).A local block- or undo-file I/O failure can leave chainstate inconsistent and trigger assertions on later processing; no production occurrence has been observed.
Details and suggested fix
If the
IF_NEEDEDflush inConnectTip()writes because the coins cache is critical or pruning is required, andFlushChainstateBlockFile()fails,ConnectTip()returns an error afterview.Flush()has merged the block intoCoinsTip(). It returns before removing the block’s conflicting mempool transactions or updatingm_chain.ActivateBestChainStep()treats this as a system error and callsMaybeUpdateMempoolForReorg(disconnectpool, false). If the mempool contains a transaction from the block, or one that conflicts with it, and that transaction spends a mature coinbase output, the filter reads the spent input fromCoinsTip()and hitsassert(!coin.IsSpent()).The tips also remain inconsistent for later processing. A subsequent
ActivateBestChain()on this chainstate retries the block and hitsassert(hashPrevBlock == view.GetBestBlock())inConnectBlock(); a reorg can hit the corresponding assertion inDisconnectTip().This path sends only
flushError, which applications may ignore.bitcoin-chainstatelogs the notification and continues callingProcessBlock(). In bitcoind, the notification requests shutdown, but anActivateBestChain()call can still run before threads are interrupted. At base, this failure was only logged andConnectTip()completed. The existingCheckDiskSpace()andruntime_errorreturns can cause the same divergence, but also sendfatalError; this change adds a trigger that sends onlyflushError.Keep
CoinsTip()andm_chaincoherent before returning the error, for example by completing the in-memory tip update when only the durability step failed. The trigger requires a local block- or undo-file I/O failure, and no production occurrence has been observed.Previous reports
Previous reports of the same concern:
90fd0f15b63e839f9fd81f53ce4fa6a08164283b. Last checked at12f691cf286ea9a020583d267b94efca102a4056.12f691cf286ea9a020583d267b94efca102a4056. Last checked at12f691cf286ea9a020583d267b94efca102a4056.Previous findings (3)
[Suggestion · still present] The flush-failure test does not check recovery on a later flush
The test does not verify that a later flush, including the shutdown flush, persists the pending state after the injected failure.
The injector deletes the block file and replaces it with a directory, and the test ends after the failed
FORCE_FLUSHcall. Recovery depends on the dirty block-index entries, file info, and coins remaining pending after the early return so a laterFlushStateToDisk()can write them. A change that drops this pending state would still pass the test.Rename the block file aside rather than deleting it, then restore it after the failure assertions. Retry
FlushStateToDisk(FlushStateMode::FORCE_FLUSH)with a freshBlockValidationState. Check that the retry succeeds and thatGetLastFlushedBlock(),CoinsDB().GetBestBlock(), and persistednHeightLastall advance tonew_tip. Keep the existing failure assertions.Location:
src/test/chainstate_write_tests.cpp:116(head).Previous reports of the same concern:
12f691cf286ea9a020583d267b94efca102a4056. Last checked at12f691cf286ea9a020583d267b94efca102a4056.12f691cf286ea9a020583d267b94efca102a4056. Last checked at12f691cf286ea9a020583d267b94efca102a4056.[Major · still present] A critical flush failure leaves CoinsTip ahead of the active chain
If the critical flush in
ConnectTipfails,view.Flush()has already merged the connected block intoCoinsTip, but the error return skipsremoveForBlock()andm_chain.SetTip().ActivateBestChainStep()then handles the system error by callingMaybeUpdateMempoolForReorg(disconnectpool, false). If the mempool contains a transaction spending a mature coinbase, that check accesses its now-spent input and hitsassert(!coin.IsSpent()). More generally, the failure leaves the in-memory coins and active-chain tips inconsistent. Roll back the in-memory changes before returning, or make the chainstate unusable and guard subsequent processing. This trigger requires a local block or undo I/O failure during a critical flush. The checked-inbitcoin-chainstateinput loop continues afterProcessBlockreturns false, but no concrete production trigger or affected caller was identified.Location:
src/validation.cpp:2784(head).First reported at
12f691cf286ea9a020583d267b94efca102a4056. Last checked at12f691cf286ea9a020583d267b94efca102a4056.[Major · still present] A failed prune flush can persist the pruned-state flag without committing pruning
When a flush also prunes files, the code writes the
prunedblockfilesflag before attempting the block/undo flush. If that flush continues to fail through the shutdown retry, the error return skipsWriteBlockIndexDB()andUnlinkPrunedFiles(). The flag is then recorded even though the persisted block-index metadata was not pruned. On restart, the flag causes startup to reject-prune=0unless the database is rebuilt with-reindex, although the failed flush did not commit the pruning operation. Defer writing the flag until the prune metadata is committed, or otherwise preserve a consistent retryable state.Location:
src/validation.cpp:2784(head).First reported at
12f691cf286ea9a020583d267b94efca102a4056. Last checked at12f691cf286ea9a020583d267b94efca102a4056.Resolved findings
[Suggestion · resolved] Assert that block-index metadata is not persisted after the failed flush
These assertions protect the flushed marker and coins DB tip, but they would also pass if FlushStateToDisk wrote block-index metadata before returning the flush error. Since mining the new block leaves block-index or block-file metadata pending for WriteBlockIndexDB, capture a relevant persisted metadata value before the injected failure and assert it remains unchanged afterward. That would cover the metadata boundary in addition to the coins and marker checks, without changing the expected failure behavior.
Location:
src/test/chainstate_write_tests.cpp:133(head).Fixed. First reported at
90fd0f15b63e839f9fd81f53ce4fa6a08164283b. Last checked at12f691cf286ea9a020583d267b94efca102a4056. The current test reads the persisted CBlockFileInfo for new_tip->nFile and asserts that nHeightLast is still at old_flushed's height. Mining the new block raised that value in memory and marked it dirty, so the check would fail if WriteBlockIndexDB ran before the early return. That covers the requested assertion on the metadata boundary.Review coverage was incomplete.
Reviewed:
12f691cf286e· Full review report · Previous reportstACK
90fd0f15b6I'm looking into pruning for the kernel (#35627), which would go through this flush path.
Added missed coverage found by AI review.
reACK
12f691cf28reACK
12f691cf28reACK
12f691cf28review ACK
12f691cf28👟Show signature
Signature:
Code review ACK
12f691cf28. Thanks for putting the test first, it makes the behavior change easy to verify.This reverses my suggestion from https://github.com/bitcoin/bitcoin/pull/27866#discussion_r1297313148 when that PR was trying to make the same change. But that suggestion was mainly based on not wanting to have an unjustified behavior change in a cleanup PR, and now there is a clear justification.
Left some comments below, but none blocking. I think this should be merged given all the review it's had so far.
In commit "test: characterize writes after flush failure" (
07d23eb755)Optional, could be a follow-up: it would be nice if the test also checked what happens on the next flush after this one fails.
With this PR, when the block file flush fails,
FlushStateToDisk()returns without writing the block index or the coins. That data stays in memory, so if the problem clears up before a laterFlushStateToDisk()call (say, the open failed because the node ran out of file descriptors), that call writes it. The last chance is normally the flush inShutdown(). If the problem doesn't clear up, the node stops at the last successful flush and catches up after a restart. The first case isn't tested right now.Moving the block file aside instead of deleting it lets the test put it back, flush again, and check that everything catches up to
new_tip:The diff is against the PR head. The retry checks pass with or without the fix (without it, the failing flush already wrote everything), so they could also go in the first commit.
Update: this is item 5 in the post-merge follow-ups list: https://github.com/bitcoin/bitcoin/pull/35714#pullrequestreview-5697890316
re: https://github.com/bitcoin/bitcoin/pull/35714#issuecomment-4983411974
In commit "validation: return block-file flush errors" (
12f691cf28)Yes, this seems expected and good. The node still shuts down, but if the problem has cleared by then, the shutdown flush can save what the failed flush skipped.
When the block file flush fails,
FlushStateToDisk()now returns without writing the block index or the coins, but that data stays in memory.flushError()requests shutdown, andShutdown()ininit.cppthen callsForceFlushStateToDisk()on each chainstate. If the problem has cleared by then (say, file descriptors released as connections close), that flush writes everything. That's what the PR description means by "Later flushes can retry and write if they succeed, including during shutdown."The flush doesn't check the interrupt before writing; it's checked by code that produces new state, like
ActivateBestChain(). Andm_last_flushed_blockadvancing on that flush is right: that flush succeeded, and with this PR the marker only moves on a successful flush.re: https://github.com/bitcoin/bitcoin/pull/35714#issuecomment-4983411974
In commit "validation: return block-file flush errors" (
12f691cf28)I'd leave out the
Assume(m_chainman.m_interrupt), because it would fire for kernel API users on an ordinary flush failure.The comment promises that the notification was sent, not that shutdown was requested. In the node,
flushError()does request shutdown, but in the kernel API it's just a user callback, and nothing sets the interrupt unless the application does. The node already keeps the two separate forfatalError()(m_shutdown_on_fatal_error).A better way to check the invariant is a test that a failed
FlushBlockFile()always callsflushError(), which #35731 adds.Update: this comes up in items 9 and 11 of the post-merge follow-ups list: https://github.com/bitcoin/bitcoin/pull/35714#pullrequestreview-5697890316
In commit "validation: return block-file flush errors" (
12f691cf28)Non-blocking: it would be nice if this comment also said why returning here is recoverable. Nothing in the code explains that the skipped writes are still pending in memory and can be written by a later flush. Maybe:
Update: this is item 6 in the post-merge follow-ups list: https://github.com/bitcoin/bitcoin/pull/35714#pullrequestreview-5697890316
In commit "validation: return block-file flush errors" (
12f691cf28)Note for reviewers: this doesn't add a new kind of failure for callers. To them a
falsereturn here looks like theCheckDiskSpace()failure a few lines up, which already returns before these writes.Since callers were my concern in https://github.com/bitcoin/bitcoin/pull/27866#discussion_r1297313148, here is what each one does:
DisconnectTip()andConnectTip()return false beforem_chain.SetTip()(connect, disconnect), after the block has already been applied toCoinsTip()(see the separate comment about that).ActivateBestChain()returns false. Its loop also stops onm_interrupt, which the node'sflushError()sets by requesting shutdown.AcceptBlock()ignores the result, with a comment saying the notification still fires.AcceptToMemoryPool()andProcessNewPackage()ignore it.ForceFlushStateToDisk(),PruneAndFlush()andPruneBlockFilesManual()log it.ResizeCoinsCaches()returns it toMaybeRebalanceCaches()andActivateSnapshot(), which ignore it.ForceFlushStateToDisk()and then readCoinsDB()(gettxoutsetinfo,scantxoutset,dumptxoutset) ignore it and can read a DB that is behind the tip, same as with the disk-space failure.MaybeValidateSnapshot()ignores it and then hashes the coins DB, which may be stale. It still returnsSTATS_FAILEDrather than marking the snapshot invalid, but only becauseSnapshotUTXOHashBreakpoint()throws once shutdown is requested, whichflushError()normally does. Not a problem for this PR. A follow-up could make it check the flush result and return early, so it doesn't depend on that. That would be a robustness cleanup, not a behavior change for the node. [Update: this is now item 10 in the post-merge follow-ups list.]re: https://github.com/bitcoin/bitcoin/pull/35714#discussion_r3741378587
Note: agree
m_next_writeshouldn't advance. But one minor side effect is the error can now be reported more than once.If the failed flush was triggered by the periodic timer or a large cache, that condition stays true. So later
PERIODICflushes (mostly from mempool acceptance) retry, fail, and callflushError()again, untilconnman->Interrupt()stops them. Before this PR the first attempt still wrote the state and advancedm_next_write, so the condition didn't stay true and there was only one report.The window is short and the node is shutting down anyway, so this seems ok.
In commit "validation: return block-file flush errors" (
12f691cf28)Note: one consequence of returning here that's easy to miss. When this happens inside
ConnectTip()orDisconnectTip(), the block has already been applied toCoinsTip()butm_chainisn't updated, so the coins tip and the chain tip disagree until shutdown.Neither
ActivateBestChain()nor mempool acceptance checks the interrupt first, so a transaction or block arriving before the network threads stop could hit the asserts inPreChecks()orConnectBlock(), and the node would abort instead of shutting down cleanly. I found this by reading the code and haven't tried to reproduce it.I don't think it should block this PR. It isn't corruption: the disk is still at the last successful flush, so the node recovers on restart the same way it would after a crash. And the
CheckDiskSpace()return above could already get into this state.For a follow-up, I think a better fix than adding interrupt checks to every path that assumes the coins tip matches the chain tip is to keep the in-memory state consistent. Memory and disk each need to be consistent on their own, but disk normally lags behind memory, and a failed flush only means it lags further. It shouldn't undo a change already made in memory. So I think
ConnectTip()andDisconnectTip()should ignore the flush result the wayAcceptBlock()does, since the error is already reported and the block really has been applied, and letActivateBestChain()stop on the interrupt as usual. Returning beforeSetTip()dates from when every block was written to disk before memory was updated; that stopped being true when flushing became periodic in #5241, but the early return stayed.Update: this is item 1 in the post-merge follow-ups list: https://github.com/bitcoin/bitcoin/pull/35714#pullrequestreview-5697890316
In commit "validation: return block-file flush errors" (
12f691cf28)Non-blocking, fine as a follow-up: if this early return happens during a prune flush and a later flush succeeds, the pruned block files are never deleted. They stay on disk until a reindex.
How it happens:
FindFilesToPrune()has already marked the files pruned in memory (PruneOneBlockFile()) before the block-file flush runs, andsetFilesToPruneis local to this call.FindFilesToPrune()skips files withnSize == 0, so nothing finds them again.Before this PR a block-file flush failure still unlinked them (the disk-space return above already had this gap).
It's only leaked disk space, not corruption. A fix could keep the pending set in a member that the next successful flush drains, or there could at least be a comment here noting the gap.
Update: this is item 7 in the post-merge follow-ups list: https://github.com/bitcoin/bitcoin/pull/35714#pullrequestreview-5697890316
In commit "validation: return block-file flush errors" (
12f691cf28)Non-blocking: this comment says "the fatal error notification inside FlushStateToDisk still fires", but with this PR a block file flush failure is reported through
flushError()instead. It would also be worth saying why ignoring the result is right. It's the same reasoning as theConnectTip()comment: don't confuse disk state with memory state.Update: this is item 6 in the post-merge follow-ups list: https://github.com/bitcoin/bitcoin/pull/35714#pullrequestreview-5697890316
Post-merge, here is a list of possible follow-ups, roughly in order of importance. It collects suggestions from the review comments above, mine and other reviewers', and from follow-up PRs. Items 1-3 can crash the node or leave a corrupt database on disk; I reproduced each with a unit test. The rest are smaller bugs, documentation and tests. Happy to review any of these.
ConnectTip()andDisconnectTip()should not return early on a flush failure after updatingCoinsTip(). Both apply the block toCoinsTip(), then return false on a flush error beforem_chain.SetTip()(disconnect, connect), so a disk error leaves the coins tip and the chain tip pointing at different blocks until shutdown.I checked this with a unit test: after a block file flush failure inside
ConnectTip(), submitting a transaction aborts on thePreChecks()assert, and creating a block template aborts on theConnectBlock()assert throughTestBlockValidity(). So a transaction orgetblocktemplatecall arriving before shutdown finishes can crash the node instead of letting it shut down cleanly.Returning false here treats a disk failure as if it were a memory failure. Memory and disk each need to be consistent on their own, and disk normally lags behind memory; a failed flush only means it lags further. These functions should ignore the flush result the way
AcceptBlock()does (the error is already reported throughflushError()), and letActivateBestChain()stop on the interrupt as usual. This predates the PR: theCheckDiskSpace()failure already returned from the same place. (original suggestion)A failed coins DB write can drop changes from memory, which can then leave a corrupt UTXO set on disk or crash the node.
CCoinsViewCache::Sync(), used for periodic and prune flushes, writes the cache to the database in several batches throughCCoinsViewDB::BatchWrite(). As each entry is added to a batch, the cache stops tracking it as needing a write (spent coins are erased, other entries marked clean), before the batch is committed.If a commit throws on a LevelDB write error, the changes in that batch are neither in the cache nor on disk, so the cache serves those spent coins from the database as unspent.
FlushStateToDisk()catches the error and requests shutdown, but the node keeps running until then. If a later flush at the same block succeeds, like the shutdown flush, it writes the remaining entries and records the database as consistent at that block without the lost batch. If a block is connected first, the flush aborts on an assert instead.I checked this with a unit test against a real on-disk
CCoinsViewDB, making one write fail partway through the flush. After the failedSync(), 29 of 200 coins spent in the new block were visible as unspent through the cache. The successful retry then recorded the database as consistent at the new block, with those 29 spent coins still in it. A restart would load that as a valid UTXO set.This predates the PR and is a different code path, but it breaks the same rule as item 1: a disk failure shouldn't change memory. Keeping entries dirty until their batch commits would fix it.
A failed block index write drops pending block index updates, which can leave a node that won't start without a reindex. As in item 2,
WriteBlockIndexDB()erasesm_dirty_fileinfoandm_dirty_blockindexbeforeWriteBatchSync()writes them. If that write throws, the block index and file info updates are no longer marked dirty, so a later flush skips them. The shutdown flush retry can succeed, and it then writes the coins on top of a block index on disk that is missing the updates.I checked this with a unit test: after a failed block index write and a successful retry, the coins DB's best block was the new tip but the new tip wasn't in the block index on disk. After a simulated restart, the node failed to start with "Error initializing block database" and needed a reindex.
Clearing the dirty sets only after the write succeeds would fix it.
Document how callers should use the
FlushStateToDisk()return value. The header comment only says "@returns true unless a system error occurred", which doesn't tell callers what a false return means for the state they hold. Items 1 and 8 are callers that misread it. Maybe something like:Tests that inject a failure at each write and check memory and disk afterwards. These would have caught items 1-3. Fail each write point in turn (block file, undo file, block index batch, each coins batch, including partial batches), then check that memory is still consistent (
CoinsTip()best block matchesm_chain.Tip(), the coins view matches the expected UTXO set) and that a restart, or a retry where that's allowed, ends up with the same state on disk as a run with no failure. A test-only option to fail the Nth database write, next to the existingsimulate_crash_ratio, would make the database cases easy.This also covers checking that a flush after a failed one succeeds and writes the skipped state, which isn't tested yet (original suggestion). @arejula27 mentioned writing a test like this locally, so it might fit in #35731.
Comments that say why the flush handling is right. The
AcceptBlock()comment still refers to "the fatal error notification", and describes ignoring the result as keeping callers from mistreating a flush failure. Ignoring the result is more than defensive: callers rely on the return value to know whether the block was stored and the block index updated. If a flush error could make it return false after those updates, the return value would stop meaning anything, which would be bad for composability even though no current caller would break. Maybe something like this (original suggestion):Separately, the new early return in
FlushStateToDisk()could say why returning is recoverable: the skipped writes stay in memory and a later flush, like the one at shutdown, can write them (original suggestion).Pruned block files aren't deleted if a prune flush fails and a later flush succeeds.
FindFilesToPrune()updates the in-memory file info before the flush, butsetFilesToPruneis a local, so the retry writes the index and never unlinks the files. The disk-space failure already had this gap; this PR adds the block-file failure as a second trigger. Keeping the pending set as a member thatUnlinkPrunedFiles()drains after the next successfulWriteBlockIndexDB()would fix it (original suggestion).I checked this with a unit test using
-prune=1 -fastprune: after a manual prune whose flush failed and a successful retry,blk00000.datwas still there, while the same prune with no failure deletes it.ActivateBestChain()returns false after its own periodic flush fails, even though the blocks it connected are fully applied in memory. The periodic flush returns false on failure, while stopping on the interrupt returns true, so callers report a failure for blocks that were connected: thegenerate*RPCs say "block not accepted", and the kernel API'sbtck_chainstate_manager_process_block()returns an error.This matches the documentation ("@returns true unless a system error occurred"), but it makes false ambiguous: callers can't tell a failed disk write from a block that couldn't be connected. The disk failure is already reported through
flushError(), so returning it again doesn't tell callers anything new. It should ignore the flush result likeAcceptBlock()and let the interrupt check end the loop, so that false only means a block couldn't be connected or disconnected. The documentation could then say that disk write failures are reported through the notifications instead.Document that kernel API users should stop validation after a flush or fatal error. Some validation code is only safe because the node's
flushError()andfatalError()handlers request shutdown, which sets the interrupt that validation checks. Kernel API users provide their own handlers, which may not request shutdown (earlier comment). Thebtck_NotifyFlushErrorand fatal error callbacks could document that the embedder should callbtck_context_interrupt()and stop submitting blocks and transactions after one fires, as the node does. That is simpler than making validation correct without it, which would add code the node doesn't need.MaybeValidateSnapshot()should check its flush result before hashing the coins DB. It callsForceFlushStateToDisk(), which only logs a failure, then hashesCoinsDB()(original comment). After a failed flush the DB is behind the tip, so the hash doesn't match and the snapshot chainstate is discarded as invalid. In the node this doesn't happen, because the shutdown request stops the hashing first, but that depends on the interrupt being set, not on anything this function checks.It should return early with a new
SnapshotCompletionResultwhen the flush fails, without discarding anything.LoadChainstate()callsMaybeValidateSnapshot()again at the next startup, so the check is retried.#35731 (@arejula27):
BlockManager-level tests and a notify-and-error helper. This covers the undo-file failure path @arejula27 asked about in this comment, which @l0rinc deferred to a lower-level test. It needs a rebase now that this is merged.RPCs that label a possibly stale coins DB with the in-memory tip.
scantxoutset(code) andCreateRolledBackUTXOSnapshot()(code) ignore theForceFlushStateToDisk()result, then readCoinsDB()and report it asm_chain.Tip(). After a failed flush the DB is at the previous flush. Minor, since the node is shutting down. If this isn't changed, the RPC help could warn that the result may lag the tip.Test style (@maflcko, @optout21). @maflcko suggested splitting the
&&in the test'sBOOST_CHECKto follow the style from #35729 and avoid a silent conflict with the Boost removal in #35713. @optout21 suggested aBOOST_CHECK_ALL-style macro that prints every value when one condition fails. Neither change was made; this only matters when #35713 is rebased.