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::addrecognizes a repeated ID with the same amount and returnsreplayedwithout 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:
FailsAfteraccepts a fixed number of bytes and then returnsBrokenPipe. - Error propagation:
submitreturnsio::Result<()>, mapping a domain error toInvalidInputand passing write errors through with?or as its return value. - State evidence: every step checks
counter.valueand the captured bytes, not just the returnedResult.
Plan before you type
- Write
submit(counter: &mut Counter, id: u32, amount: u32, output: impl Write) -> io::Result<()>. Callcounter.addfirst and map itsErrto anio::Errorof kindInvalidInput. - Write the outcome with
writeln!and return its result. - Keep the
Counterinmain, outsidesubmit, so the same receipts are available for the retry. - 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 aVec<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:
submitcreates its ownCounter, 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:
submitreplaced 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
Vecwas moved intosubmit; pass&mut outputsomainstill owns it.
Your turn
Implement submit and print one line per submission in the form result text value. The three lines should be:
Err(BrokenPipe) "" 5for ID 7, amount 5, withFailsAfter { remaining: 3 }. The fixture swallowed three bytes before failing, and the commit is already done.Ok(()) "replayed\n" 5for the same request with a workingVec<u8>.Err(InvalidInput) "" 5for ID 7, amount 8, with a freshVec<u8>.
Print the empty text for the first line yourself, since FailsAfter keeps nothing.
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
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);
}Err(BrokenPipe) "" 5
Ok(()) "replayed\n" 5
Err(InvalidInput) "" 5The 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.
Completion is saved in this browser only. It does not measure mastery.