Skip to content

validation: improve block data I/O error handling in P2P paths - #35003

Open
furszy wants to merge 5 commits into
bitcoin:masterfrom
furszy:2026_abc_io_exception
Open

furszy wants to merge 5 commits into
bitcoin:masterfrom
furszy:2026_abc_io_exception

Conversation

@furszy

@furszy furszy commented Apr 4, 2026 •

Copy link
Copy Markdown
Member

Early note: the majority of this PR consists of test coverage. The changes per se are quite small, just the issue shows up in multiple paths in slightly different forms.

The goal of the PR is to ensure I/O errors are not silently ignored during validation or P2P message handling. In some cases, such as GETDATA or GETBLOCKTXN requests, errors can be swallowed, leaving the node unresponsive to the request without any action. In a harder to reach but more severe case, a swallowed error can leave the node alive but stuck, unable to process new blocks and advance the chain. Also, silently ignoring errors obviously makes problems harder to diagnose. So this PR seeks to improve all of that.

Currently, the same root cause, inability to access the blocks directory, can produce different behaviors depending on where it occurs:


  1. If it happens during block connection, inside AcceptBlock(), the error gets caught and triggers a fatal error graceful shutdown. This is the correct behavior.

  2. If it happens during block connection (due to the unguarded FlatFileSeq::Open -> fs::create_directories call), after AcceptBlock(), inside ActivateBestChain(), the error gets thrown and swallowed by the P2P general try-catch, leaving the node in a living but stuck state. Where ActivateBestChain() will always silently fail on any posterior block processing, retrying to active the failing block.

  3. If it happens during GETDATA request, the file system error gets swallowed by the message handling general try-catch, only logging a net-debug-level message.
The remote peer is not disconnected, nor the node aborts. It just silently ignores the request. This is different to a missing block data, which currently logs the error + disconnects the peer.

  4. If it happens during GETBLOCKTXN request, the file system error either gets swallowed by the message handling general try-catch or crashes the system via an assertion, depending on if the problem is at the blocks directory level or at the block data level, which is inconsistent.

  5. If it happens during GETCFILTERS request, the file system error gets swallowed by the message handling general try-catch.

  6. If this happens in any of the index functions, the node crashes.

So, this PR makes failure handling consistent and ensures the node never enters a stuck state due to a block I/O error. Changes:

  1. GETDATA now treats the issue in the same way as other I/O errors: it logs the error + disconnect the remote peer.
  2. GETBLOCKTXN now triggers a fatal error and graceful shutdown. The error here is stricter than in GETDATA because it can only access the last 10 blocks, which must be available for reorgs.
  3. ActivateBestChain() now triggers a fatal error and graceful shutdown when it happens. Fixing the silent stuck node state scenario.
  4. GETCFILTERS now logs the error through the expected path: "Failed to find block filter in index". A more descriptive error message can be added in a follow-up PR.
  5. The index-related functions now ignore the error instead of crashing the node. This matches how the code was written, as these paths were not expecting OpenFile to throw. Better error handling can be added in a follow-up PR.

Testing Note
Can reproduce the different behaviors that cause the stuck node scenario by running the second commit’s unit test 28af683b5dfdce88892e367b308857b94ec630fe or by manually introducing an exception in ConnectTip() (which occurs inside ActivateBestChain()). Previously, the thrown exception would have being caught by the general P2P try-catch and logged only at net-debug level, which most users do not have enabled, leaving the node alive but stuck, as subsequent block connections repeatedly attempt to process the failing block, throw the exception again, and get silently swallowed. Adding a functional test for this scenario is not possible due to the requirement of failing inside ActivateBestChain(), which always occurs after AcceptBlock(), which correctly captures the error.

Separate Note
There is another assertion scenario that we can move to graceful shutdown (fatal error) in the compact block relay that I haven't done here.

Extra Note
If want to see a similar error producing a crash, but in the wallet, go to #34176.

@DrahtBot

DrahtBot commented Apr 4, 2026 •

Copy link
Copy Markdown
Contributor

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.

