streams: handle buffered write failures outside the destructor #36049

Open
l0rinc wants to merge 5 commits from l0rinc/streams-buffered-write-failure into master AGit
l0rinc commented 2026-08-20 22:06:29 +00:00 (Migrated from github.com)

Problem: Block and undo writers rely on the BufferedWriter destructor to write the last buffered bytes.
If the filesystem fills up, fwrite() can write fewer bytes than requested (my 1 TB benchmarking servers have been filling up, so I've been seeing these failures more often).
When this happens during the final flush, AutoFile::write_buffer() throws and the exception escapes the implicitly non-throwing destructor, invoking std::terminate before the node can report the write error and shut down normally.
Adding an explicit flush() alone would still leave the same bytes pending on failure, so the destructor would retry the write during unwinding.

I introduced this bug in #31551 when adding BufferedWriter.

Fix: Block and undo writers now flush explicitly. If serialization or flushing throws std::ios_base::failure, they call discard() to drop any pending bytes, log the error, close the file, and request shutdown.

BufferedWriter::flush() clears the pending byte count before calling write_buffer() and propagates any exception. Retrying would be unsafe because the stream may have obfuscated the bytes in place and a short write may already have put some of them on disk.
The destructor uses Assume to check that no bytes are pending before its fallback flush.

Manual write-error reproducer

Force AutoFile::write_buffer() to report a write failure even when fwrite() succeeds.

sed -i '' '/^.*AutoFile::write_buffer(/,/^}/s/!= src.size()/!= 0/' src/streams.cpp
cmake -B build && cmake --build build -j5 && build/bin/bitcoind -regtest -datadir="$(mktemp -d)"; echo "exit=$?"

Before this change, flushing from the destructor invokes std::terminate.

libc++abi: terminating due to uncaught exception of type std::__1::ios_base::failure: AutoFile::write_buffer: write failed: unspecified iostream_category error
zsh: abort      build/bin/bitcoind -regtest -datadir="$(mktemp -d)"
exit=134

With this change, bitcoind logs the write failure, completes normal shutdown, and exits with status 1.

Checking all blk files are present...
[error] Failed to write block file FlatFilePos(nFile=0, nPos=8): AutoFile::write_buffer: write failed: unspecified iostream_category error
...
Error: A fatal internal error occurred, see debug.log for details: Failed to write block.
[error] Writing genesis block to disk failed
[error] Error initializing block database
...
Shutdown done
exit=1
**Problem:** Block and undo writers rely on the `BufferedWriter` destructor to write the last buffered bytes. If the filesystem fills up, `fwrite()` can write fewer bytes than requested (my 1 TB benchmarking servers have been filling up, so I've been seeing these failures more often). When this happens during the final flush, `AutoFile::write_buffer()` throws and the exception escapes the implicitly non-throwing destructor, invoking `std::terminate` before the node can report the write error and shut down normally. Adding an explicit `flush()` alone would still leave the same bytes pending on failure, so the destructor would retry the write during unwinding. I introduced this bug in #31551 when adding `BufferedWriter`. **Fix:** Block and undo writers now flush explicitly. If serialization or flushing throws `std::ios_base::failure`, they call `discard()` to drop any pending bytes, log the error, close the file, and request shutdown. `BufferedWriter::flush()` clears the pending byte count before calling `write_buffer()` and propagates any exception. Retrying would be unsafe because the stream may have obfuscated the bytes in place and a short write may already have put some of them on disk. The destructor uses `Assume` to check that no bytes are pending before its fallback flush. <details> <summary>Manual write-error reproducer</summary> Force `AutoFile::write_buffer()` to report a write failure even when `fwrite()` succeeds. ```sh sed -i '' '/^.*AutoFile::write_buffer(/,/^}/s/!= src.size()/!= 0/' src/streams.cpp cmake -B build && cmake --build build -j5 && build/bin/bitcoind -regtest -datadir="$(mktemp -d)"; echo "exit=$?" ``` Before this change, flushing from the destructor invokes `std::terminate`. ```text libc++abi: terminating due to uncaught exception of type std::__1::ios_base::failure: AutoFile::write_buffer: write failed: unspecified iostream_category error zsh: abort build/bin/bitcoind -regtest -datadir="$(mktemp -d)" exit=134 ``` With this change, `bitcoind` logs the write failure, completes normal shutdown, and exits with status 1. ```text Checking all blk files are present... [error] Failed to write block file FlatFilePos(nFile=0, nPos=8): AutoFile::write_buffer: write failed: unspecified iostream_category error ... Error: A fatal internal error occurred, see debug.log for details: Failed to write block. [error] Writing genesis block to disk failed [error] Error initializing block database ... Shutdown done exit=1 ``` </details>
DrahtBot commented 2026-08-20 22:06:36 +00:00 (Migrated from github.com)

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
ACK ryanofsky, maflcko
Stale ACK sedited, w0xlt

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:

  • #36858 (refactor: break the blockstorage/validation circular dependency by pzafonte)
  • #36856 (kernel: add manual pruning by pzafonte)
  • #36738 (refactor: move block writes and pruning into BlockManager by pzafonte)
  • #36033 ([wip,nomerge,rfc] build: Require C++23 compiler 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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36049 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36049.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36049#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [ryanofsky](https://github.com/bitcoin/bitcoin/pull/36049#pullrequestreview-6044632592), [maflcko](https://github.com/bitcoin/bitcoin/pull/36049#issuecomment-7167709840) | | Stale ACK | [sedited](https://github.com/bitcoin/bitcoin/pull/36049#pullrequestreview-5798743901), [w0xlt](https://github.com/bitcoin/bitcoin/pull/36049#pullrequestreview-5847947370) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36858](https://github.com/bitcoin/bitcoin/pull/36858) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36858.svg"></sub> (refactor: break the blockstorage/validation circular dependency by pzafonte) * [#36856](https://github.com/bitcoin/bitcoin/pull/36856) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36856.svg"></sub> (kernel: add manual pruning by pzafonte) * [#36738](https://github.com/bitcoin/bitcoin/pull/36738) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36738.svg"></sub> (refactor: move block writes and pruning into BlockManager by pzafonte) * [#36033](https://github.com/bitcoin/bitcoin/pull/36033) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36033.svg"></sub> ([wip,nomerge,rfc] build: Require C++23 compiler 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. <!--5faf32d7da4f0f540f40219e4f7537a3-->
andrewtoth commented 2026-08-20 22:21:58 +00:00 (Migrated from github.com)

the exception invokes std::terminate instead of reaching normal storage-error handling.

Can you expand on why this is a problem? If there is a storage error, don't we have to crash anyways?

> the exception invokes std::terminate instead of reaching normal storage-error handling. Can you expand on why this is a problem? If there is a storage error, don't we have to crash anyways?
l0rinc commented 2026-08-20 22:35:20 +00:00 (Migrated from github.com)

If there is a storage error, don't we have to crash anyways?

Yes, the node still has to stop, but std::terminate bypasses the existing error handling.

Can you expand on why this is a problem?

Handling the exception lets the node report the storage error and run its normal shutdown cleanup.

> If there is a storage error, don't we have to crash anyways? Yes, the node still has to stop, but `std::terminate` bypasses the existing error handling. > Can you expand on why this is a problem? Handling the exception lets the node report the storage error and run its normal shutdown cleanup.
maflcko commented 2026-08-21 11:56:41 +00:00 (Migrated from github.com)

This reminds me of the other "exceptions can terminate" topics.

It would be good to find a code pattern that avoids this class of problem wholesale. It doesn't seem a great use of human (or LLM) review time to spend on such issues one-by-one. If we care about those issues, it would be better if the compiler or a clang-tidy analysis could find and prevent all of them.

This reminds me of the other "exceptions can terminate" topics. It would be good to find a code pattern that avoids this class of problem wholesale. It doesn't seem a great use of human (or LLM) review time to spend on such issues one-by-one. If we care about those issues, it would be better if the compiler or a clang-tidy analysis could find and prevent all of them.
w0xlt commented 2026-09-05 20:25:47 +00:00 (Migrated from github.com)

Concept ACK

I ran into the same bug while working in this area and implemented an alternative fix before finding this PR.

My version removes writes from the BufferedWriter destructor and requires explicit final flushing. It also adjusts AutoFile cleanup during exception unwinding and adds an exception handler for undo-write failures.

https://github.com/w0xlt/bitcoin/tree/streams/buffered-write-errors

Feel free to reuse anything you find useful.

Concept ACK I ran into the same bug while working in this area and implemented an alternative fix before finding this PR. My version removes writes from the `BufferedWriter` destructor and requires explicit final flushing. It also adjusts `AutoFile` cleanup during exception unwinding and adds an exception handler for undo-write failures. https://github.com/w0xlt/bitcoin/tree/streams/buffered-write-errors Feel free to reuse anything you find useful.
l0rinc commented 2026-09-23 22:31:08 +00:00 (Migrated from github.com)

Thanks @w0xlt, I used your explicit-flush and undo-write error-handling ideas and credited you as a co-author.

But I think forgetting to call flush() is a bigger practical risk than the rare exception from a destructor write, so I kept destructor flushing as a fallback. Block and undo writes now flush explicitly and handle failures, and a failed flush is no longer retried during exception unwinding.

Thanks @w0xlt, I used your explicit-flush and undo-write error-handling ideas and credited you as a co-author. But I think forgetting to call `flush()` is a bigger practical risk than the rare exception from a destructor write, so I kept destructor flushing as a fallback. Block and undo writes now flush explicitly and handle failures, and a failed flush is no longer retried during exception unwinding.
w0xlt (Migrated from github.com) reviewed 2026-09-24 05:22:32 +00:00
w0xlt (Migrated from github.com) left a comment
ACK cac9501d355d9853c17dcfa874d85c8e952cece0
First-time contributor

Earlier concerns remain unresolved; see the Run archive linked from the Review report.

🔵 Suggestion · Pending-byte discard() behavior is untested

The new failure test would still pass with a no-op discard(); no current block or undo serializer that throws with bytes pending was identified.

Location: src/test/streams_tests.cpp:755 (head).

🔵 Suggestion · Block and undo write-error handlers lack automated coverage

Automated write-failure coverage stops at BufferedWriter, leaving the new storage handlers' fatal notifications, failure returns, and undo-status update boundary untested.

Location: src/node/blockstorage.cpp:1180 (head).

🔵 Suggestion · The handler invariant and its cleanup arrive separately

Folding 1584299 into 1c33fa05 would present the handlers, destructor invariant, and abandonment mechanism together; no valid serialization input triggering the intermediate pending-byte case was identified.

Location: src/node/blockstorage.cpp:1016 (commit).

🔵 Suggestion · The no-retry safety rationale arrives after the behavior change

The flush() change in a4199b39 discards pending bytes before writing, but its data-safety rationale appears only in the later comment-only commit aade8e8.

Location: src/streams.h:705 (commit).

Review coverage was incomplete.


Reviewed: 1584299ae51d · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:2b20819f882b885f79f242c01722f54f2a55e27dcfa7d5e13701b4a0b5214248:c39fdacfa3b84799844a5e841c04997e3cd1142653dfad8e36dbb07c4b1e684b --> <!-- ralph-base:e211dd0186e9646167d063a16f0da88e5f72e05f --> <!-- ralph-head:1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd --> <!-- ralph-case:3ebfbff4c87ac505c6bb71b79c6b0850d86505471625304db701f800c4d78f64 --> Earlier concerns remain unresolved; see the Run archive linked from the Review report. **🔵 Suggestion · Pending-byte `discard()` behavior is untested** The new failure test would still pass with a no-op `discard()`; no current block or undo serializer that throws with bytes pending was identified. Location: [`src/test/streams_tests.cpp:755`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd/src/test/streams_tests.cpp#L755>) (head). **🔵 Suggestion · Block and undo write-error handlers lack automated coverage** Automated write-failure coverage stops at `BufferedWriter`, leaving the new storage handlers' fatal notifications, failure returns, and undo-status update boundary untested. Location: [`src/node/blockstorage.cpp:1180`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd/src/node/blockstorage.cpp#L1180>) (head). **🔵 Suggestion · The handler invariant and its cleanup arrive separately** Folding `1584299` into `1c33fa05` would present the handlers, destructor invariant, and abandonment mechanism together; no valid serialization input triggering the intermediate pending-byte case was identified. Location: src/node/blockstorage.cpp:1016 (commit). **🔵 Suggestion · The no-retry safety rationale arrives after the behavior change** The `flush()` change in `a4199b39` discards pending bytes before writing, but its data-safety rationale appears only in the later comment-only commit `aade8e8`. Location: src/streams.h:705 (commit). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`1584299ae51d`](<https://git.fish.foo/bitcoin/bitcoin/commit/1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd>) · [Review report](<https://review.fish.foo/report/36049-1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd-2773-7.html>) · [Previous reports](<https://review.fish.foo/traces/36049/>) [permalink](<https://review.fish.foo/report/36049-1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd-2773-7.html>)
sedited (Migrated from github.com) reviewed 2026-11-05 21:11:30 +00:00
sedited (Migrated from github.com) left a comment

LGTM

LGTM
sedited (Migrated from github.com) commented 2026-11-05 20:27:10 +00:00

I would prefer if we'd catch on std::runtime_error. For other exceptions, e.g. allocation failures, it might genuinely be better to immediately terminate. It would also match the exception behaviour in most of the code.

I would prefer if we'd catch on std::runtime_error. For other exceptions, e.g. allocation failures, it might genuinely be better to immediately terminate. It would also match the exception behaviour in most of the code.
l0rinc (Migrated from github.com) reviewed 2026-11-06 09:10:08 +00:00
l0rinc (Migrated from github.com) commented 2026-11-06 09:10:08 +00:00

Changed both handlers to catch std::runtime_error.
If you meant explicitly calling std::abort() here as well (maybe in a separate catch), please explain that in more detail, unless you just meant that other exceptions should fall through.

Changed both handlers to catch `std::runtime_error`. If you meant explicitly calling `std::abort()` here as well (maybe in a separate catch), please explain that in more detail, unless you just meant that other exceptions should fall through.
sedited (Migrated from github.com) approved these changes 2026-11-06 10:18:45 +00:00
sedited (Migrated from github.com) left a comment
ACK 6e17d090d18dbf1686b713bc285761a3aa042663
maflcko commented 2026-11-06 14:50:15 +00:00 (Migrated from github.com)

How is this different from AutoFile? Shouldn't this use the same bool m_was_written{false}; approach with flush+Assume+LogErr? Otherwise, we are just spending manual review on this and this will silently break again in the future?

How is this different from AutoFile? Shouldn't this use the same ` bool m_was_written{false};` approach with flush+Assume+LogErr? Otherwise, we are just spending manual review on this and this will silently break again in the future?
l0rinc commented 2026-11-06 20:43:26 +00:00 (Migrated from github.com)

How is this different from AutoFile?

BufferedWriter flushes through write_buffer() (which can throw in the destructor), while AutoFile::fclose() returns an error code.

Would you prefer keeping the explicit flushes, adding Assume(m_buf_pos == 0), and catching and logging fallback failures in the destructor, like this:

    ~BufferedWriter()
    {
        Assume(m_buf_pos == 0);
        try {
            flush();
        } catch (const std::runtime_error& e) {
            LogError("Failed to flush buffered writer: %s", e.what());
        }
    }
> How is this different from AutoFile? `BufferedWriter` flushes through `write_buffer()` (which can throw in the destructor), while `AutoFile::fclose()` returns an error code. Would you prefer keeping the explicit flushes, adding `Assume(m_buf_pos == 0)`, and catching and logging fallback failures in the destructor, like this: ```cpp ~BufferedWriter() { Assume(m_buf_pos == 0); try { flush(); } catch (const std::runtime_error& e) { LogError("Failed to flush buffered writer: %s", e.what()); } } ```
maflcko commented 2026-11-07 10:49:31 +00:00 (Migrated from github.com)

Ok, I see. So the difference is whether the dtor can throw. That is probably an internal implementation detail.

Though, the underlying issue seems to be that we want to notify the caller about a flush failure and that doesn't really work well via a dtor. So the fix for that is an explicit flush. However, if we want those explicit flushes, it should be enforced in the same way as it is done in AutoFile.

I think your suggested diff achieves that, so my preference would be to focus this pull on that. In theory, one could even drop the exception fixup from this pull afterward, and instead make flush non-throwing, so that m_buf_pos=0 can be forced in the dtor, so that a failed flush isn't immediately tried again. (If it failed to flush, re-trying it a single CPU cycle later isn't going to fix it anyway). Up to you, if you want to make flush non-throwing and instead use a nodiscard-result, but I think your suggested diff with the Assume would be good regardless.

Ok, I see. So the difference is whether the dtor can throw. That is probably an internal implementation detail. Though, the underlying issue seems to be that we want to notify the caller about a flush failure and that doesn't really work well via a dtor. So the fix for that is an explicit flush. However, if we want those explicit flushes, it should be enforced in the same way as it is done in AutoFile. I think your suggested diff achieves that, so my preference would be to focus this pull on that. In theory, one could even drop the exception fixup from this pull afterward, and instead make `flush` non-throwing, so that `m_buf_pos=0` can be forced in the dtor, so that a failed flush isn't immediately tried again. (If it failed to flush, re-trying it a single CPU cycle later isn't going to fix it anyway). Up to you, if you want to make `flush` non-throwing and instead use a nodiscard-result, but I think your suggested diff with the `Assume` would be good regardless.
l0rinc commented 2026-11-09 11:03:51 +00:00 (Migrated from github.com)

Thanks for the hints @maflcko, played with it a bit, now write_buffer is noexcept with a bool return value - and buffered flush failures log their cause and abort. Explicit final flushing is enforced with Assume, while destructor flushing remains as a prod fallback. This seems like a more holistic fix than before, let me know what you think.

Thanks for the hints @maflcko, played with it a bit, now `write_buffer` is `noexcept` with a `bool` return value - and buffered flush failures log their cause and abort. Explicit final flushing is enforced with `Assume`, while destructor flushing remains as a prod fallback. This seems like a more holistic fix than before, let me know what you think.
maflcko commented 2026-11-09 11:25:26 +00:00 (Migrated from github.com)

Ok, I see you now changed write_buffer to be nodiscard and flush to abort on error. This seems fine, but is now basically the behavior that existed before this pull (it also crashes).

My preference would be to make flush nodiscard (and possibly not even touch write_buffer/AutoFile here). This would be more consistent with the existing AutoFile fclose "flush" method.

Ok, I see you now changed `write_buffer` to be nodiscard and `flush` to abort on error. This seems fine, but is now basically the behavior that existed before this pull (it also crashes). My preference would be to make `flush` nodiscard (and possibly not even touch `write_buffer`/`AutoFile` here). This would be more consistent with the existing AutoFile `fclose` "flush" method.
l0rinc commented 2026-11-09 12:29:26 +00:00 (Migrated from github.com)

basically the behavior that existed before this pull (it also crashes)

We're always flushing explicitly outside the destructor now. It's a small difference, I know, mostly consistency and belts-and-suspenders hardening. These unlikely write/flush/read failure cases are still all over the place...
Reverted the AutoFile changes and updated flush() to return a checked result.

> basically the behavior that existed before this pull (it also crashes) We're always flushing explicitly outside the destructor now. It's a small difference, I know, mostly consistency and belts-and-suspenders hardening. These unlikely write/flush/read failure cases are still all over the place... Reverted the `AutoFile` changes and updated `flush()` to return a checked result.
maflcko (Migrated from github.com) reviewed 2026-11-09 14:23:54 +00:00
maflcko (Migrated from github.com) commented 2026-11-09 13:46:49 +00:00

nit in the third commit: This still crashes, like before this pull.

Also, the line immediately below will not crash. I think the code should be consistent and both places should do the same thing. Otherwise, it will be impossible to understand the goal of the code.

nit in the third commit: This still crashes, like before this pull. Also, the line immediately below will not crash. I think the code should be consistent and both places should do the same thing. Otherwise, it will be impossible to understand the goal of the code.
maflcko (Migrated from github.com) commented 2026-11-09 13:51:45 +00:00

basically the behavior that existed before this pull (it also crashes)

These unlikely write/flush/read failure cases are still all over the place...

Right, but I think if the code is touched for style reasons, it would be good to make the style consistent in at least two immediately following lines.

> > basically the behavior that existed before this pull (it also crashes) > These unlikely write/flush/read failure cases are still all over the place... Right, but I think if the code is touched for style reasons, it would be good to make the style consistent in at least two immediately following lines.
maflcko (Migrated from github.com) commented 2026-11-09 14:22:13 +00:00

I guess it may be easiest to restore the try-catch commit id from https://github.com/bitcoin/bitcoin/pull/36049#pullrequestreview-5798743901 , with the Assume(m_buf_pos == 0); nit addressed in the dtor

I guess it may be easiest to restore the try-catch commit id from https://github.com/bitcoin/bitcoin/pull/36049#pullrequestreview-5798743901 , with the ` Assume(m_buf_pos == 0);` nit addressed in the dtor
Lines 709-710
maflcko (Migrated from github.com) commented 2026-11-09 13:49:38 +00:00

nit in the third commit: 74c1322aee:

        Assume(m_buf_pos == 0); // Use explicit flush()
        Assert(flush());  // no-op, because flush was already called explicitly

Also, could remove the "destructor flushes" from the doxygen comment, because there is no need to document dead no-op code.

nit in the third commit: 74c1322aee3844e043bce4474e956631a20df7ff: ```cpp Assume(m_buf_pos == 0); // Use explicit flush() Assert(flush()); // no-op, because flush was already called explicitly ``` Also, could remove the "destructor flushes" from the doxygen comment, because there is no need to document dead no-op code.
maflcko (Migrated from github.com) commented 2026-11-09 14:10:16 +00:00

nit: Should document that a failed flush (returning false) will discard the buffer even though it wasn't written fully.

nit: Should document that a failed flush (returning false) will discard the buffer even though it wasn't written fully.
maflcko (Migrated from github.com) commented 2026-11-09 13:44:04 +00:00

nit in 30ac211a91: I feel like logging should stay out of this module and the caller can log, if it wants to.

nit in 30ac211a91603671fcdc8de757081a39224957c3: I feel like logging should stay out of this module and the caller can log, if it wants to.
maflcko (Migrated from github.com) commented 2026-11-09 13:28:18 +00:00

nit in the first commit, could use C++11 {} init?

nit in the first commit, could use C++11 {} init?
l0rinc (Migrated from github.com) reviewed 2026-11-09 20:01:08 +00:00
l0rinc (Migrated from github.com) left a comment

Restored the try/catch approach from the ACKed 6e17d09, following @maflcko's latest suggestion, and added the destructor’s Assume(m_buf_pos == 0) check. This means flush() isn't returning anymore (still throwing), with block and undo writers flushing explicitly and handling failures through their normal storage-error paths. It's not perfect, but it's better than before.

Restored the try/catch approach from the ACKed 6e17d09, following @maflcko's latest suggestion, and added the destructor’s `Assume(m_buf_pos == 0)` check. This means `flush()` isn't returning anymore (still throwing), with block and undo writers flushing explicitly and handling failures through their normal storage-error paths. It's not perfect, but it's better than before.
l0rinc (Migrated from github.com) commented 2026-11-09 17:01:45 +00:00

Done, thanks

Done, thanks
Lines 709-710
l0rinc (Migrated from github.com) commented 2026-11-09 17:02:56 +00:00

Did something similar

Did something similar
l0rinc (Migrated from github.com) commented 2026-11-09 17:03:03 +00:00

Done

Done
l0rinc (Migrated from github.com) commented 2026-11-09 17:01:50 +00:00

Moved

Moved
l0rinc (Migrated from github.com) commented 2026-11-09 17:00:26 +00:00

Inside BOOST_CHECK_* I usually avoid brace init - I could use parenthesis around if you insist.

Inside `BOOST_CHECK_*` I usually avoid brace init - I could use parenthesis around if you insist.
maflcko (Migrated from github.com) reviewed 2026-11-10 07:27:36 +00:00
maflcko (Migrated from github.com) commented 2026-11-10 07:27:36 +00:00

Ok, I see. Maybe assign the lambda to a var write_and_flush, which should also make the test code shroter?

Ok, I see. Maybe assign the lambda to a var `write_and_flush`, which should also make the test code shroter?
maflcko (Migrated from github.com) reviewed 2026-11-10 07:28:16 +00:00
maflcko (Migrated from github.com) commented 2026-11-10 07:28:16 +00:00

Are you sure you restored the old commit? I can't diff it and this line is still present in this pull:

$ grd 6e17d090d18dbf1686b713bc285761a3aa042663 74c1322aee3844e043bce4474e956631a20df7ff | tail -4
2:  6b2b0a2ebc < -:  ---------- streams: do not retry failed flushes
3:  6e17d090d1 < -:  ---------- blockstorage: handle buffered write failures
-:  ---------- > 2:  30ac211a91 streams: return checked buffered flush results
-:  ---------- > 3:  74c1322aee streams: require explicit final flushing
Are you sure you restored the old commit? I can't diff it and this line is still present in this pull: ``` $ grd 6e17d090d18dbf1686b713bc285761a3aa042663 74c1322aee3844e043bce4474e956631a20df7ff | tail -4 2: 6b2b0a2ebc < -: ---------- streams: do not retry failed flushes 3: 6e17d090d1 < -: ---------- blockstorage: handle buffered write failures -: ---------- > 2: 30ac211a91 streams: return checked buffered flush results -: ---------- > 3: 74c1322aee streams: require explicit final flushing
w0xlt (Migrated from github.com) reviewed 2026-11-10 19:20:34 +00:00
w0xlt (Migrated from github.com) left a comment

reACK 74c1322aee

reACK 74c1322aee3844e043bce4474e956631a20df7ff
maflcko commented 2026-11-10 19:41:22 +00:00 (Migrated from github.com)

Just for reference, there is outstanding/unaddressed review, as far as I can tell: https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4522180935 (maybe forgot to push?)

Just for reference, there is outstanding/unaddressed review, as far as I can tell: https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4522180935 (maybe forgot to push?)
l0rinc (Migrated from github.com) reviewed 2026-11-11 06:26:01 +00:00
l0rinc (Migrated from github.com) commented 2026-11-11 06:26:01 +00:00

Indeed, seem the previous push failed.

Indeed, seem the previous push failed.
l0rinc (Migrated from github.com) reviewed 2026-11-11 06:26:58 +00:00
l0rinc (Migrated from github.com) commented 2026-11-11 06:26:58 +00:00

Sure, done

Sure, done
maflcko (Migrated from github.com) reviewed 2026-11-11 08:45:28 +00:00
maflcko (Migrated from github.com) left a comment

Only change since the last sedited ack in https://github.com/bitcoin/bitcoin/pull/36049#pullrequestreview-5798743901 is adding a missing Assume(m_buf_pos == 0); // Use explicit flush().

(re)review ACK 4f06757a16 🥅

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: (re)review ACK 4f06757a16b456b2ec8e178224b2d528b2750c2 🥅
0GJG8Kno5/yMpP1OHAv4p96sM2+lMO0Pu9asy9OTpe2r3zQbAvJ062hFXD147gzSW4xGHwPVcqLH1d7Ijqr8Bg==
Only change since the last sedited ack in https://github.com/bitcoin/bitcoin/pull/36049#pullrequestreview-5798743901 is adding a missing `Assume(m_buf_pos == 0); // Use explicit flush()`. (re)review ACK 4f06757a16b456b2ec8e178224b2d528b2750c2 🥅 <details><summary>Show signature</summary> 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: (re)review ACK 4f06757a16b456b2ec8e178224b2d528b2750c2 🥅 0GJG8Kno5/yMpP1OHAv4p96sM2+lMO0Pu9asy9OTpe2r3zQbAvJ062hFXD147gzSW4xGHwPVcqLH1d7Ijqr8Bg== ``` </details>
maflcko (Migrated from github.com) commented 2026-11-11 08:36:45 +00:00

style nit: I don't like the /* comments for new code, because they are so inconsistently formatted. Could use the //! or /// for new code (and also consistent with all comments on BufferedFile methods?

style nit: I don't like the `/*` comments for new code, because they are so inconsistently formatted. Could use the `//!` or `///` for new code (and also consistent with all comments on `BufferedFile` methods?
l0rinc (Migrated from github.com) reviewed 2026-11-11 14:57:45 +00:00
l0rinc (Migrated from github.com) commented 2026-11-11 14:57:45 +00:00

Here I used /** to be consistent with BufferedWriter - adjusted both.

I agree with the formatting objection in general (I assume you mean the alignment of the middle * characters and the closing */), but mostly because multiline block comments usually take two extra lines :p.
I dislike most code comments in general, but when I do have to add one, I usually prefer a same-line ones so it's easy to ignore.
But given that others do like comments, maybe we could update the docs:

diff --git a/doc/developer-notes.md b/doc/developer-notes.md
index 7e1e61652e..139cfd4d90 100644
--- a/doc/developer-notes.md
+++ b/doc/developer-notes.md
@@ -203,40 +203,43 @@ git diff | ( cd ./src/ && clang-tidy-diff -p2 -path ../build -j $(nproc) )
 
 Bitcoin Core uses [Doxygen](https://www.doxygen.nl/) to generate its official documentation.
 
-Use Doxygen-compatible comment blocks for functions, methods, and fields.
+Use Doxygen-compatible comments for functions, methods, and fields.
+For new documentation comments, prefer `//!` or `///` over `/** ... */`.
+
+  - *Rationale*: Line comments avoid aligning leading `*` characters and closing delimiters.
+
+Prefer `///` for multiline comments, as the current Doxygen configuration automatically uses their first sentence as the brief description.
 
 For example, to describe a function use:
 
 ```c++
-/**
- * ... Description ...
- *
- * @param[in]  arg1 input description...
- * @param[in]  arg2 input description...
- * @param[out] arg3 output description...
- * @return Return cases...
- * @throws Error type and cases...
- * @pre  Pre-condition for function...
- * @post Post-condition for function...
- */
+/// ... Description ...
+///
+/// @param[in]  arg1 input description...
+/// @param[in]  arg2 input description...
+/// @param[out] arg3 output description...
+/// @return Return cases...
+/// @throws Error type and cases...
+/// @pre  Pre-condition for function...
+/// @post Post-condition for function...
 bool function(int arg1, const char *arg2, std::string& arg3)
 ```
 
 A complete list of `@xxx` commands can be found at https://www.doxygen.nl/manual/commands.html.
-As Doxygen recognizes the comments by the delimiters (`/**` and `*/` in this case), you don't
-*need* to provide any commands for a comment to be valid; just a description text is fine.
+Doxygen recognizes comments by their delimiters (`///` in this case), so you don't need to provide any commands for a comment to be valid.
+A plain description is enough.
 
 To describe a class, use the same construct above the class definition:
+
 ```c++
-/**
- * Alerts are for notifying old versions if they become too obsolete and
- * need to upgrade. The message is displayed in the status bar.
- * @see GetWarnings()
- */
+/// Alerts are for notifying old versions if they become too obsolete and need to upgrade.
+/// The message is displayed in the status bar.
+/// @see GetWarnings()
 class CAlert
 ```
 
-To describe a member or variable, place the comment on the line(s) before it, using `/**` and `*/`, `//!`, or `///`:
+To describe a member or variable, place the comment on the line(s) before it, using `//!` or `///`:
+
 ```c++
 //! Description before the member
 int var;
@@ -246,14 +249,6 @@ Avoid trailing (inline) member comments like `int var; //!< Description after th
 
   - *Rationale*: Forgetting the `<` silently breaks Doxygen output.
 
-Also OK:
-```c++
-///
-/// ... Description ...
-///
-bool function2(int arg1, const char *arg2)
-```
-
 Not picked up by Doxygen:
 ```c++
 //
Here I used `/**` to be consistent with `BufferedWriter` - adjusted both. I agree with the formatting objection in general (I assume you mean the alignment of the middle `*` characters and the closing ` */`), but mostly because multiline block comments usually take two extra lines :p. I dislike most code comments in general, but when I do have to add one, I usually prefer a same-line ones so it's easy to ignore. But given that others do like comments, maybe we could update the docs: ````patch diff --git a/doc/developer-notes.md b/doc/developer-notes.md index 7e1e61652e..139cfd4d90 100644 --- a/doc/developer-notes.md +++ b/doc/developer-notes.md @@ -203,40 +203,43 @@ git diff | ( cd ./src/ && clang-tidy-diff -p2 -path ../build -j $(nproc) ) Bitcoin Core uses [Doxygen](https://www.doxygen.nl/) to generate its official documentation. -Use Doxygen-compatible comment blocks for functions, methods, and fields. +Use Doxygen-compatible comments for functions, methods, and fields. +For new documentation comments, prefer `//!` or `///` over `/** ... */`. + + - *Rationale*: Line comments avoid aligning leading `*` characters and closing delimiters. + +Prefer `///` for multiline comments, as the current Doxygen configuration automatically uses their first sentence as the brief description. For example, to describe a function use: ```c++ -/** - * ... Description ... - * - * @param[in] arg1 input description... - * @param[in] arg2 input description... - * @param[out] arg3 output description... - * @return Return cases... - * @throws Error type and cases... - * @pre Pre-condition for function... - * @post Post-condition for function... - */ +/// ... Description ... +/// +/// @param[in] arg1 input description... +/// @param[in] arg2 input description... +/// @param[out] arg3 output description... +/// @return Return cases... +/// @throws Error type and cases... +/// @pre Pre-condition for function... +/// @post Post-condition for function... bool function(int arg1, const char *arg2, std::string& arg3) ``` A complete list of `@xxx` commands can be found at https://www.doxygen.nl/manual/commands.html. -As Doxygen recognizes the comments by the delimiters (`/**` and `*/` in this case), you don't -*need* to provide any commands for a comment to be valid; just a description text is fine. +Doxygen recognizes comments by their delimiters (`///` in this case), so you don't need to provide any commands for a comment to be valid. +A plain description is enough. To describe a class, use the same construct above the class definition: + ```c++ -/** - * Alerts are for notifying old versions if they become too obsolete and - * need to upgrade. The message is displayed in the status bar. - * @see GetWarnings() - */ +/// Alerts are for notifying old versions if they become too obsolete and need to upgrade. +/// The message is displayed in the status bar. +/// @see GetWarnings() class CAlert ``` -To describe a member or variable, place the comment on the line(s) before it, using `/**` and `*/`, `//!`, or `///`: +To describe a member or variable, place the comment on the line(s) before it, using `//!` or `///`: + ```c++ //! Description before the member int var; @@ -246,14 +249,6 @@ Avoid trailing (inline) member comments like `int var; //!< Description after th - *Rationale*: Forgetting the `<` silently breaks Doxygen output. -Also OK: -```c++ -/// -/// ... Description ... -/// -bool function2(int arg1, const char *arg2) -``` - Not picked up by Doxygen: ```c++ // ````
maflcko commented 2026-11-11 16:13:46 +00:00 (Migrated from github.com)

re-ACK 1c33fa05df 🍛

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: re-ACK 1c33fa05dfe8a87444eebfdc0436d7cea3761600 🍛
nSvXaQ7LuHT0P85tH1f/G0+k6+76mFlGf0OF6Uj945Fs3tv9wFhIktkCWiay0+KnceT965zD0oGWKLjtVOcNCw==
re-ACK 1c33fa05dfe8a87444eebfdc0436d7cea3761600 🍛 <details><summary>Show signature</summary> 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: re-ACK 1c33fa05dfe8a87444eebfdc0436d7cea3761600 🍛 nSvXaQ7LuHT0P85tH1f/G0+k6+76mFlGf0OF6Uj945Fs3tv9wFhIktkCWiay0+KnceT965zD0oGWKLjtVOcNCw== ``` </details>
maflcko (Migrated from github.com) reviewed 2026-11-11 16:16:30 +00:00
maflcko (Migrated from github.com) commented 2026-11-11 16:16:30 +00:00
+Prefer `///` for multiline comments, as the current Doxygen configuration automatically uses their first sentence as the brief description.

Is this true? I don't think it matters for doxygen. This is just a style-nit

> ```diff > +Prefer `///` for multiline comments, as the current Doxygen configuration automatically uses their first sentence as the brief description. > ``` Is this true? I don't think it matters for doxygen. This is just a style-nit
ryanofsky (Migrated from github.com) reviewed 2026-11-17 21:36:24 +00:00
ryanofsky (Migrated from github.com) left a comment

Concept ACK 1c33fa05df. Turning the std::terminate on a failed block write into normal error handling is a clear improvement, but I think BufferedWriter needs a way to close without flushing.

The new Assume(m_buf_pos == 0) in the destructor means a writer can only be destroyed safely after a flush(). That assumes the only thing that can go wrong while writing is the flush itself, and that nothing else is ever a reason to stop without writing the buffered data, such as an exception from other code in the same scope or a caller abandoning the write (interrupt/shutdown). Right now the only way to empty the buffer on an error path is a flush that fails, which flush() handles by clearing m_buf_pos before it writes. AutoFile doesn't have this problem, because fclose() satisfies its Assume whether or not the close succeeds.

The try/catch blocks added to WriteBlock and WriteBlockUndo illustrate the problem (https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4605490959): their cleanup is only correct because every exception in the block happens to come from flush(). A discard() method for error paths would mean every writer ends in an explicit flush() or discard(), with the destructor checking that, the same way AutoFile works.

    ~BufferedWriter()
    {
        Assume(m_buf_pos == 0); // Use explicit flush() or discard()
        flush();
    }

    //! Drop buffered bytes without writing them, e.g. after a write error.
    void discard() { m_buf_pos = 0; }
Concept ACK 1c33fa05dfe8a87444eebfdc0436d7cea3761600. Turning the `std::terminate` on a failed block write into normal error handling is a clear improvement, but I think `BufferedWriter` needs a way to close without flushing. The new `Assume(m_buf_pos == 0)` in the destructor means a writer can only be destroyed safely after a `flush()`. That assumes the only thing that can go wrong while writing is the flush itself, and that nothing else is ever a reason to stop without writing the buffered data, such as an exception from other code in the same scope or a caller abandoning the write (interrupt/shutdown). Right now the only way to empty the buffer on an error path is a flush that fails, which `flush()` handles by clearing `m_buf_pos` before it writes. `AutoFile` doesn't have this problem, because `fclose()` satisfies its `Assume` whether or not the close succeeds. The `try`/`catch` blocks added to `WriteBlock` and `WriteBlockUndo` illustrate the problem (https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4605490959): their cleanup is only correct because every exception in the block happens to come from `flush()`. A `discard()` method for error paths would mean every writer ends in an explicit `flush()` or `discard()`, with the destructor checking that, the same way `AutoFile` works. ```c++ ~BufferedWriter() { Assume(m_buf_pos == 0); // Use explicit flush() or discard() flush(); } //! Drop buffered bytes without writing them, e.g. after a write error. void discard() { m_buf_pos = 0; } ```
ryanofsky (Migrated from github.com) commented 2026-11-17 20:39:13 +00:00

In commit "blockstorage: handle buffered write failures" (1c33fa05df)

Could this catch std::ios_base::failure and call fileout.discard() (see the review summary), with fileout declared before the try so the catch can still call it?

As written, the cleanup here is only correct for exceptions thrown by flush(), which clears m_buf_pos before writing. std::runtime_error makes it look like any failure in the block is handled, but if anything else threw while bytes were still buffered, ~BufferedWriter would run with data pending during unwinding, before this catch runs: the Assume would abort in debug builds, and release builds would write the failed block's partial data. Nothing else in the block throws right now, but nothing prevents other exceptions that would trigger the Assume. Adding a discard() call in the catch would make this actually exception-safe. Same in WriteBlockUndo.

diff on top of 1c33fa05, with discard() from the review summary
diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp
index 971f95cb18e..53e2110c935 100644
--- a/src/node/blockstorage.cpp
+++ b/src/node/blockstorage.cpp
@@ -999,9 +999,8 @@ bool BlockManager::WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationSt
             LogError("OpenUndoFile failed for %s while writing block undo", pos.ToString());
             return FatalError(m_opts.notifications, state, _("Failed to write undo data."));
         }
+        BufferedWriter fileout{file};
         try {
-            BufferedWriter fileout{file};
-
             // Write index header
             fileout << GetParams().MessageStart() << blockundo_size;
             pos.nPos += STORAGE_HEADER_BYTES;
@@ -1013,7 +1012,8 @@ bool BlockManager::WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationSt
                 fileout << blockundo << hasher.GetHash();
             }
             fileout.flush();
-        } catch (const std::runtime_error& e) {
+        } catch (const std::ios_base::failure& e) {
+            fileout.discard();
             LogError("Failed to write block undo file %s: %s", pos.ToString(), e.what());
             (void)file.fclose();
             return FatalError(m_opts.notifications, state, _("Failed to write undo data."));
@@ -1164,16 +1164,16 @@ FlatFilePos BlockManager::WriteBlock(const CBlock& block, int nHeight)
         m_opts.notifications.fatalError(_("Failed to write block."));
         return FlatFilePos();
     }
+    BufferedWriter fileout{file};
     try {
-        BufferedWriter fileout{file};
-
         // Write index header
         fileout << GetParams().MessageStart() << block_size;
         pos.nPos += STORAGE_HEADER_BYTES;
         // Write block
         fileout << TX_WITH_WITNESS(block);
         fileout.flush();
-    } catch (const std::runtime_error& e) {
+    } catch (const std::ios_base::failure& e) {
+        fileout.discard();
         LogError("Failed to write block file %s: %s", pos.ToString(), e.what());
         (void)file.fclose();
         m_opts.notifications.fatalError(_("Failed to write block."));
In commit "blockstorage: handle buffered write failures" (1c33fa05dfe8a87444eebfdc0436d7cea3761600) Could this catch `std::ios_base::failure` and call `fileout.discard()` (see the review summary), with `fileout` declared before the `try` so the `catch` can still call it? As written, the cleanup here is only correct for exceptions thrown by `flush()`, which clears `m_buf_pos` before writing. `std::runtime_error` makes it look like any failure in the block is handled, but if anything else threw while bytes were still buffered, `~BufferedWriter` would run with data pending during unwinding, before this `catch` runs: the `Assume` would abort in debug builds, and release builds would write the failed block's partial data. Nothing else in the block throws right now, but nothing prevents other exceptions that would trigger the `Assume`. Adding a `discard()` call in the catch would make this actually exception-safe. Same in `WriteBlockUndo`. <details><summary>diff on top of 1c33fa05, with discard() from the review summary</summary> ```diff diff --git a/src/node/blockstorage.cpp b/src/node/blockstorage.cpp index 971f95cb18e..53e2110c935 100644 --- a/src/node/blockstorage.cpp +++ b/src/node/blockstorage.cpp @@ -999,9 +999,8 @@ bool BlockManager::WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationSt LogError("OpenUndoFile failed for %s while writing block undo", pos.ToString()); return FatalError(m_opts.notifications, state, _("Failed to write undo data.")); } + BufferedWriter fileout{file}; try { - BufferedWriter fileout{file}; - // Write index header fileout << GetParams().MessageStart() << blockundo_size; pos.nPos += STORAGE_HEADER_BYTES; @@ -1013,7 +1012,8 @@ bool BlockManager::WriteBlockUndo(const CBlockUndo& blockundo, BlockValidationSt fileout << blockundo << hasher.GetHash(); } fileout.flush(); - } catch (const std::runtime_error& e) { + } catch (const std::ios_base::failure& e) { + fileout.discard(); LogError("Failed to write block undo file %s: %s", pos.ToString(), e.what()); (void)file.fclose(); return FatalError(m_opts.notifications, state, _("Failed to write undo data.")); @@ -1164,16 +1164,16 @@ FlatFilePos BlockManager::WriteBlock(const CBlock& block, int nHeight) m_opts.notifications.fatalError(_("Failed to write block.")); return FlatFilePos(); } + BufferedWriter fileout{file}; try { - BufferedWriter fileout{file}; - // Write index header fileout << GetParams().MessageStart() << block_size; pos.nPos += STORAGE_HEADER_BYTES; // Write block fileout << TX_WITH_WITNESS(block); fileout.flush(); - } catch (const std::runtime_error& e) { + } catch (const std::ios_base::failure& e) { + fileout.discard(); LogError("Failed to write block file %s: %s", pos.ToString(), e.what()); (void)file.fclose(); m_opts.notifications.fatalError(_("Failed to write block.")); ``` </details>
Lines 705-709
ryanofsky (Migrated from github.com) commented 2026-11-17 20:46:38 +00:00

In commit "blockstorage: handle buffered write failures" (1c33fa05df)

re: maflcko https://github.com/bitcoin/bitcoin/pull/36049#issuecomment-5369507350

It would be good to find a code pattern that avoids this class of problem wholesale. It doesn't seem a great use of human (or LLM) review time to spend on such issues one-by-one. If we care about those issues, it would be better if the compiler or a clang-tidy analysis could find and prevent all of them.

An established pattern is the one this PR moves toward: destructors don't do work that can fail, and every object ends in an explicit call that reports success or failure, checked by an Assume in the destructor, as AutoFile does with fclose(). With a discard() method (https://github.com/bitcoin/bitcoin/pull/36049#pullrequestreview-5946234150), BufferedWriter would follow it too.

On a clang-tidy check: the existing bugprone-exception-escape check, which flags destructors that can throw, doesn't catch this bug. It reports nothing for ~BufferedWriter on master, probably because AutoFile::write_buffer() is defined in streams.cpp, where the check can't see that it throws. So it would probably need a custom bitcoin-tidy check.

A possible better alternative: throwing destructors, as in Cap'n Proto

Not something I'm suggesting for this PR, but another answer to the "wholesale" question: if ~BufferedWriter were allowed to throw, RAII would just work. The destructor would flush automatically and report a write failure like any other error, so callers wouldn't need explicit flush() or discard() calls, and if the writer were destroyed because some other exception was already propagating, that original exception would take precedence instead of the program calling std::terminate.

This is how Cap'n Proto handles it: destructors are declared noexcept(false), and kj::UnwindDetector catches a destructor's failure only when another exception is already unwinding (the same rule as Java's try-with-resources). Both current callers would work this way, since each holds the writer as a local inside a try block.

The downside is that a throwing destructor is only safe when no noexcept code sits between it and the catch. Holding the writer in std::unique_ptr, std::optional or std::vector, or destroying it inside a noexcept function, would turn the error back into std::terminate, so making this fully safe would need a bitcoin-tidy check that flags those uses.

In commit "blockstorage: handle buffered write failures" (1c33fa05dfe8a87444eebfdc0436d7cea3761600) re: maflcko https://github.com/bitcoin/bitcoin/pull/36049#issuecomment-5369507350 > It would be good to find a code pattern that avoids this class of problem wholesale. It doesn't seem a great use of human (or LLM) review time to spend on such issues one-by-one. If we care about those issues, it would be better if the compiler or a clang-tidy analysis could find and prevent all of them. An established pattern is the one this PR moves toward: destructors don't do work that can fail, and every object ends in an explicit call that reports success or failure, checked by an `Assume` in the destructor, as `AutoFile` does with `fclose()`. With a `discard()` method (https://github.com/bitcoin/bitcoin/pull/36049#pullrequestreview-5946234150), `BufferedWriter` would follow it too. On a clang-tidy check: the existing [`bugprone-exception-escape`](https://clang.llvm.org/extra/clang-tidy/checks/bugprone/exception-escape.html) check, which flags destructors that can throw, doesn't catch this bug. It reports nothing for `~BufferedWriter` on master, probably because `AutoFile::write_buffer()` is defined in `streams.cpp`, where the check can't see that it throws. So it would probably need a custom `bitcoin-tidy` check. <details><summary>A possible better alternative: throwing destructors, as in Cap'n Proto</summary> Not something I'm suggesting for this PR, but another answer to the "wholesale" question: if `~BufferedWriter` were allowed to throw, RAII would just work. The destructor would flush automatically and report a write failure like any other error, so callers wouldn't need explicit `flush()` or `discard()` calls, and if the writer were destroyed because some other exception was already propagating, that original exception would take precedence instead of the program calling `std::terminate`. This is how [Cap'n Proto](https://github.com/capnproto/capnproto/blob/v2/style-guide.md#exceptions-can-happen-anywhere-including-destructors) handles it: destructors are declared `noexcept(false)`, and `kj::UnwindDetector` catches a destructor's failure only when another exception is already unwinding (the same rule as Java's try-with-resources). Both current callers would work this way, since each holds the writer as a local inside a `try` block. The downside is that a throwing destructor is only safe when no `noexcept` code sits between it and the `catch`. Holding the writer in `std::unique_ptr`, `std::optional` or `std::vector`, or destroying it inside a `noexcept` function, would turn the error back into `std::terminate`, so making this fully safe would need a `bitcoin-tidy` check that flags those uses. </details>
ryanofsky (Migrated from github.com) reviewed 2026-11-17 21:46:50 +00:00
ryanofsky (Migrated from github.com) commented 2026-11-17 21:44:00 +00:00

In commit "streams: do not retry failed flushes" (a4199b39f9)

Note: It wasn't obvious to me why bytes were being discarded here. It looks like keeping them instead of discarding would be safer so a caller could retry, but a retry would write corrupt data: AutoFile::write_buffer() obfuscates the buffer in place before calling fwrite() and only advances its position after a successful write, so a second attempt would XOR the bytes again and write them unobfuscated. A short fwrite() can also leave part of the buffer already on disk. Maybe:

    //! Discard the buffered bytes even if writing them throws. After a failed
    //! write they can't be written again: the stream may have obfuscated them
    //! in place, and part of them may already be on disk.
In commit "streams: do not retry failed flushes" (a4199b39f92c3e572196f464a067f70b1d77cda5) Note: It wasn't obvious to me why bytes were being discarded here. It looks like keeping them instead of discarding would be safer so a caller could retry, but a retry would write corrupt data: `AutoFile::write_buffer()` obfuscates the buffer in place before calling `fwrite()` and only advances its position after a successful write, so a second attempt would XOR the bytes again and write them unobfuscated. A short `fwrite()` can also leave part of the buffer already on disk. Maybe: ```suggestion //! Discard the buffered bytes even if writing them throws. After a failed //! write they can't be written again: the stream may have obfuscated them //! in place, and part of them may already be on disk. ```
l0rinc (Migrated from github.com) reviewed 2026-11-17 22:15:27 +00:00
Lines 705-709
l0rinc (Migrated from github.com) commented 2026-11-17 22:15:27 +00:00

Thanks Russ, added your two commits on top: I’m curious what the other reviewers think.

This also reminded me of try/finally and try-with-resources in Java - I’d like us to find a structure that handles cleanup when we leave the scope, since it’s easy to miss a manual flush() or discard() on an error path. We can also work that out in a follow-up, and once we agree on a pattern, I’d love to add a bitcoin-tidy check for it.

Thanks Russ, added your two commits on top: I’m curious what the other reviewers think. This also reminded me of `try`/`finally` and `try-with-resources` in Java - I’d like us to find a structure that handles cleanup when we leave the scope, since it’s easy to miss a manual `flush()` or `discard()` on an error path. We can also work that out in a follow-up, and once we agree on a pattern, I’d love to add a bitcoin-tidy check for it.
maflcko commented 2026-11-18 07:14:59 +00:00 (Migrated from github.com)

The new Assume(m_buf_pos == 0) in the destructor means a writer can only be destroyed safely after a flush(). That assumes the only thing that can go wrong while writing is the flush itself

Correct, and I think this assumption holds. If serializing one of our valid C++ structs (like a block) failed, it seems like a severe internal bug, and I think crashing here is better. Recall that your suggested patch will also continue to crash on non-io exceptions after the first buffered byte. Also, your patch will continue to crash if there was an interrupt (somewhere else due to an io error) and then the flush failed.

No objection, just wondering what should be in scope and what should be better ignored.

> The new `Assume(m_buf_pos == 0)` in the destructor means a writer can only be destroyed safely after a `flush()`. That assumes the only thing that can go wrong while writing is the flush itself Correct, and I think this assumption holds. If serializing one of our valid C++ structs (like a block) failed, it seems like a severe internal bug, and I think crashing here is better. Recall that your suggested patch will also continue to crash on non-io exceptions after the first buffered byte. Also, your patch will continue to crash if there was an interrupt (somewhere else due to an io error) and then the flush failed. No objection, just wondering what should be in scope and what should be better ignored.
maflcko (Migrated from github.com) reviewed 2026-11-18 07:27:45 +00:00
Lines 705-709
maflcko (Migrated from github.com) commented 2026-11-18 07:27:45 +00:00

On a clang-tidy check: the existing bugprone-exception-escape check, which flags destructors that can throw, doesn't catch this bug.

Yeah, I think I looked into this earlier, but the results were too mixed. I guess it can't hurt to enable it still, because our assumption is that ctors shouldn't throw.

> On a clang-tidy check: the existing [`bugprone-exception-escape`](https://clang.llvm.org/extra/clang-tidy/checks/bugprone/exception-escape.html) check, which flags destructors that can throw, doesn't catch this bug. Yeah, I think I looked into this earlier, but the results were too mixed. I guess it can't hurt to enable it still, because our assumption is that ctors shouldn't throw.
ryanofsky (Migrated from github.com) approved these changes 2026-11-24 19:37:35 +00:00
ryanofsky (Migrated from github.com) left a comment

Code review ACK 1584299ae5. This gives BufferedWriter a safer interface: every writer ends in an explicit flush() or discard(), the destructor's Assume checks that, and a failed flush no longer leaves bytes behind to be written again. It also replaces the std::terminate on a failed block or undo write (for example a full disk) with a logged error and a shutdown.

Thanks for taking the two commits, and sorry that part of my earlier suggestion was based on bad assumptions: I proposed narrowing these catch blocks to std::ios_base::failure without understanding how the callers handle exceptions or the context around this code. Nothing in these blocks throws anything else today, so I don't think it causes a problem, and I still think discard() itself is right.

On the error handling in WriteBlock and WriteBlockUndo, I'm fine with any of the approaches discussed here as long as the behavior isn't worse than master, where any write error terminates. The error handling around these calls was inconsistent before this PR and still is, and I think that's a separate problem from the BufferedWriter interface, which is the main improvement here. I left one optional new suggestion in https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4684762185.

If you push again, feel free to squash aade8e8a37 into a4199b39f9 and 1584299ae5 into 1c33fa05df, so the flush() change comes with its explanation and the error handlers come with discard(). The Ralph review suggests the same (finding 4, finding 5).

Also the PR description has what looks like an editing note after the "I introduced this bug in #31551" line ("I’d update the Fix section to include discard()...").

Code review ACK 1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd. This gives `BufferedWriter` a safer interface: every writer ends in an explicit `flush()` or `discard()`, the destructor's `Assume` checks that, and a failed flush no longer leaves bytes behind to be written again. It also replaces the `std::terminate` on a failed block or undo write (for example a full disk) with a logged error and a shutdown. Thanks for taking the two commits, and sorry that part of my earlier suggestion was based on bad assumptions: I proposed narrowing these `catch` blocks to `std::ios_base::failure` without understanding how the callers handle exceptions or the context around this code. Nothing in these blocks throws anything else today, so I don't think it causes a problem, and I still think `discard()` itself is right. On the error handling in `WriteBlock` and `WriteBlockUndo`, I'm fine with any of the approaches discussed here as long as the behavior isn't worse than master, where any write error terminates. The error handling around these calls was inconsistent before this PR and still is, and I think that's a separate problem from the `BufferedWriter` interface, which is the main improvement here. I left one optional new suggestion in https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4684762185. If you push again, feel free to squash aade8e8a377c383b59b02beef4372e3214310231 into a4199b39f92c3e572196f464a067f70b1d77cda5 and 1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd into 1c33fa05dfe8a87444eebfdc0436d7cea3761600, so the `flush()` change comes with its explanation and the error handlers come with `discard()`. The Ralph review suggests the same ([finding 4](https://review.fish.foo/report/36049-1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd-2773-7.html#finding-finding%3A4), [finding 5](https://review.fish.foo/report/36049-1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd-2773-7.html#finding-finding%3A5)). Also the PR description has what looks like an editing note after the "I introduced this bug in #31551" line ("I’d update the **Fix** section to include `discard()`...").
ryanofsky (Migrated from github.com) commented 2026-11-24 17:59:41 +00:00

re: https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4485659497

I would prefer if we'd catch on std::runtime_error. For other exceptions, e.g. allocation failures, it might genuinely be better to immediately terminate.

Note: the latest push narrows this to std::ios_base::failure in 1584299ae5 (my suggestion from before I understood caller error handling), so a std::runtime_error that isn't an I/O error is no longer handled here. From WriteBlock it would still reach the existing std::runtime_error handlers in AcceptBlock and LoadGenesisBlock, but from WriteBlockUndo nothing catches it before ProcessMessages, which only logs it at debug level. Nothing in these blocks throws such an exception today, and allocation failures are handled the same as before. I also suggested an optional change in https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4684762185 that would make the WriteBlock catch just discard, close and rethrow, so mentioning it in case you have an opinion.

re: https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4485659497 > I would prefer if we'd catch on std::runtime_error. For other exceptions, e.g. allocation failures, it might genuinely be better to immediately terminate. Note: the latest push narrows this to `std::ios_base::failure` in 1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd (my suggestion from before I understood caller error handling), so a `std::runtime_error` that isn't an I/O error is no longer handled here. From `WriteBlock` it would still reach the existing `std::runtime_error` handlers in [`AcceptBlock`](https://github.com/bitcoin/bitcoin/blob/1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd/src/validation.cpp#L4461-L4463) and [`LoadGenesisBlock`](https://github.com/bitcoin/bitcoin/blob/1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd/src/validation.cpp#L5040-L5043), but from `WriteBlockUndo` nothing catches it before `ProcessMessages`, which only logs it at debug level. Nothing in these blocks throws such an exception today, and allocation failures are handled the same as before. I also suggested an optional change in https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4684762185 that would make the `WriteBlock` catch just discard, close and rethrow, so mentioning it in case you have an opinion.
Lines 1182-1188
ryanofsky (Migrated from github.com) commented 2026-11-24 18:36:14 +00:00

In commit "blockstorage: discard buffered bytes on I/O errors" (1584299ae5)

Not important, and fine to leave as is, but since WriteBlock's callers already catch std::runtime_error around it (AcceptBlock calls FatalError, and LoadGenesisBlock fails init), I think the simplest and most straightforward way of dealing with errors here would be for this catch to only clean up and rethrow:

} catch (...) {
    fileout.discard();
    (void)file.fclose();
    throw;
}

This way errors thrown while writing are all handled by callers instead of a subset of them handled here and others handled by callers. This would be closer to how write errors were handled before #31551, when they were thrown straight out of WriteBlock, and AcceptBlock would report the write error itself instead of adding a misleading "Failed to find position to write new block to disk".

WriteBlockUndo is different: nothing between it and the catch blocks in ProcessMessages handles exceptions, so a rethrown undo write error would only be logged at debug level and the node would keep running, as it did before #31551. So I think WriteBlockUndo should keep its own FatalError handler for now.

Ideally a follow-up would make WriteBlock and WriteBlockUndo consistent: either add a std::runtime_error catch around the WriteBlockUndo call too, so both functions can clean up and rethrow, or handle every error inside WriteBlock and drop the catches in its callers.

In commit "blockstorage: discard buffered bytes on I/O errors" (1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd) Not important, and fine to leave as is, but since `WriteBlock`'s callers already catch `std::runtime_error` around it ([`AcceptBlock`](https://github.com/bitcoin/bitcoin/blob/1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd/src/validation.cpp#L4461-L4463) calls `FatalError`, and [`LoadGenesisBlock`](https://github.com/bitcoin/bitcoin/blob/1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd/src/validation.cpp#L5040-L5043) fails init), I think the simplest and most straightforward way of dealing with errors here would be for this `catch` to only clean up and rethrow: ```cpp } catch (...) { fileout.discard(); (void)file.fclose(); throw; } ``` This way errors thrown while writing are all handled by callers instead of a subset of them handled here and others handled by callers. This would be closer to how write errors were handled before #31551, when they were thrown straight out of `WriteBlock`, and `AcceptBlock` would report the write error itself instead of adding a misleading "Failed to find position to write new block to disk". `WriteBlockUndo` is different: nothing between it and the [`catch` blocks in `ProcessMessages`](https://github.com/bitcoin/bitcoin/blob/1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd/src/net_processing.cpp#L5491-L5495) handles exceptions, so a rethrown undo write error would only be logged at debug level and the node would keep running, as it did before #31551. So I think `WriteBlockUndo` should keep its own `FatalError` handler for now. Ideally a follow-up would make `WriteBlock` and `WriteBlockUndo` consistent: either add a `std::runtime_error` catch around the `WriteBlockUndo` call too, so both functions can clean up and rethrow, or handle every error inside `WriteBlock` and drop the catches in its callers.
Lines 708-709
ryanofsky (Migrated from github.com) commented 2026-11-24 17:59:43 +00:00

In commit "blockstorage: discard buffered bytes on I/O errors" (1584299ae5)

re: maflcko https://github.com/bitcoin/bitcoin/pull/36049#issuecomment-6971812396

If serializing one of our valid C++ structs (like a block) failed, it seems like a severe internal bug, and I think crashing here is better.

Agreed, and only std::ios_base::failure is caught here, so other exceptions aren't handled in these functions.

Recall that your suggested patch will also continue to crash on non-io exceptions after the first buffered byte.

That's true in debug builds, where the destructor's Assume aborts. Release builds normally don't crash: the destructor writes the partial record and the exception continues to the caller, as on master. Either seems fine for a case that shouldn't happen.

What discard() changes is the I/O error path: the catch drops whatever is pending itself, so it no longer depends on flush() having cleared the buffer before it threw, and the destructor's Assume checks a contract the class states (finish with flush() or discard()) rather than something only a failed flush() can do.

Also, your patch will continue to crash if there was an interrupt (somewhere else due to an io error) and then the flush failed.

I'm not sure I follow this one. If the flush() inside the try fails, the catch calls discard(), and the destructor's flush() has nothing left to write. If you mean a path that leaves the scope without calling flush() or discard() (the interrupt case I mentioned), then yes: the destructor's fallback flush can still fail and terminate, and the Assume is there to catch such paths in debug builds.

No objection, just wondering what should be in scope and what should be better ignored.

I think the main goal here is the BufferedWriter interface, and I'm fine with any error handling at the two call sites that isn't worse than master. Making the two call sites handle errors the same way (https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4684762185) and a general pattern for this class of problem (https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4605579266) both seem fine as follow-ups.

In commit "blockstorage: discard buffered bytes on I/O errors" (1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd) re: maflcko https://github.com/bitcoin/bitcoin/pull/36049#issuecomment-6971812396 > If serializing one of our valid C++ structs (like a block) failed, it seems like a severe internal bug, and I think crashing here is better. Agreed, and only `std::ios_base::failure` is caught here, so other exceptions aren't handled in these functions. > Recall that your suggested patch will also continue to crash on non-io exceptions after the first buffered byte. That's true in debug builds, where the destructor's `Assume` aborts. Release builds normally don't crash: the destructor writes the partial record and the exception continues to the caller, as on master. Either seems fine for a case that shouldn't happen. What `discard()` changes is the I/O error path: the `catch` drops whatever is pending itself, so it no longer depends on `flush()` having cleared the buffer before it threw, and the destructor's `Assume` checks a contract the class states (finish with `flush()` or `discard()`) rather than something only a failed `flush()` can do. > Also, your patch will continue to crash if there was an interrupt (somewhere else due to an io error) and then the flush failed. I'm not sure I follow this one. If the `flush()` inside the `try` fails, the `catch` calls `discard()`, and the destructor's `flush()` has nothing left to write. If you mean a path that leaves the scope without calling `flush()` or `discard()` (the interrupt case I mentioned), then yes: the destructor's fallback flush can still fail and terminate, and the `Assume` is there to catch such paths in debug builds. > No objection, just wondering what should be in scope and what should be better ignored. I think the main goal here is the `BufferedWriter` interface, and I'm fine with any error handling at the two call sites that isn't worse than master. Making the two call sites handle errors the same way (https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4684762185) and a general pattern for this class of problem (https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4605579266) both seem fine as follow-ups.
ryanofsky (Migrated from github.com) commented 2026-11-24 17:59:45 +00:00

re: l0rinc https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4606518586

I'd like us to find a structure that handles cleanup when we leave the scope, since it's easy to miss a manual flush() or discard() on an error path. We can also work that out in a follow-up

A follow-up sounds right for deciding and implementing it. For reference, I think the options are roughly these:

  1. Keep explicit flush() and discard() calls, as in this PR and like AutoFile::fclose(), and add a bitcoin-tidy check that every path out of a writer's scope calls one of them. Today a missed call is at least caught at runtime by the destructor's Assume in debug builds.
  2. Have the destructor discard pending bytes automatically while an exception is unwinding (comparing std::uncaught_exceptions() with its value at construction), and keep requiring an explicit flush() on the normal path, checked by the Assume as now. Error paths would no longer need a discard() call. A bitcoin-tidy check would also be simpler than for option 1, since it would only need to check normal exits, not which calls can throw.
  3. Let the destructor flush on the normal path and throw if that fails (noexcept(false), the Cap'n Proto approach from my comment above), and discard when another exception is already unwinding. Callers wouldn't need any explicit calls, but a writer held in a container or destroyed in a noexcept function would turn errors back into std::terminate, so this would need a bitcoin-tidy check too.
  4. Replace the explicit calls with a helper that takes a callback, like WriteBuffered(file, [&](auto& writer) { writer << ...; }), which flushes after the callback returns and discards if it throws. Callers can't forget either call, but the writes have to fit in a lambda.

re: maflcko https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4610421734

I guess it can't hurt to enable it still

Yes agree this could still be a good idea

re: l0rinc https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4606518586 > I'd like us to find a structure that handles cleanup when we leave the scope, since it's easy to miss a manual `flush()` or `discard()` on an error path. We can also work that out in a follow-up A follow-up sounds right for deciding and implementing it. For reference, I think the options are roughly these: 1. Keep explicit `flush()` and `discard()` calls, as in this PR and like `AutoFile::fclose()`, and add a `bitcoin-tidy` check that every path out of a writer's scope calls one of them. Today a missed call is at least caught at runtime by the destructor's `Assume` in debug builds. 2. Have the destructor discard pending bytes automatically while an exception is unwinding (comparing `std::uncaught_exceptions()` with its value at construction), and keep requiring an explicit `flush()` on the normal path, checked by the `Assume` as now. Error paths would no longer need a `discard()` call. A `bitcoin-tidy` check would also be simpler than for option 1, since it would only need to check normal exits, not which calls can throw. 3. Let the destructor flush on the normal path and throw if that fails (`noexcept(false)`, the Cap'n Proto approach from my comment above), and discard when another exception is already unwinding. Callers wouldn't need any explicit calls, but a writer held in a container or destroyed in a `noexcept` function would turn errors back into `std::terminate`, so this would need a `bitcoin-tidy` check too. 4. Replace the explicit calls with a helper that takes a callback, like `WriteBuffered(file, [&](auto& writer) { writer << ...; })`, which flushes after the callback returns and discards if it throws. Callers can't forget either call, but the writes have to fit in a lambda. re: maflcko https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4610421734 > I guess it can't hurt to enable it still Yes agree this could still be a good idea
ryanofsky (Migrated from github.com) commented 2026-11-24 17:59:44 +00:00

In commit "blockstorage: discard buffered bytes on I/O errors" (1584299ae5)

Could add a test for discard() next to buffered_writer_flush_failure, checking that the pending bytes are dropped and the destructor doesn't write them (or hit its Assume). I should have included one in my commit. The Ralph review flagged this too: the existing failure test would still pass if discard() did nothing.

BOOST_AUTO_TEST_CASE(buffered_writer_discard)
{
    struct CountingStream {
        int write_attempts{0};
        void write_buffer(std::span<std::byte>) { ++write_attempts; }
    } stream;
    {
        BufferedWriter writer{stream, 4};
        writer.write("00"_hex);
        writer.discard();
    }
    BOOST_CHECK_EQUAL(stream.write_attempts, 0);
}
In commit "blockstorage: discard buffered bytes on I/O errors" (1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd) Could add a test for `discard()` next to `buffered_writer_flush_failure`, checking that the pending bytes are dropped and the destructor doesn't write them (or hit its `Assume`). I should have included one in my commit. The [Ralph review](https://review.fish.foo/report/36049-1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd-2773-7.html#finding-finding%3A1) flagged this too: the existing failure test would still pass if `discard()` did nothing. ```cpp BOOST_AUTO_TEST_CASE(buffered_writer_discard) { struct CountingStream { int write_attempts{0}; void write_buffer(std::span<std::byte>) { ++write_attempts; } } stream; { BufferedWriter writer{stream, 4}; writer.write("00"_hex); writer.discard(); } BOOST_CHECK_EQUAL(stream.write_attempts, 0); } ```
l0rinc commented 2026-11-25 13:48:11 +00:00 (Migrated from github.com)

Thanks, Russ! I've updated the PR description and removed the leftover AI proofreading note.
Is there anything besides the discard() test that you think is missing here? Given that we're actively changing this area, it's probably simpler to leave the code as ACKed and pick up the test and error handling in follow-ups.

Thanks, Russ! I've updated the PR description and removed the leftover AI proofreading note. Is there anything besides the `discard()` test that you think is missing here? Given that we're actively changing this area, it's probably simpler to leave the code as ACKed and pick up the test and error handling in follow-ups.
l0rinc (Migrated from github.com) reviewed 2026-11-25 13:50:03 +00:00
Lines 1182-1188
l0rinc (Migrated from github.com) commented 2026-11-25 13:50:03 +00:00

I don't mind pushing this if reviewers think this is simpler or better.

I don't mind pushing this if reviewers think this is simpler or better.
maflcko commented 2026-11-25 16:14:05 +00:00 (Migrated from github.com)

review ACK 1584299ae5 🚿

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: review ACK 1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd 🚿
rMNxM1V6xpaSyW2MDtRk6z6W/WmJqky8fLbHQSRY+6CSDj01lHYX+BYc2KA2qES5E2BhXdz6Abj+HaGOMAWRAA==
review ACK 1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd 🚿 <details><summary>Show signature</summary> 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: review ACK 1584299ae51d5c0bb821f4f51521ec6eaf9bdfbd 🚿 rMNxM1V6xpaSyW2MDtRk6z6W/WmJqky8fLbHQSRY+6CSDj01lHYX+BYc2KA2qES5E2BhXdz6Abj+HaGOMAWRAA== ``` </details>
maflcko commented 2026-11-26 09:45:49 +00:00 (Migrated from github.com)

(my 1 TB benchmarking servers have been filling up, so I've been seeing these failures more often).

Do you know why this happens? IIUC the whole point of CheckDiskSpace() right before posix_fallocate is supposed to fix that. Are the servers writing so much data (50+MiB) in the few ns between the two calls that this is racy, or is there some other bug?

Just wondering about the large picture here, because flushing any other open files during shutdown will likely fail as well anyway, and if there is another bug, it would be better to fix that bug, than to make style cleanups to this code?

Again, no objections (I've already acked), just wondering.

> (my 1 TB benchmarking servers have been filling up, so I've been seeing these failures more often). Do you know why this happens? IIUC the whole point of CheckDiskSpace() right before posix_fallocate is supposed to fix that. Are the servers writing so much data (50+MiB) in the few ns between the two calls that this is racy, or is there some other bug? Just wondering about the large picture here, because flushing any other open files during shutdown will likely fail as well anyway, and if there is another bug, it would be better to fix that bug, than to make style cleanups to this code? Again, no objections (I've already acked), just wondering.
l0rinc commented 2026-11-27 19:28:40 +00:00 (Migrated from github.com)

Do you know why this happens? IIUC the whole point of CheckDiskSpace() right before posix_fallocate is supposed to fix that.

I started seeing write errors in a few places during benchmarks that I hadn't run into before. Seek compaction put a lot of extra writes on those drives, and some of them are now reporting bad sectors too. I don't know whether any of the errors came from the block or undo writer. For the PR, I manually injected an error in AutoFile::write_buffer() (see the reproducer) so I could see what the node did when the final flush failed.

I'd expect a successful posix_fallocate() to protect those writes, as you describe. LevelDB compaction or another process could use up free space between the check and the reservation, but I don't know if that's what happened here.

The disk trouble is what made me notice these corner cases. The PR is just about what happens once a write fails. I want the node to report the original error and get a chance to shut down instead of terminating when the destructor throws.

> Do you know why this happens? IIUC the whole point of CheckDiskSpace() right before posix_fallocate is supposed to fix that. I started seeing write errors in a few places during benchmarks that I hadn't run into before. Seek compaction put a lot of extra writes on those drives, and some of them are now reporting bad sectors too. I don't know whether any of the errors came from the block or undo writer. For the PR, I manually injected an error in `AutoFile::write_buffer()` (see the reproducer) so I could see what the node did when the final flush failed. I'd expect a successful `posix_fallocate()` to protect those writes, as you describe. LevelDB compaction or another process could use up free space between the check and the reservation, but I don't know if that's what happened here. The disk trouble is what made me notice these corner cases. The PR is just about what happens once a write fails. I want the node to report the original error and get a chance to shut down instead of terminating when the destructor throws.
Sign in to join this conversation.
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36049
No description provided.