Rust BufWriter trace showing the first record accepted by the sink and the second still buffered after a flush error.

Catch Rust BufWriter Failures Before Reporting an Export as Saved

Sat, Dec 5, 2026

An export function accepts both records, returns Ok(()), and leaves its consumer with only the first line, A=1. The line ends with a newline. It parses cleanly. An operator reading that line has no way to tell that the caller also submitted B=2. Yet the producer can point to a successful call to write_all covering both records. Which part of this exchange justified reporting the export as saved?

The answer depends on who accepted the bytes. Here the function calls write_all on a BufWriter. All eight bytes fit in its queue. The next writer in the chain gets an opportunity to refuse bytes only when the wrapper tries to pass them along. If the function leaves that work to destruction, its caller can receive success after an I/O error has already cut the export short.

To see the failure, give the inner writer a ledger that survives the wrapper. Let it accept four bytes, refuse the next write, and record every call to its own flush. A second switch can refuse a flush even after all eight bytes arrive. These two failures need different responses. The evidence that distinguishes them is small enough to inspect by hand. It tells the caller whether to flush a retained remainder, retry just the sink's flush, or stop before another append duplicates a record.

Define the export completion promise

For this export, “saved” means the designated sink has accepted exactly the following eight bytes in order, once, and its own flush has succeeded after the final byte. In decimal the consumer expects 65 61 49 10 66 61 50 10. Positions four and eight are line feeds. An export with two copies of the first record fails this promise even if its last eight bytes match. An export missing the final line feed also fails, even if a text viewer displays both values.

The consumer manifest is a literal specified independently of the producer. The harness constructs its input from a Rust byte string and compares the entire ledger against those eight decimal values. It never takes whatever came back from the sink and declares that value to be the next expected result. That independence matters on the recovery path, where a plausible-looking pair of final records could conceal an earlier append.

Ownership follows the promise. The component that owns the export attempt keeps the writer until it has a result for the last required operation. On success it can release the candidate to the consumer. On error it withholds the acknowledgement and keeps enough state for someone to decide what can be retried. The test plays both roles. It can inspect a trusted sink ledger that an arbitrary implementation of Write need not expose.

The Rust documentation for BufWriter distinguishes buffering from delivery to the wrapped writer and recommends explicit flushing when errors matter. The byte manifest and the successful inner flush define this application's completion policy. The broader discussion of the engineering context for Rust helps frame the review question here. Safe ownership gives the service clear control of a live writer. The service still has to choose how far output must travel before a caller can rely on success.

Build a writer that records and refuses bytes

Implement the sink with a Vec<u8> of accepted bytes, a remaining allowance, and separate counts for write calls, flush attempts and successful flushes. The wrapper gets a Sink. The observer gets an Rc pointing to the same ledger. The caller can inspect that ledger even after the wrapper has been destroyed. Each sink operation takes a short mutable borrow through RefCell.

The write budget belongs to the sink across calls. With an allowance of four, a request for eight bytes appends the first four and returns Ok(4). The next nonempty request sees zero allowance and returns an error before touching the vector. Under the Rust Write contract, an error from a single write means that call accepted zero bytes. A sequence of writes can include earlier successes. In particular, an error from write_all does not tell the caller that the whole input is available for safe replay.

Set the byte budget before each case

Every scenario starts by calling fresh with its own ledger. Two checkpoints within a recovery scenario deliberately share that scenario's state. The sink has no clock, and no other producer can consume an allowance. The input never changes. Even the replay control appends to the same sink using the same input. Save the entire block as export_probe.rs.

use std::cell::RefCell;
use std::io::{self, BufWriter, ErrorKind, Write};
use std::rc::Rc;

const INPUT: &[u8] = b"A=1\nB=2\n";
const FIRST: &[u8] = b"A=1\n";
const SECOND: &[u8] = b"B=2\n";
// Consumer manifest: literal byte values, independent of INPUT and the writer.
const EXPECTED: &[u8] = &[65, 61, 49, 10, 66, 61, 50, 10];

