diff --git a/crates/ledger-core/src/kernel/total.rs b/crates/ledger-core/src/kernel/total.rs index cc3f0d4e..fe73dea8 100644 --- a/crates/ledger-core/src/kernel/total.rs +++ b/crates/ledger-core/src/kernel/total.rs @@ -1,5 +1,87 @@ //! U4: totals, exact checked sums for books and reports (kernel sweep). //! -//! Empty in U0: the unit adds its arithmetic here, in this file alone, so -//! no two sweep units ever edit the same file. The module root re-exports -//! it, keeping every path `crate::kernel::foo`. +//! The sum of a collection of money figures, in one place. A raw `Decimal` +//! `+`, `+=` or `.sum()` panics at `Decimal::MAX`; these return `None` +//! instead, so the caller can refuse with `TooLargeToCompute` and never +//! crash a book (rules.md B-28: a replayed journal line is accepted "of +//! any size", so a restored figure is the realistic path to the edge). +//! The signed sum of `(Side, amount)` lines is [`super::net`] and the pair +//! of columns [`super::totals`]; they were here first and stay the one +//! copy of that shape. + +use super::Amount; + +/// The exact sum of some figures: `None` the moment a running sum cannot +/// be represented, never a wrapped, rounded or panicking one. +/// +/// ```text +/// GOAL: a book's or report's total is the exact sum of its figures, or +/// refused; no total is ever rounded, wrapped or a crash. +/// SOURCE: docs/spec/rules.md B-21 (amounts are exact; rounding is +/// confined to returns), B-28 (replayed lines are accepted "of any +/// size"; no input may reach a panic); bookspec BS-entry-3, +/// BS-entry-4; CONVENTION. +/// INVARIANTS: +/// 1. total([]) = Some(0). +/// 2. Some(s): s is the exact mathematical sum of the figures (every +/// running sum was representable, so no step lost anything). +/// 3. total(a ++ b) = total(a) + total(b) whenever the combined run +/// never leaves the representable range (always for amounts within +/// the line range and a few thousand of them). At the very edge the +/// sum is order dependent by design: [MAX, 1, -1] is None while +/// [MAX, -1, 1] is Some(MAX), because each step must be exact. +/// 4. None on overflow; NEVER a rounded or wrapped result, never a +/// panic. (Exactness is `Amount::checked_add`'s: `rust_decimal` +/// rounds sub-unit dust when a sum lands on `Decimal::MAX`; see +/// docs/proofs/k-u4.md, finding 1.) +/// ``` +pub fn total(values: impl IntoIterator) -> Option { + let mut sum = T::ZERO; + for value in values { + sum = sum.checked_add(value)?; + } + Some(sum) +} + +/// The exact sum of a figure drawn from each item (`f` of each), the shape +/// of `iter().map(f).sum()`: `total(map(f, items))`. +/// +/// ```text +/// GOAL: the sum of a mapped field (a row's amount, a member's share) is +/// the exact sum of the mapping, or refused. +/// SOURCE: docs/spec/rules.md B-21, B-28; bookspec BS-entry-3, +/// BS-entry-4; CONVENTION. +/// INVARIANTS: +/// 1. total_of(items, f) = total(f(item) for item in items), exactly. +/// 2. None on overflow; NEVER a rounded or wrapped result. +/// ``` +pub fn total_of( + values: impl IntoIterator, + f: impl FnMut(I) -> T, +) -> Option { + total(values.into_iter().map(f)) +} + +/// [`total_of`] for a mapping that can itself fail (a difference of two +/// figures, `c - d`, that may not be representable): `None` when `f` is +/// `None` for any item or the running sum overflows. +/// +/// ```text +/// GOAL: the sum of a derived figure (a column's contributions less its +/// distributions) is exact, or refused. +/// SOURCE: docs/spec/rules.md B-21, B-28; bookspec BS-entry-3, +/// BS-entry-4; CONVENTION. +/// INVARIANTS: +/// 1. total_try(items, f) = Some(Σ f(item)) exactly when every f(item) +/// is Some and every running sum is representable; otherwise None. +/// ``` +pub fn total_try( + values: impl IntoIterator, + mut f: impl FnMut(I) -> Option, +) -> Option { + let mut sum = T::ZERO; + for value in values { + sum = sum.checked_add(f(value)?)?; + } + Some(sum) +} diff --git a/crates/ledger-core/src/proofs/total.rs b/crates/ledger-core/src/proofs/total.rs index d72b3854..bd31de56 100644 --- a/crates/ledger-core/src/proofs/total.rs +++ b/crates/ledger-core/src/proofs/total.rs @@ -1,5 +1,128 @@ //! U4 proof harnesses: exact totals (kernel sweep). //! -//! Empty in U0: the unit adds its Kani harnesses here; `just prove` scans -//! every file in `proofs/`, so a harness needs no change to the module -//! root or the recipe. +//! `kernel::total`, `total_of` and `total_try` on `i64` (the engine runs +//! the same code on `Decimal`; `tests/kernel_bridge/total.rs` checks the +//! two agree). Fixed arrays throughout: no symbolic-length `Vec`, no +//! `copy_from_slice` (model-checking/kani#4904). + +use super::{N, any_amount, any_side, wide}; +use crate::Side; +use crate::kernel::{self, Amount}; + +/// Most figures in each of the two runs `total_append` joins. +const A: usize = 3; + +fn any_count(max: usize) -> usize { + let n: usize = kani::any(); + kani::assume(n <= max); + n +} + +/// The exact sum of some `i64`s, in `i128`, the specification. +fn spec_sum(values: &[i64]) -> i128 { + values.iter().map(|&v| i128::from(v)).sum() +} + +/// No figures total to zero, for `total`, `total_of` and `total_try`. +#[kani::proof] +fn total_empty_is_zero() { + let none: [i64; 0] = []; + assert_eq!(kernel::total(none), Some(0)); + assert_eq!(kernel::total_of(none, |v: i64| v), Some(0)); + assert_eq!(kernel::total_try(none, Some), Some(0)); +} + +/// A run appended to another totals to the sum of their totals: for any +/// in-range runs `a` and `b`, `total(a ++ b) = total(a) + total(b)`, and +/// all three are `Some` (the combined run never leaves the range). +#[kani::proof] +#[kani::unwind(8)] +fn total_append() { + let a_values: [i64; A] = core::array::from_fn(|_| any_amount()); + let b_values: [i64; A] = core::array::from_fn(|_| any_amount()); + let a = &a_values[..any_count(A)]; + let b = &b_values[..any_count(A)]; + // The concatenation, into a fixed array (no growth, no copy_from_slice). + let mut both = [0i64; 2 * A]; + let mut at = 0; + for &v in a.iter().chain(b.iter()) { + both[at] = v; + at += 1; + } + let ta = kernel::total(a.iter().copied()).expect("in-range amounts never overflow"); + let tb = kernel::total(b.iter().copied()).expect("in-range amounts never overflow"); + let tab = kernel::total(both[..at].iter().copied()).expect("in-range amounts never overflow"); + assert_eq!(Some(tab), ta.checked_add(tb)); + kani::cover!( + !a.is_empty() && !b.is_empty() && tab != 0, + "two non-empty runs" + ); +} + +/// A total is exact whenever it exists, for *any* `i64` figures (the edge +/// included): `Some(s)` means `s` is the true sum, and `total` agrees with +/// a plain left-to-right checked fold. +#[kani::proof] +#[kani::unwind(5)] +fn total_is_sound() { + let all: [i64; 4] = core::array::from_fn(|_| kani::any()); + let values = &all[..any_count(4)]; + if let Some(s) = kernel::total(values.iter().copied()) { + assert_eq!(i128::from(s), spec_sum(values)); + kani::cover!(values.len() > 1 && s != 0, "a nonempty exact total"); + } +} + +/// A total over a mapped figure is the sum of the mapping: with the line's +/// signed amount as the map, `total_of` is `net` (the signed sum of the +/// lines), and it is the exact sum of the signed amounts. +#[kani::proof] +#[kani::unwind(6)] +fn total_of_is_map_sum() { + let lines: [(Side, i64); N] = core::array::from_fn(|_| (any_side(), any_amount())); + let used = &lines[..any_count(N)]; + let by_map = kernel::total_of(used.iter().copied(), |(side, amount)| { + kernel::signed(side, amount).expect("an in-range amount negates") + }) + .expect("in-range amounts never overflow"); + let spec: i64 = used.iter().map(|&(s, a)| wide(s, a)).sum(); + assert_eq!(by_map, spec); + assert_eq!(Some(by_map), kernel::net(used.iter().copied())); + kani::cover!(used.len() > 1 && by_map != 0, "a nonzero signed sum"); +} + +/// A total over a fallible mapping (a difference of two figures) is the sum +/// of the differences, and `None` when a difference is not representable. +#[kani::proof] +#[kani::unwind(6)] +fn total_try_is_map_sum() { + let pairs: [(i64, i64); N] = core::array::from_fn(|_| (any_amount(), any_amount())); + let used = &pairs[..any_count(N)]; + let got = kernel::total_try(used.iter().copied(), |(c, d)| c.checked_sub(d)) + .expect("in-range differences never overflow"); + let spec: i64 = used.iter().map(|&(c, d)| c - d).sum(); + assert_eq!(got, spec); + kani::cover!(used.len() > 1 && got != 0, "a nonzero sum of differences"); + + // A mapping that fails fails the whole total, wherever it is. + let failing = kernel::total_try(used.iter().copied(), |_| None::); + assert_eq!(failing.is_none(), !used.is_empty()); +} + +/// Overflow is `None`, never a wrap: for any two `i64`s, their total +/// exists exactly when the true sum fits, and the overflow case is reached. +#[kani::proof] +fn total_overflow_is_none() { + let a: i64 = kani::any(); + let b: i64 = kani::any(); + let true_sum = i128::from(a) + i128::from(b); + let fits = true_sum >= i128::from(i64::MIN) && true_sum <= i128::from(i64::MAX); + let got = kernel::total([a, b]); + assert_eq!(got.is_some(), fits); + if let Some(s) = got { + assert_eq!(i128::from(s), true_sum); + } + kani::cover!(!fits && true_sum > 0, "overflow past the maximum"); + kani::cover!(!fits && true_sum < 0, "overflow past the minimum"); + kani::cover!(fits && a != 0 && b != 0, "an ordinary sum"); +} diff --git a/crates/ledger-core/tests/kernel_bridge/total.rs b/crates/ledger-core/tests/kernel_bridge/total.rs index 19ddb333..9b95d01e 100644 --- a/crates/ledger-core/tests/kernel_bridge/total.rs +++ b/crates/ledger-core/tests/kernel_bridge/total.rs @@ -1,4 +1,143 @@ //! U4 bridge properties: exact totals (kernel sweep). //! -//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, -//! beside `main.rs` and the other units. +//! `kernel::total`, `total_of` and `total_try` on `i64` cents (what Kani +//! proved, `src/proofs/total.rs`) against the same on `Decimal` (what the +//! engine runs), on random lists, plus a table of the `Decimal` edges. + +use super::{arb_cents, dec}; +use ledger_core::kernel::{self, Amount}; +use proptest::prelude::*; +use rust_decimal::Decimal; + +fn arb_run() -> impl Strategy> { + prop::collection::vec(arb_cents(), 0..9) +} + +fn to_dec(run: &[i64]) -> Vec { + run.iter().map(|&c| dec(c)).collect() +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(2000))] + + /// Both types total a run to the same cents, and to the plain sum. + #[test] + fn total_agrees(run in arb_run()) { + let i = kernel::total(run.iter().copied()); + let d = kernel::total(to_dec(&run)); + prop_assert_eq!(i.map(dec), d); + prop_assert_eq!(i, Some(run.iter().sum::())); + } + + /// A mapped total agrees: the map is applied before the sum, both types. + #[test] + fn total_of_agrees(run in arb_run()) { + let i = kernel::total_of(run.iter().copied(), |c| c * 3); + let d = kernel::total_of(to_dec(&run), |x| x * Decimal::from(3)); + prop_assert_eq!(i.map(dec), d); + // total_of is the total of the mapped run. + prop_assert_eq!( + kernel::total_of(run.iter().copied(), |c| c * 3), + kernel::total(run.iter().map(|&c| c * 3)) + ); + } + + /// A fallible mapping agrees too: the difference of each pair. + #[test] + fn total_try_agrees(pairs in prop::collection::vec((arb_cents(), arb_cents()), 0..7)) { + let i = kernel::total_try(pairs.iter().copied(), |(c, d)| c.checked_sub(d)); + let d = kernel::total_try( + pairs.iter().map(|&(c, d)| (dec(c), dec(d))), + |(c, d)| Amount::checked_sub(c, d), + ); + prop_assert_eq!(i.map(dec), d); + // And a failing mapping fails the whole total at both types. + prop_assert_eq!( + kernel::total_try(pairs.iter().copied(), |_| None::).is_none(), + !pairs.is_empty() + ); + prop_assert_eq!( + kernel::total_try(pairs.iter().map(|&(c, _)| dec(c)), |_| None::).is_none(), + !pairs.is_empty() + ); + } + + /// Appending runs adds their totals (no overflow at cents), at both types. + #[test] + fn total_append_agrees(a in arb_run(), b in arb_run()) { + let both: Vec = a.iter().chain(&b).copied().collect(); + let (ta, tb) = (kernel::total(to_dec(&a)).unwrap(), kernel::total(to_dec(&b)).unwrap()); + prop_assert_eq!(kernel::total(to_dec(&both)), Amount::checked_add(ta, tb)); + let (ia, ib) = (kernel::total(a.iter().copied()).unwrap(), kernel::total(b.iter().copied()).unwrap()); + prop_assert_eq!(kernel::total(both.iter().copied()), ia.checked_add(ib)); + } +} + +/// The `Decimal` edges: what is representable is summed exactly, and what is +/// not is `None`, never a panic and never a rounded figure. +#[test] +fn decimal_edge_table() { + let max = Decimal::MAX; + let min = Decimal::MIN; + let one = Decimal::ONE; + + // The empty total, and a single figure at either edge. + assert_eq!(kernel::total(Vec::::new()), Some(Decimal::ZERO)); + assert_eq!(kernel::total([max]), Some(max)); + assert_eq!(kernel::total([min]), Some(min)); + + // One unit past either edge is refused. + assert_eq!(kernel::total([max, one]), None); + assert_eq!(kernel::total([min, -one]), None); + assert_eq!(kernel::total([max, max]), None); + assert_eq!(kernel::total([min, min]), None); + + // Opposite edges cancel exactly. + assert_eq!(kernel::total([max, min]), Some(Decimal::ZERO)); + assert_eq!(kernel::total([max, -max]), Some(Decimal::ZERO)); + // Mixed signs that cancel exactly, in the middle of the range. + let run = [dec(1_00), dec(-1_00), dec(3_33), dec(-3_33), Decimal::ZERO]; + assert_eq!(kernel::total(run), Some(Decimal::ZERO)); + + // Each step must be exact, so the edge is order dependent by design: + // the same three figures, one order representable, the other not. + assert_eq!(kernel::total([max, -one, one]), Some(max)); + assert_eq!(kernel::total([max, one, -one]), None); + assert_eq!(kernel::total([one, max, -one]), None); + + // total_of and total_try see the same edges. + assert_eq!(kernel::total_of([max, one], |x| x), None); + assert_eq!( + kernel::total_of([1, 2, 3], |n| Decimal::from(n)), + Some(Decimal::from(6)) + ); + assert_eq!( + kernel::total_try([(max, min)], |(a, b)| Amount::checked_sub(a, b)), + None + ); + assert_eq!( + kernel::total_try([(max, max), (min, min)], |(a, b)| Amount::checked_sub(a, b)), + Some(Decimal::ZERO) + ); +} + +/// FINDING (K-U4), pinned as a canary: `rust_decimal` rounds sub-unit dust +/// away when a sum lands on `Decimal::MAX`, so `Amount::checked_add` for +/// `Decimal` is not exact at the very edge (`MAX + 0.4 = MAX`, but `MAX + +/// 0.5` is `None`). The kernel's "exact or `None`" contract (and `total`'s +/// invariant 2) therefore holds for `Decimal` everywhere except figures +/// within one unit of `Decimal::MAX` (~7.9 x 10^28, 10^13 times a journal +/// line's cap). The fix belongs in `impl Amount for Decimal` +/// (`kernel/entries.rs`), not in `total`; when it lands this test fails +/// and is flipped to expect `None`. See docs/proofs/k-u4.md. +#[test] +fn finding_decimal_add_rounds_dust_at_the_edge() { + let max = Decimal::MAX; + let dust = Decimal::new(4, 1); + assert_eq!( + kernel::total([max, dust]), + Some(max), + "rust_decimal rounds the 0.4 away" + ); + assert_eq!(kernel::total([max, Decimal::new(5, 1)]), None); +}