The README makes promises: rejected batches change nothing, retries replay, limits hold at their exact boundaries, output failures are reported. This lesson runs the evidence for those promises. The check entry, check.rs, calls the same checks::run function that cargo test --lib calls, so the browser and Cargo exercise one set of assertions. Open the checks.rs tab while you read; it is organized into three groups, each using a technique from Day 6.
check_batches uses targeted cases. It rejects invalid names, zero IDs, zero deltas and nine-change batches, then builds a ledger with deliberately tiny limits: a maximum quantity of 10, two items and two receipts. Small limits make every boundary reachable with short inputs. After each rejected batch it compares a full snapshot of the stock and the receipt count with their values from before the attempt.
check_model is the reference model from Day 6, run against the real ledger. It checks all 64 pairs of nonzero deltas in -4..=4 against independent arithmetic, with a maximum of 6, and checks the receipt count as well as the stock. It uses a one-item ledger so the item limit cannot interfere.
check_stream covers input and output. It reads a line of exactly 256 bytes, rejects 258 bytes and confirms the reader stopped after byte 257 instead of swallowing the rest, rejects invalid UTF-8, and compares a full application transcript. A BrokenWriter fixture proves that run returns a BrokenPipe error instead of claiming success.
The snapshot helper copies the entries into a Vec<(String, u32)>. Owned values can be stored and compared after the ledger changes, which a borrowed iterator could not do.
Run the ledger checksRustinclude!("lib.rs");
#[cfg(not(test))]
mod checks;
fn main() {
checks::run();
println!("Stock ledger checks passed");
}
use crate::codec::{self, MAX_LINE_BYTES};
use crate::ledger::{ApplyError, Ledger, MaxQuantity, Outcome};
use crate::types::{Draft, Item};
use std::io::{self, Cursor, Write};
fn snapshot(ledger: &Ledger) -> Vec<(String, u32)> {
ledger.entries().map(|(item, quantity)| (item.as_str().to_owned(), quantity)).collect()
}
fn check_batches() {
assert!(Item::try_from("bad name").is_err());
assert_eq!(Item::try_from(" WIDGET ").unwrap(), Item::try_from("widget").unwrap());
assert!(Draft { id: 1, changes: vec![] }.validate().is_err());
assert!(codec::parse("0 widget:1").is_err());
assert!(codec::parse("1 widget:0").is_err());
assert!(codec::parse(&format!("1 {}", vec!["widget:1"; 9].join(";"))).is_err());
let mut ledger = Ledger::new(Box::new(MaxQuantity(10)), 2, 2);
let first = codec::parse("1 Widget:5;gadget:2").unwrap();
assert_eq!(ledger.apply(&first), Ok(Outcome::Applied));
let initial = snapshot(&ledger);
assert_eq!(ledger.apply(&first), Ok(Outcome::Replayed));
assert_eq!(snapshot(&ledger), initial);
assert_eq!(ledger.receipt_count(), 1);
assert_eq!(ledger.apply(&codec::parse("1 widget:6").unwrap()), Err(ApplyError::RetryConflict));
assert_eq!(snapshot(&ledger), initial);
for (input, error) in [
("2 widget:1;gadget:-3", ApplyError::Quantity),
("2 widget:1;gadget:9", ApplyError::Policy),
("2 widget:1;new:1", ApplyError::ItemLimit),
("2 widget:9223372036854775807", ApplyError::Arithmetic),
] {
assert_eq!(ledger.apply(&codec::parse(input).unwrap()), Err(error));
assert_eq!(snapshot(&ledger), initial);
assert_eq!(ledger.receipt_count(), 1);
}
assert_eq!(ledger.apply(&codec::parse("2 widget:-5;widget:2").unwrap()), Ok(Outcome::Applied));
assert_eq!(snapshot(&ledger), vec![("gadget".into(), 2), ("widget".into(), 2)]);
assert_eq!(ledger.apply(&first), Ok(Outcome::Replayed));
assert_eq!(ledger.apply(&codec::parse("3 gadget:1").unwrap()), Err(ApplyError::ReceiptLimit));
assert_eq!(ledger.receipt_count(), 2);
}
fn check_model() {
// An independently calculated outcome for every pair of small deltas.
for first in -4_i64..=4 {
for second in -4_i64..=4 {
if first == 0 || second == 0 { continue; }
let mut ledger = Ledger::new(Box::new(MaxQuantity(6)), 1, 2);
ledger.apply(&codec::parse("1 part:3").unwrap()).unwrap();
let result = ledger.apply(&codec::parse(&format!("2 part:{first};part:{second}")).unwrap());
let middle = 3 + first;
let final_value = middle + second;
let allowed = (0..=6).contains(&middle) && (0..=6).contains(&final_value);
assert_eq!(result.is_ok(), allowed, "deltas {first}, {second}");
let expected = if allowed { final_value as u32 } else { 3 };
assert_eq!(snapshot(&ledger), vec![("part".into(), expected)]);
assert_eq!(ledger.receipt_count(), if allowed { 2 } else { 1 });
}
}
}
struct BrokenWriter;
impl Write for BrokenWriter {
fn write(&mut self, _: &[u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::BrokenPipe, "fixture"))
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
fn check_stream() {
let boundary = vec![b' '; MAX_LINE_BYTES];
assert!(codec::read_line(&mut Cursor::new(&boundary)).unwrap().is_some());
let mut too_long = Cursor::new(vec![b' '; MAX_LINE_BYTES + 2]);
assert!(codec::read_line(&mut too_long).is_err());
assert_eq!(too_long.position(), (MAX_LINE_BYTES + 1) as u64);
assert!(codec::read_line(&mut Cursor::new([255_u8])).is_err());
assert!(codec::read_line(&mut Cursor::new(b"")).unwrap().is_none());
let mut output = Vec::new();
crate::app::run(Cursor::new(b"1 Widget:3\n\n2 widget:1;gadget:-1\n1 widget:3"), &mut output).unwrap();
assert_eq!(String::from_utf8(output).unwrap(), concat!(
"Batch 1: Applied\n",
"Line 3: quantity must fit a nonnegative u32\n",
"Batch 1: Replayed\n",
"Stock\nwidget=3\nReceipts: 1\n",
));
let error = crate::app::run(Cursor::new(b"1 item:1"), BrokenWriter).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::BrokenPipe);
}
pub fn run() {
check_batches();
check_model();
check_stream();
}
pub mod app;
pub mod codec;
pub mod ledger;
pub mod types;
#[cfg(test)]
mod checks;
#[cfg(test)]
mod tests {
#[test]
fn ledger_contract() {
super::checks::run();
}
}
use std::borrow::Cow;
use std::fmt;
pub const MAX_CHANGES: usize = 8;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Item(String);
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ValidationError {
Item,
ZeroDelta,
ZeroId,
BatchSize,
}
impl fmt::Display for ValidationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = match self {
Self::Item => "use an item of 1–24 ASCII letters, digits, hyphens or underscores",
Self::ZeroDelta => "delta must be nonzero",
Self::ZeroId => "batch ID must be positive",
Self::BatchSize => "use 1–8 changes per batch",
};
formatter.write_str(message)
}
}
impl std::error::Error for ValidationError {}
impl TryFrom<&str> for Item {
type Error = ValidationError;
fn try_from(text: &str) -> Result<Self, Self::Error> {
let text = text.trim();
if text.is_empty() || text.len() > 24 ||
!text.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_') {
return Err(ValidationError::Item);
}
let normalized: Cow<'_, str> = if text.bytes().any(|byte| byte.is_ascii_uppercase()) {
Cow::Owned(text.to_ascii_lowercase())
} else {
Cow::Borrowed(text)
};
Ok(Self(normalized.into_owned()))
}
}
impl Item {
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Change {
item: Item,
delta: i64,
}
impl Change {
pub fn new(item: Item, delta: i64) -> Result<Self, ValidationError> {
if delta == 0 {
return Err(ValidationError::ZeroDelta);
}
Ok(Self { item, delta })
}
pub fn item(&self) -> &Item { &self.item }
pub fn delta(&self) -> i64 { self.delta }
}
pub struct Draft {
pub id: u32,
pub changes: Vec<Change>,
}
#[derive(Debug)]
pub struct Batch {
id: u32,
changes: Vec<Change>,
}
impl Draft {
pub fn validate(self) -> Result<Batch, ValidationError> {
if self.id == 0 {
return Err(ValidationError::ZeroId);
}
if self.changes.is_empty() || self.changes.len() > MAX_CHANGES {
return Err(ValidationError::BatchSize);
}
Ok(Batch { id: self.id, changes: self.changes })
}
}
impl Batch {
pub fn id(&self) -> u32 { self.id }
pub fn changes(&self) -> &[Change] { &self.changes }
}
use crate::types::{Batch, Change, Item};
use std::collections::BTreeMap;
use std::fmt;
#[derive(Debug, PartialEq, Eq)]
pub enum ApplyError {
RetryConflict,
ReceiptLimit,
Arithmetic,
Quantity,
Policy,
ItemLimit,
}
impl fmt::Display for ApplyError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = match self {
Self::RetryConflict => "batch ID was used for different changes",
Self::ReceiptLimit => "receipt limit reached",
Self::Arithmetic => "arithmetic overflow",
Self::Quantity => "quantity must fit a nonnegative u32",
Self::Policy => "quantity rejected by policy",
Self::ItemLimit => "item limit reached",
};
formatter.write_str(message)
}
}
impl std::error::Error for ApplyError {}
pub trait Rule {
fn allows(&self, item: &Item, quantity: u32) -> bool;
}
pub struct MaxQuantity(pub u32);
impl Rule for MaxQuantity {
fn allows(&self, _item: &Item, quantity: u32) -> bool {
quantity <= self.0
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum Outcome {
Applied,
Replayed,
}
pub struct Ledger {
stock: BTreeMap<Item, u32>,
receipts: BTreeMap<u32, Vec<Change>>,
rule: Box<dyn Rule>,
max_items: usize,
max_receipts: usize,
}
impl Ledger {
pub fn new(rule: Box<dyn Rule>, max_items: usize, max_receipts: usize) -> Self {
Self { stock: BTreeMap::new(), receipts: BTreeMap::new(), rule, max_items, max_receipts }
}
pub fn apply(&mut self, batch: &Batch) -> Result<Outcome, ApplyError> {
if let Some(previous) = self.receipts.get(&batch.id()) {
return if previous == batch.changes() {
Ok(Outcome::Replayed)
} else {
Err(ApplyError::RetryConflict)
};
}
if self.receipts.len() >= self.max_receipts {
return Err(ApplyError::ReceiptLimit);
}
let mut staged = self.stock.clone();
for change in batch.changes() {
let old = i64::from(*staged.get(change.item()).unwrap_or(&0));
let next = old.checked_add(change.delta()).ok_or(ApplyError::Arithmetic)?;
let next = u32::try_from(next).map_err(|_| ApplyError::Quantity)?;
if !self.rule.allows(change.item(), next) {
return Err(ApplyError::Policy);
}
staged.insert(change.item().clone(), next);
if staged.len() > self.max_items {
return Err(ApplyError::ItemLimit);
}
}
self.stock = staged;
self.receipts.insert(batch.id(), batch.changes().to_vec());
Ok(Outcome::Applied)
}
pub fn entries(&self) -> impl Iterator<Item = (&Item, u32)> {
self.stock.iter().map(|(item, quantity)| (item, *quantity))
}
pub fn receipt_count(&self) -> usize {
self.receipts.len()
}
}
use crate::types::{Batch, Change, Draft, Item, ValidationError, MAX_CHANGES};
use std::fmt;
use std::io::{self, BufRead, Read};
pub const MAX_LINE_BYTES: usize = 256;
#[derive(Debug)]
pub enum ParseError {
Syntax,
Number,
Validation(ValidationError),
}
impl fmt::Display for ParseError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Syntax => formatter.write_str("use ID item:delta;item:delta"),
Self::Number => formatter.write_str("invalid batch ID or delta"),
Self::Validation(error) => write!(formatter, "{error}"),
}
}
}
impl std::error::Error for ParseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Validation(error) => Some(error),
_ => None,
}
}
}
impl From<ValidationError> for ParseError {
fn from(error: ValidationError) -> Self { Self::Validation(error) }
}
pub fn parse(text: &str) -> Result<Batch, ParseError> {
let text = text.trim();
let (id, body) = text.split_once(char::is_whitespace).ok_or(ParseError::Syntax)?;
let id = id.parse::<u32>().map_err(|_| ParseError::Number)?;
let mut changes = Vec::new();
for part in body.split(';') {
if changes.len() == MAX_CHANGES {
return Err(ValidationError::BatchSize.into());
}
let (item, delta) = part.trim().split_once(':').ok_or(ParseError::Syntax)?;
let item = Item::try_from(item)?;
let delta = delta.trim().parse::<i64>().map_err(|_| ParseError::Number)?;
changes.push(Change::new(item, delta)?);
}
Ok(Draft { id, changes }.validate()?)
}
pub fn read_line(input: &mut impl BufRead) -> io::Result<Option<String>> {
let mut bytes = Vec::new();
let count = input.take((MAX_LINE_BYTES + 1) as u64).read_until(b'\n', &mut bytes)?;
if count == 0 {
return Ok(None);
}
if count > MAX_LINE_BYTES {
return Err(io::Error::new(io::ErrorKind::InvalidData, "line exceeds 256 bytes"));
}
let line = String::from_utf8(bytes)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "input must be UTF-8"))?;
Ok(Some(line))
}
use crate::codec;
use crate::ledger::{Ledger, MaxQuantity};
use std::io::{self, BufRead, Write};
pub fn run(mut input: impl BufRead, mut output: impl Write) -> io::Result<()> {
let mut ledger = Ledger::new(Box::new(MaxQuantity(1000)), 32, 32);
let mut line_number = 0;
while let Some(line) = codec::read_line(&mut input)? {
line_number += 1;
if line.trim().is_empty() {
continue;
}
match codec::parse(&line) {
Ok(batch) => match ledger.apply(&batch) {
Ok(outcome) => writeln!(output, "Batch {}: {outcome:?}", batch.id())?,
Err(error) => writeln!(output, "Line {line_number}: {error}")?,
},
Err(error) => writeln!(output, "Line {line_number}: {error}")?,
}
}
writeln!(output, "Stock")?;
for (item, quantity) in ledger.entries() {
writeln!(output, "{}={quantity}", item.as_str())?;
}
writeln!(output, "Receipts: {}", ledger.receipt_count())?;
output.flush()
}
Text
Stock ledger checks passed
A single line of success is all you see when every assertion holds. To know that line means something, you have to watch it fail.
Exercise
Break atomicity deliberately
In ledger.rs, add self.stock = staged.clone(); immediately after staged.insert(change.item().clone(), next);. Run the checks and find the failure. Explain why the original value differs even though apply returned an error. Then remove the inserted assignment and rerun.
Hint 1: the idea
The added statement publishes an intermediate candidate before later changes are validated.
Hint 2: a first step
Find the test using 2 widget:1;gadget:-3. Compare the stock before and after that attempt.
Worked solution
The first change publishes the extra widget. The second change fails because gadget would become negative, but the original stock has already changed. The snapshot assertion right after that attempt detects the surviving widget, and the panic message points at its line in checks.rs. Note that the assertion on the returned Err still passes: only the state comparison catches this mutant. Keeping the single assignment after the loop restores rollback for the whole batch.
The documented mutants
The browser test suite does not rely on you remembering to try mutants. The project keeps four of them in a mutations.json file next to the sources, each a find-and-replace pair: the partial commit you just tried, a replay that returns RetryConflict, a quantity rule that uses < instead of <=, and a receipt limit that uses > instead of >=. The suite applies each one to the source, runs the checks, and requires an assertion failure. If someone later deletes an assertion, the matching mutant survives and the suite fails, so the tests guard themselves.
Each mutant is a plausible one-character or one-line mistake, and each one targets a different guarantee. Together they are a small, explicit claim about what the checks can detect, which is more useful than a coverage percentage.
Exercise
Find the assertion that kills each mutant
For the other three mutants, find the assertion in checks.rs that fails. Then apply each change in the ledger.rs tab and run the checks to confirm your answer. Restore the original line each time.
In the replay branch, Ok(Outcome::Replayed) becomes Err(ApplyError::RetryConflict).
In MaxQuantity, quantity <= self.0 becomes quantity < self.0.
In apply, self.receipts.len() >= self.max_receipts becomes self.receipts.len() > self.max_receipts.
Hint 1: the idea
Ask which input reaches the changed line with a value at the exact boundary. A check that never sends that input cannot kill the mutant.
Hint 2: a first step
The quantity mutant only differs when a quantity equals the maximum. Look for a check whose maximum can be reached exactly, which may not be in check_batches.
Worked solution
The replay mutant fails the first assert_eq!(ledger.apply(&first), Ok(Outcome::Replayed)) in check_batches, right after batch 1 is applied. The quantity mutant survives every targeted case in check_batches, because none of them lands exactly on 10, but check_model kills it. The first pair it fails on is (-1, 4), which ends exactly at 6: the model expects the batch to be allowed and the mutant rejects it, so the failure message reads deltas -1, 4. The receipt mutant fails the ReceiptLimit assertion for 3 gadget:1: with two receipts already stored and a limit of 2, > lets a third batch through. The model earning its keep on the quantity boundary is the practical argument for running both kinds of test.
Completion is saved in this browser only. It does not measure mastery.