#[derive(Default)]
struct Ledger {
    accepted: Vec<u8>,
    writes: usize,
    flushes: usize,
    flush_ok: usize,
    allowance: usize,
    refuse_flush: bool,
}

type Log = Rc<RefCell<Ledger>>;
struct Sink(Log);
type Writer = BufWriter<Sink>;

impl Write for Sink {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        let mut s = self.0.borrow_mut();
        s.writes += 1;
        if bytes.is_empty() {
            return Ok(0);
        }
        if s.allowance == 0 {
            return Err(io::Error::other("write budget exhausted"));
        }
        let n = bytes.len().min(s.allowance);
        s.accepted.extend_from_slice(&bytes[..n]);
        s.allowance -= n;
        Ok(n)
    }

    fn flush(&mut self) -> io::Result<()> {
        let mut s = self.0.borrow_mut();
        s.flushes += 1;
        if s.refuse_flush {
            return Err(io::Error::other("sink flush refused"));
        }
        s.flush_ok += 1;
        Ok(())
    }
}

fn fresh(allowance: usize, refuse_flush: bool) -> (Writer, Log) {
    let log = Rc::new(RefCell::new(Ledger {
        allowance, refuse_flush, ..Ledger::default()
    }));
    let writer = BufWriter::with_capacity(1024, Sink(Rc::clone(&log)));
    assert!(writer.capacity() >= 1024);
    (writer, log)
}

fn ledger(log: &Log, bytes: &[u8], writes: usize, flushes: usize, ok: usize) {
    let s = log.borrow();
    assert_eq!(s.accepted.as_slice(), bytes);
    assert_eq!((s.writes, s.flushes, s.flush_ok), (writes, flushes, ok));
}

fn queue(writer: &mut Writer, log: &Log) -> io::Result<()> {
    writer.write_all(INPUT)?;
    assert_eq!(writer.buffer(), EXPECTED);
    ledger(log, b"", 0, 0, 0);
    Ok(())
}

fn error_is(e: &io::Error, message: &str) {
    assert_eq!(e.kind(), ErrorKind::Other);
    assert_eq!(e.to_string(), message);
}

fn recover(writer: Writer) -> Writer {
    match writer.into_inner() {
        Ok(_) => panic!("expected a drain failure"),
        Err(failed) => {
            error_is(failed.error(), "write budget exhausted");
            failed.into_inner()
        }
    }
}

fn extract(writer: Writer) -> (Sink, Vec<u8>) {
    let (sink, remaining) = writer.into_parts();
    match remaining {
        Ok(bytes) => (sink, bytes),
        Err(_) => panic!("WriterPanicked: stop; write extent is uncertain"),
    }
}

fn premature(mut writer: Writer, log: &Log) -> io::Result<()> {
    queue(&mut writer, log)
}

// The caller owns this wrapper across both success and error.
fn export<W: Write>(out: &mut BufWriter<W>, bytes: &[u8]) -> io::Result<()> {
    out.write_all(bytes)?;
    out.flush()
}

