Skip to content

Inject Partial Writes and Propagate Failure

The Course
•
30 min study

Output can fail, and it can fail halfway. A pipe can close, a disk can fill, a network peer can disconnect after reading three bytes. The Write trait models this honestly: write may accept only part of the slice and return how many bytes it took, or return an error. write_all wraps that in a loop, calling write until every byte is accepted or a real error occurs. Your code should propagate that error instead of assuming output always works, and your tests need a way to make output fail on purpose.

A test fixture does that. FailsAfter accepts a fixed budget of bytes, then returns BrokenPipe forever. With it you can force a failure at an exact position, something a real terminal will never do on demand.

There is a design question hiding here too. The ledger commits its state, then writes a success line. If the write fails, the batch has still been applied. The caller sees an error, but it is an error about delivery, not about the commit. These are two separate failure boundaries, and the receipts from Day 4 are what make the gap between them safe: a client that never saw the reply can retry the same ID and receive replayed instead of a second application.

Predict and run

How many bytes can this destination accept before the report fails?

Predict, then run Rust
use std::io::{self, Write};

struct FailsAfter { remaining: usize }

impl Write for FailsAfter {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        if bytes.is_empty() { return Ok(0); }
        if self.remaining == 0 {
            return Err(io::Error::new(io::ErrorKind::BrokenPipe, "controlled failure"));
        }
        let count = bytes.len().min(self.remaining);
        self.remaining -= count;
        Ok(count)
    }
    fn flush(&mut self) -> io::Result<()> { Ok(()) }
}

fn main() {
    let mut output = FailsAfter { remaining: 3 };
    let error = output.write_all(b"abcdef").unwrap_err();
    assert_eq!(error.kind(), io::ErrorKind::BrokenPipe);
    println!("Remaining: {}", output.remaining);
}
Check your prediction
Text
Remaining: 0

The first write accepted abc and returned 3, which is a success, not an error. write_all called again with def, and only that second call failed. Three bytes escaped before the error, which is exactly what happens with a real broken pipe. Set the budget to 6 and write_all succeeds. Then write b"" with a budget of 0 and predict: it succeeds too, because write_all never calls write for an empty slice.

The other replies write can give

Besides a count or an error, two more outcomes matter. Interrupted means "try again", and write_all retries it silently. A reply of Ok(0) for a nonempty slice means the destination will accept nothing more, and write_all turns it into a WriteZero error rather than looping forever. A scripted fixture can produce each reply in order.

Script interrupted and zero-length writes Rust
use std::io::{self, Write};

#[derive(Clone, Copy)]
enum Reply { Accept(usize), Interrupt, Zero }

struct Scripted { replies: Vec<Reply>, calls: usize }

impl Write for Scripted {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        let reply = self.replies[self.calls];
        self.calls += 1;
        match reply {
            Reply::Accept(limit) => Ok(bytes.len().min(limit)),
            Reply::Interrupt => Err(io::ErrorKind::Interrupted.into()),
            Reply::Zero => Ok(0),
        }
    }
    fn flush(&mut self) -> io::Result<()> { Ok(()) }
}

fn main() {
    use Reply::*;
    for replies in [vec![Accept(2), Interrupt, Accept(4)], vec![Accept(2), Zero]] {
        let mut output = Scripted { replies, calls: 0 };
        let result = output.write_all(b"abcdef").map_err(|error| error.kind());
        println!("{result:?} after {} calls", output.calls);
    }
}
Text
Ok(()) after 3 calls
Err(WriteZero) after 2 calls

This is why you should call write_all (or writeln!, which uses it) rather than a single write. One write call that returns 2 has not written your line; it has written two bytes of it.

Buffers move the failure to flush

A BufWriter collects output in memory and passes it on in larger pieces. That makes writes cheap, and it also moves where errors appear.

Find a failure hiding in a buffer Rust
use std::io::{self, BufWriter, Write};

struct FailsAfter { remaining: usize }

impl Write for FailsAfter {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        if bytes.is_empty() { return Ok(0); }
        if self.remaining == 0 {
            return Err(io::Error::new(io::ErrorKind::BrokenPipe, "controlled failure"));
        }
        let count = bytes.len().min(self.remaining);
        self.remaining -= count;
        Ok(count)
    }
    fn flush(&mut self) -> io::Result<()> { Ok(()) }
}

fn main() {
    let mut output = BufWriter::new(FailsAfter { remaining: 3 });
    let written = writeln!(output, "stock=5");
    println!("writeln: {written:?}");
    let flushed = output.flush().map_err(|error| error.kind());
    println!("flush: {flushed:?}");
}
Text
writeln: Ok(())
flush: Err(BrokenPipe)

The line only reached the buffer, so writeln! succeeded. The real write happened during flush. If the program had skipped the explicit flush and let the BufWriter drop, the drop would have tried to flush and discarded the error. That is why the project's run ends with output.flush() as its returned value.

Commit first, then reply

The alternative order, reply and then commit, is worse: a client could be told "applied" for a batch whose commit then fails. Committing first means the worst case is a lost reply, and receipts turn a retry of a lost reply into a harmless replay.

Practice

Exercise

Your turn

Write send_report(output: impl Write) -> io::Result<()> that writes the line stock=5 followed by a newline and propagates any failure. Call it once with FailsAfter and a budget of 3 bytes, and print the error kind, which should be Err(BrokenPipe). Then call it with &mut bytes, where bytes is a Vec<u8>, and print the captured text as a String with {:?}. It should be "stock=5\n".

Your working space Rust
use std::io::{self, Write};

struct FailsAfter { remaining: usize }

impl Write for FailsAfter {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        if bytes.is_empty() { return Ok(0); }
        if self.remaining == 0 {
            return Err(io::Error::new(io::ErrorKind::BrokenPipe, "controlled failure"));
        }
        let count = bytes.len().min(self.remaining);
        self.remaining -= count;
        Ok(count)
    }
    fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
fn main() {
    // Write through a supplied destination and check both outcomes.
}
Hint 1: the idea

The helper should return io::Result<()> so the caller can observe output failure. It must not unwrap or print the error itself.

Hint 2: a first step

Use output.write_all(b"stock=5\n") and return its result directly. &mut Vec<u8> implements Write, so the same function can capture output for a test.

Worked solution
Run the solution Rust
use std::io::{self, Write};

struct FailsAfter { remaining: usize }

impl Write for FailsAfter {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        if bytes.is_empty() { return Ok(0); }
        if self.remaining == 0 {
            return Err(io::Error::new(io::ErrorKind::BrokenPipe, "controlled failure"));
        }
        let count = bytes.len().min(self.remaining);
        self.remaining -= count;
        Ok(count)
    }
    fn flush(&mut self) -> io::Result<()> { Ok(()) }
}

fn send_report(mut output: impl Write) -> io::Result<()> {
    output.write_all(b"stock=5\n")
}

fn main() {
    let failed = send_report(FailsAfter { remaining: 3 }).map_err(|error| error.kind());
    println!("budget 3: {failed:?}");
    let mut bytes = Vec::new();
    send_report(&mut bytes).unwrap();
    println!("captured: {:?}", String::from_utf8(bytes).unwrap());
}
Text
budget 3: Err(BrokenPipe)
captured: "stock=5\n"

Passing &mut bytes rather than bytes keeps ownership in main, so the captured output is still there to inspect after the call. Because send_report is generic over Write, the test and the real program share one code path. The checkpoint combines this with the counter so you can watch a commit survive a failed reply.

Was this article helpful?

Your response is saved on this device.