Problem: Block and undo writers buffer serialized data, then rely on the BufferedWriter destructor to write the remaining bytes.
fwrite() can report fewer bytes written than requested after a local storage error, e.g., if the filesystem fills up while a block is being written (my 1 TB benchmarking servers have recently been filling up, so I've been seeing these failures more often).
AutoFile::write_buffer() converts that result into an exception, and because the destructor is implicitly non-throwing, the exception invokes std::terminate.
Calling flush() before destruction is insufficient on its own because a failed flush leaves the same bytes pending, so the destructor retries the write while the original exception unwinds.
I introduced this bug in #31551 when adding BufferedWriter.
I’d update the Fix section to include discard() and describe exactly what the destructor checks. The problem statement and reproducer can stay as written.
Fix: Block and undo writers now flush explicitly before destruction.
If serialization or writing throws std::ios_base::failure, they discard any pending bytes, log the error, close the file, and request shutdown through the existing fatal-error path.
BufferedWriter clears the pending byte count before writing because the stream may obfuscate the bytes in place and a short write may already have put some of them on disk, making a retry unsafe.
The destructor uses Assume to check that no bytes are pending before attempting a fallback flush.
flush() continues to propagate exceptions, and AutoFile remains unchanged.
<details> <summary>Manual write-error reproducer</summary>
Force the error path in AutoFile::write_buffer():
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, implicit flushing 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, then 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
</details>