fn main() -> io::Result<()> {
    let (mut w, log) = fresh(8, false);
    queue(&mut w, &log)?;
    w.flush()?;
    assert!(w.buffer().is_empty());
    ledger(&log, EXPECTED, 1, 1, 1);
    println!("baseline: exact bytes, flush OK");

    let (w, log) = fresh(4, false);
    premature(w, &log)?;
    ledger(&log, FIRST, 2, 0, 0);
    println!("drop: caller got Ok, only A accepted");

    let (mut w, log) = fresh(4, false);
    queue(&mut w, &log)?;
    error_is(&w.flush().expect_err("partial drain"), "write budget exhausted");
    ledger(&log, FIRST, 2, 0, 0);
    assert_eq!(w.buffer(), SECOND);
    let (sink, pending) = extract(w);
    assert!(Rc::ptr_eq(&sink.0, &log));
    assert_eq!(pending, SECOND);
    ledger(&log, FIRST, 2, 0, 0);
    println!("partial + parts: A accepted, B retained, no extraction I/O");

    let (mut w, log) = fresh(8, true);
    queue(&mut w, &log)?;
    error_is(&w.flush().expect_err("sink flush failure"), "sink flush refused");
    assert!(w.buffer().is_empty());
    ledger(&log, EXPECTED, 1, 1, 0);
    log.borrow_mut().refuse_flush = false;
    w.flush()?;
    ledger(&log, EXPECTED, 1, 2, 1);
    println!("sink flush: failed after A+B, flush-only retry OK");

    let (mut w, log) = fresh(4, false);
    queue(&mut w, &log)?;
    let mut recovered = recover(w);
    ledger(&log, FIRST, 2, 0, 0);
    assert_eq!(recovered.buffer(), SECOND);
    println!("into_inner: Other, A accepted, B queued; retry same wrapper");
    log.borrow_mut().allowance = 4;
    recovered.flush()?;
    assert!(recovered.buffer().is_empty());
    ledger(&log, EXPECTED, 3, 1, 1);
    println!("resume: exact bytes, flush OK");

    let (mut w, log) = fresh(8, true);
    queue(&mut w, &log)?;
    let sink = w.into_inner().map_err(|e| e.into_error())?;
    ledger(&log, EXPECTED, 1, 0, 0);
    assert!(Rc::ptr_eq(&sink.0, &log));
    println!("successful unwrap: A+B accepted, zero inner flush calls");

    let (mut w, log) = fresh(4, false);
    queue(&mut w, &log)?;
    let (sink, pending) = extract(recover(w));
    assert_eq!(pending, SECOND);
    ledger(&log, FIRST, 2, 0, 0);
    log.borrow_mut().allowance = 8;
    let mut replay = BufWriter::with_capacity(1024, sink);
    export(&mut replay, INPUT)?;
    ledger(&log, b"A=1\nA=1\nB=2\n", 3, 1, 1);
    assert_ne!(log.borrow().accepted.as_slice(), EXPECTED);
    println!("full replay: A+A+B, flush OK, manifest rejected");
    Ok(())
}

Run the following in a Linux shell with a recent stable Rust toolchain. Keep the source and terminal transcript together. Shell tracing records the actual build command, and the final line is reached only if compilation and every assertion succeed.

set -ex
rustc --version
rustc --version --verbose
uname -srm
sha256sum export_probe.rs
rustc --edition=2021 -D warnings export_probe.rs -o export_probe
./export_probe
printf 'exit status: %s\n' "$?"

Evidence status: expected, unexecuted. No Rust compiler was available for this article. The numerical checkpoints and output lines below are predictions to verify by compiling and running this file. The public API pages and implementation listing reviewed on 5 December 2026 correspond to standard-library documentation version 1.100.1, revision 20ddd0171. That documentation version is not a measured compiler version. If a counter differs on your toolchain, preserve the first failed assertion, compiler details and source before drawing a conclusion about a change in behavior.

Establish the passing flush sequence

Start with an allowance of eight and a sink that accepts a flush. The code requests a capacity of 1024 bytes and checks the capacity actually reported. The capacity check alone cannot establish the starting state. The queue function submits the payload with write_all, reads buffer(), then checks all three counters and the accepted vector. At this checkpoint the wrapper should contain the complete manifest. The observer should see an empty vector, zero writes and zero flushes. Together these checks establish the starting state for a deferred drain.

Now call flush() on the wrapper and inspect it again while it is alive. The queue should be empty. The sink should have accepted the complete vector on one write and recorded one successful flush. Check the bytes through the observer even though the call returned success. A green return tests one part of the promise. Exact equality picks up a bad producer literal, an extra record or an unintended write to this sink earlier in the attempt.

