Skip to content

validation: Ignore eventual error message from flushing in AcceptBlock - #35621

Merged
fanquake merged 1 commit into
bitcoin:masterfrom
optout21:2606-acceptblock-flush-error-ignore
Jul 6, 2026
Merged

fanquake merged 1 commit into
bitcoin:masterfrom
optout21:2606-acceptblock-flush-error-ignore

Conversation

@optout21

@optout21 optout21 commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Shortcut: see #35570 (comment) and #29700 (comment) .

Summary. At the end of ChainstateManager::AcceptBlock, the flushing of the chain state is initiated, but any potential failure from FlushStateToDisk is ignored. However, the error message might get propagated upwards. This change makes sure that both the error status and the error message are ignored, and adds an explanatory comment.

Related/background. The potential inconsistency between the return value and state returned from AcceptBlock was found during refactoring of the return of BlockValidationState in #35570. PR #29700 also touches this part by adding an explanatory comment, see #29700 (comment) . Splitting this minor behavior change out of #35570 makes that PR a clean (no-bahavior-change) refactor (this option was mentioned from the start, and also proposed by reviewers; see: #35570 (comment) ).

Motivation

Details. ChainstateManager::AcceptBlock is called for new block candidates. After checks and inclusion, it triggers flushing of the updated chain state to disk, by calling Chainstate::FlushStateToDisk. This method returns a bool and also takes & returns a BlockValidationState state. In case of error it returns false, and sets the state (to Error) and the reject reason string. At the call site, the return value is ignored, but for the state the state variable of AcceptBlock is provided, so an Error state may get propagated upwards in the call chain. A caller may react to this Error state.

Rationale for ignoring the flush error
The validation code flushes internally in several places, and mostly doesn't treat flush failures as errors returned to callers. Disk errors should never be mistreated as block validation failure. Note that the fatal error notification inside FlushStateToDisk still fires, so the node will shut down on unrecoverable flush errors regardless.

Relevant use case. AcceptBlock is called from the following methods (excluding test code):

  • ChainstateManager::ProcessNewBlock
  • Twice from ChainstateManager::LoadExternalBlockFile

Of these, in two places the state returned is not used at all. Only at validation.cpp:5056 is the state used.

            BlockValidationState state;
            if (AcceptBlock(pblock, state, nullptr, true, dbp, nullptr, true)) {
                nLoaded++;
            }
            if (state.IsError()) {
                break;
            }

Here a flush error may trigger the break, causing an early exit from the loop over blocks in a block file. Post-change the returned state will not be Error in a disk error case, so the break will not be hit here. However:

  • This branch is only called for blocks that are not known yet
  • In case of disk error case the fatal error handler will cause the node to shut down in any case.

Based on the above, the change in error return behavior is acceptable.

At the end of `ChainstateManager::AcceptBlock`, errors from
`FlushStateToDisk` (e.g. low disk space during pruning)
are ignored, so that callers can't mistreat a flush failure
as a block validation failure.
The internal fatal error notification still fires, so the node
will shut down on unrecoverable flush errors.
For state a dummy value is used, and the return value is ignored.
Previously the in-out `state` parameter was used, so it could
return a flush error message.

Co-authored-by: Ryan Ofsky <[email protected]>
@DrahtBot

DrahtBot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/35621.

Reviews

See the guideline for information on the review process.

Type Reviewers
ACK dergoegge, sedited, maflcko, ismaelsadeeq, l0rinc

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:

  • #35646 (RFC: Separate out runtime errors from BlockValidationState using util::Expected by yuvicc)
  • #29700 (kernel, refactor: return error status on all fatal errors by ryanofsky)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

@sedited

sedited commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@dergoegge dergoegge left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Code review ACK 256482a

@DrahtBot
DrahtBot requested a review from sedited July 1, 2026 13:31
@sedited

sedited commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

I'm not sure about the approach here. Are there cases where it is legitimate that we use the passed out BlockValidationState from FlushStateToDisk? If not, could we just remove it as an argument there?

@optout21

optout21 commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Are there cases where it is legitimate that we use the passed out BlockValidationState from FlushStateToDisk?

Valid question, but the answer is yes, there are. Here are some call chains where an error from FlushStateToDisk can make a difference:

  • ActivateBestChain -> ActivateBestChainStep -> ConnectTip -> FlushStateToDisk
  • ActivateBestChain -> ActivateBestChainStep -> DisconnectTip -> FlushStateToDisk
  • ActivateBestChain -> FlushStateToDisk
  • InvalidateBlock -> InvalidateBlock -> DisconnectTip -> FlushStateToDisk

(ActivateBestChain may be called by PreciousBlock, ProcessNewBlock, LoadExternalBlockFile, InvalidateBlock, ReconsiderBlock.)

@sedited sedited left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK 256482a

@maflcko

maflcko commented Jul 2, 2026

Copy link
Copy Markdown
Member

Here a flush error may trigger the break, causing an early exit from the loop over blocks in a block file. Post-change the returned state will not be Error in a disk error case, so the break will not be hit here. However:

* This branch is only called for blocks that are not known yet (so not in case of reindex)

* In case of disk error case the fatal error handler will cause the node to shut down in any case.

I am not sure this is fully correct.

A -reindex discards everything, including the block tree, no block is known, including the genesis block. Moreover, the initload thread will attempt to activate the genesis block, which init.cpp blocks on:

src/init.cpp:2075:     * Wait for genesis block to be processed.

So what happens depends on whether the genesis block resulted in a flush error or not:

  • (1) If the genesis block resulted in a flush error (maybe quota issues in the block dir?), then the program will fully deadlock, and would have to be killed with SIGKILL on current master.

The reason for the deadlock is the break you mention. When the break is hit, it will obviously skip activating the genesis block in initload.

  • (2) If another block resulted in a flush error, the init.cpp main thread was already unlocked, and the fatal flush error would trigger the break and then the interrupt on current master.

Now with this pull request:

  • (1) The deadlock is fixed, because the break is ignored, and the genesis block is activated.
  • (2) As you say, the break will not be hit, but the interrupt will result in an equivalent early return (without log of the result)

So my recommendation would be to correct the pull description and drop the word not (before in case of reindex).

Moreover, I wonder what the point of the break is, when it is sometimes ignored anyway. Moreover, the break is completely untested code, before and after this pull request.

Idk, but given that reviewers will have to understand what the break means here and that it is possibly useless, it could make sense to just remove it here?

lgtm ACK 256482a

@maflcko

maflcko commented Jul 2, 2026

Copy link
Copy Markdown
Member

Idk, but given that reviewers will have to understand what the break means here and that it is possibly useless, it could make sense to just remove it here?

off-topic: [trigger-warning]: To expand on this, the commit message in commit 78100ea by Claude is ai slop, because it claims that Error refers to block validation errors, but a quick glance at src/consensus/validation.h reveals that runtime errors are tracked separate from validation errors.

@optout21

optout21 commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor Author

The break in question can still be hit, as AcceptBlock can return false+Error, when WriteBlock fails (called before FlushStateToDisk). For this reason, I'm reluctant to remove the break in this PR. But i agree that it is untested.

