From 5ae26f1288e0b66c860f71e836f3f595186bfce8 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 12:26:05 -0700 Subject: [PATCH] test: totals past exact arithmetic are refused, never a panic ledger-core/tests/exact_totals.rs: the engine's sum/add/sub helpers, arap's document_total, audit::check_articulation (current_earnings + closed was a raw + that panicked for a public caller's MAX figures) and the frozen close splits' try_ twins refuse at Decimal::MAX with TooLargeToCompute, and give the infallible rules' exact result for ordinary input. ledger-store/tests/exact_totals.rs: an invoice or a bill of enormous lines is refused and journals nothing. (A posted entry's lines are capped when it posts, restored or new, so report sums over posted lines cannot reach the edge; documents are the figures that can.) Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/src/audit.rs | 6 +- crates/ledger-core/src/ledger.rs | 16 ++-- crates/ledger-core/src/reports.rs | 16 ++-- crates/ledger-core/tests/exact_totals.rs | 104 ++++++++++++++++++++++ crates/ledger-store/tests/exact_totals.rs | 71 +++++++++++++++ 5 files changed, 199 insertions(+), 14 deletions(-) create mode 100644 crates/ledger-core/tests/exact_totals.rs create mode 100644 crates/ledger-store/tests/exact_totals.rs diff --git a/crates/ledger-core/src/audit.rs b/crates/ledger-core/src/audit.rs index 9731e0f4..dabbfdf0 100644 --- a/crates/ledger-core/src/audit.rs +++ b/crates/ledger-core/src/audit.rs @@ -525,8 +525,10 @@ fn schedules(ledger: &Ledger, through: NaiveDate) -> Vec { } }; if let Some((first, _)) = months.first() { - let total = crate::kernel::total_of(&months, |&(_, a)| a) - .map_or_else(|| "a sum too large to compute".to_string(), |t| t.to_string()); + 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/ledger.rs b/crates/ledger-core/src/ledger.rs index 8c6b6f5d..dc1133ca 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -3850,7 +3850,11 @@ impl Ledger { let parts = if posts { regime.allocate( &key, - crate::money::add_exact(regime.closed, net, "the members' closed earnings")?, + crate::money::add_exact( + regime.closed, + net, + "the members' closed earnings", + )?, ®ime.given, self.base_currency.allocation_places(), )? @@ -6406,7 +6410,8 @@ impl Ledger { return Err(LedgerError::TooLargeToCompute(format!("{doc}'s figures"))); } }; - let owed = crate::money::sum_exact(after[..=i].iter().copied(), &format!("{doc}'s figures"))?; + 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) @@ -8425,11 +8430,8 @@ impl Ledger { .ok_or(LedgerError::UnknownAccount(cash_account))?; self.check_controls(&PAYROLL)?; let payables = self.payroll_tax_payables(); - let total = crate::money::sum_exact_of( - &payables, - |(_, b)| *b, - "the payroll taxes payable", - )?; + 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/reports.rs b/crates/ledger-core/src/reports.rs index c1cb085c..98fa93aa 100644 --- a/crates/ledger-core/src/reports.rs +++ b/crates/ledger-core/src/reports.rs @@ -1308,9 +1308,7 @@ pub fn members_equity( 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::Credit => add_exact(m, l.amount.amount, "a member's capital")?, crate::Side::Debit => sub_exact(m, l.amount.amount, "a member's capital")?, }; } @@ -1381,7 +1379,11 @@ pub fn members_equity( let other_alloc = end_regime.allocate( &key, sub_exact( - sub_exact(end_bs.total_equity, begin_bs.total_equity, "the change in equity")?, + sub_exact( + end_bs.total_equity, + begin_bs.total_equity, + "the change in equity", + )?, explained, "the change in equity", )?, @@ -1400,7 +1402,11 @@ pub fn members_equity( let too_large = "a member's income"; let income = sub_exact( add_exact( - sub_exact(sub_exact(ending, beginning, too_large)?, contributions, too_large)?, + sub_exact( + sub_exact(ending, beginning, too_large)?, + contributions, + too_large, + )?, distributions, too_large, )?, 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-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"); +}