This is also how to distinguish a fixture failure from an export failure. If the first inspection already finds bytes at the sink, the experiment did not set up the intended buffered case. If the first inspection passes but the last flush counter is zero, the claimed flush boundary lacks evidence. Leave the first failed assertion visible. A final comparison of file lengths or a screenshot of two displayed lines cannot tell the reviewer where the two paths diverged.

Observing the receiving writer is also central to following a writer across log rotation. Here the sink identity remains fixed. In subsequent cases only the allowance, the flush switch or the operation chosen by the export owner changes. Keep the passing case in the same executable as the failures so a later change to the sink cannot quietly invalidate the comparison.

Let destruction hide a drain failure

Run the same setup with an allowance of four. The premature function owns the wrapper by value, queues both records and returns the result of that operation. Rust drops its local writer as control leaves the function. The shared ledger stays alive in the caller, which can inspect what happened during the lifetime of that otherwise inaccessible object. There is no sleep between the function returning and the caller reading the ledger. Waiting longer would add no evidence.

The expected write count is two. The first call consumes the allowance and records A=1\n. The second sees a nonempty remainder and refuses it. The sink's flush counter stays at zero. The consumer now has a syntactically complete first record and no second record. This particular choice of budget makes a content check essential. A parser that accepts every complete line in front of it can finish successfully. It needs the independent expectation of a second line to identify the missing data.

Identify the false success return

Read the function from the caller's side. The last fallible expression constructs the return value. Dropping the local writer happens before the caller can inspect that value, but destruction supplies no Result that could replace it. The caller's ? therefore continues down the success path. The standard library documents that the destructor attempts to write pending data and ignores errors encountered during that attempt. An ordinary scope exit is enough to expose this defect. The fixture has no panic or abrupt termination.

At this point a failure ledger can describe the missing suffix by comparing accepted bytes with the manifest. The caller cannot inspect or take a suffix out of the destroyed wrapper. Mark the queue as unavailable after drop. Recording “zero bytes buffered” here would erase the difference between an observed empty queue and the loss of the only object that could report its contents. The consequence is visible on both sides of the handoff. The consumer can act on a false receipt, and the producer has lost the writer it could have used to send the missing record.

Surface the error with an explicit flush

Move the fallible operation back inside the writer's lifetime. The fresh four-byte case starts at the same checkpoint as the drop case. When the test calls w.flush(), the sink accepts the first four bytes and refuses the next write. This time the caller receives an io::Error of kind Other with the fixture's message write budget exhausted. The test requires that particular error. An assertion that merely expects some failure could pass when the sink fails for a different reason at a different stage.

Three observations locate the failure. The accepted bytes are exactly A=1\n. The wrapper's buffer() exposes exactly B=2\n. The sink has seen two write calls and zero calls to its own flush method. Rust BufWriter flush errors can therefore originate in a write before the sink's own flush runs. The first part of the wrapper operation must send the queued bytes. An error there returns control immediately.

In the reviewed BufWriter implementation, the drain tracks successful write counts and removes that many bytes from the front of the queue as it exits. That accounts for the predicted four-byte suffix. The precise suffix and call counts in this scenario are implementation observations to verify on the recorded toolchain. Code that depends on them should check them at the recovery point, particularly after a runtime change.

There is a similar evidence problem in separating an in-memory update from a stored HDF5 change. In this Rust case the input really did reach the wrapper. Reading the live queue tells the recovery owner which bytes remain under its control. Reading the ledger explains why sending the entire original slice again would be an append after a successful prefix. Preserve those observations together before modifying the allowance or letting ownership pass out of scope.

Inspect a failure after every byte was accepted

Set an allowance of eight and enable the independent flush-error switch. The same buffered input can now drain completely. The queued-byte comparison after the failing call should find an empty slice, and the accepted vector should satisfy the full byte manifest. The wrapper still returns Err. The sink recorded one write, one flush attempt and zero successful flushes. Its error message in this case is sink flush refused.

Consider what a support engineer could infer from a dump of the vector alone. Both records are present, both newlines have the expected value, and the length is eight. All of that is true of the passing case as well. Asking the consumer to count its rows again would produce the same answer. The missing piece of evidence is the final operation required by the agreement. The sink increments the successful-flush counter only after its refusal check, so its two flush counters answer different questions.

