diff --git a/crates/ledger-core/src/arap.rs b/crates/ledger-core/src/arap.rs index a8247d61..92a8df0c 100644 --- a/crates/ledger-core/src/arap.rs +++ b/crates/ledger-core/src/arap.rs @@ -1064,9 +1064,7 @@ pub struct Invoice { /// line as written (rules.md B-28), so its lines are bounded only by what /// the version that wrote it checked. pub fn document_total(lines: &[DocumentLine], what: &str) -> Result { - lines - .iter() - .try_fold(Decimal::ZERO, |sum, l| sum.checked_add(l.amount)) + crate::kernel::total_of(lines, |l| l.amount) .ok_or_else(|| LedgerError::TooLargeToCompute(format!("{what}'s total"))) } diff --git a/crates/ledger-core/src/audit.rs b/crates/ledger-core/src/audit.rs index 460c80de..dabbfdf0 100644 --- a/crates/ledger-core/src/audit.rs +++ b/crates/ledger-core/src/audit.rs @@ -333,7 +333,9 @@ pub fn check_equation(bs: &crate::reports::BalanceSheetStatement) -> Option Decimal { +/// `None` when the sum is past exact arithmetic (the check is skipped, as +/// `articulation` skips a statement it cannot make). +fn closed_net(ledger: &Ledger, through: NaiveDate) -> Option { let mut net = Decimal::ZERO; for id in ledger.closing_entry_ids() { let Some(e) = ledger.get_entry(id) else { @@ -351,11 +353,11 @@ fn closed_net(ledger: &Ledger, through: NaiveDate) -> Decimal { Side::Credit => -l.amount.amount, }; if matches!(a.account_type, AccountType::Revenue | AccountType::Expense) { - net += signed; + net = crate::kernel::Amount::checked_add(net, signed)?; } } } - net + Some(net) } fn articulation(ledger: &Ledger, through: NaiveDate) -> Option { @@ -369,7 +371,7 @@ fn articulation(ledger: &Ledger, through: NaiveDate) -> Option { check_articulation( pnl.net_income(), bs.current_earnings, - closed_net(ledger, through), + closed_net(ledger, through)?, ) } @@ -380,7 +382,8 @@ pub fn check_articulation( current_earnings: Decimal, closed: Decimal, ) -> Option { - (net_income != current_earnings + closed).then(|| { + let explained = crate::kernel::Amount::checked_add(current_earnings, closed)?; + (net_income != explained).then(|| { Finding::new( "pnl_not_articulated", Subject::Books, @@ -522,7 +525,10 @@ fn schedules(ledger: &Ledger, through: NaiveDate) -> Vec { } }; if let Some((first, _)) = months.first() { - let total: Decimal = months.iter().map(|(_, a)| *a).sum(); + let total = crate::kernel::total_of(&months, |&(_, a)| a).map_or_else( + || "a sum too large to compute".to_string(), + |t| t.to_string(), + ); out.push(Finding::new( "schedule_behind", Subject::Schedule(s.id), diff --git a/crates/ledger-core/src/form1099.rs b/crates/ledger-core/src/form1099.rs index 6724229a..be357298 100644 --- a/crates/ledger-core/src/form1099.rs +++ b/crates/ledger-core/src/form1099.rs @@ -704,9 +704,7 @@ fn entry_buckets( } fn sum3(b: [Decimal; 3]) -> Result { - b[0].checked_add(b[1]) - .and_then(|s| s.checked_add(b[2])) - .ok_or_else(|| LedgerError::TooLargeToCompute("a payment's buckets".into())) + kernel::total(b).ok_or_else(|| LedgerError::TooLargeToCompute("a payment's buckets".into())) } /// The vendor's part of `payment` when the entry names several parties: @@ -768,13 +766,13 @@ fn split_share(b: [Decimal; 3], v: Decimal) -> Result<[Decimal; 3], LedgerError> let mut part = kernel::round_places(q, 2, kernel::Rounding::TowardZero).ok_or_else(too_large)?; while times(part)? > num { - part -= cent; + part = part.checked_sub(cent).ok_or_else(too_large)?; } - while times(part + cent)? <= num { - part += cent; + while times(part.checked_add(cent).ok_or_else(too_large)?)? <= num { + part = part.checked_add(cent).ok_or_else(too_large)?; } // The remainder, over the common denominator ap. - rems[i] = num - times(part)?; + rems[i] = num.checked_sub(times(part)?).ok_or_else(too_large)?; parts[i] = part; } kernel::apportion(av, &mut parts, &rems, cent).ok_or_else(too_large)?; diff --git a/crates/ledger-core/src/k1.rs b/crates/ledger-core/src/k1.rs index 622ec80d..efd375af 100644 --- a/crates/ledger-core/src/k1.rs +++ b/crates/ledger-core/src/k1.rs @@ -66,6 +66,8 @@ //! 3001 1,500): 1,500.00 property each, no cash. //! ``` +use crate::kernel::Amount; +use crate::money::{add_exact, sub_exact, sum_exact_of, sum_exact_try}; use crate::reports::{MemberCapital, members_equity}; use crate::{AccountId, AccountType, EntryId, Ledger, LedgerError, PartyId, Side}; use chrono::NaiveDate; @@ -178,10 +180,16 @@ pub fn k1_detail( { if closings.contains(&e.id()) { for (i, m) in members.iter().enumerate() { - let effect: Decimal = std::iter::once(m.capital_account) - .chain(m.distribution_account) - .map(|a| side_sum(e, Side::Credit, a) - side_sum(e, Side::Debit, a)) - .sum(); + let effect = sum_exact_try( + std::iter::once(m.capital_account).chain(m.distribution_account), + |a| { + Amount::checked_sub( + side_sum(e, Side::Credit, a).ok()?, + side_sum(e, Side::Debit, a).ok()?, + ) + }, + "a member's closing effect", + )?; if !effect.is_zero() { lines.push(K1Line { member: i, @@ -195,12 +203,12 @@ pub fn k1_detail( } lines.extend(entry_lines(ledger, e, members, cash, places)?); } - let total = |i: usize, k: K1Kind| -> Decimal { - lines - .iter() - .filter(|l| l.member == i && l.kind == k) - .map(|l| l.amount) - .sum() + let total = |i: usize, k: K1Kind| -> Result { + sum_exact_of( + lines.iter().filter(|l| l.member == i && l.kind == k), + |l| l.amount, + "a member's K-1 contributions", + ) }; let rows = me .members @@ -211,30 +219,40 @@ pub fn k1_detail( // Each entry's property is at most that member's credit in it, // and contributions are those credits' sum: property never // exceeds contributions, and is never negative. - let prop = total(i, K1Kind::PropertyContribution); - K1Row { + let prop = total(i, K1Kind::PropertyContribution)?; + Ok(K1Row { name: col.name, share: m.share, beginning: col.beginning, - contributions_cash: col.contributions - prop, + contributions_cash: sub_exact( + col.contributions, + prop, + "a member's cash contributions", + )?, contributions_property: prop, net_income: col.net_income, distributions: col.distributions, other: col.other, ending: col.ending, - } + }) }) - .collect(); + .collect::>()?; Ok(K1Detail { rows, lines }) } /// Σ of an entry's lines on `account`, on `side`. -fn side_sum(e: &crate::JournalEntry, side: Side, account: AccountId) -> Decimal { - e.lines() - .iter() - .filter(|l| l.side == side && l.account == account) - .map(|l| l.amount.amount) - .sum() +fn side_sum( + e: &crate::JournalEntry, + side: Side, + account: AccountId, +) -> Result { + sum_exact_of( + e.lines() + .iter() + .filter(|l| l.side == side && l.account == account), + |l| l.amount.amount, + "an entry's lines on an account", + ) } /// One entry's contribution and distribution lines, as [`k1_detail`] @@ -256,33 +274,44 @@ pub(crate) fn entry_lines( kind, amount, }; - let pool: Decimal = e - .lines() - .iter() - .filter(|l| l.side == Side::Debit && is_property_account(ledger, cash, l.account)) - .map(|l| l.amount.amount) - .sum(); + let pool = sum_exact_of( + e.lines() + .iter() + .filter(|l| l.side == Side::Debit && is_property_account(ledger, cash, l.account)), + |l| l.amount.amount, + "an entry's property debits", + )?; // Contributions are credits to capital (members_equity's). let credits: Vec = members .iter() .map(|m| side_sum(e, Side::Credit, m.capital_account)) - .collect(); + .collect::>()?; let takes = share_property(pool, &credits, places)?; let mut lines = Vec::new(); for (i, m) in members.iter().enumerate() { let (credit, take) = (credits[i], takes[i]); - if !(credit - take).is_zero() { - lines.push(line(i, K1Kind::CashContribution, credit - take)); + let cash_part = sub_exact(credit, take, "a member's cash contribution")?; + if !cash_part.is_zero() { + lines.push(line(i, K1Kind::CashContribution, cash_part)); } if !take.is_zero() { lines.push(line(i, K1Kind::PropertyContribution, take)); } // Distributions: debits to capital, net debits to the // distributions account (members_equity's). - let taken = side_sum(e, Side::Debit, m.capital_account) - + m.distribution_account.map_or(Decimal::ZERO, |d| { - side_sum(e, Side::Debit, d) - side_sum(e, Side::Credit, d) - }); + let from_distributions = match m.distribution_account { + None => Decimal::ZERO, + Some(d) => sub_exact( + side_sum(e, Side::Debit, d)?, + side_sum(e, Side::Credit, d)?, + "a member's distributions", + )?, + }; + let taken = add_exact( + side_sum(e, Side::Debit, m.capital_account)?, + from_distributions, + "a member's distributions", + )?; if !taken.is_zero() { lines.push(line(i, K1Kind::Distribution, -taken)); } 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/ledger.rs b/crates/ledger-core/src/ledger.rs index 6358a1c1..90ea71dd 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -3822,17 +3822,26 @@ impl Ledger { let shares: Vec = members.iter().map(|m| m.share).collect(); Ok(match to { CloseTo::MembersLastAbsorbs(_) => ( - periods::allocate_last_absorbs(net, &shares), + periods::try_allocate_last_absorbs(net, &shares)?, MemberRule::LastAbsorbs, ), - CloseTo::MembersPerClose(_) => (periods::allocate(net, &shares), MemberRule::PerClose), + CloseTo::MembersPerClose(_) => { + (periods::try_allocate(net, &shares)?, MemberRule::PerClose) + } CloseTo::MembersRun(_) => { // The run rule: what the run gives each member with this // close, less what it gave them before. let before = self.member_close_run(&member_key(members)); - let after = periods::allocate(before + net, &shares); - let prior = periods::allocate(before, &shares); - let parts = after.iter().zip(&prior).map(|(a, p)| a - p).collect(); + let after = periods::try_allocate( + crate::money::add_exact(before, net, "the members' close run")?, + &shares, + )?; + let prior = periods::try_allocate(before, &shares)?; + let parts = after + .iter() + .zip(&prior) + .map(|(a, p)| crate::money::sub_exact(*a, *p, "the members' close run")) + .collect::>()?; (parts, MemberRule::Run) } _ => { @@ -3842,7 +3851,11 @@ impl Ledger { let parts = if posts { regime.allocate( &key, - regime.closed + net, + crate::money::add_exact( + regime.closed, + net, + "the members' closed earnings", + )?, ®ime.given, self.base_currency.allocation_places(), )? @@ -4045,7 +4058,8 @@ impl Ledger { "a count of members closes starts at close 1 or later, not 0".into(), )); } - let total: Decimal = members.iter().map(|m| m.share).sum(); + let total = + crate::money::sum_exact_of(members, |m| m.share, "the members' shares")?; if members.is_empty() || total != Decimal::ONE || members.iter().any(|m| m.share <= Decimal::ZERO) @@ -6397,7 +6411,8 @@ impl Ledger { return Err(LedgerError::TooLargeToCompute(format!("{doc}'s figures"))); } }; - let owed: Decimal = after[..=i].iter().sum(); + let owed = + crate::money::sum_exact(after[..=i].iter().copied(), &format!("{doc}'s figures"))?; let on = grid[i]; let payments: Vec = self .standing_payments(doc) @@ -8416,7 +8431,8 @@ impl Ledger { .ok_or(LedgerError::UnknownAccount(cash_account))?; self.check_controls(&PAYROLL)?; let payables = self.payroll_tax_payables(); - let total: Decimal = payables.iter().map(|(_, b)| *b).sum(); + let total = + crate::money::sum_exact_of(&payables, |(_, b)| *b, "the payroll taxes payable")?; if total.is_zero() { return Err(LedgerError::NothingToRemit); } diff --git a/crates/ledger-core/src/money.rs b/crates/ledger-core/src/money.rs index 2ed53c1c..d7578b9e 100644 --- a/crates/ledger-core/src/money.rs +++ b/crates/ledger-core/src/money.rs @@ -153,6 +153,51 @@ impl Money { } } +/// The exact sum of some figures ([`crate::kernel::total`]), or +/// `TooLargeToCompute` naming `what` when a running sum cannot be held: +/// the engine's way to total a column without a raw `.sum()` that would +/// panic at `Decimal::MAX` (rules.md B-21, B-28). +pub fn sum_exact( + values: impl IntoIterator, + what: &str, +) -> Result { + crate::kernel::total(values).ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string())) +} + +/// [`sum_exact`] over a figure drawn from each item +/// ([`crate::kernel::total_of`]). +pub fn sum_exact_of( + values: impl IntoIterator, + f: impl FnMut(I) -> Decimal, + what: &str, +) -> Result { + crate::kernel::total_of(values, f) + .ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string())) +} + +/// [`sum_exact`] over a derived figure that can itself be unrepresentable +/// ([`crate::kernel::total_try`]). +pub fn sum_exact_try( + values: impl IntoIterator, + f: impl FnMut(I) -> Option, + what: &str, +) -> Result { + crate::kernel::total_try(values, f) + .ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string())) +} + +/// `a + b` exactly, or `TooLargeToCompute` naming `what` (a checked `+`). +pub fn add_exact(a: Decimal, b: Decimal, what: &str) -> Result { + crate::kernel::Amount::checked_add(a, b) + .ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string())) +} + +/// `a - b` exactly, or `TooLargeToCompute` naming `what` (a checked `-`). +pub fn sub_exact(a: Decimal, b: Decimal, what: &str) -> Result { + crate::kernel::Amount::checked_sub(a, b) + .ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string())) +} + impl fmt::Debug for Money { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} {}", self.amount, self.currency) diff --git a/crates/ledger-core/src/payouts.rs b/crates/ledger-core/src/payouts.rs index ff91bf6c..3c9c8554 100644 --- a/crates/ledger-core/src/payouts.rs +++ b/crates/ledger-core/src/payouts.rs @@ -17,6 +17,7 @@ //! no platform: callers (or a format-specific parser) supply the numbers //! from the payout statement, which is the entry's receipt. +use crate::money::{add_exact, sub_exact, sum_exact_of}; use crate::{AccountId, AccountType, ChartOfAccounts, ClassId, LedgerError, Side}; use rust_decimal::Decimal; @@ -165,23 +166,27 @@ pub fn payout_plan( for a in &payout.adjustments { check(a.account, a.amount, "adjustment", &[])?; } - let gross: Decimal = payout.revenue.iter().map(|l| l.amount).sum(); - let fees: Decimal = payout.fees.iter().map(|l| l.amount).sum(); - let adjustments: Decimal = payout - .adjustments - .iter() - .map(|a| match a.side { + let gross = sum_exact_of(&payout.revenue, |l| l.amount, "the payout's revenue")?; + let fees = sum_exact_of(&payout.fees, |l| l.amount, "the payout's fees")?; + let adjustments = sum_exact_of( + &payout.adjustments, + |a| match a.side { Side::Credit => a.amount, Side::Debit => -a.amount, - }) - .sum(); - let expected = gross - fees + adjustments; + }, + "the payout's adjustments", + )?; + let expected = add_exact( + sub_exact(gross, fees, "the payout's total")?, + adjustments, + "the payout's total", + )?; if expected != payout.deposit { return bad(format!( "payout doesn't reconcile: gross {gross} − fees {fees} + adjustments \ {adjustments} = {expected}, but the deposit is {} (off by {})", payout.deposit, - payout.deposit - expected + sub_exact(payout.deposit, expected, "the payout's difference")? )); } let mut plan = Vec::new(); diff --git a/crates/ledger-core/src/periods.rs b/crates/ledger-core/src/periods.rs index a1f92ee7..8774c514 100644 --- a/crates/ledger-core/src/periods.rs +++ b/crates/ledger-core/src/periods.rs @@ -124,9 +124,25 @@ pub fn allocate( amount: rust_decimal::Decimal, shares: &[rust_decimal::Decimal], ) -> Vec { + try_allocate(amount, shares) + .expect("shares sum to 1, so the shortfall is under one cent per member") +} + +/// [`allocate`], refusing with `TooLargeToCompute` instead of panicking +/// when a share of `amount` is beyond exact arithmetic (a replayed close +/// carries a journaled amount of any size, rules.md B-28). The same split, +/// to the cent, for every amount [`allocate`] accepts. +pub fn try_allocate( + amount: rust_decimal::Decimal, + shares: &[rust_decimal::Decimal], +) -> Result, LedgerError> { use rust_decimal::Decimal; + let too_large = || LedgerError::TooLargeToCompute(format!("the members' shares of {amount}")); let magnitude = amount.abs(); - let exact: Vec = shares.iter().map(|s| magnitude * s).collect(); + let exact: Vec = shares + .iter() + .map(|s| magnitude.checked_mul(*s).ok_or_else(too_large)) + .collect::>()?; let mut parts: Vec = exact .iter() .map(|e| { @@ -134,15 +150,19 @@ pub fn allocate( .expect("a cent place of a representable amount is representable") }) .collect(); - let remainders: Vec = exact.iter().zip(&parts).map(|(e, p)| e - p).collect(); + let remainders: Vec = exact + .iter() + .zip(&parts) + .map(|(e, p)| e.checked_sub(*p).ok_or_else(too_large)) + .collect::>()?; crate::kernel::apportion(magnitude, &mut parts, &remainders, Decimal::new(1, 2)) - .expect("shares sum to 1, so the shortfall is under one cent per member"); + .ok_or_else(too_large)?; if amount.is_sign_negative() { for p in &mut parts { *p = -*p; } } - parts + Ok(parts) } /// The rule closes used before 2026-10-13: each share rounded half away @@ -152,16 +172,31 @@ pub fn allocate_last_absorbs( amount: rust_decimal::Decimal, shares: &[rust_decimal::Decimal], ) -> Vec { + try_allocate_last_absorbs(amount, shares).expect("allocated amounts are in range") +} + +/// [`allocate_last_absorbs`], refusing with `TooLargeToCompute` instead of +/// panicking when `amount × share` or the plug is beyond exact arithmetic +/// (replay of a legacy close with a huge journaled amount, rules.md B-28). +/// The same split, to the cent, for every amount [`allocate_last_absorbs`] +/// accepts: this is the frozen rule, only its overflow now an error. +pub fn try_allocate_last_absorbs( + amount: rust_decimal::Decimal, + shares: &[rust_decimal::Decimal], +) -> Result, LedgerError> { use crate::kernel::{Rounding, round_places}; + let too_large = || LedgerError::TooLargeToCompute(format!("the members' shares of {amount}")); let mut parts: Vec<_> = shares .iter() .map(|s| { - round_places(amount * s, 2, Rounding::HalfAwayFromZero) - .expect("a cent place of a representable amount is representable") + amount + .checked_mul(*s) + .and_then(|p| round_places(p, 2, Rounding::HalfAwayFromZero)) + .ok_or_else(too_large) }) - .collect(); - crate::kernel::plug_last(amount, &mut parts).expect("allocated amounts are in range"); - parts + .collect::>()?; + crate::kernel::plug_last(amount, &mut parts).ok_or_else(too_large)?; + Ok(parts) } /// What one members close gives each member: [`allocate`]'s split of the 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/src/reports.rs b/crates/ledger-core/src/reports.rs index 125417fb..a9605507 100644 --- a/crates/ledger-core/src/reports.rs +++ b/crates/ledger-core/src/reports.rs @@ -4,6 +4,7 @@ //! (`docs/oracle.md`) diffs: the same fixture books through two engines must //! produce byte-identical [`snapshot`] output. +use crate::money::{add_exact, sub_exact, sum_exact, sum_exact_of, sum_exact_try}; use crate::{AccountType, Class, ClassId, JournalEntry, JournalLine, Ledger, LedgerError}; use chrono::NaiveDate; use rust_decimal::Decimal; @@ -267,8 +268,8 @@ fn profit_and_loss_where( -line.amount.amount }; match account.account_type { - AccountType::Revenue => revenue += signed, - AccountType::Expense => expenses += signed, + AccountType::Revenue => revenue = add_exact(revenue, signed, "total revenue")?, + AccountType::Expense => expenses = add_exact(expenses, signed, "total expenses")?, _ => {} } } @@ -311,14 +312,16 @@ pub fn balance_sheet(ledger: &Ledger) -> Result { } let balance = ledger.account_balance(account.id)?; match account.account_type { - AccountType::Asset => assets += balance, - AccountType::Liability => liabilities += balance, - AccountType::Equity => equity += balance, + AccountType::Asset => assets = add_exact(assets, balance, "total assets")?, + AccountType::Liability => { + liabilities = add_exact(liabilities, balance, "total liabilities")? + } + AccountType::Equity => equity = add_exact(equity, balance, "total equity")?, AccountType::Revenue | AccountType::Expense => {} } } let current_earnings = unclosed_earnings(ledger)?.net_income(); - equity += current_earnings; + equity = add_exact(equity, current_earnings, "total equity")?; Ok(BalanceSheet { assets, liabilities, @@ -409,7 +412,8 @@ fn statement_lines( crate::Side::Debit => line.amount.amount, crate::Side::Credit => -line.amount.amount, }; - *movement.entry(line.account).or_default() += signed; + let slot = movement.entry(line.account).or_default(); + *slot = add_exact(*slot, signed, "an account's movement")?; } } let mut out = BTreeMap::new(); @@ -514,8 +518,8 @@ fn profit_and_loss_counted( _ => {} } } - let total_revenue = revenue.iter().map(|l| l.amount).sum(); - let total_expenses = expenses.iter().map(|l| l.amount).sum(); + let total_revenue = sum_exact_of(&revenue, |l| l.amount, "total revenue")?; + let total_expenses = sum_exact_of(&expenses, |l| l.amount, "total expenses")?; Ok(( ProfitAndLossStatement { start, @@ -820,13 +824,21 @@ pub fn balance_sheet_as_of( AccountType::Asset => assets.push(line), AccountType::Liability => liabilities.push(line), AccountType::Equity => equity.push(line), - AccountType::Revenue => current_earnings += line.amount, - AccountType::Expense => current_earnings -= line.amount, + AccountType::Revenue => { + current_earnings = add_exact(current_earnings, line.amount, "current earnings")? + } + AccountType::Expense => { + current_earnings = sub_exact(current_earnings, line.amount, "current earnings")? + } } } - let total_assets = assets.iter().map(|l| l.amount).sum(); - let total_liabilities = liabilities.iter().map(|l| l.amount).sum(); - let total_equity = equity.iter().map(|l| l.amount).sum::() + current_earnings; + let total_assets = sum_exact_of(&assets, |l| l.amount, "total assets")?; + let total_liabilities = sum_exact_of(&liabilities, |l| l.amount, "total liabilities")?; + let total_equity = add_exact( + sum_exact_of(&equity, |l| l.amount, "total equity")?, + current_earnings, + "total equity", + )?; Ok(BalanceSheetStatement { as_of, assets, @@ -949,7 +961,8 @@ pub fn general_ledger( crate::Side::Credit => -line.amount.amount, }; if entry.date() < start { - *begin.entry(line.account).or_default() += signed; + let slot = begin.entry(line.account).or_default(); + *slot = add_exact(*slot, signed, "an account's beginning balance")?; continue; } if entry.date() > end { @@ -1002,9 +1015,13 @@ pub fn general_ledger( let (mut total_debits, mut total_credits) = (Decimal::ZERO, Decimal::ZERO); let mut posted = Vec::with_capacity(lines.len()); for (side, amount, mut p) in lines { - balance += if side == normal { amount } else { -amount }; - total_debits += p.debit; - total_credits += p.credit; + balance = add_exact( + balance, + if side == normal { amount } else { -amount }, + "an account's running balance", + )?; + total_debits = add_exact(total_debits, p.debit, "an account's total debits")?; + total_credits = add_exact(total_credits, p.credit, "an account's total credits")?; p.balance = balance; posted.push(p); } @@ -1184,7 +1201,7 @@ pub fn members_equity( return Err(LedgerError::InvalidMembers("no members given".to_string())); } let shares: Vec = members.iter().map(|m| m.share).collect(); - let total_share: Decimal = shares.iter().sum(); + let total_share = sum_exact(shares.iter().copied(), "the members' shares")?; if total_share != Decimal::ONE || shares.iter().any(|s| *s <= Decimal::ZERO) { return Err(LedgerError::InvalidMembers(format!( "member shares must be positive and sum to 1, got {total_share}" @@ -1214,23 +1231,23 @@ pub fn members_equity( let end_bs = balance_sheet_as_of(ledger, end)?; // Capital account balances before the period, and their movement in it. - let capital_before = |id: crate::AccountId| -> Decimal { + let capital_before = |id: crate::AccountId| -> Result { let mut m = Decimal::ZERO; for e in ledger.posted_entries().filter(|e| e.date() < start) { for l in e.lines().iter().filter(|l| l.account == id) { - match l.side { - crate::Side::Credit => m += l.amount.amount, - crate::Side::Debit => m -= l.amount.amount, - } + m = match l.side { + crate::Side::Credit => add_exact(m, l.amount.amount, "a member's capital")?, + crate::Side::Debit => sub_exact(m, l.amount.amount, "a member's capital")?, + }; } } - m + Ok(m) }; // Contributions and distributions move a capital account; a closing // entry allocating earnings into it is income, already counted below. let closings = ledger.closing_entry_ids(); let cancelled = cancelled_in_span(ledger, start, end); - let flows = |id: crate::AccountId| -> (Decimal, Decimal) { + let flows = |id: crate::AccountId| -> Result<(Decimal, Decimal), LedgerError> { let (mut credits, mut debits) = (Decimal::ZERO, Decimal::ZERO); for e in ledger.posted_entries().filter(|e| { e.date() >= start @@ -1240,35 +1257,48 @@ pub fn members_equity( }) { for l in e.lines().iter().filter(|l| l.account == id) { match l.side { - crate::Side::Credit => credits += l.amount.amount, - crate::Side::Debit => debits += l.amount.amount, + crate::Side::Credit => { + credits = add_exact(credits, l.amount.amount, "a member's contributions")? + } + crate::Side::Debit => { + debits = add_exact(debits, l.amount.amount, "a member's distributions")? + } } } } - (credits, debits) + Ok((credits, debits)) }; // A member's capital is their capital account plus their distributions // account (a debit balance, so it reduces capital). let capital: Vec = members .iter() .map(|m| { - capital_before(m.capital_account) - + m.distribution_account.map_or(Decimal::ZERO, capital_before) + add_exact( + capital_before(m.capital_account)?, + m.distribution_account + .map_or(Ok(Decimal::ZERO), capital_before)?, + "a member's capital", + ) }) - .collect(); + .collect::>()?; // (contributions, distributions): credits to capital are // contributions; debits to capital and net debits to the distributions // account are distributions. let flow: Vec<(Decimal, Decimal)> = members .iter() .map(|m| { - let (credits, debits) = flows(m.capital_account); + let (credits, debits) = flows(m.capital_account)?; let (dc, dd) = m .distribution_account - .map_or((Decimal::ZERO, Decimal::ZERO), flows); - (credits, debits + dd - dc) + .map_or(Ok((Decimal::ZERO, Decimal::ZERO)), flows)?; + let distributions = sub_exact( + add_exact(debits, dd, "a member's distributions")?, + dc, + "a member's distributions", + )?; + Ok((credits, distributions)) }) - .collect(); + .collect::>()?; // Everything in equity that isn't a capital account is partnership // earnings not yet distributed. Each member's share of it is allocated @@ -1276,26 +1306,30 @@ pub fn members_equity( // depends on which statement shows it: one statement's ending is the // next one's beginning, to the minor unit (a capital account is one // running balance: Treas. Reg. §1.704-1(b)(2)(iv)(b)). - let capital_through = |id: crate::AccountId, through: NaiveDate| -> Decimal { - let mut m = Decimal::ZERO; - for e in ledger.posted_entries().filter(|e| e.date() <= through) { - for l in e.lines().iter().filter(|l| l.account == id) { - match l.side { - crate::Side::Credit => m += l.amount.amount, - crate::Side::Debit => m -= l.amount.amount, + let capital_through = + |id: crate::AccountId, through: NaiveDate| -> Result { + let mut m = Decimal::ZERO; + for e in ledger.posted_entries().filter(|e| e.date() <= through) { + for l in e.lines().iter().filter(|l| l.account == id) { + m = match l.side { + crate::Side::Credit => add_exact(m, l.amount.amount, "a member's capital")?, + crate::Side::Debit => sub_exact(m, l.amount.amount, "a member's capital")?, + }; } } - } - m - }; + Ok(m) + }; let capital_end: Vec = members .iter() .map(|m| { - capital_through(m.capital_account, end) - + m.distribution_account - .map_or(Decimal::ZERO, |d| capital_through(d, end)) + add_exact( + capital_through(m.capital_account, end)?, + m.distribution_account + .map_or(Ok(Decimal::ZERO), |d| capital_through(d, end))?, + "a member's capital", + ) }) - .collect(); + .collect::>()?; // As of a date, a member's share of the earnings not yet in capital is // what the next members close would give them of it: their split of // everything closed to these members and shares (the regime's closes @@ -1313,38 +1347,76 @@ pub fn members_equity( let nothing = vec![Decimal::ZERO; members.len()]; let unclosed_share = |undistributed: Decimal, regime: &crate::ledger::Regime| { let closed = regime.allocate(&key, regime.closed, ¬hing, places)?; - regime.allocate(&key, regime.closed + undistributed, &closed, places) + let whole = add_exact(regime.closed, undistributed, "the members' closed earnings")?; + regime.allocate(&key, whole, &closed, places) }; let end_regime = ledger.members_regime(&key, Some(end)); let begin_alloc = unclosed_share( - begin_bs.total_equity - capital.iter().sum::(), + sub_exact( + begin_bs.total_equity, + sum_exact(capital.iter().copied(), "the members' capital")?, + "the members' undistributed earnings", + )?, &ledger.members_regime(&key, Some(day_before)), )?; let end_alloc = unclosed_share( - end_bs.total_equity - capital_end.iter().sum::(), + sub_exact( + end_bs.total_equity, + sum_exact(capital_end.iter().copied(), "the members' capital")?, + "the members' undistributed earnings", + )?, &end_regime, )?; - let explained = flow.iter().map(|(c, d)| c - d).sum::() + pnl.net_income(); + let explained = add_exact( + sum_exact_try( + flow.iter(), + |&(c, d)| crate::kernel::Amount::checked_sub(c, d), + "the members' net contributions", + )?, + pnl.net_income(), + "the period's explained equity", + )?; // "Other" is split anew on each statement, its tied unit to the member // the count as of `end` lists first, as the ending's are: a reorder of // the members in the settings moves no cent between their other (and // so their income) either. let other_alloc = end_regime.allocate( &key, - end_bs.total_equity - begin_bs.total_equity - explained, + sub_exact( + sub_exact( + end_bs.total_equity, + begin_bs.total_equity, + "the change in equity", + )?, + explained, + "the change in equity", + )?, ¬hing, places, )?; let mut cols = Vec::with_capacity(members.len()); for (i, m) in members.iter().enumerate() { - let beginning = capital[i] + begin_alloc[i]; - let ending = capital_end[i] + end_alloc[i]; + let beginning = add_exact(capital[i], begin_alloc[i], "a member's beginning capital")?; + let ending = add_exact(capital_end[i], end_alloc[i], "a member's ending capital")?; let (contributions, distributions) = flow[i]; // The member's income is what the roll-forward leaves: their share // of the period's income, give or take the rounding cent that keeps // the running balance exact. The members' incomes sum to net income. - let income = ending - beginning - contributions + distributions - other_alloc[i]; + let too_large = "a member's income"; + let income = sub_exact( + add_exact( + sub_exact( + sub_exact(ending, beginning, too_large)?, + contributions, + too_large, + )?, + distributions, + too_large, + )?, + other_alloc[i], + too_large, + )?; cols.push(MemberEquityColumn { name: m.name.clone(), beginning: zero_clean(beginning), @@ -1355,15 +1427,17 @@ pub fn members_equity( ending: zero_clean(ending), }); } - let sum = |f: fn(&MemberEquityColumn) -> Decimal| cols.iter().map(f).sum::(); + let sum = |f: fn(&MemberEquityColumn) -> Decimal| { + sum_exact_of(&cols, f, "the members' equity totals") + }; let total = MemberEquityColumn { name: "Total".to_string(), - beginning: sum(|c| c.beginning), - contributions: sum(|c| c.contributions), - net_income: sum(|c| c.net_income), - distributions: sum(|c| c.distributions), - other: sum(|c| c.other), - ending: sum(|c| c.ending), + beginning: sum(|c| c.beginning)?, + contributions: sum(|c| c.contributions)?, + net_income: sum(|c| c.net_income)?, + distributions: sum(|c| c.distributions)?, + other: sum(|c| c.other)?, + ending: sum(|c| c.ending)?, }; debug_assert_eq!(total.ending, end_bs.total_equity); Ok(MembersEquityStatement { @@ -1724,7 +1798,11 @@ pub fn fixed_asset_register( total_depreciable_basis: depreciable_total, total_tax_basis_723: total_723, missing_basis: missing, - ledger_cost: cost_accounts.iter().map(|&id| net(id)).sum(), - ledger_accumulated: -accum_accounts.iter().map(|&id| net(id)).sum::(), + ledger_cost: sum_exact_of(&cost_accounts, |&id| net(id), "the ledger's asset cost")?, + ledger_accumulated: -sum_exact_of( + &accum_accounts, + |&id| net(id), + "the ledger's accumulated depreciation", + )?, }) } diff --git a/crates/ledger-core/src/tax_capital.rs b/crates/ledger-core/src/tax_capital.rs index b934c25e..fc9f9fcd 100644 --- a/crates/ledger-core/src/tax_capital.rs +++ b/crates/ledger-core/src/tax_capital.rs @@ -79,6 +79,7 @@ //! ``` use crate::k1::{K1Kind, K1Row, k1_detail}; +use crate::money::sum_exact_of; use crate::reports::MemberCapital; use crate::{AccountId, AssetId, AssetStatus, EntryId, Ledger, LedgerError, Side}; use chrono::NaiveDate; @@ -586,19 +587,19 @@ fn entry_wholes( n: usize, cash: &[AccountId], ) -> Result, LedgerError> { - let by_member = |kind| -> Vec { + let by_member = |kind| -> Result, LedgerError> { (0..n) .map(|i| { - lines - .iter() - .filter(|l| l.member == i && l.kind == kind) - .map(|l| l.amount) - .sum() + sum_exact_of( + lines.iter().filter(|l| l.member == i && l.kind == kind), + |l| l.amount, + "a member's K-1 lines", + ) }) .collect() }; let mut out = Vec::new(); - let takes = by_member(K1Kind::PropertyContribution); + let takes = by_member(K1Kind::PropertyContribution)?; if takes.iter().any(|t| !t.is_zero()) { let p = entry_property(ledger, e, cash)?; out.push((BUILT_IN_GAIN, p.built_in_gain, takes.clone())); @@ -606,7 +607,7 @@ fn entry_wholes( out.push((PREPAID, p.prepaid, takes)); } // Distributions are negative lines; weights are what each took. - let taken: Vec = by_member(K1Kind::Distribution) + let taken: Vec = by_member(K1Kind::Distribution)? .into_iter() .map(|d| -d) .collect(); @@ -757,7 +758,7 @@ fn entry_property( }) .try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount)) .ok_or_else(too_large)?; - let pool = pool - prepaid; + let pool = pool.checked_sub(prepaid).ok_or_else(too_large)?; let (mut linked, mut big, mut unknown) = (Decimal::ZERO, Decimal::ZERO, Decimal::ZERO); for a in ledger .registered_assets() @@ -783,7 +784,7 @@ fn entry_property( mismatch: Some((linked, pool)), }); } - let rest = pool - linked; + let rest = pool.checked_sub(linked).ok_or_else(too_large)?; Ok(EntryProperty { built_in_gain: big, prepaid, @@ -818,21 +819,23 @@ fn span( } for id in entries { let e = ledger.get_entry(id).ok_or(LedgerError::UnknownEntry(id))?; - let lines = |kind| -> Vec { + let lines = |kind| -> Result, LedgerError> { (0..n) .map(|i| { - detail - .lines - .iter() - .filter(|l| l.entry == id && l.member == i && l.kind == kind) - .map(|l| l.amount) - .sum() + sum_exact_of( + detail + .lines + .iter() + .filter(|l| l.entry == id && l.member == i && l.kind == kind), + |l| l.amount, + "a member's K-1 lines", + ) }) .collect() }; let none = EntryParts::default(); let part = parts.get(&id).unwrap_or(&none); - let takes = lines(K1Kind::PropertyContribution); + let takes = lines(K1Kind::PropertyContribution)?; if takes.iter().any(|t| !t.is_zero()) { let p = entry_property(ledger, e, cash)?; // Only the members with property in the entry have a part of diff --git a/crates/ledger-core/tests/exact_totals.rs b/crates/ledger-core/tests/exact_totals.rs new file mode 100644 index 00000000..92d16229 --- /dev/null +++ b/crates/ledger-core/tests/exact_totals.rs @@ -0,0 +1,104 @@ +//! Totals past exact arithmetic are refused, never a panic (kernel sweep +//! unit K-U4; rules.md B-21, B-28). +//! +//! A replayed journal line is accepted "of any size", so a restored +//! figure can sit at `Decimal::MAX`; every sum the engine makes of such +//! figures must return `TooLargeToCompute` (or skip a check), where a raw +//! `+` / `.sum()` used to crash the process. Each test names the site it +//! guards; before this unit each of them panicked. + +use ledger_core::arap::{DocumentLine, document_total}; +use ledger_core::audit::check_articulation; +use ledger_core::money::{add_exact, sub_exact, sum_exact, sum_exact_of, sum_exact_try}; +use ledger_core::periods::{ + allocate, allocate_last_absorbs, try_allocate, try_allocate_last_absorbs, +}; +use ledger_core::{LedgerError, kernel}; +use rust_decimal::Decimal; + +fn too_large(r: Result) { + assert!( + matches!(r, Err(LedgerError::TooLargeToCompute(_))), + "expected TooLargeToCompute, got {r:?}" + ); +} + +fn dec(s: &str) -> Decimal { + s.parse().unwrap() +} + +#[test] +fn the_engine_sums_refuse_at_the_edge() { + let max = Decimal::MAX; + too_large(sum_exact([max, Decimal::ONE], "a column")); + too_large(sum_exact_of([max, max], |x| x, "a column")); + too_large(sum_exact_try([(max, -max)], |_| None, "a column")); + too_large(add_exact(max, Decimal::ONE, "a balance")); + too_large(sub_exact(-max, Decimal::ONE, "a balance")); + // And the ordinary case is exact. + assert_eq!( + sum_exact([dec("1.10"), dec("2.20"), dec("-3.30")], "a column").unwrap(), + Decimal::ZERO + ); + assert_eq!( + add_exact(dec("0.10"), dec("0.20"), "x").unwrap(), + dec("0.30") + ); +} + +/// arap::document_total (store: create_invoice / create_bill). +#[test] +fn a_documents_lines_past_exact_arithmetic_are_refused() { + let line = |amount| DocumentLine { + description: "x".into(), + amount, + class_id: None, + account: None, + quantity: None, + unit_price: None, + }; + let big = [line(Decimal::MAX), line(Decimal::ONE)]; + too_large(document_total(&big, "the invoice")); + let ok = [line(dec("10.00")), line(dec("5.25"))]; + assert_eq!(document_total(&ok, "the invoice").unwrap(), dec("15.25")); +} + +/// audit::check_articulation (current_earnings + closed was a raw +). +#[test] +fn the_articulation_check_skips_what_it_cannot_compute() { + assert!(check_articulation(Decimal::MAX, Decimal::MAX, Decimal::MAX).is_none()); + // An ordinary mismatch is still reported, and a match is not. + assert!(check_articulation(dec("10"), dec("4"), dec("5")).is_some()); + assert!(check_articulation(dec("10"), dec("4"), dec("6")).is_none()); +} + +/// periods::allocate / allocate_last_absorbs (amount * share was raw: a +/// replayed close with a huge journaled amount). The frozen rules' +/// results do not move; only the overflow is an error. +#[test] +fn the_frozen_close_splits_refuse_instead_of_panicking() { + let two = Decimal::from(2); + too_large(try_allocate(Decimal::MAX, &[two])); + too_large(try_allocate_last_absorbs(Decimal::MAX, &[two])); + too_large(try_allocate(-Decimal::MAX, &[two])); + + // The same split as the infallible rule for ordinary inputs. + for amount in ["100.00", "0.07", "-33.33", "0.01", "1234567.89"] { + let shares = [dec("0.5"), dec("0.3"), dec("0.2")]; + let a = dec(amount); + assert_eq!(try_allocate(a, &shares).unwrap(), allocate(a, &shares)); + assert_eq!( + try_allocate_last_absorbs(a, &shares).unwrap(), + allocate_last_absorbs(a, &shares) + ); + } +} + +/// The kernel total over the line cap's edge: ten of the largest allowed +/// line sum exactly (no refusal where the cap says it must work). +#[test] +fn lines_at_the_cap_still_sum_exactly() { + let cap = kernel::MAX_LINE_AMOUNT; + let ten = kernel::total(std::iter::repeat_n(cap, 10)).unwrap(); + assert_eq!(ten, cap * Decimal::from(10)); +} diff --git a/crates/ledger-core/tests/kernel_bridge/total.rs b/crates/ledger-core/tests/kernel_bridge/total.rs index 19ddb333..e8a35880 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], Decimal::from), + 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); +} diff --git a/crates/ledger-gui/src/pages/cash.rs b/crates/ledger-gui/src/pages/cash.rs index 2a020532..108beb0f 100644 --- a/crates/ledger-gui/src/pages/cash.rs +++ b/crates/ledger-gui/src/pages/cash.rs @@ -181,8 +181,15 @@ fn runway(ui: &mut Ui, b: &Books) { ui.label(RichText::new("Needs at least one full month of books.").color(p.muted)); return; } - let net: Decimal = months.iter().map(|(_, _, i, o)| i - o).sum::() - / Decimal::from(months.len() as u64); + // Exact or refused: books near the arithmetic's limit show a + // note, never a crash (rules.md B-28). + let Some(net) = ledger_core::kernel::total_try(&months, |&(_, _, i, o)| { + ledger_core::kernel::Amount::checked_sub(i, o) + }) + .and_then(|sum| sum.checked_div(Decimal::from(months.len() as u64))) else { + ui.label(RichText::new("The figures are too large to compute.").color(p.muted)); + return; + }; let net = net.round_dp(2); let big = |ui: &mut Ui, label: &str, value: String, color| { ui.vertical(|ui| { diff --git a/crates/ledger-mcp/src/server.rs b/crates/ledger-mcp/src/server.rs index b250a400..42e7333f 100644 --- a/crates/ledger-mcp/src/server.rs +++ b/crates/ledger-mcp/src/server.rs @@ -1348,7 +1348,9 @@ fn preview_lines_for( } else { -amount.amount }; - let after = before + delta; + let after = + ledger_core::money::add_exact(before, delta, "the account's balance after the line") + .map_err(|e| e.to_string())?; out.push(PreviewLine { account_id: *account_id, code: account.code.clone(), diff --git a/crates/ledger-mcp/src/tools/assets.rs b/crates/ledger-mcp/src/tools/assets.rs index 4d11d13f..3278aec0 100644 --- a/crates/ledger-mcp/src/tools/assets.rs +++ b/crates/ledger-mcp/src/tools/assets.rs @@ -839,7 +839,15 @@ impl BooksServer { description, period: r.period, amount: money(r.amount), - caught_up: money((r.amount - r.scheduled).max(Decimal::ZERO)), + caught_up: money( + ledger_core::money::sub_exact( + r.amount, + r.scheduled, + "the catch-up depreciation", + ) + .map_err(|e| e.to_string())? + .max(Decimal::ZERO), + ), entry_id, already_posted: r.already_posted, }); @@ -916,14 +924,20 @@ impl BooksServer { .map(code_of) .collect::>()?; let code_refs: Vec<&str> = codes.iter().map(|s| s.as_str()).collect(); - let debits = preview.accumulated - + proceeds.amount - + preview.catch_up_depreciation - + if preview.gain_loss < Decimal::ZERO { - -preview.gain_loss - } else { - Decimal::ZERO - }; + let debits = ledger_core::money::sum_exact( + [ + preview.accumulated, + proceeds.amount, + preview.catch_up_depreciation, + if preview.gain_loss < Decimal::ZERO { + -preview.gain_loss + } else { + Decimal::ZERO + }, + ], + "the disposal's debits", + ) + .map_err(|e| e.to_string())?; let receipt_required = self .settings() .policy diff --git a/crates/ledger-mcp/src/tools/payroll.rs b/crates/ledger-mcp/src/tools/payroll.rs index b8aa7ae9..2155b8c1 100644 --- a/crates/ledger-mcp/src/tools/payroll.rs +++ b/crates/ledger-mcp/src/tools/payroll.rs @@ -114,12 +114,12 @@ impl BooksServer { return Err(party_required("pass agency: the tax agency paid")); } // Total before remitting, for the response. - let total: Decimal = store - .ledger() - .payroll_tax_payables() - .iter() - .map(|(_, b)| *b) - .sum(); + let total = ledger_core::money::sum_exact_of( + store.ledger().payroll_tax_payables(), + |(_, b)| b, + "the payroll taxes payable", + ) + .map_err(|e| e.to_string())?; let entry_id = store .remit_payroll_taxes(parse_date(&p.date)?, cash) .map_err(|e| e.to_string())?; diff --git a/crates/ledger-mcp/src/tools/reports.rs b/crates/ledger-mcp/src/tools/reports.rs index 38dbbbdf..e4e975b4 100644 --- a/crates/ledger-mcp/src/tools/reports.rs +++ b/crates/ledger-mcp/src/tools/reports.rs @@ -31,21 +31,24 @@ fn movement_over( ledger: &Ledger, account: AccountId, entries: &[&ledger_core::JournalEntry], -) -> Decimal { - let movement: Decimal = entries - .iter() - .flat_map(|e| e.lines()) - .filter(|l| l.account == account) - .map(|l| match l.side { +) -> Result { + let movement = ledger_core::money::sum_exact_of( + entries + .iter() + .flat_map(|e| e.lines()) + .filter(|l| l.account == account), + |l| match l.side { Side::Debit => l.amount.amount, Side::Credit => -l.amount.amount, - }) - .sum(); + }, + "an account's movement", + ) + .map_err(|e| e.to_string())?; let account = ledger.chart().get(account).expect("account exists"); - match account.account_type.normal_side() { + Ok(match account.account_type.normal_side() { Side::Debit => movement, Side::Credit => -movement, - } + }) } fn lines_out(lines: &[ledger_core::StatementLine]) -> Vec { @@ -835,7 +838,7 @@ impl BooksServer { if a.placeholder { continue; } - let m = movement_over(ledger, a.id, &in_range); + let m = movement_over(ledger, a.id, &in_range)?; if !m.is_zero() { totals.push(DigestTotal { code: a.code.clone(), diff --git a/crates/ledger-package/src/package.rs b/crates/ledger-package/src/package.rs index 2ec0ea60..dd0505a7 100644 --- a/crates/ledger-package/src/package.rs +++ b/crates/ledger-package/src/package.rs @@ -64,7 +64,7 @@ use crate::reports::{ Settings, bs_statement, cash_flow_for, member_capitals, pnl_statement, report_members, report_meta, year_earnings, }; -use crate::text::{csv_escape, money, share_text}; +use crate::text::{csv_escape, money, share_text, total_text}; use crate::tins::{TinSource, tin_type_key}; use crate::vendor_1099::{vendor_1099_csv, vendor_1099_csv_name, vendor_1099_worksheet}; @@ -292,13 +292,13 @@ pub fn build_package( // a K-1 (each member gets their own). if rows.len() > 1 { let sum = |f: fn(&ledger_core::k1::K1Row) -> Decimal| { - rows.iter().map(f).sum::() + ledger_core::kernel::total_of(&rows, f) }; - let share: Decimal = company.members.iter().map(|m| m.share).sum(); + let share = ledger_core::kernel::total_of(&company.members, |m| m.share); let mut cells = vec![ csv_escape("Total, all members (not a K-1)"), String::new(), - share_text(share), + share.map_or_else(|| total_text(None), share_text), String::new(), String::new(), String::new(), @@ -315,7 +315,7 @@ pub fn build_package( sum(|r| r.other), sum(|r| r.ending), ] { - cells.push(money(v)); + cells.push(total_text(v)); } w.push_str(&cells.join(",")); w.push('\n'); @@ -530,18 +530,16 @@ pub fn build_package( e.id(), clean(&a.file_name) )); - let amount: Decimal = e - .lines() - .iter() - .filter(|l| l.side == Side::Debit) - .map(|l| l.amount.amount) - .sum(); + let amount = ledger_core::kernel::total_of( + e.lines().iter().filter(|l| l.side == Side::Debit), + |l| l.amount.amount, + ); index.push_str(&format!( "{},{},\"{}\",{},{},{}\n", e.id(), e.date(), e.description().replace('"', "\"\""), - money(amount), + total_text(amount), name, a.blob_sha )); diff --git a/crates/ledger-package/src/text.rs b/crates/ledger-package/src/text.rs index 0ac8b287..55dc48a0 100644 --- a/crates/ledger-package/src/text.rs +++ b/crates/ledger-package/src/text.rs @@ -29,6 +29,13 @@ pub fn money(n: Decimal) -> String { n.to_string() } +/// A total as [`money`] prints it, or "too large to compute" when the sum +/// of its figures was past exact arithmetic (`kernel::total` gave `None`): +/// a printed total is exact or says so, and never crashes the export. +pub fn total_text(total: Option) -> String { + total.map_or_else(|| "too large to compute".to_string(), money) +} + /// A member's share as the K-1 worksheet prints it: at least two places, /// however it was written ("50%", "0.5" and "0.500" all print "0.50"; a /// share of a third keeps its places). The printed text depends on the diff --git a/crates/ledger-package/src/vendor_1099.rs b/crates/ledger-package/src/vendor_1099.rs index d40bae55..4b1b3414 100644 --- a/crates/ledger-package/src/vendor_1099.rs +++ b/crates/ledger-package/src/vendor_1099.rs @@ -34,7 +34,7 @@ use ledger_core::{Decision1099, EntryId, Ledger, PartyId, Payment1099, Status109 use rust_decimal::Decimal; use crate::reports::Settings; -use crate::text::{csv_escape, money}; +use crate::text::{csv_escape, money, total_text}; use crate::tins::{TinSource, tin_type_key}; /// Where payments to vendors come from, for the 1099 worksheet: the @@ -193,12 +193,12 @@ fn entries_text(ids: &[EntryId]) -> String { /// "1 payment" or "3 payments", with their total. fn payments_text(list: &[Payment1099]) -> String { - let total: Decimal = list.iter().map(|p| p.amount).sum(); + let total = ledger_core::kernel::total_of(list, |p| p.amount); let n = list.len(); format!( "{n} payment{} totaling {}", if n == 1 { "" } else { "s" }, - money(total) + total_text(total) ) } diff --git a/crates/ledger-store/src/store.rs b/crates/ledger-store/src/store.rs index 12d1a30a..d278ca95 100644 --- a/crates/ledger-store/src/store.rs +++ b/crates/ledger-store/src/store.rs @@ -2566,12 +2566,13 @@ impl Store { Some((e, d, if i % 2 == 0 { amount } else { -amount })) }) .collect(); - let at_disposal: Decimal = dated - .iter() - .filter(|(_, d, _)| *d <= month_end) - .map(|(_, _, a)| *a) - .sum(); - let in_the_end: Decimal = dated.iter().map(|(_, _, a)| *a).sum(); + let what = format!("{period}'s depreciation run"); + let at_disposal = ledger_core::money::sum_exact_of( + dated.iter().filter(|(_, d, _)| *d <= month_end), + |(_, _, a)| *a, + &what, + )?; + let in_the_end = ledger_core::money::sum_exact_of(&dated, |(_, _, a)| *a, &what)?; if at_disposal != in_the_end { // The entries the difference is in: those dated after the // month (or the run itself, dated after a reversal of it). @@ -3446,7 +3447,7 @@ impl Store { let ar = self.ensure_control_account(&ledger_core::RECEIVABLES)?; let revenue = self.ensure_control_account(&ledger_core::REVENUE)?; let invoice_id = self.ledger.next_invoice_id(); - let total: Decimal = lines.iter().map(|l| l.amount).sum(); + let total = arap::document_total(lines, "the invoice")?; let description = format!("Invoice {invoice_id}"); let mut posting = vec![(ar, Side::Debit, total, None)]; posting.extend(arap::document_parts(lines, "the invoice")?.into_iter().map( @@ -3741,7 +3742,7 @@ impl Store { let expense = self.ensure_control_account(&ledger_core::GENERAL_EXPENSES)?; let ap = self.ensure_control_account(&ledger_core::PAYABLES)?; let bill_id = self.ledger.next_bill_id(); - let total: Decimal = lines.iter().map(|l| l.amount).sum(); + let total = arap::document_total(lines, "the bill")?; let description = format!("Bill {bill_id}"); let mut posting: Vec<_> = arap::document_parts(lines, "the bill")? .into_iter() @@ -4449,7 +4450,8 @@ impl Store { return Err(LedgerError::UnknownAccount(cash_account).into()); } let payables = self.ledger.payroll_tax_payables(); - let total: Decimal = payables.iter().map(|(_, b)| *b).sum(); + let total = + ledger_core::money::sum_exact_of(&payables, |(_, b)| *b, "the payroll taxes payable")?; if total.is_zero() { return Err(LedgerError::NothingToRemit.into()); } @@ -4496,11 +4498,11 @@ impl Store { )?); // Name the entry as a remittance, as payroll.run names a run's // (readers like the viewer tell it from a hand-made entry by this). - let total: Decimal = plan - .iter() - .filter(|(_, s, _)| *s == Side::Debit) - .map(|(_, _, m)| m.amount) - .sum(); + let total = ledger_core::money::sum_exact_of( + plan.iter().filter(|(_, s, _)| *s == Side::Debit), + |(_, _, m)| m.amount, + "the payroll tax remittance", + )?; journaled.push(self.append_journal( "payroll.taxes_remitted", json!({"entry_id": entry_id, "date": date.to_string(), "total": total.to_string()}), diff --git a/crates/ledger-store/tests/exact_totals.rs b/crates/ledger-store/tests/exact_totals.rs new file mode 100644 index 00000000..a607e28e --- /dev/null +++ b/crates/ledger-store/tests/exact_totals.rs @@ -0,0 +1,71 @@ +//! Documents whose lines' sum is past exact arithmetic are refused, never a +//! panic (kernel sweep unit K-U4; rules.md B-21, B-28). +//! +//! A posted entry's lines are bounded by the line cap at the moment it +//! posts, restored or new (`entry.posted` validates), so a report's sums +//! over posted lines cannot reach the edge; a document's lines are the +//! figures that can be restored "of any size", and are what this guards. +//! +//! ```text +//! GOAL: a document whose lines sum past exact arithmetic is refused with +//! a ledger error and journals nothing. +//! SOURCE: docs/spec/rules.md B-28 (a replayed line is accepted of any +//! size), B-21 (amounts are exact); bookspec BS-entry-3, +//! BS-entry-4. +//! ``` + +use chrono::NaiveDate; +use ledger_core::Currency; +use ledger_core::arap::DocumentLine; +use ledger_store::{Store, StoreError}; +use rust_decimal::Decimal; +use std::path::PathBuf; + +struct TestDir(PathBuf); + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn test_dir(name: &str) -> TestDir { + let dir = std::env::temp_dir().join(format!( + "wanderbooks-store-exact-totals-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + TestDir(dir) +} + +fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() +} + +/// Store::create_invoice / create_bill: lines whose sum is past exact +/// arithmetic are refused (the raw .sum() ran before the checked +/// document_total), and the books are untouched. +#[test] +fn a_document_of_enormous_lines_is_refused_not_a_panic() { + let dir = test_dir("documents"); + let mut s = Store::create(&dir.0, Currency::USD).unwrap(); + let customer = s.add_customer("Cedar").unwrap(); + let vendor = s.add_vendor("Pine").unwrap(); + let line = |amount: Decimal| DocumentLine { + description: "x".into(), + amount, + class_id: None, + account: None, + quantity: None, + unit_price: None, + }; + let lines = || vec![line(Decimal::MAX), line(Decimal::MAX)]; + let before = std::fs::read_to_string(dir.0.join(ledger_store::JOURNAL_FILE)).unwrap(); + let invoice = s.create_invoice(customer, d(2026, 1, 2), d(2026, 2, 1), lines()); + assert!(matches!(invoice, Err(StoreError::Ledger(_))), "{invoice:?}"); + let bill = s.create_bill(vendor, d(2026, 1, 2), d(2026, 2, 1), lines()); + assert!(matches!(bill, Err(StoreError::Ledger(_))), "{bill:?}"); + let after = std::fs::read_to_string(dir.0.join(ledger_store::JOURNAL_FILE)).unwrap(); + assert_eq!(before, after, "a refused document journals nothing"); +} diff --git a/docs/proofs/k-u4.md b/docs/proofs/k-u4.md new file mode 100644 index 00000000..6f15a41c --- /dev/null +++ b/docs/proofs/k-u4.md @@ -0,0 +1,190 @@ +# K-U4: collection totals (`kernel/total.rs`) + +Kernel sweep unit U4 (`plan/kernel-sweep-audit.md` sections 2 and 3). The +authority is rules.md B-21 (amounts are exact; rounding only on returns) and +B-28 (no input may reach a panic), bookspec `BS-entry-3` and `BS-entry-4`. + +## The functions + +| Function | Meaning | +|---|---| +| `kernel::total(values)` | exact sum of any figures; `None` the moment a running sum is not representable | +| `kernel::total_of(items, f)` | `total` of `f(item)`: the shape of `iter().map(f).sum()` | +| `kernel::total_try(items, f)` | like `total_of` for a mapping that can itself fail (`c - d`) | + +The signed sum of `(Side, amount)` lines is **not** new: it is +`kernel::net` (and `kernel::totals` for the two columns), which stay the one +copy of that shape. The audit's proposed `signed_total` is exactly `net`; +none was added. The engine-side wrappers (`money::sum_exact`, +`sum_exact_of`, `sum_exact_try`, `add_exact`, `sub_exact`) only map `None` +to `LedgerError::TooLargeToCompute`; they call the kernel and add no +arithmetic. + +## Kani harnesses (`src/proofs/total.rs`) + +All on `i64`, fixed arrays (no symbolic-length `Vec`, no `copy_from_slice`, +model-checking/kani#4904), each with `kani::cover!`. + +| Harness | Law | Bounds | Time | +|---|---|---|---| +| `total_empty_is_zero` | `total([])`, `total_of([])`, `total_try([])` are `Some(0)` | none | 0.1 s | +| `total_append` | `total(a ++ b) = total(a) + total(b)`, all `Some`, for in-range runs | two runs of 0..=3 amounts, each at most 2^40 | 60 s | +| `total_is_sound` | `Some(s)` means `s` is the true sum, for **any** `i64` figures (edge included) | 0..=4 arbitrary `i64` | 1.9 s | +| `total_of_is_map_sum` | `total_of` with the signed amount as the map is the signed sum, and equals `net` | 0..=4 lines, in-range | 7.4 s | +| `total_try_is_map_sum` | `total_try` of differences is the sum of the differences; a failing map fails the total | 0..=4 pairs, in-range | 5.3 s | +| `total_overflow_is_none` | for two arbitrary `i64`s, `total` is `Some` exactly when the true sum fits; both overflow directions covered | all `i64` pairs | 0.5 s | + +Times: alone, `cargo kani --exact --harness`, the shared dev machine under +`nice -n 10`, 2026-11-08. `total_append` was 115 s at runs of up to 4 and +was reduced to up to 3 (the same law; 60 s) to keep `just prove` fast. A +version with one array split at a symbolic point (`split_at`) did not +finish in 10 minutes and was dropped. + +Why the bounds are enough: the law is about appending, so zero, one and +several figures on each side exercise every shape; `total_is_sound` covers +the overflow edge with unconstrained `i64`s. Beyond the bounds the Lean +statement carries it for any length (below). + +## Order dependence at the edge + +`total` is a left-to-right checked fold: every running sum must be +representable. So `total([MAX, 1, -1])` is `None` while +`total([MAX, -1, 1])` is `Some(MAX)`. `total_append` is stated for runs that +never leave the range (always true for line-capped amounts); `total_is_sound` +is the unconditional statement (a `Some` is never wrong). The bridge edge +table pins both orders. + +## Lean + +No new law (the audit said so; confirmed against +`~/Code/bookspec/lean/Bookspec/Basic.lean`, which `verify/lean`'s `Basic` +mirrors): + +- `Basic.net_append` (`net (xs ++ ys) = net xs + net ys`) is the direct + counterpart of `total_append` for the signed sum, i.e. `total_of` with the + line's signed amount; `net_cons`/`net_nil` give the empty case. +- `Basic.sumOver_add`, `sumOver_neg`, `sumOver_zero` cover sums of a mapped + field. There is no `sumOver_append` over index lists; for a plain list of + integers the statement is core Lean's `List.sum_append`. If an explicit + named theorem is wanted it is a three-line induction like `net_append`; + I did not write Lean in this unit. +- Overflow (`None`) has no Lean counterpart: Lean's `Int` is unbounded. + That half is carried by `total_overflow_is_none`, `total_is_sound` and the + bridge edge table. + +## Bridge (`tests/kernel_bridge/total.rs`) + +- `total_agrees`, `total_of_agrees`, `total_try_agrees`, + `total_append_agrees`: i64 vs `Decimal` on random runs (2,000 cases each). +- `decimal_edge_table`: empty, `Decimal::MAX`/`MIN` alone, one unit past + either edge (`None`), `MAX + MAX`, `MAX + MIN` and `MAX + -MAX` cancel + exactly, mixed signs cancelling in the middle, the order-dependent edge, + `total_of`/`total_try` at the edge. +- `finding_decimal_add_rounds_dust_at_the_edge`: see finding 1. + +## Findings + +1. **`Amount::checked_add` for `Decimal` is not exact within one unit of + `Decimal::MAX`.** `Decimal::MAX.checked_add(0.4)` is `Some(MAX)`: + `rust_decimal` rounds sub-unit dust when the sum would need a 97th bit + (`MAX + 0.5` is `None`). The kernel's "exact or `None`" contract + therefore fails for figures in the top unit of `Decimal`'s range + (~7.9 x 10^28, 10^13 times a line's cap), for every kernel function that + adds, not only `total`. Not reachable by posted lines (capped at 10^15). + Not fixed here: it lives in `impl Amount for Decimal` + (`kernel/entries.rs`), shared by every unit. A canary test pins the + present behaviour. Suggested fix: refuse any `Decimal` sum whose result + scale is below the larger operand scale (rounding happened). +2. **The audit's section 2.1 overstated reachability.** `money.rs` + `checked_add`/`checked_sub` were already checked; + `ledger-gui/books.rs` `share_of_what_for` was already checked. A posted + entry's lines are validated against the line cap when it posts, restored + or new, so sums over posted lines (the reports) cannot reach the edge; + the store's `create_invoice`/`create_bill` raw `.sum()` ran after + `validate_lines` (cap). What genuinely panicked with a public caller's + arguments: `audit::check_articulation` (`current_earnings + closed`), + `periods::allocate_last_absorbs` / `allocate` (`amount * share`), and the + kernel-less helpers with `Decimal` arguments. All now refuse. Documents, + drafts and recurring entries are the figures B-28 lets restore oversized. + +## Sites replaced + +(file:line at this commit; each `sum_exact*` / `add_exact` / `sub_exact` / +`kernel::total*` use) + +- **ledger-core** (about 90 sites): + `reports.rs` 271-272 (P&L by class), 315-324 (balance sheet), 416 + (statement lines), 521-522 (P&L statement totals), 824-834 (balance sheet + as of), 961-1020 (general ledger begin and running balances and column + totals), 1200 (members' shares), 1235-1427 (members' equity: capital, + flows, distributions, income, totals), 1797-1798 (asset register); + `k1.rs` 183, 207, 227, 249, 277, 293, 304, 310; `tax_capital.rs` 591, + 823, and 759/`rest` (checked `-`); `form1099.rs` 707 (`sum3` was a copy of + the kernel's sum, now `kernel::total`) and the `split_share` loop; + `payouts.rs` 169-189; `audit.rs` 528 (and `closed_net`, + `check_articulation`); `ledger.rs` 3824-3853 (close splits), 4061 + (member shares), 6414, 8434; `periods.rs` 127-180 (`try_allocate`, + `try_allocate_last_absorbs`, the infallible rules delegate to them); + `arap.rs` 1066 (`document_total` is now `kernel::total_of`). +- **ledger-store** `store.rs` 2570, 2575, 3450, 3745, 4454, 4501 (6). +- **ledger-package** `package.rs` 295, 297, 301, 318, 533, 542; + `vendor_1099.rs` 196, 201; `text.rs` 35 (`total_text`) (8). +- **ledger-mcp** `server.rs` 1352; `tools/assets.rs` 843, 927; + `tools/payroll.rs` 117; `tools/reports.rs` 35 (5). +- **ledger-gui** `pages/cash.rs` 186 (1). +- **ledger-import**: none (see below). + +## Not replaced (infallible public signatures) + +Also left raw, found by the review (2026-11-08), each bounded by the +posted-line cap or a validated input: `ledger.rs` ~2305 (a document's +mirror moves), ~4000 (`member_close_run`), ~8106 (`reconciliation_report`, +a fallible function: a candidate for unit K-U8, control and +reconciliation totals); `ledger-config` `lib.rs` ~362 (the members' +shares, each validated to (0, 1]); `ledger-import` `xlsx.rs` ~390; the +viewer's `pages/invoices.rs` ~203, `pages/reconciliation.rs` ~171, +`pages/reports.rs` ~468, `books.rs` ~142 (display, unit K-U9). + +The regression test comparing `try_allocate` with `allocate` checks the +delegation only (`allocate` calls it). The review compared both frozen +rules, reimplemented from before this unit, over 20,000 random cases +and the edges: identical. A property test with that independent +reference is worth adding with unit V-D2. + +A raw sum remains where the function returns a bare figure and changing it +to `Result` would change many callers and existing tests. Each is unreachable +with posted-line-capped figures; each is a signature decision, not a +refactor: + +- `reports.rs` `trial_balance*` (movements, column totals), `project_entries`, + `ProfitAndLossStatement::net_income` and `BalanceSheet::balanced`. +- `tax.rs` `TaxSummary::book_net`/`tax_net` (`sum` helper). +- `cashflow.rs` `kinds()`; `ledger.rs` `Regime` (`closed`, `given`); + `payroll.rs` `payroll_remit_plan` (its caller now refuses first); + `analysis.rs`, `conventions.rs`, `shares.rs`, `parties.rs` running sums. +- `ledger-import/report.rs` (`statement` builders return a bare `Statement`), + `templates.rs` `equal_shares` (n owners, tiny). +- `ledger-gui/books.rs` view-model sums (display only). +- `tax_capital.rs` 485-502: multiplication by +/-1 and a value less its + own truncation cannot overflow. +- Rounding calls: left for K-U2. + +## Regression tests + +- `ledger-core/tests/exact_totals.rs`: the helpers refuse at `Decimal::MAX`; + `document_total`; `check_articulation(MAX, MAX, MAX)` (panicked before); + `try_allocate*` refuse where `allocate*` panicked and equal them for + ordinary input; ten lines at the cap still sum. +- `ledger-store/tests/exact_totals.rs`: an invoice and a bill of + `Decimal::MAX` lines are refused and journal nothing. +- No test for the mcp previews or the gui cash page: their inputs are posted + balances, which the line cap keeps far from the edge (finding 2), and the + public tool API cannot construct an oversized one. + +## `just prove` + +`nice -n 10 just prove` on the shared dev machine, 2026-11-08: **59 Kani +harnesses verified** (53 before, plus these 6; every cover satisfied), then +Lean (118 headline theorems, standard axioms only); 616 s wall clock for +the whole recipe under load from other workers' builds (Kani's own +reported time for the heaviest harness of the run was 235 s).