Type Reviewers
Concept ACK pinheadmz
Approach NACK josibake
Stale ACK frankomosh, sedited, rkrux, w0xlt, l0rinc
User requested bot ignore maflcko

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:

  • #36946 (scripted-diff: [test] Add util/check.h includes for assertions by maflcko)
  • #36548 (net: serve MSG_BLOCK by stripping witnesses in place by l0rinc)
  • #36000 (validation: prefetch blocks while connecting by l0rinc)
  • #35731 (Indexes: Harden the flush-error notification invariant by arejula27)
  • #35139 (test: [NOMERGE,SKETCH] Add thread-safe fast-failing test macros by maflcko)

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

LLM Linter (✨ experimental)

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • src/test/flatfile_tests.cpp: FlatFileSeq seq(data_dir, "a", 100)

Possible places where comparison-specific test macros should replace generic comparisons:

  • src/test/flatfile_tests.cpp: BOOST_CHECK_THROW(seq.Allocate(...), fs::filesystem_error) → Prefer BOOST_CHECK_EXCEPTION with a predicate that checks the expected failure message, rather than only the exception type.

2026-11-03 21:13:23

@pinheadmz

Copy link
Copy Markdown
Member

concept ACK
Thanks for the thorough PR description! Definitely helps me to understand the code changes before even looking at them. Can also see its minimal changes with lots of test coverage, will review.

@frankomosh frankomosh 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.

tACK 72f7a67370255cab1bf0dfcf39920dd23a3c268b

Built from source. All new tests pass:

  • flatfile_tests: 9 cases, no errors
  • validation_chainstate_tests: 5 cases, no errors
  • blockmanager_tests: 8 cases, no errors
  • p2p_handle_io_errors.py: both scenarios pass

Also manually reverted the GETBLOCKTXN fix (commit ba034f4) by removing the fatalError call and replacing with a silent return. The functional test correctly caught this kind of mutation. the test expected the node to shut down, but the mutant node stayed alive, causing a timeout failure. Mutant killed by p2p_handle_io_errors.py. Unit tests did not detect this mutation. Also process_messages and process_message fuzz harnesses both passed without detecting the mutation, confirming the functional test is providing the critical oracle here.

Line 5915 in SendMessages has assert(ret) after a ReadBlock call in the compact block announcement path. I think this is the same pattern as the GETBLOCKTXN assert fixed in commit 4. I believe this is the "another assertion scenario in compact block relay" mentioned in the PR description. Is this planned as a follow-up? Happy to take it if so.

@DrahtBot
DrahtBot requested a review from pinheadmz April 8, 2026 04:45

@maflcko maflcko 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, left a test suggestion, which could make review easier

Comment thread test/functional/p2p_handle_io_errors.py Resolved
@furszy

furszy commented Apr 11, 2026

Copy link
Copy Markdown
Member Author

Line 5915 in SendMessages has assert(ret) after a ReadBlock call in the compact block announcement path. I think this is the same pattern as the GETBLOCKTXN assert fixed in commit 4. I believe this is the "another assertion scenario in compact block relay" mentioned in the PR description. Is this planned as a follow-up? Happy to take it if so.

Yes @frankomosh. All yours :).