Keep the queue and the sink states distinct

Decide which operation is outstanding before prescribing a retry. This synthetic sink implements a failed flush by returning an error without mutating any bytes. Clearing the switch and calling the same wrapper's flush a second time is therefore a bounded experiment. The expected write count stays at one. The number of flush attempts advances to two, and the successful count advances to one. Only now does this case satisfy both sides of the promise. Appending either record would change a vector that was already correct.

That retry is justified by the implementation of this sink, the absence of other writers and the still-owned wrapper. A different inner writer may document a different consequence of a failed flush. If the caller cannot establish whether another flush is meaningful on that writer, retain the error and route the attempt to its owner. The error kind alone is insufficient. Both failure switches in the lab deliberately return Other; one stops after a prefix, the other after the entire payload. An error classifier keyed only on that enum value would give both callers the same advice.

Recover the wrapper from into_inner

Some export helpers consume a buffered writer because their caller wants the underlying writer back. That changes where the caller looks for recovery state. BufWriter::into_inner(self) consumes the wrapper and attempts to drain its pending bytes. On success it yields the inner writer. On failure the result contains an IntoInnerError<BufWriter<W>>. The input binding has moved, but the error object now owns the buffered writer the caller needs.

In the fresh four-byte case, recover matches the result explicitly. Its Err(failed) arm borrows the I/O error using failed.error(), checks the kind and fixture message, then consumes that same error container with failed.into_inner(). This second operation returns the buffered writer. It allows inspection of buffer() and a subsequent recovery attempt. The similar method names make their receiver types worth spelling out in a code review. Switching from the wrapper to the error container changes both the meaning of the call and its return type.

Hold on to the container until you have chosen an owner for the wrapper. Converting it straight into an io::Error gives the caller a convenient error to log but relinquishes the enclosed writer. If destruction then attempts another drain, a later look at the sink could describe a different state from the one that caused the original error. When recovery matters, arrange to keep the value you need on the error path. Recording an error string cannot substitute for retaining that value.

Check the scope of unwrapping

The failing drain alone cannot tell us whether a successful unwrap would invoke the sink's flush. Give a fresh sink eight bytes of allowance and configure its own flush to fail. If unwrapping called that method, the sink would record the attempt. In the inspected implementation, into_inner calls the internal drain, flush_buf. The predicted outcome here is a successful unwrap, all eight bytes accepted and a flush counter of zero. The still-enabled refusal switch makes that zero a meaningful control.

The public description of unwrapping refers to flushing out the buffer. Its scope is the queued bytes. The implementation's separate call to the underlying writer's flush belongs to the wrapper's explicit flush operation. Those descriptions are consistent. A service that promises a successful inner flush should perform one explicitly and handle its result even when it also needs the raw writer back.

Take the remaining bytes out without another write

There are cases where the immediate job is to preserve evidence and stop making I/O attempts. Start at the failed explicit drain. The caller owns a wrapper containing the second record and has already observed the first at the sink. Calling into_inner on that wrapper would try to drain it again. Calling into_parts instead consumes it and yields the inner writer along with a result for the buffered bytes. The operation performs no drain.

The fixture brackets extraction with the same ledger assertion. Before extraction there have been two write calls, no flush attempts and four accepted bytes. After extraction all three observations must be identical. The recovered sink refers to the very same allocation as the observer, checked with Rc::ptr_eq. The returned vector must equal the independently specified second record. These checks would catch an extraction routine that silently retried the write, returned a replacement sink, or handed off the original eight bytes as pending.

Read the type of the second part carefully. It is a Result<Vec<u8>, WriterPanicked>. A prior panic during an inner write can make the extent of previous progress uncertain. The harness explicitly stops on that variant. It injects ordinary I/O errors only, so a panic signal would put this run outside the fixture's assumptions. In particular, access to bytes associated with an uncertain operation would not establish which of them a consumer had already received.

