Skip to content

Compare Against a Small Reference Model

The Course
•
30 min study

Hand-picked test cases test the cases you thought of. The bugs you did not think of live in the gaps between them. Day 6 is about evidence that your tests would actually catch mistakes, and the first tool is a reference model: a second, deliberately simple calculation of what the answer should be, compared with the real implementation over every input in a small range.

The model must reach its answer a different way. If it called adjust or apply, it would share their bugs and agree with them. Here the model uses plain i64 arithmetic, which cannot overflow for these tiny numbers: start from 3, add the first delta to get the middle value, add the second to get the end value, and require both to be nonnegative. If either is negative the batch must fail, and the stored value must still be 3. That is the whole contract in three lines, short enough to check by eye.

Enumerating every pair in a small range is exhaustive in that range, deterministic, and fast. It covers successes, early failures, late failures and exact-zero boundaries without you choosing them. The idea behind it, sometimes called the small scope hypothesis, is that most logic bugs show up on small inputs. Machine-specific limits such as i64::MAX are outside the range, so they still need their own targeted cases.

Predict and run

How many delta pairs are checked by the two inclusive ranges?

Predict, then run 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(())
}
fn main() {
    let mut cases = 0;
    for first in -2_i64..=2 {
        for second in -2_i64..=2 {
            let mut stock = vec![3];
            let result = apply(&mut stock, &[(0, first), (0, second)]);
            let middle = 3 + first;
            let end = middle + second;
            let allowed = middle >= 0 && end >= 0;
            assert_eq!(result.is_ok(), allowed);
            assert_eq!(stock, vec![if allowed { end as u32 } else { 3 }]);
            cases += 1;
        }
    }
    println!("Cases: {cases}");
}
Check your prediction
Text
Cases: 25

Each inclusive range -2..=2 has five values, so the loops check 5 times 5 pairs, and every one agreed with the model. Count the failures, though: only (-2, -2), which ends at -1, is rejected. A range can be thinner than it looks, so check that it exercises both outcomes. Widen both ranges to -4..=4 and find a pair whose middle value is negative but whose final sum is positive, such as (-4, 4). The model says it must fail, and apply agrees.

Let the model find a bug

The real test of a model is whether it notices a broken implementation. Swap in the in-place version from Day 4, which writes each change directly into the stored vector, and collect every disagreement instead of stopping at the first.

Count where a buggy version disagrees 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")
}

// A plausible bug: it writes each change straight into the stored vector.
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 disagreements = Vec::new();
    for first in -4_i64..=4 {
        for second in -4_i64..=4 {
            let mut stock = vec![3];
            let result = apply_in_place(&mut stock, &[(0, first), (0, second)]);
            let middle = 3 + first;
            let end = middle + second;
            let allowed = middle >= 0 && end >= 0;
            let expected = vec![if allowed { end as u32 } else { 3 }];
            if result.is_ok() != allowed || stock != expected {
                disagreements.push((first, second, stock[0], expected[0]));
            }
        }
    }
    println!("Disagreements: {}", disagreements.len());
    for (first, second, stored, expected) in disagreements {
        println!("({first}, {second}): stored {stored}, expected {expected}");
    }
}
Text
Disagreements: 9
(-3, -4): stored 0, expected 3
(-3, -3): stored 0, expected 3
(-3, -2): stored 0, expected 3
(-3, -1): stored 0, expected 3
(-2, -4): stored 1, expected 3
(-2, -3): stored 1, expected 3
(-2, -2): stored 1, expected 3
(-1, -4): stored 2, expected 3
(-1, -3): stored 2, expected 3

Every disagreement is a late failure: the first change succeeded and leaked, then the second failed. Pairs that start with -4 fail on the first change, before anything is written, so the buggy version gets them right by accident. That is exactly the kind of case a hand-written test might pick, and then pass. The model found all nine without anyone choosing them.

Notice also that the return value was correct in all nine cases; only the stored state was wrong. A model that compared only is_ok() would have reported zero disagreements.

Keep the model dumber than the code

A reference model is useful when it is obviously correct, not when it is efficient. Plain arithmetic, a linear scan, or a Vec searched by hand are all fine. If the model needs its own tests, it is too clever.

Practice

Exercise

Your turn

Add an upper limit of 6 to apply: after each staged adjustment, a slot above 6 fails the batch with "limit". Then check every pair in -4..=4 against a model that requires both the middle and the end value to be in 0..=6. Assert the original state after every rejected batch, and print the number of cases and how many the model accepted. Expect Cases: 81 and Accepted: 43.

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(())
}
fn main() {
    // Add a per-change upper bound inside the staged loop, then compare with the model.
}
Hint 1: the idea

Validate the staged slot after each adjustment, inside the loop. The model should compute the two mathematical values on its own and test each with (0..=6).contains(&value).

Hint 2: a first step

Add if *slot > 6 { return Err("limit"); } right after the assignment to the staged slot, and count accepted cases with a second counter incremented when allowed is true.

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)?;
        if *slot > 6 { return Err("limit"); }
    }
    *stock = staged;
    Ok(())
}
fn main() {
    let mut cases = 0;
    let mut accepted = 0;
    for first in -4_i64..=4 {
        for second in -4_i64..=4 {
            let mut stock = vec![3];
            let result = apply(&mut stock, &[(0, first), (0, second)]);
            let middle = 3 + first;
            let end = middle + second;
            let allowed = (0..=6).contains(&middle) && (0..=6).contains(&end);
            assert_eq!(result.is_ok(), allowed, "deltas {first}, {second}");
            assert_eq!(stock, vec![if allowed { end as u32 } else { 3 }]);
            cases += 1;
            if allowed { accepted += 1; }
        }
    }
    println!("Cases: {cases}");
    println!("Accepted: {accepted}");
}
Text
Cases: 81
Accepted: 43

The accepted count is a cheap sanity check on the model itself: if it were 0 or 81, the range would not be exercising both outcomes. Checking only the end value would wrongly accept pairs like (4, -4), whose middle value 7 breaks the limit. The Day 7 project runs this same model against the real ledger, skipping zero deltas because its parser rejects them.

Was this article helpful?

Your response is saved on this device.