feat(kernel): total, total_of and total_try, the exact checked sum with Kani proofs and a bridge

A raw Decimal + / += / .sum() panics at Decimal::MAX; a replayed journal
line is accepted 'of any size' (rules.md B-28) so a restored figure is the
realistic path to that edge, and amounts are exact (B-21): a total is the
exact sum or it is refused. kernel::total sums any figures, total_of a
mapped field, total_try a fallible mapping (a difference), each None on
overflow. The signed sum of (Side, amount) lines stays kernel::net/totals.

Kani (proofs/total.rs, fixed arrays): total_empty_is_zero, total_append,
total_is_sound (any i64), total_of_is_map_sum (= net), total_try_is_map_sum,
total_overflow_is_none, each with covers. Bridge (kernel_bridge/total.rs):
i64 vs Decimal on random runs, a Decimal edge table, and a canary for the
finding that rust_decimal rounds dust when a sum lands on Decimal::MAX.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-08 11:59:32 -07:00
1 parent 75c666a7ce
commit b3d504067f
3 files changed
+352 -8

No files matched your search

+85 -3
View File
@@ -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<T: Amount>(values: impl IntoIterator<Item = T>) -> Option<T> {
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<T: Amount, I>(
values: impl IntoIterator<Item = I>,
f: impl FnMut(I) -> T,
) -> Option<T> {
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<T: Amount, I>(
values: impl IntoIterator<Item = I>,
mut f: impl FnMut(I) -> Option<T>,
) -> Option<T> {
let mut sum = T::ZERO;
for value in values {
sum = sum.checked_add(f(value)?)?;
}
Some(sum)
}
+126 -3
View File
@@ -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::<i64>);
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");
}