Skip to content

Checkpoint: Observe a Commit After Output Fails

The Course
•
32 min study

This checkpoint stages the most common real-world retry: the server applied the request, then the reply was lost on the way back. From the client's side, the call failed. From the ledger's side, it succeeded. You will build a submit function that commits and then reports, force the report to fail partway through, and prove two things with evidence rather than hope: the commit survived the failed reply, and the client's retry is answered without a second change.

What you will use

  • Receipts: Counter::add recognizes a repeated ID with the same amount and returns replayed without changing the value.
  • Commit before reply: the state change happens first, so the worst outcome of an output failure is a lost reply.
  • Injected failure: FailsAfter accepts a fixed number of bytes and then returns BrokenPipe.
  • Error propagation: submit returns io::Result<()>, mapping a domain error to InvalidInput and passing write errors through with ? or as its return value.
  • State evidence: every step checks counter.value and the captured bytes, not just the returned Result.

Plan before you type

  1. Write submit(counter: &mut Counter, id: u32, amount: u32, output: impl Write) -> io::Result<()>. Call counter.add first and map its Err to an io::Error of kind InvalidInput.
  2. Write the outcome with writeln! and return its result.
  3. Keep the Counter in main, outside submit, so the same receipts are available for the retry.
  4. Run three submissions: ID 7 amount 5 with a 3-byte budget, the same request with a Vec<u8>, and ID 7 amount 8 with a Vec<u8>. Print the result kind, the captured text and the value after each.
Prove it can fail

Swap the order inside submit so it writes applied before calling add. The first submission should now fail before the commit, leaving the value at 0, and your value check after it must fail. Then replace Counter::default() with a fresh counter for the retry: the retry should report applied and your captured-text check should catch it.

Mistakes worth checking for

  • Retry reports applied: submit creates its own Counter, or the test builds a new one for the retry, so the receipt is lost.
  • Value is 10 after the retry: the receipt lookup is missing, so the retry applied the amount again.
  • Error kind is not BrokenPipe: submit replaced the write error with its own, hiding why delivery failed.
  • Conflict writes text: the domain error was printed to the output instead of being returned.
  • The test cannot see the bytes: the Vec was moved into submit; pass &mut output so main still owns it.
Exercise

Your turn

Implement submit and print one line per submission in the form result text value. The three lines should be:

  • Err(BrokenPipe) "" 5 for ID 7, amount 5, with FailsAfter { remaining: 3 }. The fixture swallowed three bytes before failing, and the commit is already done.
  • Ok(()) "replayed\n" 5 for the same request with a working Vec<u8>.
  • Err(InvalidInput) "" 5 for ID 7, amount 8, with a fresh Vec<u8>.

Print the empty text for the first line yourself, since FailsAfter keeps nothing.

Your working space Rust
use std::collections::BTreeMap;

#[derive(Default)]
struct Counter {
    value: u32,
    receipts: BTreeMap<u32, u32>,
}

impl Counter {
    fn add(&mut self, id: u32, amount: u32) -> Result<&'static str, &'static str> {
        if let Some(previous) = self.receipts.get(&id) {
            return if *previous == amount { Ok("replayed") } else { Err("conflict") };
        }
        let next = self.value.checked_add(amount).ok_or("overflow")?;
        self.value = next;
        self.receipts.insert(id, amount);
        Ok("applied")
    }
}

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() {
    // Implement submit and test the failed response followed by a retry.
}
Hint 1: the idea

Keep the counter outside submit so the test can inspect it and retry after the writer fails. The function borrows it with &mut Counter.

Hint 2: a first step

Start from counter.add(id, amount). Its error is a message, not an io::Error, so convert it before ? can return it from submit. Only after the counter has accepted the change should anything be written.

Worked solution
Run the solution Rust
use std::collections::BTreeMap;

#[derive(Default)]
struct Counter {
    value: u32,
    receipts: BTreeMap<u32, u32>,
}

impl Counter {
    fn add(&mut self, id: u32, amount: u32) -> Result<&'static str, &'static str> {
        if let Some(previous) = self.receipts.get(&id) {
            return if *previous == amount { Ok("replayed") } else { Err("conflict") };
        }
        let next = self.value.checked_add(amount).ok_or("overflow")?;
        self.value = next;
        self.receipts.insert(id, amount);
        Ok("applied")
    }
}

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 submit(counter: &mut Counter, id: u32, amount: u32, mut output: impl Write) -> io::Result<()> {
    let outcome = counter.add(id, amount)
        .map_err(|message| io::Error::new(io::ErrorKind::InvalidInput, message))?;
    writeln!(output, "{outcome}")
}

fn main() {
    let mut counter = Counter::default();
    let result = submit(&mut counter, 7, 5, FailsAfter { remaining: 3 });
    println!("{:?} {:?} {}", result.map_err(|error| error.kind()), "", counter.value);
    assert_eq!(counter.value, 5);

    for amount in [5, 8] {
        let mut output = Vec::new();
        let result = submit(&mut counter, 7, amount, &mut output);
        let text = String::from_utf8(output).unwrap();
        println!("{:?} {text:?} {}", result.map_err(|error| error.kind()), counter.value);
    }
    assert_eq!(counter.value, 5);
    assert_eq!(counter.receipts.len(), 1);
}
Text
Err(BrokenPipe) "" 5
Ok(()) "replayed\n" 5
Err(InvalidInput) "" 5

The first line is the whole lesson in one row: an error, and yet the value is 5. A client that treats every error as "nothing happened" and sends a different amount under the same ID gets the third line, a conflict, instead of silently adding 8. All of this holds only within one running Counter; a server that restarts would need its receipts in durable storage. Day 7 puts these guarantees, and the tests that prove them, into one project.

Was this article helpful?

Your response is saved on this device.