The resulting ownership question also arises when preserving bytes across Go buffer reuse. Here the vector obtained from the ordinary successful extraction is owned and the input has always been constant. What the next owner needs is the vector's meaning. Label it as pending after the recorded prefix on this particular sink. Include the error and the fact that the sink has never completed a flush. Once the wrapper has been taken apart, nobody else can call flush on that old wrapper. Any continuation must deliberately take responsibility for the returned writer and remainder.

Resume using the recovered buffer

Use the failed unwrap case for the positive recovery test. Keep the BufWriter returned by the error. Its queue should be the second record. The observer should still see the first record and two write attempts. Before granting any more allowance, compare each side with its own literal. A length of four on each side is necessary but too weak. If both sides contained the first record, a length-based check would authorize the wrong continuation.

Grant exactly four further bytes to the same sink. Call recovered.flush() without a preceding write_all. The wrapper already owns the bytes it needs to submit. The additional write should append B=2\n and consume the allowance. Its own queue should then be empty. The underlying sink gets its first flush call and accepts it. Across the whole attempt the ledger should report three writes, one flush attempt and one successful flush. Two writes came before recovery, including the one that refused the remainder.

The final comparison uses the full consumer manifest. It covers the accepted prefix as well as the bytes sent during recovery. A test of just the last four bytes would pass even if the prefix had been duplicated or removed. Keeping the original ledger through the successful retry lets the reviewer account for the entire export. Resetting the ledger at the time of repair would turn the experiment into a test of a different starting state.

Retain the evidence needed to resume

At the handoff, record the following facts together. The harness checks the first three in code and emits the intended retry action before changing the budget.

Evidence at failure

Value expected before enabling writes

Inner error

Other, message write budget exhausted

Previously accepted

A=1\n, on the sink still inside the recovered wrapper

Pending in that wrapper

B=2\n, with zero successful sink flushes

Authorized next operation

Grant four bytes and flush this wrapper once

The owner should be able to point to the writer it will use when following that last instruction. A logged suffix documents an observation. The live wrapper preserves the queue that will actually be used. If another component has taken the writer, written through its inner handle, or allowed another drain since the observation, reacquire evidence before proceeding. A new instance containing the same source bytes begins with a different queue and cannot inherit this retry decision.

Reproduce a duplicate caused by full replay

A useful negative control starts at exactly the state from which a correct retry was possible. The harness makes a fresh four-byte sink, queues eight bytes, and obtains the wrapper from a failed unwrap. It takes the wrapper apart, verifies that the pending vector is the second record, and keeps the returned sink. At this point there is no live old wrapper that could perform another write on destruction. The first record is present exactly once.

Now model a caller that knows only the original request and chooses to resubmit it. Grant eight additional bytes, wrap the same sink again, and invoke the result-returning export helper with the entire original input. The helper successfully submits all eight bytes and flushes. The predicted sink contents, written as an escaped byte string, are A=1\nA=1\nB=2\n. The first four bytes belong to the interrupted attempt. The next eight belong to the replay. Every individual write count is truthful.

The harness asserts the full twelve-byte result, then asserts that the consumer's eight-byte manifest rejects it. Both checks matter. A test that requires just a mismatch could pass because of an unrelated defect that produced no records at all. The exact negative expectation demonstrates which record was duplicated and keeps the replay case distinguishable from the truncated drop case. Keeping a successful final flush in this control also demonstrates the importance of checking the sink's initial state.

The related account of why replaying a download can duplicate rows gives a downstream reviewer a reason to ask about previous appends. For this export, ask for the complete accepted extent, the sink's identity, and the evidence tying that extent to the same attempt. If a caller lost its wrapper and the sink offers no trustworthy view of prior side effects, a fresh invocation supplies none of that evidence. Hold the candidate until the downstream owner can reconcile what is already present. Finding both expected keys somewhere in the output is too weak a release criterion.