For my statement on reindex: I may be wrong there. I based this on tests with starting bitcoind with -reindex, and my observation was that the if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) condition was not satisfied. I had to change the code (force pindex to nullptr) to force it into the loop and observe what happens when FlushStateToDisk/AcceptBlock returns a forced Error. I'm not sure of the semantics of this if (my guess was that this is active when loading a block from an external file that is already present in the current chain).

As I have no strong grounds, I have removed the "(so not in case of reindex)" mention from the PR description.

@ismaelsadeeq ismaelsadeeq left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Concept ACK

re #35621 (comment) and #35621 (comment)

I think it will be better if we accompany this with a test?

Comment thread src/validation.cpp
Comment on lines +4407 to +4408
BlockValidationState flush_state_ignore;
(void)ActiveChainstate().FlushStateToDisk(flush_state_ignore, FlushStateMode::NONE);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

As @sedited ? mentioned, this indicates a code smell: passing a dummy state means the API does not express the real intent. AcceptBlock() wants the
pruning/flush side effect and fatal notification, but does not want to report the result as block validation state.

A cleaner approach would be to expose a validation-state-free method for this path, e.g. MaybePruneBlockFiles(), that could be another small wrapper similar to PruneAndFlush() and ForceFlushStateToDisk(). Those still use a dummy state internally, but at least the call site reads as better.

More broadly, this indicates FlushStateToDisk() is doing too much. It could be split into smaller helpers that wrappers can compose, so callers do not need dummy block validation state.

Comment thread src/validation.cpp
Comment on lines +4404 to +4405
// The fatal error notification inside FlushStateToDisk still fires,
// so the node will shut down on unrecoverable flush errors regardless.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit:

Hmm, I think from @maflcko description of the deadlock issue on the reindex path #35621 (comment), requesting shutdown does not mean we shut down regardless.

Suggested change
// The fatal error notification inside FlushStateToDisk still fires,
// so the node will shut down on unrecoverable flush errors regardless.
// The fatal error notification inside FlushStateToDisk still fires, so
// unrecoverable flush errors requests node shutdown.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

heh, I think this pull request fixes the deadlock, so it seems fine to say "shut down", or "request shutdown". No strong opinion, either seems fine.

@maflcko

maflcko commented Jul 2, 2026

Copy link
Copy Markdown
Member

For my statement on reindex: I may be wrong there. I based this on tests with starting bitcoind with -reindex, and my observation was that the if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) condition was not satisfied.

Are you sure? Locally I can trivially trigger this. Also, refer to this diff:

