diff --git a/crates/ledger-core/src/arap.rs b/crates/ledger-core/src/arap.rs index e054aac0..a47ec7c8 100644 --- a/crates/ledger-core/src/arap.rs +++ b/crates/ledger-core/src/arap.rs @@ -1355,10 +1355,14 @@ pub struct AgingRow { impl AgingRow { /// Total outstanding; refused past exact arithmetic. pub fn total(&self) -> Result { - [self.days_30, self.days_60, self.days_90, self.days_90_plus] - .into_iter() - .try_fold(self.current, Decimal::checked_add) - .ok_or_else(|| LedgerError::TooLargeToCompute(format!("{}'s aging total", self.name))) + crate::kernel::aging_total( + self.current, + self.days_30, + self.days_60, + self.days_90, + self.days_90_plus, + ) + .ok_or_else(|| LedgerError::TooLargeToCompute(format!("{}'s aging total", self.name))) } /// Add `other`'s buckets to this row's; refused past exact arithmetic. diff --git a/crates/ledger-core/src/kernel/control.rs b/crates/ledger-core/src/kernel/control.rs index 6e6df45d..c7422047 100644 --- a/crates/ledger-core/src/kernel/control.rs +++ b/crates/ledger-core/src/kernel/control.rs @@ -1,5 +1,116 @@ -//! U8: control and aging, what is due or overdue (kernel sweep). +//! U8: control, aging and reconciliation totals (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`. +//! Three identities the books state by name, each a short chain of exact +//! additions and subtractions: an aging row's five buckets sum to what is +//! owed (BS-arap-1), a control account's balance less its documents and its +//! unattached lines is its difference, which is always zero (BS-arap-2), and +//! a member's book capital less tax capital is their reconciliation total +//! (BS-partner-4). Naming them here puts them under proof rather than +//! leaving each a hand-written sum at its call site. The sums reuse +//! [`super::total`]; the chains of differences are checked one step at a +//! time, so none of them can panic or round. + +use super::{Amount, total}; + +/// What an aging row owes: its five buckets, current, 1-30, 31-60, 61-90 +/// and over 90 days, added exactly. +/// +/// ```text +/// GOAL: an aging row's total is exactly the sum of its five buckets, so +/// the buckets partition what is owed and no bucket is lost or +/// counted twice in the total. +/// SOURCE: BS-arap-1 (an aging puts each open balance in exactly one +/// bucket, so the buckets sum to the open balances); BS-entry-3, +/// BS-entry-4 (exact, no panic). +/// INVARIANTS: +/// 1. Some(t): t = current + b30 + b60 + b90 + b90p, exactly. +/// 2. The order of the buckets does not change a total that exists +/// for in-range figures; aging_total of five zeros is Some(0). +/// 3. None when a running sum cannot be represented; NEVER a rounded or +/// wrapped figure, never a panic. +/// SCENARIOS: +/// 1. IF a customer owes 100.00 current and 40.00 over 90 days past due: +/// - SHOULD total 140.00 +/// BECAUSE every bucket counts once. +/// 2. IF the buckets are Decimal::MAX and 1 in any two places: +/// - SHOULD be None +/// BECAUSE the sum is not representable. +/// ``` +pub fn aging_total(current: T, b30: T, b60: T, b90: T, b90p: T) -> Option { + total([current, b30, b60, b90, b90p]) +} + +/// A control account's difference: its balance less what its documents +/// still owe on it, less its unattached lines. +/// +/// ```text +/// GOAL: the control check's difference is the balance less the documents +/// and the unattached lines, exactly; it is zero whenever the +/// balance is those two sums, which it always is, as both sides sum +/// the same lines. +/// SOURCE: BS-arap-2 (a control account's balance equals the sum of its +/// documents plus its unattached lines); BS-ledger-8; BS-entry-4. +/// INVARIANTS: +/// 1. Some(d): d = balance - documents - unattached, exactly. +/// 2. control_difference(documents + unattached, documents, unattached) +/// = Some(0), and conversely Some(0) means balance = documents + +/// unattached: the difference vanishes exactly when the account +/// agrees with its subledger. +/// 3. None when a step cannot be represented; NEVER a rounded or +/// wrapped figure, never a panic. +/// SCENARIOS: +/// 1. IF the balance is 150.00, the documents 100.00 and one unattached +/// line 50.00: +/// - SHOULD be 0 +/// BECAUSE 150.00 = 100.00 + 50.00. +/// 2. IF the balance is 100.00 and the documents 90.00 with nothing +/// unattached: +/// - SHOULD be 10.00 +/// BECAUSE the account holds 10.00 no document explains. +/// ``` +pub fn control_difference(balance: T, documents: T, unattached: T) -> Option { + balance + .checked_sub(documents) + .and_then(|d| d.checked_sub(unattached)) +} + +/// A member's book capital less their tax capital, by cause: the +/// beginning difference, plus the built-in gain, plus property without a +/// basis, less property distributed (all at book). +/// +/// ```text +/// GOAL: the reconciliation total is exactly book ending less tax ending +/// as far as the books know it: what contributing and distributing +/// property does to the two capitals is the only way they part. +/// SOURCE: BS-partner-4 (the book-to-tax capital reconciliation: book +/// ending less tax ending = beginning (book less tax) + built-in +/// gain share + property without a basis (at book) - property +/// distributed (at book)); BS-asset-4 (the section 704(c) +/// built-in gain); BS-entry-4. +/// INVARIANTS: +/// 1. Some(t): t = beginning + built_in_gain + without_basis - +/// distributed, exactly. +/// 2. For any book and tax capital rows that differ only by those +/// causes (tax contributions = book contributions less the gain and +/// the property without a basis; tax distributions = book +/// distributions less what was distributed), book ending less tax +/// ending = reconciliation_total (Lean: Bookspec.Reconcile). +/// 3. None when a step cannot be represented; NEVER a rounded or +/// wrapped figure, never a panic. +/// SCENARIOS: +/// 1. IF two members jointly contribute a laptop worth 1,440.00 whose +/// basis is 1,688.40 (no other activity): +/// - SHOULD give each a total of -124.20 +/// BECAUSE book property is 720.00 and tax 844.20. +/// ``` +pub fn reconciliation_total( + beginning: T, + built_in_gain: T, + without_basis: T, + distributed: T, +) -> Option { + beginning + .checked_add(built_in_gain)? + .checked_add(without_basis)? + .checked_sub(distributed) +} diff --git a/crates/ledger-core/src/kernel/entries.rs b/crates/ledger-core/src/kernel/entries.rs index 5b003408..4565f3ac 100644 --- a/crates/ledger-core/src/kernel/entries.rs +++ b/crates/ledger-core/src/kernel/entries.rs @@ -180,6 +180,12 @@ impl Amount for i32 { fn checked_add(self, rhs: Self) -> Option { i32::checked_add(self, rhs) } + // The native subtraction: the default negates `rhs` first and so + // refused `x - MIN` even where the difference fits (found by the + // K-U8 harnesses: `None` must mean overflow, and only overflow). + fn checked_sub(self, rhs: Self) -> Option { + i32::checked_sub(self, rhs) + } fn checked_neg(self) -> Option { i32::checked_neg(self) } @@ -234,6 +240,12 @@ impl Amount for i64 { fn checked_add(self, rhs: Self) -> Option { i64::checked_add(self, rhs) } + // The native subtraction: the default negates `rhs` first and so + // refused `x - MIN` even where the difference fits (found by the + // K-U8 harnesses: `None` must mean overflow, and only overflow). + fn checked_sub(self, rhs: Self) -> Option { + i64::checked_sub(self, rhs) + } fn checked_neg(self) -> Option { i64::checked_neg(self) } diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index 95f5cf4c..6e14fca1 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -7494,10 +7494,9 @@ impl Ledger { } } let documents_total = doc_totals.get(&account).copied().unwrap_or_default(); - let difference = balance - .checked_sub(documents_total) - .and_then(|d| d.checked_sub(unattached_sum)) - .ok_or_else(too_large)?; + let difference = + crate::kernel::control_difference(balance, documents_total, unattached_sum) + .ok_or_else(too_large)?; out.push(arap::ControlCheck { role: role.key.to_string(), account, diff --git a/crates/ledger-core/src/proofs/control.rs b/crates/ledger-core/src/proofs/control.rs index d67021f4..1d3e9ed7 100644 --- a/crates/ledger-core/src/proofs/control.rs +++ b/crates/ledger-core/src/proofs/control.rs @@ -3,3 +3,121 @@ //! 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. + +use super::any_amount; +use crate::kernel::{self, Amount}; + +/// An aging row's total is exactly the sum of its five buckets, for +/// **any** five `i64` figures (the edge included): `Some(t)` means `t` is +/// the true sum (checked in `i128`, which holds any five `i64`s), and +/// whenever every bucket is within a journal line's range the total +/// exists. Five fixed figures, no `Vec`; no bound is fixed beyond the +/// five buckets an aging row has. +#[kani::proof] +fn aging_total_is_sum() { + let b: [i64; 5] = core::array::from_fn(|_| kani::any()); + let spec: i128 = b.iter().map(|&v| i128::from(v)).sum(); + let got = kernel::aging_total(b[0], b[1], b[2], b[3], b[4]); + if let Some(t) = got { + assert_eq!(i128::from(t), spec); + kani::cover!(t != 0, "a nonzero total exists"); + } + // `None` only on overflow: whenever every running prefix fits in + // `i64` (not only inside the line-range box), the total exists. + let mut run: i128 = 0; + let mut fits = true; + for &v in &b { + run += i128::from(v); + fits &= i64::try_from(run).is_ok(); + } + if fits { + assert!(got.is_some(), "every prefix fits, so the total exists"); + kani::cover!(run != 0, "a nonzero total from fitting prefixes"); + } + if b.iter().all(|v| v.in_line_range()) { + assert!(got.is_some(), "in-range buckets always total"); + kani::cover!( + b.iter().all(|&v| v != 0) && got.is_some(), + "five nonzero buckets" + ); + } + // The all-in-range case on its own: the total is the sum, for a + // positive owing and negative (credit) buckets alike. + let a: [i64; 5] = core::array::from_fn(|_| any_amount()); + let spec: i128 = a.iter().map(|&v| i128::from(v)).sum(); + let t = kernel::aging_total(a[0], a[1], a[2], a[3], a[4]).expect("in-range figures total"); + assert_eq!(i128::from(t), spec); + kani::cover!( + a.iter().any(|&v| v < 0) && a.iter().any(|&v| v > 0), + "mixed signs" + ); +} + +/// The control difference is `balance - documents - unattached`, exactly, +/// and it vanishes exactly when the balance is the documents plus the +/// unattached lines: the BS-arap-2 identity. For any three `i64`s: `Some(d)` +/// means `d` is the true difference (checked in `i128`); a balance that is +/// the sum of the other two (when that sum fits) differs by `Some(0)`; and +/// `Some(0)` means the balance is that sum. +#[kani::proof] +fn control_difference_identity() { + let (balance, docs, unattached): (i64, i64, i64) = (kani::any(), kani::any(), kani::any()); + let spec = i128::from(balance) - i128::from(docs) - i128::from(unattached); + let got = kernel::control_difference(balance, docs, unattached); + // `None` only on overflow: whenever both steps fit in `i64`, it exists. + let first = i128::from(balance) - i128::from(docs); + if i64::try_from(first).is_ok() && i64::try_from(spec).is_ok() { + assert!(got.is_some(), "both steps fit, so the difference exists"); + kani::cover!(spec != 0, "a nonzero difference from fitting steps"); + } + if let Some(d) = got { + assert_eq!(i128::from(d), spec); + if d == 0 { + assert_eq!( + i128::from(balance), + i128::from(docs) + i128::from(unattached) + ); + kani::cover!(docs != 0 && unattached != 0, "agrees with both parts"); + } else { + kani::cover!(true, "a nonzero difference"); + } + } + // The agreeing books: a balance of the documents plus the unattached + // lines (in range, so the sum fits) has no difference. + let (docs, unattached) = (any_amount(), any_amount()); + let balance = docs + unattached; + assert_eq!( + kernel::control_difference(balance, docs, unattached), + Some(0) + ); + kani::cover!( + docs > 0 && unattached < 0, + "documents with a credit unattached" + ); +} + +/// The reconciliation total is `beginning + built_in_gain + without_basis +/// - distributed`, exactly, for **any** four `i64`s when it exists +/// (checked in `i128`); and whenever the four are within a journal line's +/// range it exists. +#[kani::proof] +fn reconciliation_total_identity() { + let f: [i64; 4] = core::array::from_fn(|_| kani::any()); + let spec = i128::from(f[0]) + i128::from(f[1]) + i128::from(f[2]) - i128::from(f[3]); + let got = kernel::reconciliation_total(f[0], f[1], f[2], f[3]); + if let Some(t) = got { + assert_eq!(i128::from(t), spec); + kani::cover!(t != 0, "a nonzero total"); + } + // `None` only on overflow: whenever every running prefix fits in + // `i64`, the total exists. + let p1 = i128::from(f[0]) + i128::from(f[1]); + let p2 = p1 + i128::from(f[2]); + if [p1, p2, spec].iter().all(|&p| i64::try_from(p).is_ok()) { + assert!(got.is_some(), "every prefix fits, so the total exists"); + kani::cover!(spec != 0, "a nonzero total from fitting prefixes"); + } + if f.iter().all(|v| v.in_line_range()) { + assert!(got.is_some()); + } +} diff --git a/crates/ledger-core/src/tax_capital.rs b/crates/ledger-core/src/tax_capital.rs index 8cb33d22..a3c29a45 100644 --- a/crates/ledger-core/src/tax_capital.rs +++ b/crates/ledger-core/src/tax_capital.rs @@ -274,10 +274,12 @@ pub struct Reconciliation { impl Reconciliation { /// Book ending less tax ending (as far as known). pub fn total(&self) -> Option { - self.beginning - .checked_add(self.built_in_gain_704c)? - .checked_add(self.property_without_basis)? - .checked_sub(self.property_distributed) + crate::kernel::reconciliation_total( + self.beginning, + self.built_in_gain_704c, + self.property_without_basis, + self.property_distributed, + ) } } diff --git a/crates/ledger-core/tests/kernel_bridge/control.rs b/crates/ledger-core/tests/kernel_bridge/control.rs index 25566dd9..974e40ac 100644 --- a/crates/ledger-core/tests/kernel_bridge/control.rs +++ b/crates/ledger-core/tests/kernel_bridge/control.rs @@ -2,11 +2,16 @@ //! //! `kernel::running_bounds` and `kernel::bounds_kept` at `i64` cents (what //! Kani proves, law 34) against the same on `Decimal` (what the engine -//! runs), on random documents. +//! runs), on random documents. And K-U8's three identities, +//! `kernel::aging_total`, `control_difference` and `reconciliation_total`, +//! at `i64` (`src/proofs/control.rs`) against `Decimal`, and `Decimal` +//! against an independent exact `i128` reference, with the edges that must +//! be `None`. use super::{arb_cents, dec}; use ledger_core::kernel; use proptest::prelude::*; +use rust_decimal::Decimal; proptest! { #![proptest_config(ProptestConfig::with_cases(1000))] @@ -40,3 +45,293 @@ proptest! { ); } } + +/// An exact reference: the sum with signs, in `i128`, `None` when any +/// running step leaves what `Decimal` holds at scale 2 (a 96-bit +/// mantissa). Independent of the kernel and of `Decimal` arithmetic. +fn ref_chain(terms: &[(i128, bool)]) -> Option { + const LIMIT: i128 = (1i128 << 96) - 1; + let mut acc = 0i128; + for &(v, plus) in terms { + acc = if plus { acc + v } else { acc - v }; + if acc.abs() > LIMIT { + return None; + } + } + Some(acc) +} + +/// Cents anywhere in `Decimal`'s scale-2 mantissa range, edges included. +fn arb_wide_cents() -> impl Strategy { + let limit: i128 = (1i128 << 96) - 1; + prop_oneof![ + arb_cents().prop_map(i128::from), + (-limit..=limit), + Just(limit), + Just(-limit), + Just(limit - 1), + ] +} + +fn dec_wide(cents: i128) -> Decimal { + Decimal::from_i128_with_scale(cents, 2) +} + +/// `Decimal`'s answer against the exact reference: the same figure, or +/// `None` or a rounded figure when the reference is `None`. FINDING (K-U8, the K-U4 finding +/// again): where a step's exact result does not fit the 96-bit mantissa at +/// scale 2, `rust_decimal` does not refuse but rounds the result to a +/// coarser scale (so `Amount::checked_add` is not "exact or `None`" near +/// the top of the range, not only at `Decimal::MAX`). The reference is +/// `None` there and `Decimal` is `Some` at a scale below 2; the +/// assertion pins that shape, and the canary test below flips when the +/// fix lands in `impl Amount for Decimal`. +fn same_or_rounded( + got: Option, + want: Option, + exact: i128, +) -> Result<(), TestCaseError> { + match (got, want) { + (Some(g), Some(w)) => prop_assert_eq!((g.mantissa(), g.scale()), (w, 2)), + (None, None) => {} + // Rounded at a coarser scale at some step (a later step may bring + // it back to scale 2): not exact, and no panic; the finding. + // The figure is still close to the exact value (`exact`, in + // cents): each coarser step loses at most one unit of its scale + // (at worst the whole units, 100 cents), over at most four steps. + // (A later step can bring the scale back to 2, so the bound is + // not tied to the final scale.) + (Some(g), None) => { + let shown = g.mantissa() * 10i128.pow(2u32.saturating_sub(g.scale())); + prop_assert!( + g.scale() <= 2 && (shown - exact).abs() <= 400, + "{g} is not within four whole units of {exact} cents" + ); + } + (None, Some(w)) => prop_assert!(false, "refused an exact {w}"), + } + Ok(()) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(2000))] + + /// The aging total is the same cents at `i64` and `Decimal`, and the + /// plain sum. + #[test] + fn aging_total_agrees(b in prop::array::uniform5(arb_cents())) { + let i = kernel::aging_total(b[0], b[1], b[2], b[3], b[4]); + let d = kernel::aging_total(dec(b[0]), dec(b[1]), dec(b[2]), dec(b[3]), dec(b[4])); + prop_assert_eq!(i.map(dec), d); + prop_assert_eq!(i, Some(b.iter().sum::())); + } + + /// The control difference agrees at both types, is the plain + /// difference, and is zero for agreeing books. + #[test] + fn control_difference_agrees( + balance in arb_cents(), docs in arb_cents(), unattached in arb_cents(), + ) { + let i = kernel::control_difference(balance, docs, unattached); + let d = kernel::control_difference(dec(balance), dec(docs), dec(unattached)); + prop_assert_eq!(i.map(dec), d); + prop_assert_eq!(i, Some(balance - docs - unattached)); + prop_assert_eq!( + kernel::control_difference(dec(docs + unattached), dec(docs), dec(unattached)), + Some(Decimal::ZERO) + ); + } + + /// The reconciliation total agrees at both types, and is the plain + /// chain. + #[test] + fn reconciliation_total_agrees(f in prop::array::uniform4(arb_cents())) { + let i = kernel::reconciliation_total(f[0], f[1], f[2], f[3]); + let d = kernel::reconciliation_total(dec(f[0]), dec(f[1]), dec(f[2]), dec(f[3])); + prop_assert_eq!(i.map(dec), d); + prop_assert_eq!(i, Some(f[0] + f[1] + f[2] - f[3])); + } + + /// `Decimal` against the exact `i128` reference, over the whole + /// mantissa range: the same figure, or `None` exactly when a step + /// leaves the range; never a panic. + #[test] + fn decimal_matches_i128_reference(f in prop::array::uniform5(arb_wide_cents())) { + let (a, b, c, d, e) = (f[0], f[1], f[2], f[3], f[4]); + let got = kernel::aging_total(dec_wide(a), dec_wide(b), dec_wide(c), dec_wide(d), dec_wide(e)); + let want = ref_chain(&[(a, true), (b, true), (c, true), (d, true), (e, true)]); + same_or_rounded(got, want, a + b + c + d + e)?; + + let got = kernel::control_difference(dec_wide(a), dec_wide(b), dec_wide(c)); + let want = ref_chain(&[(a, true), (b, false), (c, false)]); + same_or_rounded(got, want, a - b - c)?; + + let got = kernel::reconciliation_total(dec_wide(a), dec_wide(b), dec_wide(c), dec_wide(d)); + let want = ref_chain(&[(a, true), (b, true), (c, true), (d, false)]); + same_or_rounded(got, want, a + b + c - d)?; + } +} + +/// The edges: what is representable is exact, and what is not is `None`. +#[test] +fn control_identity_edges() { + let (max, min, one, zero) = (Decimal::MAX, Decimal::MIN, Decimal::ONE, Decimal::ZERO); + + // Aging: every bucket at the edge alone, past it, and cancelling. + assert_eq!(kernel::aging_total(max, zero, zero, zero, zero), Some(max)); + assert_eq!(kernel::aging_total(min, zero, zero, zero, zero), Some(min)); + assert_eq!(kernel::aging_total(max, one, zero, zero, zero), None); + assert_eq!(kernel::aging_total(zero, zero, zero, zero, max), Some(max)); + assert_eq!(kernel::aging_total(max, max, zero, zero, zero), None); + assert_eq!(kernel::aging_total(min, min, zero, zero, zero), None); + assert_eq!(kernel::aging_total(max, zero, zero, zero, min), Some(zero)); + assert_eq!( + kernel::aging_total(zero, zero, zero, zero, zero), + Some(zero) + ); + + // Control: balance past either edge, documents or unattached that + // push it past, and a difference that lands exactly on an edge. + assert_eq!(kernel::control_difference(max, zero, zero), Some(max)); + assert_eq!(kernel::control_difference(min, one, zero), None); + assert_eq!(kernel::control_difference(min, zero, one), None); + assert_eq!(kernel::control_difference(max, min, zero), None); + assert_eq!(kernel::control_difference(zero, min, zero), Some(max)); + assert_eq!(kernel::control_difference(zero, zero, min), Some(max)); + assert_eq!(kernel::control_difference(max, max, zero), Some(zero)); + assert_eq!(kernel::control_difference(zero, max, min), Some(zero)); + + // Reconciliation: each step, each sign. + assert_eq!(kernel::reconciliation_total(max, one, zero, zero), None); + assert_eq!(kernel::reconciliation_total(max, zero, one, zero), None); + assert_eq!(kernel::reconciliation_total(min, zero, zero, one), None); + assert_eq!( + kernel::reconciliation_total(zero, zero, zero, min), + Some(max) + ); + assert_eq!( + kernel::reconciliation_total(max, zero, zero, max), + Some(zero) + ); + assert_eq!(kernel::reconciliation_total(max, one, zero, one), None); + assert_eq!( + kernel::reconciliation_total(max, zero, min, zero), + Some(zero) + ); +} + +/// The laptop (K-1 scenario 1): two members each at -124.20, as the +/// worksheet's own figures give it. +#[test] +fn reconciliation_laptop() { + let gain = Decimal::new(-12420, 2); + assert_eq!( + kernel::reconciliation_total(Decimal::ZERO, gain, Decimal::ZERO, Decimal::ZERO), + Some(gain) + ); +} + +/// FINDING (K-U8, K-U10 candidate), pinned as a canary: the dust the K-U4 +/// finding saw at `Decimal::MAX` is wider than that. Two cents-scale +/// figures whose exact sum needs more than 96 bits at scale 2 sum to a +/// rounded figure at scale 1, not to `None`. Here 0.01 plus the largest +/// scale-2 figure is 792281625142643375935439503.36, which `rust_decimal` +/// returns as 792281625142643375935439503.4. Reachable only with figures +/// near 7.9 x 10^26, a hundred billion times a journal line's cap, so the +/// engine's line cap keeps it out of every ordinary path. +#[test] +fn finding_decimal_add_rounds_scale_near_the_top() { + let top = Decimal::from_i128_with_scale((1i128 << 96) - 1, 2); + let got = kernel::aging_total( + Decimal::new(1, 2), + Decimal::ZERO, + Decimal::ZERO, + Decimal::ZERO, + top, + ); + assert_eq!( + got.map(|g| (g.mantissa(), g.scale())), + Some((7922816251426433759354395034, 1)) + ); +} + +/// Any `Decimal`, scale and sign included, mantissas up to the whole +/// 96 bits (so sums reach the overflow and rounding edges). +fn arb_decimal() -> impl Strategy { + ( + prop_oneof![ + -1_000_000_000i128..=1_000_000_000, + -((1i128 << 96) - 1)..=((1i128 << 96) - 1), + Just((1i128 << 96) - 1), + Just(-((1i128 << 96) - 1)), + ], + 0u32..=28, + ) + .prop_map(|(m, s)| Decimal::from_i128_with_scale(m, s)) +} + +fn shown(d: Option) -> String { + d.map_or("None".into(), |d| format!("{d} (scale {})", d.scale())) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(20000))] + + /// The routed sites give the figures, scales and refusals the + /// hand-written chains they replaced did (K-U8's compatibility check), + /// compared as strings: the old `AgingRow::total`, the old + /// `control_check` difference, the old `Reconciliation::total`. + #[test] + fn kernel_matches_the_replaced_chains(f in prop::array::uniform5(arb_decimal())) { + let old_aging = [f[1], f[2], f[3], f[4]] + .into_iter() + .try_fold(f[0], Decimal::checked_add); + prop_assert_eq!( + shown(kernel::aging_total(f[0], f[1], f[2], f[3], f[4])), + shown(old_aging) + ); + let old_diff = f[0].checked_sub(f[1]).and_then(|d| d.checked_sub(f[2])); + prop_assert_eq!( + shown(kernel::control_difference(f[0], f[1], f[2])), + shown(old_diff) + ); + let old_recon = f[0] + .checked_add(f[1]) + .and_then(|x| x.checked_add(f[2])) + .and_then(|x| x.checked_sub(f[3])); + prop_assert_eq!( + shown(kernel::reconciliation_total(f[0], f[1], f[2], f[3])), + shown(old_recon) + ); + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(2000))] + + /// The worksheet's identity (BS-partner-4), at both types: a book row + /// and a tax row that differ only by the three causes differ at the + /// ending by `reconciliation_total`. (Kani did not finish this one at + /// nine terms, 500 s, nor at seven, 110 s; Lean's + /// `Control.reconciliation_identity` carries it at any size, and this + /// property checks it on the engine's own type.) + #[test] + fn reconciliation_worksheet_identity( + f in prop::array::uniform5(arb_cents()), + g in prop::array::uniform5(arb_cents()), + ) { + let (bb, tb, cash, prop_book, income) = (f[0], f[1], f[2], f[3], f[4]); + let (other, dist_book, gain, without, distributed) = (g[0], g[1], g[2], g[3], g[4]); + let book = bb + cash + prop_book + income + other - dist_book; + let tax = tb + cash + (prop_book - gain - without) + income + other + - (dist_book - distributed); + prop_assert_eq!( + kernel::reconciliation_total(bb - tb, gain, without, distributed), + Some(book - tax) + ); + prop_assert_eq!( + kernel::reconciliation_total(dec(bb - tb), dec(gain), dec(without), dec(distributed)), + Some(dec(book - tax)) + ); + } +} diff --git a/crates/ledger-package/src/aging.rs b/crates/ledger-package/src/aging.rs index ef3c6d61..33f68390 100644 --- a/crates/ledger-package/src/aging.rs +++ b/crates/ledger-package/src/aging.rs @@ -4,7 +4,7 @@ //! package build the same CSV from this, and its XLSX/PDF from //! [`aging_statement`], so a CPA's two copies can't differ. -use ledger_core::{DocRef, Ledger}; +use ledger_core::{DocRef, Ledger, LedgerError, kernel}; use rust_decimal::Decimal; use crate::text::{csv_escape, money}; @@ -26,9 +26,7 @@ pub fn aging_csv( .map_err(|e| e.to_string())?; let mut out = String::from(AGING_CSV_HEADER); out.push('\n'); - let mut total = Decimal::ZERO; for d in &docs { - total += d.outstanding; out.push_str(&format!( "{},{},{},{},{},{},{},{},{},{},{}\n", csv_escape(&number(ledger, d.doc)), @@ -44,6 +42,7 @@ pub fn aging_csv( d.days_overdue, )); } + let total = outstanding_total(&docs)?; let (code, balance, difference) = tie_out(ledger, invoices, as_of)?; let account = if code.is_empty() { "GL —".to_string() @@ -59,6 +58,28 @@ pub fn aging_csv( Ok(out) } +fn too_large() -> String { + LedgerError::TooLargeToCompute("the aging total".into()).to_string() +} + +/// The sum of the open documents' outstanding balances, or a refusal when +/// it is past exact arithmetic (BS-entry-4): never a panic. +fn outstanding_total(docs: &[ledger_core::AgingDocument]) -> Result { + kernel::total_of(docs, |d| d.outstanding).ok_or_else(too_large) +} + +/// The five bucket sums over the party rows and their grand total, or a +/// refusal when any is past exact arithmetic (BS-entry-4). +fn column_totals(rows: &[ledger_core::AgingRow]) -> Result<[Decimal; 6], String> { + let current = kernel::total_of(rows, |r| r.current).ok_or_else(too_large)?; + let d30 = kernel::total_of(rows, |r| r.days_30).ok_or_else(too_large)?; + let d60 = kernel::total_of(rows, |r| r.days_60).ok_or_else(too_large)?; + let d90 = kernel::total_of(rows, |r| r.days_90).ok_or_else(too_large)?; + let d90p = kernel::total_of(rows, |r| r.days_90_plus).ok_or_else(too_large)?; + let total = kernel::aging_total(current, d30, d60, d90, d90p).ok_or_else(too_large)?; + Ok([current, d30, d60, d90, d90p, total]) +} + /// The same aging as a laid-out statement for XLSX and PDF: one line per /// party with its six bucket amounts, the totals, and the tie-out. pub fn aging_statement( @@ -89,20 +110,8 @@ pub fn aging_statement( currency: false, rule_above: false, }]; - let (mut current, mut d30, mut d60, mut d90, mut d90p) = ( - Decimal::ZERO, - Decimal::ZERO, - Decimal::ZERO, - Decimal::ZERO, - Decimal::ZERO, - ); for r in &party_rows { let total = r.total().map_err(|e| e.to_string())?; - current += r.current; - d30 += r.days_30; - d60 += r.days_60; - d90 += r.days_90; - d90p += r.days_90_plus; out_rows.push(Row { kind: RowKind::Line, label: r.name.clone(), @@ -118,7 +127,7 @@ pub fn aging_statement( rule_above: false, }); } - let total = current + d30 + d60 + d90 + d90p; + let [current, d30, d60, d90, d90p, total] = column_totals(&party_rows)?; out_rows.push(Row { kind: RowKind::Total, label: "Total".into(), @@ -214,3 +223,37 @@ fn tie_out( .unwrap_or_default(); Ok((code, check.balance, check.difference)) } + +#[cfg(test)] +mod tests { + use super::*; + + fn row(current: Decimal, days_90_plus: Decimal) -> ledger_core::AgingRow { + ledger_core::AgingRow { + name: "Big".into(), + current, + days_30: Decimal::ZERO, + days_60: Decimal::ZERO, + days_90: Decimal::ZERO, + days_90_plus, + } + } + + /// An aging past exact arithmetic is refused with an error, never a + /// panic (BS-entry-4): a column, or the grand total, that `Decimal` + /// cannot hold. + #[test] + fn an_aging_past_exact_arithmetic_is_refused() { + let one = Decimal::ONE; + // One column overflows across two parties. + let err = column_totals(&[row(Decimal::MAX, one), row(one, one)]).unwrap_err(); + assert!(err.contains("the aging total"), "{err}"); + // Every column fits but the grand total does not. + let err = column_totals(&[row(Decimal::MAX, one)]).unwrap_err(); + assert!(err.contains("the aging total"), "{err}"); + // Within range, the totals are exact. + let ok = column_totals(&[row(Decimal::from(3), one), row(one, one)]).unwrap(); + assert_eq!(ok[0], Decimal::from(4)); + assert_eq!(ok[5], Decimal::from(6)); + } +} diff --git a/docs/proofs/k-u8.md b/docs/proofs/k-u8.md new file mode 100644 index 00000000..7299a672 --- /dev/null +++ b/docs/proofs/k-u8.md @@ -0,0 +1,198 @@ +# K-U8: control, aging and reconciliation totals (`kernel/control.rs`) + +_Folded into `docs/verification.md` by the integrator; this note is the +unit's own record._ + +Kernel sweep unit U8 (`plan/kernel-sweep-audit.md` section 3). The audit +cites its three rules by the retired numbering; the bookspec ids +(`docs/spec/rules.md` maps them) are BS-arap-1 (aging), BS-arap-2 (a control account is its documents) and +BS-asset-4 (the section 704(c) built-in gain). The reconciliation itself +is BS-partner-4's (the book-to-tax capital identity), which the K-1 +module already cites, so the functions cite it too. + +## What remained after K-U4 + +K-U4 routed the plain sums through `kernel::total*`. Still computed by +hand, each a short chain at one call site: + +- `arap::AgingRow::total`: `current + 30 + 60 + 90 + 90+`, a + `try_fold(checked_add)`. +- `Ledger::control_check`: `difference = balance − documents_total − + unattached`, two chained `checked_sub`s. +- `tax_capital::Reconciliation::total`: `beginning + built-in gain + + property without a basis − property distributed`, three chained checked + steps. + +These are the identities the audit asked to name: the rules say the +buckets partition the open balances, the control difference is always +zero, and the reconciliation holds exactly. Naming them puts each under a +harness and a Lean theorem rather than leaving them as sums. + +## The API + +```rust +pub fn aging_total(current: T, b30: T, b60: T, b90: T, b90p: T) -> Option +pub fn control_difference(balance: T, documents: T, unattached: T) -> Option +pub fn reconciliation_total( + beginning: T, built_in_gain: T, without_basis: T, distributed: T, +) -> Option +``` + +`aging_total` is `total([..five buckets..])`. The other two are the exact +chains `checked_sub, checked_sub` and `checked_add, checked_add, +checked_sub`, in the order the replaced code used, so a figure's scale and +a refusal are unchanged. All three return `None` rather than panic or +round. + +## Kani harnesses (`src/proofs/control.rs`) + +On `i64`, fixed arrays or plain bindings (no `Vec`, no `copy_from_slice`), +each with `kani::cover!`. No bound is fixed beyond the arity: each +harness quantifies over **arbitrary `i64`s** (the edge included) and +checks `Some(x)` against an exact `i128` specification, and that `None` +means overflow and only overflow: every harness computes the `i128` +running prefixes and asserts `Some` whenever each prefix fits in `i64` +(the whole `i64` range, not only the journal-line box of 2^40, which is +also kept as a cover). + +Finding, from tightening them (2026-11-09): the first run of the +tightened `control_difference_identity` failed. `Amount::checked_sub`'s +default negates `rhs` and adds, so `i64` (and `i32`) refused `x - MIN` +even where the difference fits. A model-type gap, not a `Decimal` one +(`Decimal` negation is total), but exactly what `None only on overflow` +forbids; `i32` and `i64` now override `checked_sub` with the native one. + +| Harness | Law | Verification | +|---|---|---| +| `aging_total_is_sum` | 46 | five arbitrary `i64` buckets: `Some(t)` is the true sum; five in-range buckets always total; mixed signs reached (4 covers). 20.4 s verification, 31.2 s wall | +| `control_difference_identity` | 46 | three arbitrary `i64`s: `Some(d)` is `balance − documents − unattached`; `d = 0` exactly when `balance = documents + unattached`; agreeing in-range books differ by `Some(0)` (4 covers). 0.8 s verification, 10.3 s wall | +| `reconciliation_total_identity` | 46 | four arbitrary `i64`s: `Some(t)` is `beginning + gain + without − distributed`; in-range figures always total (2 covers; one `unreachable` check, which is the proof's `expect`, reported unreachable as it should be). 1.7 s verification, 11.7 s wall | + +Times: `cargo kani -p ledger-core --exact --harness proofs::control::`, +the verifier's own time and the wall time including Kani's build, the +shared dev machine under `nice -n 15`, 2026-11-09. + +What the solver could not do: the **worksheet** statement, that a book +capital row and a tax capital row differing only by the three causes +differ at the ending by `reconciliation_total`. As a harness over nine +terms it did not finish in 500 s, and over seven (the common cash, income +and other terms cancelled) not in 110 s; the proof is the equality of two +differently associated 64-bit sums, which bit-blasting is poor at. It was +dropped, not weakened. After review, both smaller forms were tried: +(a) the nine terms on `i32` (line range 2^20): no verdict in 400 s; +(b) the seven terms (cash, income and other fixed at `0`) on `i32`: no +verdict in 300 s; (b) alone on `i64` was the 110 s attempt above. The +solver does not close two differently associated sums at either width, +so no harness. Lean's `Control.reconciliation_identity` proves it +at any size, and `reconciliation_worksheet_identity` in the bridge checks +it on both `i64` and `Decimal`. + +The bookspec law each harness proves (machine-readable for the +traceability gate, `crates/ledger-core/tests/bookspec/traceability.rs`): + +| Harness | Law | +|---|---| +| `aging_total_is_sum` | 46 | +| `control_difference_identity` | 46 | +| `reconciliation_total_identity` | 46 | + +## Bridge (`tests/kernel_bridge/control.rs`) + +- `aging_total_agrees`, `control_difference_agrees`, + `reconciliation_total_agrees`: `i64` cents against `Decimal`, and the + plain `i64` sum, on random cents; agreeing books give `Some(0)`. +- `decimal_matches_i128_reference`: `Decimal` against an independent exact + `i128` reference (running sum with signs, the 96-bit mantissa as the + range) over the whole mantissa range with the edges `±(2^96 − 1)` and + one in from them. +- `control_identity_edges`: `Decimal::MAX`/`MIN` in every position, each + overflowing step `None`, each cancelling pair `Some(0)`; never a panic. + (`0 − MIN` is `MAX`, representable: `Decimal` is symmetric.) +- `reconciliation_worksheet_identity`: the worksheet statement above, on + `i64` and `Decimal`. +- `reconciliation_laptop`: the K-1 module's laptop scenario, −124.20. +- `kernel_matches_the_replaced_chains`: 20,000 random `Decimal`s of any + scale (0 to 12) and mantissa up to 96 bits, the new function against + the exact hand-written chain it replaced, compared as strings including + the scale: identical for all three, `None`s included. +- `finding_decimal_add_rounds_scale_near_the_top`: see the finding. + +## Finding (a K-U10 case, not a behaviour change) + +K-U4's finding was that `rust_decimal`'s add rounds dust when a sum lands +on `Decimal::MAX`. The bridge's exact reference shows it is wider: any +add whose exact result needs more than 96 bits *at the operands' scale* +is not refused but **rounded to a coarser scale**. `0.01 + +792281625142643375935439503.35` (the largest scale-2 figure) returns +`792281625142643375935439503.4`, not `None`; a later step can bring the +scale back to 2, so a chain's result can differ from the exact figure at +scale 2 as well. The reference property therefore accepts a rounded +`Some` where the reference says `None` and pins one case as a canary, to +flip when `impl Amount for Decimal` is fixed. It is reachable only near +7.9 × 10^26 at scale 2 (a hundred billion times a journal line's cap), so +no ordinary path sees it, but it means "exact or `None`" is not yet true +of `Decimal` at its edge (K-U10's, with K-U4's finding). + +## Lean (bookspec `lean/Bookspec/Control.lean`, law 46) + +- `aging_partitions`: any documents placed in one of five buckets have + five bucket sums that add (`agingTotal`) to the sum of their balances, + by induction with `five_buckets_once`; `agingTotal_comm`. +- `control_difference_zero`: the control difference + (`controlDifference`) is zero for any account, from + `Documents.control_agrees`; `controlDifference_eq_zero_iff`. +- `reconciliation_identity`: a book row's ending less a tax row's ending + is `reconciliationTotal` of the beginning difference and the three + causes; `reconciliation_beginning_only`, + `reconciliationTotal_causes`. + +BS-arap-1's invariant `sum_b owed(b) = sum of open balances` and +BS-arap-2's aging invariant link `aging_partitions`; BS-arap-2 gains an +invariant for the control check's zero difference +(`control_difference_zero`); BS-partner-4's reconciliation invariant links +`reconciliation_identity`. Integers do not overflow in the model; the +kernel's `None` is the bridge's. The documents' day and the unattached +chain are `Documents`' own. No `sorry`; `#print axioms` shows only +`propext`, `Quot.sound` and (once) `Classical.choice`. + +## Sites routed and left + +Routed: + +- `arap::AgingRow::total` → `kernel::aging_total`. +- `Ledger::control_check`'s difference → `kernel::control_difference`. +- `tax_capital::Reconciliation::total` → `kernel::reconciliation_total`. + +The figures, scales and errors are unchanged: the replaced chains are +checked against the kernel as strings (`kernel_matches_the_replaced_chains`) +and every golden passes untouched. + +Left, with why: + +- `ledger-package::aging` (the CSV's total and the statement's column + totals): done after review. The raw `+=` and `current + d30 + ...` that + panicked at the `Decimal` edge are now `kernel::total_of` and + `kernel::aging_total`, a past-exact aging returns + `TooLargeToCompute("the aging total")` as an `Err`, and the unit test + `an_aging_past_exact_arithmetic_is_refused` checks it. Only the error + path changed: no golden moves. The store cannot be driven there (a + journal line is capped at one quadrillion), so the test reaches the + seam through the pure helpers `column_totals` and `outstanding_total`. +- `ledger-package::attention`'s overdue sum (`days_30 + 60 + 90 + 90+`) + is already checked (`try_fold(checked_add)`) and is the overdue + subtotal, not the aging total; left. +- `tax_capital`'s `book.beginning − beginning.known` (one checked + subtraction) and the rows' `known` chain are single steps or the + documented invariant 4 chain, already checked; no identity to name + beyond what is routed. +- `ledger-gui::pages::reports`' aging totals: per-column checked sums + already; display. + +## Gates + +- `cargo test -p ledger-core`: all tests and every golden unchanged, + against the `k-u8` bookspec branch (patched checker/runner). +- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`. +- Kani: the three harnesses above. +- bookspec: `lake build`, `lake env lean Audit.lean` (standard axioms), + `cargo test --workspace`, `render -- --check`, `scripts/spec-floors.sh main`.