Put finalization inside the result-returning function

The helper in the source has two fallible operations. Both run on the same borrowed writer. Use it where the service currently issues its receipt.

fn export<W: Write>(out: &mut BufWriter<W>, bytes: &[u8]) -> io::Result<()> {
    out.write_all(bytes)?;
    out.flush()
}

The first error returns directly to the caller. If the first operation succeeds, the value returned from flush becomes the result of the function. Success can now travel to the caller only after the writer has reported success from explicit finalization. The caller owns out before the call and still owns it on either return path. That makes this signature suitable for a caller that will inspect the wrapper, retain it for a bounded retry, or deliberately take it apart to suspend further I/O.

A borrowed writer also sets a precondition. Its queue belongs to this export and its destination must be in the agreed starting state. If the caller passes an already-used sink containing the first record, this helper can successfully append a complete payload and leave the wrong export behind. The replay control uses this very helper to demonstrate that possibility. For the fixture, the outer owner gates release on the manifest and the inner-flush evidence after the helper returns. A generic W: Write offers no ledger from which a helper could reconstruct an arbitrary consumer's starting state.

Treat a failure from the first operation with care as well. The fixture ensures that all eight input bytes enter an empty queue before its induced failure. A larger input or a prefilled wrapper can cause I/O during write_all itself. If that call fails, the caller may lack a total count for the portion of this particular request already accepted. Do not apply the four-byte recovery arithmetic to that path. Preserve the object and the stage at which the failure occurred. In a service whose error report must distinguish the stages, attach that context where each call returns its error.

Specify the extra boundary for a real file

For a BufWriter<File>, describe the file promise separately. A service that promises file synchronization first checks the buffered write, then explicitly flushes the wrapper. While it still owns the writer it invokes out.get_ref().sync_all()? if the contract includes file content and metadata synchronization. If the promise concerns content and permits omitting some metadata work, evaluate sync_data() for that contract. Propagate the selected synchronization result before issuing a receipt. The Rust File documentation describes both operations and the platform-dependent scope of the distinction.

Ordering matters. A synchronization request issued while the second record is still in a user-space buffer cannot establish that the file received that record. Likewise, a failed synchronization after a successful buffered flush gives the owner a synchronization error to handle. Appending both records again would risk duplication. The synthetic sink exercises one fallible finalization policy in memory. A file-oriented service needs evidence for the additional operation it actually advertises.

Review the completion evidence as a table

Read each row at its named checkpoint. A and B in the table include their terminating line feeds. “A B” denotes the concatenation of those two four-byte records in that order. The queue column describes the wrapper at that point, except for the explicitly labeled returned vector. The flush column gives the result of calling the wrapper's flush. An unwrap can attempt to write bytes without such a call. Recording which operation ran prevents a successful drain from being entered as a successful sink flush.

Expected checkpoint

Initial write_all

Sink bytes

Pending

Explicit flush

Wrapper recovery or ownership

Caller decision

Before first drain

Ok

Empty

A B

Uncalled

Live

Wait

Passing flush

Ok

A B

Empty

Ok

Live

Accept

Scope exit

Ok

A

Unavailable

Uncalled

Destroyed

Reject false success

Partial drain

Ok

A

B

Err during write

Still owned

Hold for suffix decision

Parts after partial drain

Ok

A

B, returned vector

Prior Err

Sink and vector now owned separately

Preserve

Inner flush refuses

Ok

A B

Empty

Err from sink flush

Still owned

Hold, no byte replay

Flush-only retry

Ok

A B

Empty

Ok on retry

Same wrapper

Accept

Unwrap after partial drain

Ok

A

B

Uncalled

From IntoInnerError

Authorize bounded resume

Flush recovered wrapper

Ok

A B

Empty

Ok

Same recovered wrapper

Accept

Successful unwrap alone

Ok

A B

Wrapper consumed

Uncalled

Inner sink returned

Flush evidence missing

Full replay after prefix

Ok twice

A A B

Empty on replay

