The intermediate reading queue checked one update at a time, so an error could only ever affect the update that caused it. A stock batch is different: it contains several ordered changes that belong together, such as "receive five widgets and ship two gadgets". If the third change fails, the first two must not survive on their own, or the stored stock describes a batch that never happened. That property is called atomicity: all of the batch applies, or none of it does.
The simplest way to get it in Rust is to stage. Clone the state into a local staged value, apply every change to the clone, and replace the original with a single assignment after the loop. Any ? inside the loop returns early and drops the clone, so the original is never touched on a failure path. Each change sees the changes before it, which preserves the batch's order and makes repeated updates to the same item behave as written.
Predict and run
Does the successful first adjustment survive the second adjustment's failure?
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(())
}
fn main() {
let mut stock = vec![5, 2];
println!("{:?}", apply(&mut stock, &[(0, 1), (1, -3)]));
println!("{stock:?}");
apply(&mut stock, &[(0, -5), (0, 2)]).unwrap();
println!("{stock:?}");
}Check your prediction
Err("out of range")
[5, 2]
[2, 2]Slot 0 became 6 in staged, then slot 1 failed, and staged was dropped with the early return. The second batch takes slot 0 to zero and then back up to 2. Run its changes in the other order, [(0, 2), (0, -5)], and predict: the result is the same, because neither intermediate value leaves the domain. Try [(0, -6), (0, 2)] too. The final sum would be valid, yet the batch fails, because the contract checks every intermediate state.
What goes wrong without a stage
The tempting version mutates the stored vector directly. It compiles, it returns the right error, and it is wrong.
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_in_place(stock: &mut Vec<u32>, changes: &[(usize, i64)]) -> Result<(), &'static str> {
for (index, delta) in changes {
let slot = stock.get_mut(*index).ok_or("unknown slot")?;
*slot = adjust(*slot, *delta)?;
}
Ok(())
}
fn main() {
let mut stock = vec![5, 2];
println!("{:?}", apply_in_place(&mut stock, &[(0, 1), (1, -3)]));
println!("{stock:?}");
}Err("out of range")
[6, 2]The caller sees an error and reasonably assumes nothing happened, but slot 0 gained a unit. This is why a test that checks only the returned Err proves nothing about atomicity: you must also compare the stored state with its value before the attempt.
Why not validate first and mutate afterwards?
A second idea is to check every change against the current stock, then apply them all in place once the checks pass. That fails as soon as one batch touches the same item twice, because each check looks at the original value instead of the value the earlier change would leave.
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 precheck(stock: &[u32], changes: &[(usize, i64)]) -> Result<(), &'static str> {
for (index, delta) in changes {
let old = *stock.get(*index).ok_or("unknown slot")?;
adjust(old, *delta)?;
}
Ok(())
}
fn main() {
let stock = vec![5];
let batch = [(0, -5), (0, -1)];
println!("precheck: {:?}", precheck(&stock, &batch));
let mut staged = stock.clone();
let mut result = Ok(0);
for (index, delta) in batch {
result = adjust(staged[index], delta);
match result {
Ok(next) => staged[index] = next,
Err(_) => break,
}
}
println!("cumulative: {result:?}");
}precheck: Ok(())
cumulative: Err("out of range")Each change is fine alone, but together they remove six units from five. A correct validator has to simulate the cumulative state, and once it does that, it has built the staged copy anyway. Staging is the validation.
The trade-off is cost. Cloning copies the whole state for every batch, which is fine for a few dozen items and wasteful for a million. Larger systems keep an overlay of only the touched keys or record an undo log and reverse it on failure. Both keep the same rule this lesson relies on: the commit point is a single operation that cannot fail. Here that is *stock = staged, a move that drops the old vector and cannot return an error halfway.
Panics leave the original intact too
If something inside the loop panicked and the panic unwound, staged would be dropped and stock would still hold its old value. Staging protects against early returns of every kind, not only ?.
Practice
Your turn
Start from [5, 2] and use apply for three batches. After each, print the result and the stored vector.
[(0, 1), (9, 1)]fails withErr("unknown slot")after a valid first change. The vector must still be[5, 2].[(0, 1), (1, i64::MAX)]fails withErr("overflow")after a valid first change. The vector must still be[5, 2].[(0, -5), (0, 3)]succeeds and touches slot 0 twice. The vector becomes[3, 2].
Also assert the vector against a saved copy of the initial state after each failure, so the program stops if rollback breaks.
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(())
}
fn main() {
// Create [5, 2] and verify both rollback cases.
}Hint 1: the idea
A returned error alone does not prove rollback. Compare the stored vector after each failed attempt with the state from before it.
Hint 2: a first step
Write let initial = stock.clone(); before the first batch, then assert_eq!(stock, initial); after each failure.
Worked solution
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(())
}
fn main() {
let mut stock = vec![5, 2];
let initial = stock.clone();
let result = apply(&mut stock, &[(0, 1), (9, 1)]);
println!("{result:?} {stock:?}");
assert_eq!(stock, initial);
let result = apply(&mut stock, &[(0, 1), (1, i64::MAX)]);
println!("{result:?} {stock:?}");
assert_eq!(stock, initial);
let result = apply(&mut stock, &[(0, -5), (0, 3)]);
println!("{result:?} {stock:?}");
assert_eq!(stock, vec![3, 2]);
}Err("unknown slot") [5, 2]
Err("overflow") [5, 2]
Ok(()) [3, 2]The unknown slot is found by get_mut, not by arithmetic, and still leaves no trace: every early return discards the same stage. The final success also shows that the failed attempts did not poison the stored state. The next lesson asks what should happen when the same batch arrives twice.
Completion is saved in this browser only. It does not measure mastery.