mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:08:38 +00:00
streams: handle buffered write failures outside the destructor #36049
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36049
Loading…
Reference in a new issue
No description provided.
Delete branch "l0rinc/streams-buffered-write-failure"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem: Block and undo writers rely on the
BufferedWriterdestructor 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, invokingstd::terminatebefore 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 calldiscard()to drop any pending bytes, log the error, close the file, and request shutdown.BufferedWriter::flush()clears the pending byte count before callingwrite_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
Assumeto check that no bytes are pending before its fallback flush.Manual write-error reproducer
Force
AutoFile::write_buffer()to report a write failure even whenfwrite()succeeds.Before this change, flushing from the destructor invokes
std::terminate.With this change,
bitcoindlogs the write failure, completes normal shutdown, and exits with status 1.The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
Reviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.
Can you expand on why this is a problem? If there is a storage error, don't we have to crash anyways?
Yes, the node still has to stop, but
std::terminatebypasses the existing error handling.Handling the exception lets the node report the storage error and run its normal shutdown cleanup.
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.
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
BufferedWriterdestructor and requires explicit final flushing. It also adjustsAutoFilecleanup 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.
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.ACK
cac9501d35Earlier concerns remain unresolved; see the Run archive linked from the Review report.
🔵 Suggestion · Pending-byte
discard()behavior is untestedThe 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
1584299into1c33fa05would 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 ina4199b39discards pending bytes before writing, but its data-safety rationale appears only in the later comment-only commitaade8e8.Location: src/streams.h:705 (commit).
Review coverage was incomplete.
Reviewed:
1584299ae51d· Review report · Previous reportspermalink
LGTM
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.
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.ACK
6e17d090d1How 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?BufferedWriterflushes throughwrite_buffer()(which can throw in the destructor), whileAutoFile::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: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
flushnon-throwing, so thatm_buf_pos=0can 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 makeflushnon-throwing and instead use a nodiscard-result, but I think your suggested diff with theAssumewould be good regardless.Thanks for the hints @maflcko, played with it a bit, now
write_bufferisnoexceptwith aboolreturn value - and buffered flush failures log their cause and abort. Explicit final flushing is enforced withAssume, while destructor flushing remains as a prod fallback. This seems like a more holistic fix than before, let me know what you think.Ok, I see you now changed
write_bufferto be nodiscard andflushto 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
flushnodiscard (and possibly not even touchwrite_buffer/AutoFilehere). This would be more consistent with the existing AutoFilefclose"flush" method.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
AutoFilechanges and updatedflush()to return a checked result.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.
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.
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 dtornit in the third commit:
74c1322aee:Also, could remove the "destructor flushes" from the doxygen comment, because there is no need to document dead no-op code.
nit: Should document that a failed flush (returning false) will discard the buffer even though it wasn't written fully.
nit in
30ac211a91: I feel like logging should stay out of this module and the caller can log, if it wants to.nit in the first commit, could use C++11 {} init?
Restored the try/catch approach from the ACKed
6e17d09, following @maflcko's latest suggestion, and added the destructor’sAssume(m_buf_pos == 0)check. This meansflush()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.Done, thanks
Did something similar
Done
Moved
Inside
BOOST_CHECK_*I usually avoid brace init - I could use parenthesis around if you insist.Ok, I see. Maybe assign the lambda to a var
write_and_flush, which should also make the test code shroter?Are you sure you restored the old commit? I can't diff it and this line is still present in this pull:
reACK
74c1322aeeJust 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?)
Indeed, seem the previous push failed.
Sure, done
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:
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 onBufferedFilemethods?Here I used
/**to be consistent withBufferedWriter- 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:
re-ACK
1c33fa05df🍛Show signature
Signature:
Is this true? I don't think it matters for doxygen. This is just a style-nit
Concept ACK
1c33fa05df. Turning thestd::terminateon a failed block write into normal error handling is a clear improvement, but I thinkBufferedWriterneeds 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 aflush(). 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, whichflush()handles by clearingm_buf_posbefore it writes.AutoFiledoesn't have this problem, becausefclose()satisfies itsAssumewhether or not the close succeeds.The
try/catchblocks added toWriteBlockandWriteBlockUndoillustrate 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 fromflush(). Adiscard()method for error paths would mean every writer ends in an explicitflush()ordiscard(), with the destructor checking that, the same wayAutoFileworks.In commit "blockstorage: handle buffered write failures" (
1c33fa05df)Could this catch
std::ios_base::failureand callfileout.discard()(see the review summary), withfileoutdeclared before thetryso thecatchcan still call it?As written, the cleanup here is only correct for exceptions thrown by
flush(), which clearsm_buf_posbefore writing.std::runtime_errormakes it look like any failure in the block is handled, but if anything else threw while bytes were still buffered,~BufferedWriterwould run with data pending during unwinding, before thiscatchruns: theAssumewould 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 theAssume. Adding adiscard()call in the catch would make this actually exception-safe. Same inWriteBlockUndo.diff on top of
1c33fa05, with discard() from the review summaryIn commit "blockstorage: handle buffered write failures" (
1c33fa05df)re: maflcko https://github.com/bitcoin/bitcoin/pull/36049#issuecomment-5369507350
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
Assumein the destructor, asAutoFiledoes withfclose(). With adiscard()method (https://github.com/bitcoin/bitcoin/pull/36049#pullrequestreview-5946234150),BufferedWriterwould follow it too.On a clang-tidy check: the existing
bugprone-exception-escapecheck, which flags destructors that can throw, doesn't catch this bug. It reports nothing for~BufferedWriteron master, probably becauseAutoFile::write_buffer()is defined instreams.cpp, where the check can't see that it throws. So it would probably need a custombitcoin-tidycheck.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
~BufferedWriterwere 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 explicitflush()ordiscard()calls, and if the writer were destroyed because some other exception was already propagating, that original exception would take precedence instead of the program callingstd::terminate.This is how Cap'n Proto handles it: destructors are declared
noexcept(false), andkj::UnwindDetectorcatches 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 atryblock.The downside is that a throwing destructor is only safe when no
noexceptcode sits between it and thecatch. Holding the writer instd::unique_ptr,std::optionalorstd::vector, or destroying it inside anoexceptfunction, would turn the error back intostd::terminate, so making this fully safe would need abitcoin-tidycheck that flags those uses.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 callingfwrite()and only advances its position after a successful write, so a second attempt would XOR the bytes again and write them unobfuscated. A shortfwrite()can also leave part of the buffer already on disk. Maybe:Thanks Russ, added your two commits on top: I’m curious what the other reviewers think.
This also reminded me of
try/finallyandtry-with-resourcesin Java - I’d like us to find a structure that handles cleanup when we leave the scope, since it’s easy to miss a manualflush()ordiscard()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.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.
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.
Code review ACK
1584299ae5. This givesBufferedWritera safer interface: every writer ends in an explicitflush()ordiscard(), the destructor'sAssumechecks that, and a failed flush no longer leaves bytes behind to be written again. It also replaces thestd::terminateon 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
catchblocks tostd::ios_base::failurewithout 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 thinkdiscard()itself is right.On the error handling in
WriteBlockandWriteBlockUndo, 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 theBufferedWriterinterface, 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
aade8e8a37intoa4199b39f9and1584299ae5into1c33fa05df, so theflush()change comes with its explanation and the error handlers come withdiscard(). 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()...").re: https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4485659497
Note: the latest push narrows this to
std::ios_base::failurein1584299ae5(my suggestion from before I understood caller error handling), so astd::runtime_errorthat isn't an I/O error is no longer handled here. FromWriteBlockit would still reach the existingstd::runtime_errorhandlers inAcceptBlockandLoadGenesisBlock, but fromWriteBlockUndonothing catches it beforeProcessMessages, 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 theWriteBlockcatch just discard, close and rethrow, so mentioning it in case you have an opinion.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 catchstd::runtime_erroraround it (AcceptBlockcallsFatalError, andLoadGenesisBlockfails init), I think the simplest and most straightforward way of dealing with errors here would be for thiscatchto only clean up and rethrow: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, andAcceptBlockwould report the write error itself instead of adding a misleading "Failed to find position to write new block to disk".WriteBlockUndois different: nothing between it and thecatchblocks inProcessMessageshandles 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 thinkWriteBlockUndoshould keep its ownFatalErrorhandler for now.Ideally a follow-up would make
WriteBlockandWriteBlockUndoconsistent: either add astd::runtime_errorcatch around theWriteBlockUndocall too, so both functions can clean up and rethrow, or handle every error insideWriteBlockand drop the catches in its callers.In commit "blockstorage: discard buffered bytes on I/O errors" (
1584299ae5)re: maflcko https://github.com/bitcoin/bitcoin/pull/36049#issuecomment-6971812396
Agreed, and only
std::ios_base::failureis caught here, so other exceptions aren't handled in these functions.That's true in debug builds, where the destructor's
Assumeaborts. 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: thecatchdrops whatever is pending itself, so it no longer depends onflush()having cleared the buffer before it threw, and the destructor'sAssumechecks a contract the class states (finish withflush()ordiscard()) rather than something only a failedflush()can do.I'm not sure I follow this one. If the
flush()inside thetryfails, thecatchcallsdiscard(), and the destructor'sflush()has nothing left to write. If you mean a path that leaves the scope without callingflush()ordiscard()(the interrupt case I mentioned), then yes: the destructor's fallback flush can still fail and terminate, and theAssumeis there to catch such paths in debug builds.I think the main goal here is the
BufferedWriterinterface, 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.re: l0rinc https://github.com/bitcoin/bitcoin/pull/36049#discussion_r4606518586
A follow-up sounds right for deciding and implementing it. For reference, I think the options are roughly these:
flush()anddiscard()calls, as in this PR and likeAutoFile::fclose(), and add abitcoin-tidycheck 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'sAssumein debug builds.std::uncaught_exceptions()with its value at construction), and keep requiring an explicitflush()on the normal path, checked by theAssumeas now. Error paths would no longer need adiscard()call. Abitcoin-tidycheck would also be simpler than for option 1, since it would only need to check normal exits, not which calls can throw.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 anoexceptfunction would turn errors back intostd::terminate, so this would need abitcoin-tidycheck too.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
Yes agree this could still be a good idea
In commit "blockstorage: discard buffered bytes on I/O errors" (
1584299ae5)Could add a test for
discard()next tobuffered_writer_flush_failure, checking that the pending bytes are dropped and the destructor doesn't write them (or hit itsAssume). I should have included one in my commit. The Ralph review flagged this too: the existing failure test would still pass ifdiscard()did nothing.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.I don't mind pushing this if reviewers think this is simpler or better.
review ACK
1584299ae5🚿Show signature
Signature:
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.
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.