Skip to content

streams: handle buffered write failures outside the destructor - #36049

Open
l0rinc wants to merge 5 commits into
bitcoin:masterfrom
l0rinc:l0rinc/streams-buffered-write-failure
Open

l0rinc wants to merge 5 commits into
bitcoin:masterfrom
l0rinc:l0rinc/streams-buffered-write-failure

Conversation

@l0rinc

@l0rinc l0rinc commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

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

@DrahtBot

DrahtBot commented Aug 20, 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
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.

@andrewtoth

Copy link
Copy Markdown
Contributor

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

l0rinc commented Aug 20, 2026

Copy link
Copy Markdown
Contributor Author

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

maflcko commented Aug 21, 2026

Copy link
Copy Markdown
Member

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

w0xlt commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

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
l0rinc force-pushed the l0rinc/streams-buffered-write-failure branch from d5f4241 to cac9501 Compare September 23, 2026 22:26
@l0rinc

l0rinc commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

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 w0xlt left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK cac9501

@sedited sedited left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

Comment thread src/node/blockstorage.cpp Resolved
@l0rinc
l0rinc force-pushed the l0rinc/streams-buffered-write-failure branch from cac9501 to 6e17d09 Compare November 6, 2026 09:08

@sedited sedited left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ACK 6e17d09

@DrahtBot
DrahtBot requested a review from w0xlt November 6, 2026 10:18
@maflcko

maflcko commented Nov 6, 2026

Copy link
Copy Markdown
Member

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

l0rinc commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

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());
        }
    }

@maflcko

maflcko commented Nov 7, 2026

Copy link
Copy Markdown
Member

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 l0rinc changed the title streams: avoid termination on buffered write failure streams: log and abort on buffered write failures Nov 9, 2026
@l0rinc
l0rinc force-pushed the l0rinc/streams-buffered-write-failure branch from 6e17d09 to e334c0e Compare November 9, 2026 10:59
@l0rinc

l0rinc commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

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

maflcko commented Nov 9, 2026

Copy link
Copy Markdown
Member

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
l0rinc force-pushed the l0rinc/streams-buffered-write-failure branch from e334c0e to 74c1322 Compare November 9, 2026 12:27
@l0rinc

l0rinc commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

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.

