Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, 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
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 Feel free to reuse anything you find useful. |
d5f4241 to
cac9501
Compare
|
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 |
cac9501 to
6e17d09
Compare
|
How is this different from AutoFile? Shouldn't this use the same |
Would you prefer keeping the explicit flushes, adding ~BufferedWriter()
{
Assume(m_buf_pos == 0);
try {
flush();
} catch (const std::runtime_error& e) {
LogError("Failed to flush buffered writer: %s", e.what());
}
} |
|
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 |
6e17d09 to
e334c0e
Compare
|
Thanks for the hints @maflcko, played with it a bit, now |
|
Ok, I see you now changed My preference would be to make |
e334c0e to
74c1322
Compare
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... |
| 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); |
There was a problem hiding this comment.
nit in the first commit, could use C++11 {} init?
There was a problem hiding this comment.
Inside BOOST_CHECK_* I usually avoid brace init - I could use parenthesis around if you insist.
There was a problem hiding this comment.
Ok, I see. Maybe assign the lambda to a var write_and_flush, which should also make the test code shroter?
| pos.nPos += STORAGE_HEADER_BYTES; | ||
| // Write block | ||
| fileout << TX_WITH_WITNESS(block); | ||
| Assert(fileout.flush()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Indeed, seem the previous push failed.
| Assume(m_buf_pos == 0); | ||
| Assert(flush()); |
There was a problem hiding this comment.
nit in the third commit: 74c1322:
Assume(m_buf_pos == 0); // Use explicit flush()
Assert(flush()); // no-op, because flush was already called explicitlyAlso, could remove the "destructor flushes" from the doxygen comment, because there is no need to document dead no-op code.
There was a problem hiding this comment.
Did something similar
There was a problem hiding this 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.
(edit: previous push didn't succeed for some reason)
| 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); |
There was a problem hiding this comment.
Inside BOOST_CHECK_* I usually avoid brace init - I could use parenthesis around if you insist.
| pos.nPos += STORAGE_HEADER_BYTES; | ||
| // Write block | ||
| fileout << TX_WITH_WITNESS(block); | ||
| Assert(fileout.flush()); |
| Assume(m_buf_pos == 0); | ||
| Assert(flush()); |
There was a problem hiding this comment.
Did something similar
|
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.
74c1322 to
4f06757
Compare
maflcko
left a comment
There was a problem hiding this comment.
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==
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]>
4f06757 to
1c33fa0
Compare
|
re-ACK 1c33fa0 🍛 Show signatureSignature: |
ryanofsky
left a comment
There was a problem hiding this comment.
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; }| // Write block | ||
| fileout << TX_WITH_WITNESS(block); | ||
| fileout.flush(); | ||
| } catch (const std::runtime_error& e) { |
There was a problem hiding this comment.
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."));| ~BufferedWriter() | ||
| { | ||
| Assume(m_buf_pos == 0); // Use explicit flush() | ||
| flush(); | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
On a clang-tidy check: the existing
bugprone-exception-escapecheck, 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.
There was a problem hiding this comment.
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()ordiscard()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:
- Keep explicit
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. - 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 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. - 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 anoexceptfunction would turn errors back intostd::terminate, so this would need abitcoin-tidycheck too. - 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
| flush(); | ||
| } | ||
|
|
||
| //! Discard the buffered bytes even if writing them throws |
There was a problem hiding this comment.
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:
| //! 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.
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
left a comment
There was a problem hiding this comment.
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()...").
| //! Drop buffered bytes without writing them, e.g. after a write error. | ||
| void discard() { m_buf_pos = 0; } |
There was a problem hiding this comment.
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); | ||
| } | ||
| } |
There was a problem hiding this comment.
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);
}| ~BufferedWriter() | ||
| { | ||
| Assume(m_buf_pos == 0); // Use explicit flush() | ||
| flush(); | ||
| } |
There was a problem hiding this comment.
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()ordiscard()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:
- Keep explicit
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. - 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 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. - 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 anoexceptfunction would turn errors back intostd::terminate, so this would need abitcoin-tidycheck too. - 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
| } 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(); | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I don't mind pushing this if reviewers think this is simpler or better.
|
Thanks, Russ! I've updated the PR description and removed the leftover AI proofreading note. |
|
review ACK 1584299 🚿 Show signatureSignature: |
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 I'd expect a successful 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. |

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.