@furszy
furszy force-pushed the 2026_abc_io_exception branch from 5a25f94 to fc86ae4 Compare April 11, 2026 22:23
Comment thread test/functional/p2p_handle_io_errors.py Outdated
block_hash = node.getblockhash(3) # Not in recent cache
with simulate_io_error(node.blocks_path):
# Bug: we currently swallow the GETDATA request, never reply to the other party, and log issue under debug-NET
with node.assert_debug_log(expected_msgs=["[ProcessMessages] [net] ProcessMessages(getdata, 37 bytes): Exception 'filesystem error"],

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Note: intentionally not checking for a specific filesystem error msg, since it slightly vary across OS. Specific msg doesn't matter, this first commit just proves the error is swallowed in master.

@furszy
furszy force-pushed the 2026_abc_io_exception branch from fc86ae4 to 825dfc2 Compare April 12, 2026 12:09

@maflcko maflcko 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.

Looks like the test fails on the second commit, or so?

Also, provided some more test nits. Feel free to ignore.

825dfc200520d503fec64346ed01a8b12ec8fa54~4 📭

Show signature

Signature:

untrusted comment: signature from minisign secret key on empty file; verify via: minisign -Vm "${path_to_any_empty_file}" -P RWTRmVTMeKV5noAMqVlsMugDDCyyTSbA3Re5AkUrhvLVln0tSaFWglOw -x "${path_to_this_whole_four_line_signature_blob}"
RUTRmVTMeKV5npGrKx1nqXCw5zeVHdtdYURB/KlyA/LMFgpNCs+SkW9a8N95d+U4AP1RJMi+krxU1A3Yux4bpwZNLvVBKy0wLgM=
trusted comment: 825dfc200520d503fec64346ed01a8b12ec8fa54~4 📭
HuyWCmP9dlHdaEd4PL2XkITSC+f4T6nxsowBmRtzkzVkthldhUIEhYd8dWE2Z+BGoWVYLPWjRRxIPvoLUhqCCg==

Comment thread test/functional/p2p_handle_io_errors.py Resolved
Comment thread test/functional/p2p_handle_io_errors.py Outdated
self.setup_clean_chain = True

def test_block_connect_on_broken_fs(self):
self.log.info("Test block connect on inaccessible filesystem")

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 in 75a8a957a5181a3cebfc9d3dd064330d52c51dbb:

From the pull description:

If it happens during block connection, after AcceptBlock(), inside ActivateBestChain(), the file system error gets thrown and swallowed by the P2P general try-catch, leaving the node in a living but stuck state. Where ActivateBestChain() will always silently fail on any posterior block processing, retrying to active the failing block.

You claim that a failure in ActivateBestChain will leave the node alive, but stuck. However, when writing a test for this, I found that it properly shut down:

diff --git a/test/functional/p2p_handle_io_errors.py b/test/functional/p2p_handle_io_errors.py
index 4438ad1dd5..4706dfebd4 100755
--- a/test/functional/p2p_handle_io_errors.py
+++ b/test/functional/p2p_handle_io_errors.py
@@ -14,2 +14,3 @@ from test_framework.blocktools import (
     create_block,
+    create_empty_fork,
 )
@@ -49,5 +50,6 @@ class P2PBlockIOErrorTest(BitcoinTestFramework):
         self.setup_clean_chain = True
+        self.extra_args = [['-fastprune']]
 
-    def test_block_connect_on_broken_fs(self):
-        self.log.info("Test block connect on inaccessible filesystem")
+    def test_block_accept_on_broken_fs(self):
+        self.log.info("Test block accept on inaccessible filesystem")
         node = self.nodes[0]
@@ -70,2 +72,24 @@ class P2PBlockIOErrorTest(BitcoinTestFramework):
 
+    def test_block_connect_on_broken_fs(self):
+        self.log.info("Test block connect on inaccessible filesystem")
+        node = self.nodes[0]
+        peer = node.add_p2p_connection(P2PInterface())
+        blocks = create_empty_fork(node, fork_length=2)
+        large_block = self.generatetodescriptor(node, 1, f"raw({'55'*100_000})")[0]
+        peer.send_and_ping(msg_block(blocks[0]))
+        (node.blocks_path / 'blk00002.dat').unlink()
+        node.getblock(large_block)
+
+        with node.assert_debug_log(expected_msgs=["ActivateBestChain failed (Failed to read block.)"]):
+            peer.send_without_ping(msg_block(blocks[1]))
+            peer.wait_for_disconnect()
+
+        node.wait_until_stopped(
+            expect_error=True,
+            expected_stderr=re.compile(r"fatal internal error"),
+        )
+
+        # Restart node for next test
+        self.start_node(0, extra_args=['-reindex'])
+
     def test_getdata_on_broken_fs(self):
@@ -125,2 +149,3 @@ class P2PBlockIOErrorTest(BitcoinTestFramework):
 
+        self.test_block_accept_on_broken_fs()
         self.test_block_connect_on_broken_fs()

I guess it could make sense to add the test?

Also, it could make sense to clarify that point 2 in the pull request description refers to a thrown exception, presumably only from create_directories, and does not refer to any IO error?

Just a nit, and up to you, if you want to keep this pull focussed only on the create_directories call, or be a more general io error handling improvement in P2P paths, with test coverage.

@furszy furszy Apr 13, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You claim that a failure in ActivateBestChain will leave the node alive, but stuck. However, when writing a test for this, I found that it properly shut down.

Yeah ok. Your test exercises a missing block file, not the inability to access the directory. If we want to replicate the stuck, the goal there should be to get the node stuck by making it throw inside the create_directories call.

I had a test early in this branch that reproduced the "throw inside ActivateBestChain" through the P2P path in a deterministic way (which is not easy due to AcceptBlock happening first). But I did not like that it relied on another bug in reconsiderblock to trigger this one.

Basically, the approach was to invalidate the tip, submit a fork, make the directory inaccessible, and then reconsider the block, which throws internally but resets the block validity flags (the operation is not atomically reverted upon failure). After that, sending any number of descendant blocks via P2P will be swallowed due to the inability to activate the very first block. But it was ugly to depend on reconsiderblock to trigger it.

I guess it could make sense to add the test?

Yes! for sure. Pulling it.

Also, it could make sense to clarify that point 2 in the pull request description refers to a thrown exception, presumably only from create_directories, and does not refer to any IO error?

Sure. Will do.

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.

I had a test early in this branch that reproduced the "throw inside ActivateBestChain" through the P2P path in a deterministic way (which is not easy due to AcceptBlock happening first). But I did not like that it relied on another bug in reconsiderblock to trigger this one.

Basically, the approach was to invalidate the tip, submit a fork, make the directory inaccessible, and then reconsider the block, which throws internally but resets the block validity flags (the operation is not atomically reverted upon failure). After that, sending any number of descendant blocks via P2P will be swallowed due to the inability to activate the very first block. But it was ugly to depend on reconsiderblock to trigger it.

Ah interesting. I presume the bug still exists after this pull requests, as the ReconsiderBlock function is not changed here? Just wondering, as the bug seems unrelated to the bug fixed in this pull request. Also, I agree that such a test may be too spicy to include here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I presume the bug still exists after this pull requests, as the ReconsiderBlock function is not changed here?

Would say it is partially fixed but haven't tried it. ReconsiderBlock internally calls ActivateBestChain, which triggers a fatal error after this PR, instead of throwing an exception. So it is a matter of whether we are flushing the block flags reset to disk prior to aborting or not. Because, if we do, the node would fail early on any following up startup.

Comment thread test/functional/p2p_handle_io_errors.py Resolved
Comment thread test/functional/p2p_handle_io_errors.py Resolved
@furszy

furszy commented Apr 13, 2026 •

Copy link
Copy Markdown
Member Author

Looks like the test fails on the second commit, or so?

It seems the assertion error message is libc-dependent.
Linux logs "Assertion `expr' failed" while MacOS logs "Assertion failed: (expr), ...".

Will make the wait_until_stopped expected error a bit more general and check for "Assertion" wording only. That is more than enough to check the crash reason.
The last commit makes it clear with the fatal error change anyway.

@furszy
furszy force-pushed the 2026_abc_io_exception branch from 825dfc2 to 476fc0f Compare April 13, 2026 16:10
@sedited

sedited commented Sep 20, 2026

Copy link
Copy Markdown
Contributor

@furszy @maflcko do you have suggestions on how to continue here? There are stale approvals, but I don't think the discussion was fully resolved. I'm still fine with patching this case.

@furszy

furszy commented Sep 20, 2026

Copy link
Copy Markdown
Member Author

@furszy @maflcko do you have suggestions on how to continue here? There are stale approvals, but I don't think the discussion was fully resolved. I'm still fine with patching this case.

I did not continue the discussion on the other PR to avoid blocking progress if others were happy with it. I'm generally not fan of nacking, while at the same time I disagree with the abrupt termination approach for the reasons stated there. I don't think it is safe to assume crashing at any point is harmless. And aborting from low-level objects/functions obscures it even more in my view, and could affect other running systems like the wallet that may not be affected.

I think we stalled here due to #36101 rather than any concrete drawback from this approach. Plus no one really wants to move AutoFile to throw exceptions at this point in time, as it is not clear the advantages we will get from it.

At least in my view, this PR seems the pragmatic approach, as it follows our current code structure, the AutoFile contract (file opening errors presented as AutoFile ::IsNull()), introduces lot of test coverage, and can easily evolve to any other error handling mechanism we decide to adopt in the future.

@maflcko

maflcko commented Sep 23, 2026

Copy link
Copy Markdown
Member

I'm still fine with patching this case.

Yeah, same. I think it is fine to patch. I don't care too much about the implementation details (exceptions vs return values), but I think the current blockers for me is explained in #35676 (comment): It introduces a regression for indexes, and I think it is unclear if people want to fully fix this class of problem (i.e. merge #35676 in some way or another, or if #35676 should be closed for some given rationale ...)

@w0xlt

w0xlt commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

One concern I see here is the behavior of getrawtransaction with -txindex: when the blocks directory is missing and cannot be recreated, it previously reported a filesystem error. With the new if (!read_only) guard, it instead reports that the transaction wasn’t found.

#35728 would address this regression as well as related issues already present on master. The CheckDiskSpace() issues also predate this PR, and #35676 proposes handling them by explicitly aborting. However, its overlapping changes to FlatFileSeq::Open() would need to be reconciled with the approach here.

@maflcko

maflcko commented Oct 9, 2026

Copy link
Copy Markdown
Member

Another point is that this is fixing the rare case (blocks on p2p are expected every ~10min or so), but the same i/o error is hit every ~5min via CheckDiskSpace. Of course, there is no need to include this in this pull here, but at least there should be agreement what the expected user outcome in the other case should be. See the discussion in #35676 (discussion can continue in that closed thread).

Add tests showing that block disk I/O failures triggered
through P2P requests are silently swallowed.

The idea is to simulate I/O errors by making the blocks directory
temporarily inaccessible while the node is running. This allows block
reads to fail when serving P2P requests.

Aside from the well behaving test cases, this covers a few cases
where the node mishandles the error:

- GETDATA: failures should be handled locally by disconnecting the
  peer and logging the error, without impacting node operation.

- GETBLOCKTXN: failures when accessing recent blocks violate our
  "last 10 blocks must always be available for reorgs" rule and
  must result in a fatal error, rather than being caught and only
  logged by the P2P message handling general try-catch.

- txindex/txospenderindex: getrawtransaction and gettxspendingprevout
  open the block file directly, so filesysteme exceptions leak out as
  a generic RPC error instead of being handled cleanly.

- GETCFILTERS: failures should be logged through the filter index read
  path and leave the node running, rather than being swallowed by the
  P2P messages general try-catch.

Co-authored-by: MarcoFalke <*~=`'#}+{/-|&$^[email protected]>
@furszy
furszy force-pushed the 2026_abc_io_exception branch 2 times, most recently from c7e2e11 to 881c642 Compare November 3, 2026 20:29
@DrahtBot

DrahtBot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task lint: https://github.com/bitcoin/bitcoin/actions/runs/41711678048/job/126181051799
LLM reason (✨ experimental): CI failed the lint check because src/test/util/common.cpp is missing a trailing newline.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@furszy

furszy commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

Rebased post #35728 merge. I presume we may be able to proceed now? but I may be wrong too.
re CheckDiskSpace: I think we can tackle it in a separate PR, and keep this one as is.

The callers of this function don't expect it to throw.

For example, when the blocks directory becomes inaccessible
(e.g. volume detach or permission changed), FlatFileSeq::Open's
call to fs::create_directories() throws filesystem_error. On the
block connection path, if this occurs during ActivateBestChain(),
just after AcceptBlock() the exception bypasses FatalError entirely.
It gets caught by ProcessMessage's general catch-all with only a
NET-level debug log, swallowing the error msg for any regular
user, and every subsequent block arrival retries the same failing
read, leaving the node looking healthy while the block processing
mechanism is stuck.
Cover the two ActivateBestChain paths that read data from
disk: ConnectTip (block connection) and DisconnectTip (reorg).

Simulate inaccessible block and undo files, ensure fatal error
and shutdown is triggered.
Verifies that BlockManager behaves the same way whether a block file is
missing or the blocks directory is inaccessible.

Reads (ReadBlock, ReadRawBlock, ReadBlockUndo) return false, writes
(WriteBlock, WriteBlockUndo) return null/false, and failures are logged.

The goal is consistent failure handling. Previously, missing block files
returned false and logged an error, while an inaccessible blocks directory
was throwing an exception.
…tdown

A failure here indicates a serious inconsistency or disk issue, and the
current behavior is to abort immediately, which is correct but not the best.
Replace assert with a fatal error so the node shuts down through the normal
shutdown path instead.

This does not change the outcome (the node still stops), but allows a more
controlled teardown, giving other components a chance to flush their state
even when a particular block (or the blocks dir) on disk is unreachable.
E.g. the blocks dir might be the only affected, the mempool might be ok,
and we don't want to lose such information.
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.

10 participants