Comment thread src/test/streams_tests.cpp Outdated
void write_buffer(std::span<std::byte>) { if (++write_attempts == 1) throw std::ios_base::failure{"write failed"}; }
} stream;
BOOST_CHECK_EXCEPTION([&] {
BufferedWriter writer(stream, buffer_size);

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 the first commit, could use C++11 {} init?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sure, done

Comment thread src/streams.h Resolved
Comment thread src/node/blockstorage.cpp Outdated
pos.nPos += STORAGE_HEADER_BYTES;
// Write block
fileout << TX_WITH_WITNESS(block);
Assert(fileout.flush());

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

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.

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.

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 guess it may be easiest to restore the try-catch commit id from #36049 (review) , with the Assume(m_buf_pos == 0); nit addressed in the dtor

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done, thanks

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Indeed, seem the previous push failed.

Comment thread src/streams.h Outdated
Comment on lines +708 to +709
Assume(m_buf_pos == 0);
Assert(flush());

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 the third commit: 74c1322:

        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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Did something similar

Comment thread src/streams.h Resolved

@l0rinc l0rinc left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.
(edit: previous push didn't succeed for some reason)

Comment thread src/test/streams_tests.cpp Outdated
void write_buffer(std::span<std::byte>) { if (++write_attempts == 1) throw std::ios_base::failure{"write failed"}; }
} stream;
BOOST_CHECK_EXCEPTION([&] {
BufferedWriter writer(stream, buffer_size);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Comment thread src/node/blockstorage.cpp Outdated
pos.nPos += STORAGE_HEADER_BYTES;
// Write block
fileout << TX_WITH_WITNESS(block);
Assert(fileout.flush());

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done, thanks

Comment thread src/streams.h Resolved
Comment thread src/streams.h Outdated
Comment on lines +708 to +709
Assume(m_buf_pos == 0);
Assert(flush());

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Did something similar

Comment thread src/streams.h Resolved
@l0rinc l0rinc changed the title streams: log and abort on buffered write failures streams: handle buffered write failures outside the destructor Nov 9, 2026

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

reACK 74c1322

@DrahtBot
DrahtBot requested a review from sedited November 10, 2026 19:20
@maflcko

maflcko commented Nov 10, 2026

Copy link
Copy Markdown
Member

Just for reference, there is outstanding/unaddressed review, as far as I can tell: #36049 (comment) (maybe forgot to push?)

Record write errors and the destructor retry after a failed buffered flush before changing error reporting.
Prepare the existing buffered stream tests for explicit flushing.
@l0rinc
l0rinc force-pushed the l0rinc/streams-buffered-write-failure branch from 74c1322 to 4f06757 Compare November 11, 2026 06:25

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

Only change since the last sedited ack in #36049 (review) is adding a missing Assume(m_buf_pos == 0); // Use explicit flush().

(re)review ACK 4f06757 🥅

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==

Comment thread src/streams.h Resolved
@DrahtBot
DrahtBot requested a review from w0xlt November 11, 2026 08:45
l0rinc and others added 2 commits November 11, 2026 15:55
A failed `BufferedWriter::flush()` leaves bytes pending, so the destructor retries the write while the exception unwinds.
Clear the pending byte count before writing so the original exception can propagate without another write.
Flush block and undo data explicitly, catch write errors, log their cause, and request normal fatal shutdown, consistently with the adjacent file-close error handling.
Detect missing explicit flushes with `Assume` in the `BufferedWriter` destructor.

Co-authored-by: woltx <[email protected]>
@l0rinc
l0rinc force-pushed the l0rinc/streams-buffered-write-failure branch from 4f06757 to 1c33fa0 Compare November 11, 2026 14:55
@maflcko

maflcko commented Nov 11, 2026

Copy link
Copy Markdown
Member

re-ACK 1c33fa0 🍛

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==

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

Concept ACK 1c33fa0. 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 (#36049 (comment)): 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; }

Comment thread src/node/blockstorage.cpp Outdated
// Write block
fileout << TX_WITH_WITNESS(block);
fileout.flush();
} catch (const std::runtime_error& e) {

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.

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

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 1c33fa0, 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."));

Comment thread src/streams.h
Comment on lines +701 to +705
~BufferedWriter()
{
Assume(m_buf_pos == 0); // Use explicit flush()
flush();
}

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.

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

re: maflcko #36049 (comment)

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 (#36049 (review)), 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

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.

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.

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.

re: l0rinc #36049 (comment)

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 #36049 (comment)

I guess it can't hurt to enable it still

Yes agree this could still be a good idea

Comment thread src/streams.h Outdated
flush();
}

//! Discard the buffered bytes even if writing them throws

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.

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

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:

Suggested change
//! Discard the buffered bytes even if writing them throws
//! 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.

A serialization failure can leave a partial record buffered. Keep the writer alive through the I/O error handler so it can drop those bytes before closing the file.
@maflcko

maflcko commented Nov 18, 2026

Copy link
Copy Markdown
Member

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.

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

Code review ACK 1584299. 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 #36049 (comment).

If you push again, feel free to squash aade8e8 into a4199b3 and 1584299 into 1c33fa0, 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()...").

Comment thread src/node/blockstorage.cpp Resolved
Comment thread src/streams.h
Comment on lines +707 to +708
//! Drop buffered bytes without writing them, e.g. after a write error.
void discard() { m_buf_pos = 0; }

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.

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

re: maflcko #36049 (comment)

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 (#36049 (comment)) and a general pattern for this class of problem (#36049 (comment)) both seem fine as follow-ups.

BOOST_CHECK_EXCEPTION(write_and_flush(), std::ios_base::failure, HasReason{"write failed"});
BOOST_CHECK_EQUAL(stream.write_attempts, 1);
}
}

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.

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

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);
}

Comment thread src/streams.h
Comment on lines +701 to +705
~BufferedWriter()
{
Assume(m_buf_pos == 0); // Use explicit flush()
flush();
}

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.

re: l0rinc #36049 (comment)

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 #36049 (comment)

I guess it can't hurt to enable it still

Yes agree this could still be a good idea

Comment thread src/node/blockstorage.cpp
Comment on lines +1176 to 1182
} 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."));
return FlatFilePos();
}

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.

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

@DrahtBot
DrahtBot requested a review from maflcko November 24, 2026 19:37
@l0rinc

l0rinc commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

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.

@maflcko

maflcko commented Nov 25, 2026

Copy link
Copy Markdown
Member

review ACK 1584299 🚿

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==

@maflcko

maflcko commented Nov 26, 2026

Copy link
Copy Markdown
Member

(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

l0rinc commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

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 up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants