From 3376c3d54994630f018a4d5cccc2a492685090bd Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 12:17:58 -0700 Subject: [PATCH] refactor(core): every report and book total goes through the kernel's checked sum A raw Decimal + / += / .sum() panics at Decimal::MAX, and a replayed journal line is accepted of any size (rules.md B-28), so a total of restored figures must be exact or refused (B-21), never a crash. The reports (P&L, balance sheet, general ledger, members' equity, asset register), K-1 lines, tax-basis wholes, payouts, the 1099 split, the audit's articulation check, the members close split and arap's document_total now sum with kernel::total / total_of / total_try and add or subtract with checked arithmetic, refusing with TooLargeToCompute. money::sum_exact* and add_exact/sub_exact are the engine's thin wrappers over the kernel (no second copy of the sum). form1099::sum3 was a copy of the kernel's sum and is now kernel::total. periods::allocate and allocate_last_absorbs (frozen replay rules) keep their signatures and results to the cent; each gains a try_ twin that returns TooLargeToCompute where the raw amount * share used to panic, and the ledger's close split calls the twins. Behaviour for every ordinary input is unchanged: no figure moves, no test or golden edited. Infallible public signatures (trial_balance, ProfitAndLossStatement::net_income, tax book_net, project_entries, cash-flow kinds, the Regime) keep their raw sums; making them fallible would change ~100 callers and is a decision, not a refactor. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/src/arap.rs | 4 +- crates/ledger-core/src/audit.rs | 16 +- crates/ledger-core/src/form1099.rs | 12 +- crates/ledger-core/src/k1.rs | 97 +++++++----- crates/ledger-core/src/ledger.rs | 32 ++-- crates/ledger-core/src/money.rs | 45 ++++++ crates/ledger-core/src/payouts.rs | 25 ++-- crates/ledger-core/src/periods.rs | 54 ++++++- crates/ledger-core/src/reports.rs | 206 +++++++++++++++++--------- crates/ledger-core/src/tax_capital.rs | 39 ++--- 10 files changed, 368 insertions(+), 162 deletions(-) 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..9731e0f4 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,8 @@ 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 03d453ce..f837821d 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: @@ -763,13 +761,13 @@ fn split_share(b: [Decimal; 3], v: Decimal) -> Result<[Decimal; 3], LedgerError> let q = num.checked_div(ap).ok_or_else(too_large)?; let mut part = q.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::ToZero); 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 72ab31df..54e77d93 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/ledger.rs b/crates/ledger-core/src/ledger.rs index cf753637..8c6b6f5d 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -3821,17 +3821,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) } _ => { @@ -3841,7 +3850,7 @@ 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(), )? @@ -4044,7 +4053,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) @@ -6396,7 +6406,7 @@ 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) @@ -8415,7 +8425,11 @@ 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 06888e4c..eab92e58 100644 --- a/crates/ledger-core/src/periods.rs +++ b/crates/ledger-core/src/periods.rs @@ -124,22 +124,42 @@ 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, RoundingStrategy::ToZero}; + 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| e.round_dp_with_strategy(2, ToZero)) .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 @@ -149,13 +169,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 rust_decimal::RoundingStrategy::MidpointAwayFromZero; + let too_large = || LedgerError::TooLargeToCompute(format!("the members' shares of {amount}")); let mut parts: Vec<_> = shares .iter() - .map(|s| (amount * s).round_dp_with_strategy(2, MidpointAwayFromZero)) - .collect(); - crate::kernel::plug_last(amount, &mut parts).expect("allocated amounts are in range"); - parts + .map(|s| { + amount + .checked_mul(*s) + .map(|p| p.round_dp_with_strategy(2, MidpointAwayFromZero)) + .ok_or_else(too_large) + }) + .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/reports.rs b/crates/ledger-core/src/reports.rs index 01c96cdd..c1cb085c 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, @@ -816,13 +820,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, @@ -945,7 +957,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 { @@ -998,9 +1011,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); } @@ -1180,7 +1197,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}" @@ -1210,23 +1227,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 @@ -1236,35 +1253,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 @@ -1272,26 +1302,32 @@ 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 @@ -1309,38 +1345,68 @@ 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), @@ -1351,15 +1417,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 { @@ -1720,7 +1788,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 85b9a708..5964a4c8 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; @@ -584,19 +585,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())); @@ -604,7 +605,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(); @@ -755,7 +756,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() @@ -781,7 +782,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, @@ -816,21 +817,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