Ok on replay

New wrapper, same sink

Reject duplicate

The program emits the following lines only after reaching the associated assertions. This is expected output. When recording an actual run, retain its exit status and diagnostic output as well. Several completed lines followed by an assertion failure constitute evidence up to that checkpoint only.

baseline: exact bytes, flush OK
drop: caller got Ok, only A accepted
partial + parts: A accepted, B retained, no extraction I/O
sink flush: failed after A+B, flush-only retry OK
into_inner: Other, A accepted, B queued; retry same wrapper
resume: exact bytes, flush OK
successful unwrap: A+B accepted, zero inner flush calls
full replay: A+A+B, flush OK, manifest rejected

Review the byte columns vertically. The passing flush, the refused inner flush and the successful unwrap alone all show identical sink bytes. Their caller decisions differ because their finalization evidence differs. Now read across the partial-drain row. Its pair of byte columns explains why the original wrapper can make progress after repair. Finally, compare the replay row with the passing flush. Both end with an empty queue and an explicit success. Only one has the candidate the consumer requested.

Choose a bounded recovery or stop condition

A release decision has to give the next owner an operation they can actually perform. “Retry on I/O error” leaves unresolved which bytes to supply, which writer owns them and whether the destination can accept another attempt. Use the following table at the point where the caller would otherwise mark the export complete. Its retry permissions apply to the fixed sink and the stated evidence.

Condition observed

Next owner

Authorized action

Release criterion

Exact manifest and successful sink flush after the final byte

Export caller

Hand off the reviewed candidate

Both observations belong to the same completed attempt

Known accepted prefix and exact complementary suffix in the live wrapper

Writer owner

Correct the refusal, then flush that wrapper once

Whole ledger equals the manifest and sink flush succeeds

Exact manifest, empty queue, failed inner flush

Sink owner

Establish the effect of the failure. For this fixture clear the switch and retry flush alone

Same exact ledger, no extra write, successful later flush

Exact bytes after successful unwrap, no flush evidence

Owner of the returned sink

Explicitly flush the sink and handle its result

Recorded success after the final byte, manifest still exact

Duplicate records, missing ownership or uncertain previous side effects

Export owner and consumer responsible for reconciliation

Stop appending. Keep the candidate and record the known extent

Release only a corrected candidate whose full contents and finalization can be verified

A corrected candidate needs its own reviewable identity. If a recovery owner elects to rebuild on a separately established empty sink, carry forward the intended manifest and keep the rejected attempt out of the consumer handoff. Confirm that the consumer will use the corrected candidate. A clean new export is insufficient evidence to release an older candidate that already contains the duplicated first line. Inside this lab the only in-place byte retry authorized by the positive recovery case uses the recovered queue and its original sink.

When handing an inconclusive case to another owner, include the operation that failed, the last known accepted bytes, the observed queue if available, the last flush outcome and the writer's current owner. Distinguish “never inspected” from an observed zero. If there is a log entry for the submission but no observation from the sink, say so. That short list makes it possible to identify the missing evidence without asking another engineer to repeat the operation that created the uncertainty.

Practice backend handoffs with observable outcomes

One way to review a backend export is to give a colleague the return value and ask which consumer action it authorizes. Then give them the sink ledger. In the scope-exit case, those two pieces of evidence tell different stories. In the inner-flush case the bytes look right and the error is real. In the replay case the final call genuinely succeeds and the complete export is still wrong. Each case asks the reviewer to make a different decision using the same two records.

For a project review, have the producer identify the last fallible operation it owns. Have the consumer state its expected contents before examining the output. Then walk through the failed handoff together and identify who can still act on the writer. The most informative question after the partial drain is quite specific. If the four accepted bytes are still there, what call sends only the four that remain? A defensible answer names the recovered wrapper, the explicit flush and the comparison that permits release afterward.

For practice making producer and consumer contracts explicit in backend projects, explore Refonte Learning's Backend Developer Program, which includes hands-on work with Node.js and Express.