diff --git a/src/validation.cpp b/src/validation.cpp
index 87cf646b8b..31c93dbc43 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -5041,3 +5042,4 @@ void ChainstateManager::LoadExternalBlockFile(
                     if (!pindex || (pindex->nStatus & BLOCK_HAVE_DATA) == 0) {
-                        // This block can be processed immediately; rewind to its start, read and deserialize it.
+                        std::cout << "// This block can be processed immediately; rewind to its start, read and deserialize it." << std::endl;
+                        assert(false);
                         blkdat.SetPos(nBlockPos);

Which yields:

$ ./bld-cmake/bin/bitcoin-qt -datadir=/tmp/regtest -regtest -reindex 
// This block can be processed immediately; rewind to its start, read and deserialize it.
bitcoin-qt: validation.cpp:5044: void ChainstateManager::LoadExternalBlockFile(AutoFile &, FlatFilePos *, std::multimap<uint256, FlatFilePos> *): Assertion `false' failed.

Of course if there are no block files, then there is nothing to reindex. Did you make sure that block files exist, before you try to reindex?

@optout21

optout21 commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

passing a dummy state means the API does not express the real intent (@ismaelsadeeq)

On a related note, among the methods returning BlockValidationState there are some that may return validation errors (Invalid, but not Error), some that may return runtime errors (Error, but not Invalid), and some that may return either error as well. It would be nice if this was reflected/enforced in the types used as well. ValidationState is based on the three-state ModeState enum (Valid, Invalid, Error). Having structs for validation-only and runtime-error-only would be cleaner. This would also be handy with the util::Expected approach, suggested in #35570 (#35570 (comment)).

@optout21

optout21 commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

Are you sure? Locally I can trivially trigger this. Also, refer to this diff:

Retested, and you are right, I'm observing what you described, not my previous observation (probably I managed to end up with some invalid state, after repeatedly trying to force errors).

I also tried with a forced error from FlushStateToDisk (patch below), and the break was triggered.
If I removed the break, the next break, after ActivateBestChain was hit, so the loop still exited after the first failing block.

diff
diff --git a/src/validation.cpp b/src/validation.cpp
index 5341c604c4..7468e7d71a 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -2719,6 +2719,8 @@ bool Chainstate::FlushStateToDisk(
 
     try {
     {
+        return FatalError(m_chainman.GetNotifications(), state, strprintf(_("FORCED ERROR")));
+
         bool fFlushForPrune = false;
 
         CoinsCacheSizeState cache_state = GetCoinsCacheSizeState();
@@ -5057,7 +5059,8 @@ void ChainstateManager::LoadExternalBlockFile(
                             nLoaded++;
                         }
                         if (state.IsError()) {
-                            break;
+                            std::cout << "BREAK1\n";
+                            //break;
                         }
                     } else if (hash != params.GetConsensus().hashGenesisBlock && pindex->nHeight % 1000 == 0) {
                         LogDebug(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), pindex->nHeight);
@@ -5074,6 +5077,7 @@ void ChainstateManager::LoadExternalBlockFile(
                 if (hash == params.GetConsensus().hashGenesisBlock && WITH_LOCK(::cs_main, return ActiveHeight()) == -1) {
                     BlockValidationState state;
                     if (!ActiveChainstate().ActivateBestChain(state, nullptr)) {
+                        std::cout << "BREAK2\n";
                         break;
                     }
                 }
@@ -5088,6 +5092,7 @@ void ChainstateManager::LoadExternalBlockFile(
                     // reliable for the purpose of pruning while importing.
                     if (auto result{ActivateBestChains()}; !result) {
                         LogDebug(BCLog::REINDEX, "%s\n", util::ErrorString(result).original);
+                        std::cout << "BREAK3\n";
                         break;
                     }
                 }

@ismaelsadeeq

Copy link
Copy Markdown
Member

re #35621 (comment)

I looked closely at the described deadlock at init's genesis wait, and it is still reachable after this fix
lthough not through the flush error anymore.

The "import stops before genesis activation while init waits for genesis" deadlock doesn't need the
state.IsError() break at all the time. During -reindex, it can be triggered by any shutdown request that lands after the main thread parks in the genesis wait and before the scan activates genesis: a Ctrl+C in that window, or a fatal
error that results in an interrupt makes the scan return at first or next check. The window is normally milliseconds (genesis is the first entry of blk00000.dat), but it grows
arbitrarily large if the file begins with blocks whose parents aren't known yet, since those pass through the
out-of-order path without activating anything.

This occur because during -reindex, the block index and chainstate are wiped, and LoadGenesisBlock()
at startup is skipped because it's gated on m_blockfiles_indexed:

if (chainman.m_blockman.m_blockfiles_indexed && !chainman.ActiveChainstate().LoadGenesisBlock()) {

With no chain tip, the main thread parks here until the import thread activates genesis:

bitcoin/src/init.cpp

Lines 2085 to 2090 in 0a1bbec

{
WAIT_LOCK(kernel_notifications.m_tip_block_mutex, lock);
kernel_notifications.m_tip_block_cv.wait(lock, [&]() EXCLUSIVE_LOCKS_REQUIRED(kernel_notifications.m_tip_block_mutex) {
return kernel_notifications.TipBlock() || ShutdownRequested(node);
});
}

A cv.wait(lock, pred) evaluates its predicate once on entry, and afterwards only when the cv is notified.

A shutdown request wakes nobody: the SIGINT/SIGTERM handler is (correctly) restricted to async-signal-safe
operations it sets a flag and writes a pipe byte, and cannot notify a condition variable:

bool SignalInterrupt::operator()()
{
#ifdef WIN32
std::unique_lock<std::mutex> lk(m_mutex);
m_flag = true;
m_cv.notify_one();
#else
// This must be reentrant and safe for calling in a signal handler, so using a condition variable is not safe.
// Make sure that the token is only written once even if multiple threads call this concurrently or in
// case of a reentrant signal.
if (!m_flag.exchange(true)) {
// Write an arbitrary byte to the write end of the pipe.
int res = m_pipe_w.TokenWrite('x');
if (res != 0) {
return false;
}
}
#endif
return true;
}

The same applies to a fatal error AbortNode() just trips the same flag.
The interrupted reindex then cancels the only wakeup. The import thread polls the flag and returns early,
skipping both the LoadGenesisBlock() fallback and ActivateBestChains():

chainman.LoadExternalBlockFile(file, &pos, &blocks_with_unknown_parent);
if (chainman.m_interrupt) {
LogInfo("Interrupt requested. Exit reindexing.");
return;
}
}
WITH_LOCK(::cs_main, chainman.m_blockman.m_block_tree_db->WriteReindexing(false));
chainman.m_blockman.m_blockfiles_indexed = true;
LogInfo("Reindexing finished");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
chainman.ActiveChainstate().LoadGenesisBlock();

So blockTip() the notification the main thread sleeps on never fires:
kernel::InterruptResult KernelNotifications::blockTip(SynchronizationState state, const CBlockIndex& index, double verification_progress)
{
{
LOCK(m_tip_block_mutex);
Assume(index.GetBlockHash() != uint256::ZERO);
m_state.tip_block = index.GetBlockHash();
m_tip_block_cv.notify_all();
}

Interrupt() would notify the cv, but it only runs after AppInitMain returns, and the stuck thread is the
main thread inside AppInitMain:

bitcoin/src/init.cpp

Lines 294 to 295 in 0a1bbec

// Wake any threads that may be waiting for the tip to change.
if (node.notifications) WITH_LOCK(node.notifications->m_tip_block_mutex, node.notifications->m_tip_block_cv.notify_all());

ShutdownRequested() is true and the wait predicate would return true, but it is never re-evaluated. Further SIGINT/SIGTERM just re-set the flag. The node logs "Interrupt requested. Exit reindexing." and
can then only be killed with SIGKILL.

The reindex loop's early return is the one import path that bypasses it. I have a deterministic reproducer
(functional test ismaelsadeeq@87a803f), And a fix is attached that wakes the cv on the return of importBlocks so we can check for the ShutdownRequested output ismaelsadeeq@2747f67.

Because of the short interval required to trigger this, I had to add lots of dummy block headers to the genesis block file to be able to reproduce deterministically.

Before fix
 74b5b6ca377d209050f575786c38e9ead86ce49b39f9fc9e947ef04046fbe960, parent 0000000000000000000000000000000000000000000000000000000000000000 not known
2026-07-03T11:53:56.867815Z [initload] [node/blockstorage.cpp:1300] [ImportBlocks] Interrupt requested. Exit reindexing.
2026-07-03T11:53:56.871930Z [initload] [node/mempool_persist.cpp:77] [LoadMempool] Loading 0 mempool transactions from file...
2026-07-03T11:53:56.871935Z [initload] [node/mempool_persist.cpp:149] [LoadMempool] Imported mempool transactions from file: 0 succeeded, 0 failed, 0 expired, 0 already there, 0 waiting for initial broadcast
2026-07-03T11:53:56.871940Z [initload] [util/thread.cpp:21] [TraceThread] initload thread exit

❯ build/test/functional/feature_reindex_deadlock.py
2026-07-03T11:59:02.790731Z TestFramework (INFO): PRNG seed is: 6100894769303648655
2026-07-03T11:59:02.841112Z TestFramework (INFO): Initializing test directory /tmp/bitcoin_func_test_myujz0uz
2026-07-03T11:59:03.309559Z TestFramework (INFO): Replace blk00000.dat with 2000000 genesis-free out-of-order entries
2026-07-03T11:59:03.524207Z TestFramework (INFO): Request shutdown while the reindex scan is before genesis activation
2026-07-03T11:59:04.080428Z TestFramework (INFO): Check that the node terminates
2026-07-03T12:00:04.087747Z TestFramework.utils (ERROR): wait_until() failed. Predicate: ''''
        self.wait_until(lambda: self.is_node_stopped(**kwargs), timeout=timeout)
'''
2026-07-03T12:00:04.138216Z TestFramework (ERROR): Unexpected exception:
Traceback (most recent call last):
  File "/home/ismaelsadeeq/bitcoin-dev/bitcoin-core/bitcoin/build/test/functional/feature_reindex_deadlock.py", line 78, in run_test
    node.wait_until_stopped()
  File "/home/ismaelsadeeq/bitcoin-dev/bitcoin-core/bitcoin/test/functional/test_framework/test_node.py", line 528, in wait_until_stopped
    self.wait_until(lambda: self.is_node_stopped(**kwargs), timeout=timeout)
  File "/home/ismaelsadeeq/bitcoin-dev/bitcoin-core/bitcoin/test/functional/test_framework/test_node.py", line 862, in wait_until
    return wait_until_helper_internal(test_function, timeout=timeout, timeout_factor=self.timeout_factor, check_interval=check_interval)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/ismaelsadeeq/bitcoin-dev/bitcoin-core/bitcoin/test/functional/test_framework/util.py", line 450, in wait_until_helper_internal
    raise AssertionError("Predicate {} not true after {} seconds".format(predicate_source, timeout))
AssertionError: Predicate ''''
        self.wait_until(lambda: self.is_node_stopped(**kwargs), timeout=timeout)
''' not true after 60 seconds

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ismaelsadeeq/bitcoin-dev/bitcoin-core/bitcoin/test/functional/test_framework/test_framework.py", line 145, in main
    self.run_test()
  File "/home/ismaelsadeeq/bitcoin-dev/bitcoin-core/bitcoin/build/test/functional/feature_reindex_deadlock.py", line 81, in run_test
    raise AssertionError("node hung in init's genesis wait after shutdown was requested")
AssertionError: node hung in init's genesis wait after shutdown was requested
2026-07-03T12:00:04.189344Z TestFramework (INFO): Not stopping nodes as test failed. The dangling processes will be cleaned up later.
2026-07-03T12:00:04.189461Z TestFramework (WARNING): Not cleaning up dir /tmp/bitcoin_func_test_myujz0uz
2026-07-03T12:00:04.189495Z TestFramework (ERROR): Test failed. Test logging available at /tmp/bitcoin_func_test_myujz0uz/test_framework.log
2026-07-03T12:00:04.189575Z TestFramework (ERROR):
2026-07-03T12:00:04.189656Z TestFramework (ERROR): Hint: Call /home/ismaelsadeeq/bitcoin-dev/bitcoin-core/bitcoin/test/functional/combine_logs.py '/tmp/bitcoin_func_test_myujz0uz' to consolidate all logs
2026-07-03T12:00:04.189693Z TestFramework (ERROR):
2026-07-03T12:00:04.189716Z TestFramework (ERROR): If this failure happened unexpectedly or intermittently, please file a bug and provide a link or upload of the combined log.
2026-07-03T12:00:04.189767Z TestFramework (ERROR): https://github.com/bitcoin/bitcoin/issues
2026-07-03T12:00:04.189806Z TestFramework (ERROR):
After fix
❯ build/test/functional/feature_reindex_deadlock.py
2026-07-03T12:00:41.118370Z TestFramework (INFO): PRNG seed is: 8598874981728148931
2026-07-03T12:00:41.168752Z TestFramework (INFO): Initializing test directory /tmp/bitcoin_func_test_qr6uqzpu
2026-07-03T12:00:41.637280Z TestFramework (INFO): Replace blk00000.dat with 2000000 genesis-free out-of-order entries
2026-07-03T12:00:41.867916Z TestFramework (INFO): Request shutdown while the reindex scan is before genesis activation
2026-07-03T12:00:42.429017Z TestFramework (INFO): Check that the node terminates
2026-07-03T12:00:42.429280Z TestFramework (INFO): Check that a restart resumes the reindex and recovers genesis
2026-07-03T12:00:48.519849Z TestFramework (INFO): Stopping nodes
2026-07-03T12:00:48.721112Z TestFramework (INFO): Cleaning up /tmp/bitcoin_func_test_qr6uqzpu on exit
2026-07-03T12:00:48.721150Z TestFramework (INFO): Tests successful

@maflcko

maflcko commented Jul 3, 2026

Copy link
Copy Markdown
Member

The window is normally milliseconds (genesis is the first entry of blk00000.dat), but it grows
arbitrarily large if the file begins with blocks whose parents aren't known yet

Good catch, but I don't think having the genesis block not in the first spot in blk0.dat is possible, unless the file was maliciously crafted?

lgtm 2747f67 on the fix.

@maflcko

maflcko commented Jul 3, 2026

Copy link
Copy Markdown
Member

I also tried with a forced error from FlushStateToDisk (patch below), and the break was triggered.
If I removed the break, the next break, after ActivateBestChain was hit, so the loop still exited after the first failing block.

Interesting. Though, I still don't see the point of the break on Error. I presume any runtime error in validation must pass through FatalError, which triggers a shutdown, which leads to an early return.

Having the break here seems like a belt-and-suspenders for a case where an error is set, but it wasn't set by FatalError, which is a bug. Looks like Failed to find position to write new block to disk is such a possible bug (and obviously completely untested).

My recommendation would still be to remove this break and fix all the bugs, but fine if you want to leave if for a later pull (I've already acked this one).

The later two breaks should likely be removed for the same reason.

@ismaelsadeeq ismaelsadeeq left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

ACK 256482a

@l0rinc

l0rinc commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

lightly tested ACK 256482a

Reviewed the small change and skimmed the relevant discussion. I also checked it locally with a monkey-patched FlushStateToDisk failure: with the old call shape the forced error dirties the caller-visible BlockValidationState, while with this change AcceptBlock still returns true and the caller-visible state stays valid.

I did not go deep into the broader reindex/deadlock follow-ups, but this narrow fix looks correct to me. Good find, @optout21.

Test used to verify the fix
diff --git a/src/test/validation_chainstate_tests.cpp b/src/test/validation_chainstate_tests.cpp
index 141c67da4a..8a8a6c7acb 100644
--- a/src/test/validation_chainstate_tests.cpp
+++ b/src/test/validation_chainstate_tests.cpp
@@ -25,11 +25,13 @@

 #include <boost/test/unit_test.hpp>

+#include <atomic>
 #include <memory>
 #include <optional>
 #include <vector>

 class CTxMemPool;
+extern std::atomic_bool g_force_flush_state_to_disk_failure_once;

 BOOST_FIXTURE_TEST_SUITE(validation_chainstate_tests, ChainTestingSetup)

@@ -98,6 +100,27 @@ BOOST_FIXTURE_TEST_CASE(connect_tip_does_not_cache_inputs_on_failed_connect, Tes
     BOOST_CHECK(!chainstate.CoinsTip().HaveCoinInCache(outpoint));    // input not cached
 }

+BOOST_FIXTURE_TEST_CASE(acceptblock_ignores_final_flush_error_state, TestChain100Setup)
+{
+    ChainstateManager& chainman{*Assert(m_node.chainman)};
+    m_node.notifications->m_shutdown_on_fatal_error = false;
+
+    const auto block{std::make_shared<const CBlock>(CreateBlock({}, CScript{} << OP_TRUE))};
+
+    LOCK(cs_main);
+    BlockValidationState state;
+    CBlockIndex* pindex{nullptr};
+    bool new_block{false};
+    BOOST_REQUIRE(CheckBlock(*block, state, Params().GetConsensus()));
+
+    g_force_flush_state_to_disk_failure_once = true;
+    const bool accepted{chainman.AcceptBlock(block, state, &pindex, /*fRequested=*/true, /*dbp=*/nullptr, &new_block, /*min_pow_checked=*/true)};
+
+    BOOST_CHECK(accepted);
+    BOOST_CHECK(state.IsValid()); // Fails without the fix
+    BOOST_CHECK(new_block);
+}
+
 //! Test UpdateTip behavior for both active and background chainstates.
 //!
 //! When run on the background chainstate, UpdateTip should do a subset
diff --git a/src/validation.cpp b/src/validation.cpp
index 87cf646b8b..b84318ddb6 100644
--- a/src/validation.cpp
+++ b/src/validation.cpp
@@ -66,6 +66,7 @@
 #include <validationinterface.h>

 #include <algorithm>
+#include <atomic>
 #include <cassert>
 #include <chrono>
 #include <deque>
@@ -78,6 +79,8 @@
 #include <utility>

 using kernel::CCoinsStats;
+
+std::atomic_bool g_force_flush_state_to_disk_failure_once{false};
 using kernel::ChainstateRole;
 using kernel::CoinStatsHashType;
 using kernel::ComputeUTXOStats;
@@ -2711,6 +2714,9 @@ bool Chainstate::FlushStateToDisk(
 {
     LOCK(cs_main);
     assert(this->CanFlushToDisk());
+    if (mode == FlushStateMode::NONE && g_force_flush_state_to_disk_failure_once.exchange(false)) {
+        return FatalError(m_chainman.GetNotifications(), state, _("Forced FlushStateToDisk test error"));
+    }
     std::set<int> setFilesToPrune;
     bool full_flush_completed = false;

@optout21

optout21 commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

the described deadlock at init's genesis wait, and it is still reachable

Great job digging up this issue -- fortunately it's a low-probability low-impact. Do you plan to create a new PR with it? I wouldn't include in this one.

@optout21

optout21 commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

rfm?

@fanquake
fanquake merged commit bab0120 into bitcoin:master Jul 6, 2026
26 checks passed
sedited added a commit that referenced this pull request Jul 6, 2026
c1313b1 init: wake genesis wait after ImportBlocks() returns (ismaelsadeeq)

Pull request description:

  During startup with `-reindex`, the block index and chainstate are wiped, and
  the normal `LoadGenesisBlock()` startup path is skipped while block files are
  being indexed. The init thread can then wait for genesis to be processed via the
  tip-block condition variable.

  If shutdown is requested after the init thread enters that wait but before the
  import thread activates genesis, the reindex scan can return early without
  calling the later `LoadGenesisBlock()` fallback or `ActivateBestChains()`.
  Because no block tip is connected, the block-tip notification never fires. The
  wait predicate would accept `ShutdownRequested(node)`, but it is not evaluated
  again unless the condition variable is notified.

  Notify the tip-block condition variable after `ImportBlocks()` returns so the
  genesis wait can observe shutdown and exit cleanly.

  Described in detail #35621 (comment)

  The current test covers the path, but won't fail deterministically. You can use L0rinc suggested patch for a deterministic patch that demonstrate the deadlock on master #35652 (review)

ACKs for top commit:
  maflcko:
    review ACK c1313b1 🦁
  mzumsande:
    Code Review ACK [c1313b1](c1313b1)
  sedited:
    tACK c1313b1

Tree-SHA512: b17faaa2042882f2acebf688f4a28fd6bb11cc5d7f978991fe2bcba7a9df6ed82a0a2811f2e71a929189570a7926f148afdbeef5c1ca57a081e3bb914c2f6fe2
oleonardolima added a commit to oleonardolima/rust-bitcoinkernel that referenced this pull request Jul 9, 2026
…05fc7ab

81405fc7ab Merge bitcoin/bitcoin#35689: test: Inline incorrect check in `util_tests`
cd2a4bc510 test: Redeclare variable as signed in `util_tests`
6f1c56f03a Merge bitcoin/bitcoin#35670: net: optimize compact block extra tx iteration
e94fda8a40 Merge bitcoin/bitcoin#35685: doc: Archive 30.3 release notes
5223cf1795 Merge bitcoin/bitcoin#35616: refactor: Use u64 over size_t for all cache sizes to fix a 32-bit overflow
c0e91efdb3 Merge bitcoin/bitcoin#35295: validation: fetch block input prevouts in parallel during ConnectBlock
f0da26cfc8 Merge bitcoin/bitcoin#34997: p2p: Don't participate in addr relay with feelers
443179a9eb doc: Archive 30.3 release notes
fabafd91f1 refactor: Use u64 over size_t for all cache sizes to fix a 32-bit overflow
32941e1314 Merge bitcoin/bitcoin#35649: depends: move FreeBSD SDK handling to CI
f379d716b1 Merge bitcoin/bitcoin#35669: doc: archive release notes for v31.1
881bb7b355 Merge bitcoin/bitcoin#35673: refactor: Move LoadGenesisBlock to ChainstateManager
3f3e644beb Merge bitcoin/bitcoin#35678: private broadcast: define and use new RPC_LIMIT_EXCEEDED error code ( + other follow-ups)
e3b026bf56 Merge bitcoin/bitcoin#34020: mining: add getTransactions(ByWitnessID) IPC methods
62f9089343 Merge bitcoin/bitcoin#35386: doc: add an AI contribution policy
fa615bd163 refactor: Move LoadGenesisBlock to ChainstateManager
8ac222484c private broadcast: remove no-op [[nodiscard]]
191bdcba26 test: align test better with described scenario
7ad311be18 test: use BOOST_CHECK_EQUAL for PrivateBroadcast::AddResult
82a02a2a22 rpc: define and use new  RPC_LIMIT_EXCEEDED error code
a64df338e6 Merge bitcoin/bitcoin#35651: doc: Improve offline-signing-tutorial after 32489
4498fa5d5b Merge bitcoin/bitcoin#35406: private broadcast: limit outstanding txs to count of 10,000
ec5edcd72b Merge bitcoin/bitcoin#35661: Update libmultiprocess subtree to add `ThreadMap.makePool` method
ea67fea062 Merge bitcoin/bitcoin#35464: kernel: Add function for creating chainparams with a signet challenge
a7b5f23bb8 Merge bitcoin/bitcoin#35667: refactor: Use `NetworkErrorString` for macOS code in `netif.cpp`
69fc991791 Merge bitcoin/bitcoin#32606: p2p: Drop unsolicited CMPCTBLOCK from non-HB peer and when blocksonly
1a3cbf1bd2 net: optimize compact block extra tx iteration
bc33509ae2 Merge bitcoin/bitcoin#35650: doc: Add release notes for 32489 (exportwatchonlywallet RPC)
2b6e767d96 doc: archive release notes for v31.1
b0735336ee p2p: Don't participate in addr relay with feeler connections
302733fd96 Merge bitcoin/bitcoin#35652: init: fix reindex deadlock by waking cv after interrupt
c1313b199f init: wake genesis wait after ImportBlocks() returns
eccb04a321 refactor: Use `NetworkErrorString` for macOS code in `netif.cpp`
f79ecfd9c7 Merge bitcoin/bitcoin#35658: refactor: Drop unneeded `<sys/types.h>` include before `<ifaddrs.h>`
22ac4ad949 ci: ensure we use correct lld version in OpenBSD job
495f43f7b3 ci: FreeBSD 15.1
244739db9d depends: move FreeBSD SDK handling to CI
bab0120053 Merge bitcoin/bitcoin#35621: validation: Ignore eventual error message from flushing in AcceptBlock
02afa66169 Merge commit '6b0a907302364649dcaffeb0340b985f14141b4e' into pr/subtree-11
6b0a907302 Squashed 'src/ipc/libmultiprocess/' changes from 3edbe8f67c1..16bf05dea02
22c328d388 refactor: Drop unneeded `<sys/types.h>` include before `<ifaddrs.h>`
2063f02bd5 Merge bitcoin/bitcoin#35510: test: SOCKS5 proxy: expect that connection may be reset during SOCKS5 handshake or data forwarding
1360001f43 Merge bitcoin/bitcoin#34959: wallet: Enforce BDB btree levels and overflow item sizes
10ffef4b3b Merge bitcoin/bitcoin#35604: log: expose `-logratelimit` in normal help
b393985aa0 Merge bitcoin/bitcoin#35634: txospenderindex: use zero-byte entry values
1835f2fcbf Merge bitcoin/bitcoin#35653: fuzz: Remove `ConsumeUniValue`
9f3e427228 fuzz: Remove ConsumeUniValue
68cb7840d2 doc: improve offline-signing-tutorial after 32489
32ddfc92d9 Merge bitcoin/bitcoin#35599: doc: Add release notes for #33671 (getbalances nonmempool field)
f56804bcf5 Merge bitcoin/bitcoin#35640: ci: use a 8x instance over 16x for riscv job
239d6c5260 Merge bitcoin/bitcoin#35614: HTTPServer: Prevent race condition between worker thread and I/O thread
cddbad325d doc: Add release notes for 32489 (exportwatchonlywallet RPC)
0a1bbec688 Merge bitcoin/bitcoin#32489: wallet: Add `exportwatchonlywallet` RPC to export a watchonly version of a wallet
4a007126fb Merge bitcoin/bitcoin#35147: depends: Boost 1.91.0-1
31abaa264c doc: add an AI contribution policy
a15bdc0598 doc: update offline-signing-tutorial to use exportwatchonlywallet rpc
a388076401 test: Test for exportwatchonlywallet
d053e3e5c8 wallet, rpc: Add exportwatchonlywallet RPC
444878efef wallet: Add CWallet::ExportWatchOnly
f9273f01db wallet: Move listdescriptors retrieving from RPC to CWallet
a1c83789a7 wallet: Write new descriptor's cache in AddWalletDescriptor
1e996640e6 wallet: Use Descriptor::CanSelfExpand() in CanGetAddresses()
d2ee9227da descriptor: Add CanSelfExpand()
2990bd7735 Merge bitcoin/bitcoin#35118: fuzz: add ipc round-trip fuzz target
fb1d152c24 depends: Boost 1.91.0-1
ba48852f9e Merge bitcoin/bitcoin#35438: test: introduce NodeSigner, run feature_taproot.py without wallet compiled
47bbed052e ci: use true|false over "true|false"
9a25bc3989 ci: use a 8x instance over 16x
9871dc7ab4 Merge bitcoin/bitcoin#31425: CI: Add Riscv bare metal job
113402286e doc: add txospenderindex release note
ce06878288 index: shrink txospenderindex value markers
a99148d576 test kernel: Don't log on warnings change
5b4fd284f4 kernel: Generate a signet with a challenge
037ad77071 fuzz: add IPC round-trip target
a8823c0996 Merge bitcoin/bitcoin#35607: nanobench: fix performance counter buffer initialization
f26c15bdd2 Merge bitcoin/bitcoin#35397: ci: add OpenBSD Clang cross job
91586f701e test: introduce NodeSigner, run feature_taproot.py without wallet compiled
771200ca43 test: return full keypair from `getnewdestination` helper
4e29de719e private broadcast: add release note for limited cap
cbf8c107c1 Release cs_main between individual private tx re-attempts
5aea3d0373 private broadcast: limit outstanding txs to count of 10,000
dc282ff31d Merge bitcoin/bitcoin#35597: logging: More fully remove libevent log category
ec98037f7a Merge bitcoin/bitcoin#35615: fuzz: restore CreateSock in PCP targets
43d89bb6e1 Merge bitcoin/bitcoin#35610: bitcoin-util: Add netmagic command
e35c805489 Merge bitcoin/bitcoin#35129: test: add fuzz test for private broadcast
dc1c17c085 doc: add release notes
0e10937184 fuzz: add coins_view_stacked fuzz harness to test concurrent leveldb reads
ce610a6ff4 fuzz: update harnesses to cover CoinsViewOverlay::StartFetching
760fb22dc3 test: add unit tests for CoinsViewOverlay::StartFetching
d69a3b20de doc: update CoinsViewOverlay docstring to describe parallel fetching
ab2a379237 coins: fetch inputs in parallel
fdf283036a coins: add ready flag to InputToFetch
ede11b8314 validation: collect block inputs in CoinsViewOverlay before ConnectBlock
f82043af50 coins: introduce thread pool in CoinsViewOverlay
5bf1c32008 validation: add -prevoutfetchthreads configuration option
a318f43254 bitcoin-util: Add netmagic command
256482ab56 validation: In AcceptBlock, ignore flush result
3c76bd4356 Merge bitcoin/bitcoin#35603: build: QRencode cleanups
f595daf1dd test: ensure HTTPServer race condition is fixed
b98b10c072 test: introduce a worker thread in http socket error test
922b08d375 test: socket error handling in HTTPServer using ErrorSock mock socket
73da2a8a52 http: prevent race condition between worker thread and I/O thread
57b3bf8496 Merge bitcoin/bitcoin#35609: ci: Bump tsan config to ubuntu:26.04 with -U_FORTIFY_SOURCE
d64ea15824 ci: add openBSD cross CI job
5404b62074 depends: add openbsd_LDFLAGS
2a9e35d293 Merge bitcoin/bitcoin#35588: scripted-diff: Rename `Sock::{RECV,SEND,ERR}`
a0e5e30010 fuzz: restore CreateSock in PCP targets
41ceea400e scripted-diff: Rename `StatusLevel::{INFO,WARN,ERR}`
f395acdeee scripted-diff: Rename `Sock::{RECV,SEND,ERR}`
7a74f65293 Merge bitcoin/bitcoin#35536: fuzz: share a single mocked steady clock across FuzzedSock instances
e1290ce7f7 Merge bitcoin/bitcoin#35543: test: introduce ExtendedPrivateKey and ExtendedPublicKey classes
7ac25c9177 util, refactor: Rename local `ERR` in `Sock::Accept`
bbbbab86a8 ci: Bump tsan config to ubuntu:26.04 with -U_FORTIFY_SOURCE
095596ddf7 log: expose -logratelimit option
ea9afb61a1 Merge bitcoin/bitcoin#35602: doc: Clarify build docs about `pkgconf` / `pkg-config` requirements
672eedc46b Merge bitcoin/bitcoin#35220: fuzz: connman: strengthen assertions and extend coverage
0e5c718d8a Merge bitcoin/bitcoin#35506: test: ensure group data cluster pointers are live
b6b1d0653a nanobench: fix perf counter buffer init
93012d7ff9 Merge bitcoin/bitcoin#35601: wallet: remove experimental warning from send and sendall
829255c8be cmake: Remove `SelectLibraryConfigurations` from `FindQRencode` module
5c55606da9 depends: Remove unused `lib/pkgconfig` in `qrencode` package
402ba10b20 cmake: Drop optional `PkgConfig` use in `FindQRencode` module
8ebfff0f88 doc: add send RPC release note
fb8a103886 doc: Clarify build docs about `pkgconf` / `pkg-config` requirements
5884f5a4fa wallet: remove experimental warning from send RPCs
7b84e5106c Merge bitcoin/bitcoin#35595: ci: remove some packages from Chimera job
58560c281d ci: remove some packages from Chimera job
295ce6f45c Merge bitcoin/bitcoin#35576: test: raise `feature_reindex` RPC timeout
b36730a3ef  Add CI job for riscv bare metal
bfdbf513f6 Add CI job for producing a static bare metal binary
a9a1d92a1d build: Add option for building for bare metal envs
9b2ef81757 doc: add release notes for #33671 (getbalances nonmempool field)
633044f143 Merge bitcoin/bitcoin#35266: rpc, wallet: add an option to not load the wallet after migrating
d6269e2a90 Merge bitcoin/bitcoin#35594: fuzz: cover async chainstate compaction
3765b428d1 logging: More fully remove libevent log category
703a671fbc fuzz: compact coins view db during fuzzing
0868c85fd5 refactor: rename async coin compaction
6fa4132298 fuzz: share a single mocked steady clock across FuzzedSock instances
8791c4764c test: use ExtendedPrivateKey in wallet_taproot.py
89ceafafb9 test: use ExtendedPrivateKey in wallet_listdescriptors.py
bbfffcab58 test: use ExtendedPrivateKey in wallet_send.py
2ab6e590f7 test: use ExtendedPrivateKey in wallet_keypool.py
9e20118720 test: use ExtendedPrivateKey in wallet_fundrawtransaction.py
06af0cddbb test: use ExtendedPrivateKey in wallet_descriptor.py
4100fac20e test: use ExtendedPrivateKey in wallet_createwallet.py
ff3f6def9a test: use ExtendedPrivateKey in wallet_bumpfee.py
003f2a01f6 test: use ExtendedPrivateKey in feature_notifications.py
f988e6d6e6 test: use ExtendedPrivateKey in wallet_importdescriptors.py
0cdd817a82 add release note
517d37ce3e test: tests wallet migration with load_wallet disabled
b98dd63da7 rpc: Add load_wallet argument to migratewallet RPC
4acd063ba6 wallet: make loading the wallet after migrating optional
1a3cfdf1b7 fuzz: connman: cover AddLocalServices/RemoveLocalServices
c507fb3063 fuzz: connman: add outbound-bytes invariants
4a6fce43ea fuzz: connman: add AddNode/RemoveAddedNode invariants
9e6546c517 test: raise reindex mining RPC timeout
d2a03d50ac test: add extendedkey.py unit tests by using BIP32 test vectors
afdb378082 test: introduce ExtendedPrivateKey and ExtendedPublicKey classes
55e3a57f22 qa: Avoid UTXO reuse between test functions
9c5dd2926a p2p: Ignore CMPCTBLOCK from peer that hasn't sent SENDCMPCT
bf9884f4e5 p2p: make blocksonly nodes ignore CMPCTBLOCK messages
92cea63c71 test: (Un)solicited invalid cb -> get disconnected.
e845e26344 test: p2p: Nodes ignore unsolicited CMPCTBLOCK's
8313591715 p2p: Drop unsolicited CMPCTBLOCK from non-HB peer
44f377a71f refactor: test: Static assert_highbandwidth_states
25457a3272 test: Tighten getblocktxn checks in parallel cb reconstruction test.
2ee4fafa3f test: add fuzz test for private broadcast
08b7c61fc7 private broadcast: enforce sending to unique node ids
9a8ef9b0a3 test: SOCKS5 proxy: expect that connection may be reset during handshake
eb3208364a test: SOCKS5 proxy: expect that connection may be reset when forwarding
4dbaa7cc65 test: generalise byte_to_base58 utility function to allow more version types
df9eb72b12 test: ensure group data cluster pointers are live
a5859edef4 fuzz: connman: set m_local_services/m_use_addrman_outgoing/m_max_automatic_connections
4b84c9125a fuzz: connman: add network activity invariants
9784818442 mining: add getTransactionsByWitnessID() IPC method
d282ae6883 mining: add getTransactionsByTxID() IPC method
0d5e4d4712 test: restart node after IPC option override test
f16b3613cd ipc: Serialize null CTransactionRef as empty Data
0f466e1094 mempool: add lookup by witness hash
51dd90fb50 refactor: Merge announce_cmpct_block() defs into one
97d08d62ba refactor: store wallet names to MigrationResult
8a739a5510 build: allow ipc fuzz builds
b2de59d486 wallet, bdbro: Validate btree page levels
dc3a2b9c3b wallet, bdbro: Enforce overflow data lengths

git-subtree-dir: libbitcoinkernel-sys/bitcoin
git-subtree-split: 81405fc7abbd1889f3978b8924e7acbe12b3403b
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Jul 10, 2026
…e from flushing in AcceptBlock

2f22b57 validation: In AcceptBlock, ignore flush result (optout)

Pull request description:

  Shortcut: see bitcoin/bitcoin#35570 (comment) and bitcoin/bitcoin#29700 (comment) .

  **Summary.** At the end of `ChainstateManager::AcceptBlock`, the flushing of the chain state is initiated, but any potential failure from `FlushStateToDisk` is ignored. However, the error message might get propagated upwards. This change makes sure that both the error status and the error message are ignored, and adds an explanatory comment.

  **Related/background.** The potential inconsistency between the return value and state returned from `AcceptBlock`  was found during refactoring of the return of `BlockValidationState` in #35570. PR #29700 also touches this part by adding an explanatory comment, see bitcoin/bitcoin#29700 (comment) . Splitting this minor behavior change out of #35570 makes that PR a clean (no-bahavior-change) refactor (this option was mentioned from the start, and also proposed by reviewers; see: bitcoin/bitcoin#35570 (comment) ).

  **Motivation**

  - Get rid of the potential inconsistency between the return value (`true`) and state returned (`Error`). This facilitates refactoring of the error returns in #35570.
  - Make the ignoring clear and explicit, so there is no doubt about it being intentional or not.

  **Details.** `ChainstateManager::AcceptBlock` is called for new block candidates. After checks and inclusion, it triggers flushing of the updated chain state to disk, by calling `Chainstate::FlushStateToDisk`. This method returns a bool and also takes & returns a `BlockValidationState` state. In case of error it returns `false`, and sets the state (to `Error`) and the reject reason string. At the call site, the return value is ignored, but for the state the state variable of `AcceptBlock` is provided, so an Error state may get propagated upwards in the call chain. A caller may react to this Error state.

  **Rationale for ignoring the flush error**
  The validation code flushes internally in several places, and mostly doesn't treat flush failures as errors returned to callers. Disk errors should never be mistreated as block validation failure. Note that the fatal error notification inside `FlushStateToDisk` still fires, so the node will shut down on unrecoverable flush errors regardless.

  **Relevant use case.** `AcceptBlock` is called from the following methods (excluding test code):

  - `ChainstateManager::ProcessNewBlock`
  - Twice from `ChainstateManager::LoadExternalBlockFile`

  Of these, in two places the `state` returned is not used at all. Only at `validation.cpp:5056` is the state used.

  ```
              BlockValidationState state;
              if (AcceptBlock(pblock, state, nullptr, true, dbp, nullptr, true)) {
                  nLoaded++;
              }
              if (state.IsError()) {
                  break;
              }
  ```

  Here a flush error *may* trigger the `break`, causing an early exit from the loop over blocks in a block file. Post-change the returned state will not be `Error` in a disk error case, so the `break` will not be hit here. However:

  - This branch is only called for blocks that are not known yet
  - In case of disk error case the fatal error handler will cause the node to shut down in any case.

  Based on the above, the change in error return behavior is acceptable.

ACKs for top commit:
  maflcko:
    lgtm ACK 2f22b57
  l0rinc:
    lightly tested ACK 2f22b57
  dergoegge:
    Code review ACK 2f22b57
  sedited:
    ACK 2f22b57
  ismaelsadeeq:
    ACK 2f22b57

Tree-SHA512: c72747b5725739117d6061c3b3d5e6910bd06325a072b20708475c8e178a7ad8a6509b30cc8b547c92011a1267e4ad2feef31a992110072e5f37a4ac1f5c79d8
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Jul 10, 2026
…after interrupt

953d012 init: wake genesis wait after ImportBlocks() returns (ismaelsadeeq)

Pull request description:

  During startup with `-reindex`, the block index and chainstate are wiped, and
  the normal `LoadGenesisBlock()` startup path is skipped while block files are
  being indexed. The init thread can then wait for genesis to be processed via the
  tip-block condition variable.

  If shutdown is requested after the init thread enters that wait but before the
  import thread activates genesis, the reindex scan can return early without
  calling the later `LoadGenesisBlock()` fallback or `ActivateBestChains()`.
  Because no block tip is connected, the block-tip notification never fires. The
  wait predicate would accept `ShutdownRequested(node)`, but it is not evaluated
  again unless the condition variable is notified.

  Notify the tip-block condition variable after `ImportBlocks()` returns so the
  genesis wait can observe shutdown and exit cleanly.

  Described in detail bitcoin/bitcoin#35621 (comment)

  The current test covers the path, but won't fail deterministically. You can use L0rinc suggested patch for a deterministic patch that demonstrate the deadlock on master bitcoin/bitcoin#35652 (review)

ACKs for top commit:
  maflcko:
    review ACK 953d012 🦁
  mzumsande:
    Code Review ACK [953d012](bitcoin/bitcoin@953d012)
  sedited:
    tACK 953d012

Tree-SHA512: b17faaa2042882f2acebf688f4a28fd6bb11cc5d7f978991fe2bcba7a9df6ed82a0a2811f2e71a929189570a7926f148afdbeef5c1ca57a081e3bb914c2f6fe2
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Aug 19, 2026
…e from flushing in AcceptBlock

256482ab566360bd9d9ae0cb9c16e1a85c2de5ac validation: In AcceptBlock, ignore flush result (optout)

Pull request description:

  Shortcut: see bitcoin/bitcoin#35570 (comment) and bitcoin/bitcoin#29700 (comment) .

  **Summary.** At the end of `ChainstateManager::AcceptBlock`, the flushing of the chain state is initiated, but any potential failure from `FlushStateToDisk` is ignored. However, the error message might get propagated upwards. This change makes sure that both the error status and the error message are ignored, and adds an explanatory comment.

  **Related/background.** The potential inconsistency between the return value and state returned from `AcceptBlock`  was found during refactoring of the return of `BlockValidationState` in #35570. PR #29700 also touches this part by adding an explanatory comment, see bitcoin/bitcoin#29700 (comment) . Splitting this minor behavior change out of #35570 makes that PR a clean (no-bahavior-change) refactor (this option was mentioned from the start, and also proposed by reviewers; see: bitcoin/bitcoin#35570 (comment) ).

  **Motivation**

  - Get rid of the potential inconsistency between the return value (`true`) and state returned (`Error`). This facilitates refactoring of the error returns in #35570.
  - Make the ignoring clear and explicit, so there is no doubt about it being intentional or not.

  **Details.** `ChainstateManager::AcceptBlock` is called for new block candidates. After checks and inclusion, it triggers flushing of the updated chain state to disk, by calling `Chainstate::FlushStateToDisk`. This method returns a bool and also takes & returns a `BlockValidationState` state. In case of error it returns `false`, and sets the state (to `Error`) and the reject reason string. At the call site, the return value is ignored, but for the state the state variable of `AcceptBlock` is provided, so an Error state may get propagated upwards in the call chain. A caller may react to this Error state.

  **Rationale for ignoring the flush error**
  The validation code flushes internally in several places, and mostly doesn't treat flush failures as errors returned to callers. Disk errors should never be mistreated as block validation failure. Note that the fatal error notification inside `FlushStateToDisk` still fires, so the node will shut down on unrecoverable flush errors regardless.

  **Relevant use case.** `AcceptBlock` is called from the following methods (excluding test code):

  - `ChainstateManager::ProcessNewBlock`
  - Twice from `ChainstateManager::LoadExternalBlockFile`

  Of these, in two places the `state` returned is not used at all. Only at `validation.cpp:5056` is the state used.

  ```
              BlockValidationState state;
              if (AcceptBlock(pblock, state, nullptr, true, dbp, nullptr, true)) {
                  nLoaded++;
              }
              if (state.IsError()) {
                  break;
              }
  ```

  Here a flush error *may* trigger the `break`, causing an early exit from the loop over blocks in a block file. Post-change the returned state will not be `Error` in a disk error case, so the `break` will not be hit here. However:

  - This branch is only called for blocks that are not known yet
  - In case of disk error case the fatal error handler will cause the node to shut down in any case.

  Based on the above, the change in error return behavior is acceptable.

ACKs for top commit:
  maflcko:
    lgtm ACK 256482ab566360bd9d9ae0cb9c16e1a85c2de5ac
  l0rinc:
    lightly tested ACK 256482ab566360bd9d9ae0cb9c16e1a85c2de5ac
  dergoegge:
    Code review ACK 256482ab566360bd9d9ae0cb9c16e1a85c2de5ac
  sedited:
    ACK 256482ab566360bd9d9ae0cb9c16e1a85c2de5ac
  ismaelsadeeq:
    ACK 256482ab566360bd9d9ae0cb9c16e1a85c2de5ac

Tree-SHA512: c72747b5725739117d6061c3b3d5e6910bd06325a072b20708475c8e178a7ad8a6509b30cc8b547c92011a1267e4ad2feef31a992110072e5f37a4ac1f5c79d8
Kino1994 pushed a commit to Kino1994/bitcoin-full-history that referenced this pull request Aug 19, 2026
…after interrupt

c1313b199fe320c8d3e7ba01577378dfb85009cf init: wake genesis wait after ImportBlocks() returns (ismaelsadeeq)

Pull request description:

  During startup with `-reindex`, the block index and chainstate are wiped, and
  the normal `LoadGenesisBlock()` startup path is skipped while block files are
  being indexed. The init thread can then wait for genesis to be processed via the
  tip-block condition variable.

  If shutdown is requested after the init thread enters that wait but before the
  import thread activates genesis, the reindex scan can return early without
  calling the later `LoadGenesisBlock()` fallback or `ActivateBestChains()`.
  Because no block tip is connected, the block-tip notification never fires. The
  wait predicate would accept `ShutdownRequested(node)`, but it is not evaluated
  again unless the condition variable is notified.

  Notify the tip-block condition variable after `ImportBlocks()` returns so the
  genesis wait can observe shutdown and exit cleanly.

  Described in detail bitcoin/bitcoin#35621 (comment)

  The current test covers the path, but won't fail deterministically. You can use L0rinc suggested patch for a deterministic patch that demonstrate the deadlock on master bitcoin/bitcoin#35652 (review)

ACKs for top commit:
  maflcko:
    review ACK c1313b199fe320c8d3e7ba01577378dfb85009cf 🦁
  mzumsande:
    Code Review ACK [c1313b1](bitcoin/bitcoin@c1313b1)
  sedited:
    tACK c1313b199fe320c8d3e7ba01577378dfb85009cf

Tree-SHA512: b17faaa2042882f2acebf688f4a28fd6bb11cc5d7f978991fe2bcba7a9df6ed82a0a2811f2e71a929189570a7926f148afdbeef5c1ca57a081e3bb914c2f6fe2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants