Skip to content

Checkpoint: Commit Stock and Receipt Together

The Course
•
32 min study

Today you built two guarantees separately: a batch of changes applies completely or not at all, and a repeated request is recognized instead of applied twice. Real ledgers need both at once, and the interesting bugs live where they meet. A receipt recorded for a batch that then failed would block the corrected retry forever. A batch applied without a receipt would be applied again on retry. In this checkpoint you join the two pieces into a Store so that stock and receipts always change together.

What you will use

  • Checked arithmetic: adjust widens, adds with checked_add and narrows, so every arithmetic failure is a returned error.
  • Staging: apply changes a clone and commits with one infallible assignment.
  • Receipts with payloads: a BTreeMap from batch ID to its ordered changes, compared on every repeat.
  • Check order: receipt lookup before any arithmetic, so a replay never depends on the current stock.

Plan before you type

  1. Look up the batch ID in receipts. If it exists, compare the stored changes with the incoming slice and return Ok(false) for a match or Err("conflict") otherwise.
  2. Call apply(&mut self.stock, changes)?. If it fails, return before touching receipts.
  3. Only after apply succeeds, insert changes.to_vec() under the ID and return Ok(true).
  4. Write checks for a late failure, a corrected retry under the same ID, an identical replay, a conflict, and a replay of a batch that could not be applied again to today's stock.
Prove it can fail

Move the receipts.insert line above the call to apply and run your checks. The late-failure case should now leave a receipt behind, and the corrected retry should report conflict. Then delete the receipt lookup entirely: the replay of batch 8 should fail with out of range. If your checks still pass with either change, they are not watching the right state.

Mistakes worth checking for

  • Corrected retry reports conflict: the receipt was recorded before apply finished, so a failed batch claimed its ID.
  • Replay changes the stock: the receipt lookup runs after apply, or is missing.
  • Replay of an old batch fails: arithmetic runs before the receipt lookup, so the retry is judged against stock that has moved on.
  • Conflict check passes for reordered changes: you compared the changes as a set; the batch is ordered, so Vec equality is the right comparison.
  • Tests pass but prove little: they check only return values, not stock and the number of receipts.
Exercise

Your turn

Write Store::commit(&mut self, id: u32, changes: &[(usize, i64)]) -> Result<bool, &'static str>, where Ok(true) means applied and Ok(false) means replayed. Start with stock [5, 2] and no receipts, then print each result followed by the stock and the receipt count:

  • Batch 7 [(0, 1), (1, -3)] fails late with Err("out of range"), leaving [5, 2] and 0 receipts.
  • Batch 7 corrected to [(0, 1)] gives Ok(true) and [6, 2].
  • The same batch 7 again gives Ok(false); batch 7 with [(0, 2)] gives Err("conflict").
  • Batch 8 [(1, -2)] gives Ok(true) and [6, 0]. Repeating it gives Ok(false), even though applying it again would make slot 1 negative.
Your working space Rust
fn adjust(old: u32, delta: i64) -> Result<u32, &'static str> {
    let next = i64::from(old).checked_add(delta).ok_or("overflow")?;
    u32::try_from(next).map_err(|_| "out of range")
}

fn apply(stock: &mut Vec<u32>, changes: &[(usize, i64)]) -> Result<(), &'static str> {
    let mut staged = stock.clone();
    for (index, delta) in changes {
        let slot = staged.get_mut(*index).ok_or("unknown slot")?;
        *slot = adjust(*slot, *delta)?;
    }
    *stock = staged;
    Ok(())
}

use std::collections::BTreeMap;

struct Store {
    stock: Vec<u32>,
    receipts: BTreeMap<u32, Vec<(usize, i64)>>,
}

fn main() {
    // Add Store::commit and test a late failure followed by a corrected retry.
}
Hint 1: the idea

Look up the receipt first. Record a new receipt only after apply succeeds, so a failure leaves both fields exactly as they were.

Hint 2: a first step

A Vec<(usize, i64)> can be compared with a &[(usize, i64)] directly: previous == changes compares length and every element in order.

Worked solution
Run the solution Rust
fn adjust(old: u32, delta: i64) -> Result<u32, &'static str> {
    let next = i64::from(old).checked_add(delta).ok_or("overflow")?;
    u32::try_from(next).map_err(|_| "out of range")
}

fn apply(stock: &mut Vec<u32>, changes: &[(usize, i64)]) -> Result<(), &'static str> {
    let mut staged = stock.clone();
    for (index, delta) in changes {
        let slot = staged.get_mut(*index).ok_or("unknown slot")?;
        *slot = adjust(*slot, *delta)?;
    }
    *stock = staged;
    Ok(())
}

use std::collections::BTreeMap;

struct Store {
    stock: Vec<u32>,
    receipts: BTreeMap<u32, Vec<(usize, i64)>>,
}

impl Store {
    fn commit(&mut self, id: u32, changes: &[(usize, i64)]) -> Result<bool, &'static str> {
        if let Some(previous) = self.receipts.get(&id) {
            return if previous == changes { Ok(false) } else { Err("conflict") };
        }
        apply(&mut self.stock, changes)?;
        self.receipts.insert(id, changes.to_vec());
        Ok(true)
    }
}

fn main() {
    let mut store = Store { stock: vec![5, 2], receipts: BTreeMap::new() };
    let batches: [(u32, &[(usize, i64)]); 6] = [
        (7, &[(0, 1), (1, -3)]),
        (7, &[(0, 1)]),
        (7, &[(0, 1)]),
        (7, &[(0, 2)]),
        (8, &[(1, -2)]),
        (8, &[(1, -2)]),
    ];
    for (id, changes) in batches {
        let result = store.commit(id, changes);
        println!("{id}: {result:?} {:?} receipts={}", store.stock, store.receipts.len());
    }
    assert_eq!(store.stock, vec![6, 0]);
    assert_eq!(store.receipts.len(), 2);
}
Text
7: Err("out of range") [5, 2] receipts=0
7: Ok(true) [6, 2] receipts=1
7: Ok(false) [6, 2] receipts=1
7: Err("conflict") [6, 2] receipts=1
8: Ok(true) [6, 0] receipts=2
8: Ok(false) [6, 0] receipts=2

Each line prints the receipt count after the call, so the lines tell the whole story. The late failure left no receipt, which let the corrected batch 7 claim the ID. The final replay of batch 8 succeeds against stock where slot 1 is already 0, proving the lookup runs before any arithmetic. These guarantees cover recoverable errors inside one running program; surviving a crash needs durable storage that commits both maps in one step. Day 5 turns to making this state readable and reportable.

Was this article helpful?

Your response is saved on this device.