diff --git a/crates/ledger-core/src/analysis.rs b/crates/ledger-core/src/analysis.rs index 4f9ec9b3..306bc20d 100644 --- a/crates/ledger-core/src/analysis.rs +++ b/crates/ledger-core/src/analysis.rs @@ -6,6 +6,7 @@ //! are built from the same posted entries and statements as everything //! else, so a number on a chart always ties to a number on a statement. +use crate::money::{add_in_range, on_side, sub_in_range}; use crate::reports::profit_and_loss_for_period; use crate::{AccountId, AccountType, Ledger, LedgerError, Side}; use chrono::{Datelike, Days, Months, NaiveDate}; @@ -84,11 +85,11 @@ pub fn balance_series( let Some(account) = ledger.chart().get(line.account) else { continue; }; - let signed = if line.side == account.account_type.normal_side() { - line.amount.amount - } else { - -line.amount.amount - }; + let signed = on_side( + account.account_type.normal_side(), + line.side, + line.amount.amount, + ); postings.push((entry.date(), signed)); } } @@ -98,7 +99,7 @@ pub fn balance_series( let mut i = 0; for date in dates { while i < postings.len() && postings[i].0 <= *date { - running += postings[i].1; + running = add_in_range(running, postings[i].1); i += 1; } out.push(running); @@ -137,7 +138,7 @@ pub struct IntervalPnl { impl IntervalPnl { /// Revenue minus expenses. pub fn net(&self) -> Decimal { - self.revenue - self.expenses + sub_in_range(self.revenue, self.expenses) } } @@ -203,14 +204,14 @@ pub fn flows_by_interval( let mut net = Decimal::ZERO; for line in entry.lines().iter().filter(|l| set.contains(&l.account)) { match line.side { - Side::Debit => net += line.amount.amount, - Side::Credit => net -= line.amount.amount, + Side::Debit => net = add_in_range(net, line.amount.amount), + Side::Credit => net = sub_in_range(net, line.amount.amount), } } if net > Decimal::ZERO { - slot.2 += net; + slot.2 = add_in_range(slot.2, net); } else { - slot.3 -= net; + slot.3 = sub_in_range(slot.3, net); } } out diff --git a/crates/ledger-core/src/arap.rs b/crates/ledger-core/src/arap.rs index a47ec7c8..48ce38d2 100644 --- a/crates/ledger-core/src/arap.rs +++ b/crates/ledger-core/src/arap.rs @@ -145,11 +145,7 @@ impl DocRef { /// A line's amount as this document counts it: plus on /// [`Self::owed_side`], minus on the other. pub fn counted(self, side: crate::Side, amount: Decimal) -> Decimal { - if side == self.owed_side() { - amount - } else { - -amount - } + crate::money::on_side(self.owed_side(), side, amount) } } @@ -1368,7 +1364,8 @@ impl AgingRow { /// Add `other`'s buckets to this row's; refused past exact arithmetic. pub(crate) fn add(&mut self, other: &AgingRow) -> Result<(), LedgerError> { let too_large = || LedgerError::TooLargeToCompute(format!("{}'s aging", self.name)); - let sum = |a: Decimal, b: Decimal| a.checked_add(b).ok_or_else(too_large); + let sum = + |a: Decimal, b: Decimal| crate::kernel::Amount::checked_add(a, b).ok_or_else(too_large); let (current, days_30, days_60, days_90, days_90_plus) = ( sum(self.current, other.current)?, sum(self.days_30, other.days_30)?, diff --git a/crates/ledger-core/src/assets.rs b/crates/ledger-core/src/assets.rs index 97961fa1..4edfab76 100644 --- a/crates/ledger-core/src/assets.rs +++ b/crates/ledger-core/src/assets.rs @@ -22,6 +22,7 @@ //! the §704(c) built-in gain or loss at contribution. use crate::money::Steps; +use crate::money::neg; use crate::{ AccountId, AccountType, ChartOfAccounts, EntryId, EntryStatus, Ledger, LedgerError, Money, kernel, @@ -684,11 +685,9 @@ fn schedule_months(asset: &Asset, through: NaiveDate) -> Result, } let too_large = || LedgerError::TooLargeToCompute(format!("asset {}'s depreciation schedule", asset.id)); - let depreciable = asset - .cost - .amount - .checked_sub(asset.salvage_value.amount) - .ok_or_else(too_large)?; + let depreciable = + crate::kernel::Amount::checked_sub(asset.cost.amount, asset.salvage_value.amount) + .ok_or_else(too_large)?; if depreciable <= Decimal::ZERO { return Ok(Vec::new()); } @@ -721,10 +720,7 @@ fn schedule_months(asset: &Asset, through: NaiveDate) -> Result, period: format!("{:04}-{:02}", p.year, p.month), amount: steps.decimal(through_k - charged).ok_or_else(too_large)?, accumulated, - book_value: asset - .cost - .amount - .checked_sub(accumulated) + book_value: crate::kernel::Amount::checked_sub(asset.cost.amount, accumulated) .ok_or_else(too_large)?, }, }); @@ -760,11 +756,11 @@ pub fn accumulated_scheduled_through( /// [`crate::Ledger::accumulated_posted`] (the register's and the tools' /// `book_value`, BS-asset-3). pub fn scheduled_book_value(asset: &Asset, as_of: NaiveDate) -> Result { - asset - .cost - .amount - .checked_sub(accumulated_scheduled_through(asset, as_of)?) - .ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s book value", asset.id))) + crate::kernel::Amount::checked_sub( + asset.cost.amount, + accumulated_scheduled_through(asset, as_of)?, + ) + .ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s book value", asset.id))) } /// A change to what the books carry for an asset's depreciation, in the @@ -839,7 +835,7 @@ pub(crate) fn run_chain_entries( .get_entry(id) .filter(|x| x.status() == EntryStatus::Posted) { - out.push((e.date(), if adds { amount } else { -amount })); + out.push((e.date(), if adds { amount } else { neg(amount) })); } link = reversals.get(&id).copied(); adds = !adds; @@ -929,8 +925,7 @@ pub fn run_amounts( RunAmount { amount, scheduled: own, - over: g - .checked_sub(s) + over: crate::kernel::Amount::checked_sub(g, s) .map_or(Decimal::ZERO, |o| o.max(Decimal::ZERO)), }, ) @@ -981,7 +976,7 @@ fn cumulatives( li += 1; } while let Some(r) = runs.get(ri).filter(|r| (r.year, r.month) <= (y, m)) { - carry = carry.checked_add(r.amount).ok_or_else(too_large)?; + carry = crate::kernel::Amount::checked_add(carry, r.amount).ok_or_else(too_large)?; ri += 1; } months.push((y, m)); @@ -1096,8 +1091,7 @@ pub fn catch_up_room( let too_large = || LedgerError::TooLargeToCompute(format!("asset {}'s depreciation run", asset.id)); let c = cumulatives(asset, (year, month), latest, &lines, posted)?; - let over = c.carried[0] - .checked_sub(c.scheduled[0]) + let over = crate::kernel::Amount::checked_sub(c.carried[0], c.scheduled[0]) .ok_or_else(too_large)? .max(Decimal::ZERO); Ok(RunAmount { @@ -1154,15 +1148,13 @@ pub fn disposal_amounts( check_disposal(asset, proceeds)?; let accumulated = accumulated_scheduled_through(asset, date)?; let too_large = || LedgerError::TooLargeToCompute(format!("asset {}'s disposal", asset.id)); - let book = asset - .cost - .amount - .checked_sub(accumulated) - .ok_or_else(too_large)?; + let book = + crate::kernel::Amount::checked_sub(asset.cost.amount, accumulated).ok_or_else(too_large)?; Ok(DisposalAmounts { book_value: book, accumulated, - gain_loss: proceeds.amount.checked_sub(book).ok_or_else(too_large)?, + gain_loss: crate::kernel::Amount::checked_sub(proceeds.amount, book) + .ok_or_else(too_large)?, }) } diff --git a/crates/ledger-core/src/audit.rs b/crates/ledger-core/src/audit.rs index 7d4053dc..c570406e 100644 --- a/crates/ledger-core/src/audit.rs +++ b/crates/ledger-core/src/audit.rs @@ -36,7 +36,7 @@ use serde::Serialize; use crate::evidence::{Policy, Requirement}; use crate::settings::Settings; -use crate::{AccountType, DocStatus, EntryId, EntryStatus, Ledger, PeriodStatus, Side}; +use crate::{AccountType, DocStatus, EntryId, EntryStatus, Ledger, PeriodStatus}; /// How much a finding matters. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] @@ -350,10 +350,7 @@ fn closed_net(ledger: &Ledger, through: NaiveDate) -> Option { let Some(a) = ledger.chart().get(l.account) else { continue; }; - let signed = match l.side { - Side::Debit => l.amount.amount, - Side::Credit => -l.amount.amount, - }; + let signed = crate::money::signed_amount(l.side, l.amount.amount); if matches!(a.account_type, AccountType::Revenue | AccountType::Expense) { net = crate::kernel::Amount::checked_add(net, signed)?; } @@ -536,16 +533,29 @@ pub fn check_split( trued_up: bool, ) -> Vec { // B(n) as derived above: (n-1)*u/2, floored at u. `unit` is a power - // of ten and n is small, so the product and the halving are exact. + // of ten and n is small, so the product and the halving are exact. A + // bound exact arithmetic could not hold (no real unit and member + // count reach it) falls to the floor, the stricter of the two: the + // audit then raises a drift it might have allowed, never hides one. let legacy_bound = { let others = Decimal::new(split.len().saturating_sub(1) as i64, 0); - let last = others * unit / Decimal::new(2, 0); - if last > unit { last } else { unit } + match crate::kernel::Amount::checked_mul(others, unit) + .and_then(|product| crate::kernel::Amount::checked_div_exact(product, Decimal::TWO)) + { + Some(last) if last > unit => last, + _ => unit, + } }; split .iter() .filter(|m| { - let drift = (m.running - m.exact).abs(); + // A difference exact arithmetic cannot hold is no drift + // under a unit: raised. + let Some(drift) = + crate::kernel::Amount::checked_sub(m.running, m.exact).map(|d| d.abs()) + else { + return true; + }; if trued_up { drift >= unit } else { diff --git a/crates/ledger-core/src/cashflow.rs b/crates/ledger-core/src/cashflow.rs index e180d199..55bd7ad8 100644 --- a/crates/ledger-core/src/cashflow.rs +++ b/crates/ledger-core/src/cashflow.rs @@ -12,6 +12,7 @@ //! falls, what a member or lender paid for the company, pairs reversals, //! names the kinds and checks the result foots. +use crate::money::{add_in_range, neg, signed_amount, sub_in_range}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use chrono::NaiveDate; @@ -405,7 +406,7 @@ impl CashFlowStatement { for l in self.lines(section) { match out.last_mut() { Some(k) if k.kind == l.kind => { - k.amount += l.amount; + k.amount = add_in_range(k.amount, l.amount); k.entries.push(l.entry); } _ => out.push(CashFlowKind { @@ -643,8 +644,7 @@ pub fn role_problems( /// cannot fail on posted entries): the sections sum to the change in /// cash, or nothing is produced. pub fn foot(sections_sum: Decimal, net_change: Decimal) -> Result { - let difference = sections_sum - .checked_sub(net_change) + let difference = crate::kernel::Amount::checked_sub(sections_sum, net_change) .ok_or_else(|| too_large("the cash flow statement's footing"))?; if !difference.is_zero() { return Err(LedgerError::CashFlowDoesNotFoot { @@ -665,14 +665,11 @@ fn too_large(what: &str) -> LedgerError { } fn add(a: Decimal, b: Decimal, what: &str) -> Result { - a.checked_add(b).ok_or_else(|| too_large(what)) + crate::kernel::Amount::checked_add(a, b).ok_or_else(|| too_large(what)) } fn signed(side: Side, amount: Decimal) -> Decimal { - match side { - Side::Debit => amount, - Side::Credit => -amount, - } + signed_amount(side, amount) } /// What a line part belongs to within its section: the kind its cash is @@ -1075,7 +1072,7 @@ fn bill_splits(roles: &Roles<'_>, chains: &Chains) -> Result Decimal::ZERO && operating_liability(l.account)? { let part = left.min(l.amount.amount); out.parts.insert((b.id(), i), (part, bucket.clone())); - left -= part; + left = sub_in_range(left, part); } } // Each payment pays the equipment part first, in the order paid: @@ -1085,13 +1082,13 @@ fn bill_splits(roles: &Roles<'_>, chains: &Chains) -> Result, chains: &Chains) -> Result cur) else { break; }; paid.push((re.date(), undo)); - undo = -undo; + undo = neg(undo); cur = r; } if ledger.in_effect(p.id()) { - owed -= part; + owed = sub_in_range(owed, part); } - this -= part; + this = sub_in_range(this, part); } } } @@ -1301,7 +1298,7 @@ fn analyse<'a>( ..part.clone() }); } - part.amount = amount - inv; + part.amount = sub_in_range(amount, inv); if part.amount.is_zero() { continue; } @@ -1401,7 +1398,7 @@ fn analyse<'a>( if total > Decimal::ZERO { inflow = add(inflow, total, "an entry's exchange")?; } else { - outflow = add(outflow, -total, "an entry's exchange")?; + outflow = add(outflow, neg(total), "an entry's exchange")?; } } if !total.is_zero() { @@ -1427,7 +1424,7 @@ fn analyse<'a>( if m > Decimal::ZERO { debits = add(debits, m, "an entry's exchange")?; } else { - credits = add(credits, -m, "an entry's exchange")?; + credits = add(credits, neg(m), "an entry's exchange")?; } } let exchanged = kernel::exchanged(debits, credits, inflow, outflow) @@ -1490,9 +1487,9 @@ impl Chains { fn negated(f: &EntryFlows) -> EntryFlows { EntryFlows { - cash: -f.cash, - flows: f.flows.map(|x| -x), - noncash: f.noncash.map(|x| -x), + cash: neg(f.cash), + flows: f.flows.map(neg), + noncash: f.noncash.map(neg), } } @@ -1526,8 +1523,8 @@ fn pairs(kept: &[Analysed<'_>]) -> HashSet { r.kinds[k].len() == x.kinds[k].len() && r.kinds[k].iter().zip(&x.kinds[k]).all(|(rk, xk)| { rk.bucket == xk.bucket - && rk.cash == -xk.cash - && rk.on_behalf == -xk.on_behalf + && rk.cash == neg(xk.cash) + && rk.on_behalf == neg(xk.on_behalf) }) }); if mirror { @@ -1968,7 +1965,7 @@ pub fn cash_flow( { for &(date, part) in paid { if date <= params.end { - exchanged -= part; + exchanged = sub_in_range(exchanged, part); } } exchanged = exchanged.max(Decimal::ZERO); @@ -2017,8 +2014,7 @@ pub fn cash_flow( } } } - let net_change_in_cash = cash_ending - .checked_sub(cash_beginning) + let net_change_in_cash = crate::kernel::Amount::checked_sub(cash_ending, cash_beginning) .ok_or_else(|| too_large("the change in cash"))?; let sections_sum = add( add(totals[0], totals[1], "the sections' sum")?, @@ -2072,7 +2068,7 @@ fn reconcile( let (mut g, mut dep) = (Decimal::ZERO, Decimal::ZERO); for p in &a.parts { if p.pl { - net_income = add(net_income, -p.signed(), WHAT)?; + net_income = add(net_income, neg(p.signed()), WHAT)?; if p.flow == Flow::Investing { if roles.depreciation.contains(&p.account) { dep = add(dep, p.signed(), WHAT)?; @@ -2204,7 +2200,7 @@ fn reconcile( if up { "Increase in" } else { "Decrease in" }, named(&code) ), - amount: -movement, + amount: neg(movement), account: Some(code), entries: Vec::new(), }); diff --git a/crates/ledger-core/src/conventions.rs b/crates/ledger-core/src/conventions.rs index c8045cc4..6fb05c72 100644 --- a/crates/ledger-core/src/conventions.rs +++ b/crates/ledger-core/src/conventions.rs @@ -779,10 +779,16 @@ fn check_template(t: &Template) -> Result { l.share ) })?; - match l.side { - Side::Debit => debit += share, - Side::Credit => credit += share, - } + let side_total = match l.side { + Side::Debit => &mut debit, + Side::Credit => &mut credit, + }; + *side_total = crate::kernel::Amount::checked_add(*side_total, share).ok_or_else(|| { + format!( + "template line {n}: share {:?} has too many digits to add up exactly", + l.share + ) + })?; let account = line_text(&format!("template line {n} account"), &l.account, 64)?; if account.starts_with('{') && slot(&account).is_none() { return Err(format!( diff --git a/crates/ledger-core/src/evidence.rs b/crates/ledger-core/src/evidence.rs index 6291fc43..d3bfacef 100644 --- a/crates/ledger-core/src/evidence.rs +++ b/crates/ledger-core/src/evidence.rs @@ -200,12 +200,11 @@ impl Policy { /// total past exact arithmetic is refused (TooLargeToCompute), never /// a panic. pub fn entry_debits(entry: &JournalEntry) -> Result { - entry - .lines() - .iter() - .filter(|l| l.side == Side::Debit) - .try_fold(Decimal::ZERO, |sum, l| sum.checked_add(l.amount.amount)) - .ok_or_else(|| LedgerError::TooLargeToCompute(format!("entry {}'s debits", entry.id()))) + crate::kernel::total_of( + entry.lines().iter().filter(|l| l.side == Side::Debit), + |l| l.amount.amount, + ) + .ok_or_else(|| LedgerError::TooLargeToCompute(format!("entry {}'s debits", entry.id()))) } fn account_codes(ledger: &Ledger, entry: &JournalEntry) -> Vec { @@ -343,7 +342,7 @@ impl Policy { // A sum past exact arithmetic is past the threshold. total = Self::entry_debits(other) .ok() - .and_then(|d| total.checked_add(d)) + .and_then(|d| crate::kernel::Amount::checked_add(total, d)) .unwrap_or(Decimal::MAX); } if !group.is_empty() && total > self.threshold { diff --git a/crates/ledger-core/src/form1099.rs b/crates/ledger-core/src/form1099.rs index 11f11279..aeb2e7d0 100644 --- a/crates/ledger-core/src/form1099.rs +++ b/crates/ledger-core/src/form1099.rs @@ -37,6 +37,7 @@ //! them and the report takes an override. Confirm with the CPA. use crate::kernel::{self, Bucket, PayRole, Tag}; +use crate::money::neg; use crate::settings::Source; use crate::{AccountId, AccountType, EntryId, Ledger, LedgerError, VendorId}; use chrono::{Datelike, NaiveDate}; @@ -769,7 +770,7 @@ fn split_share(b: [Decimal; 3], v: Decimal) -> Result<[Decimal; 3], LedgerError> kernel::apportion(av, &mut parts, &rems, cent).ok_or_else(too_large)?; if v.is_sign_negative() { for x in parts.iter_mut().filter(|x| !x.is_zero()) { - *x = -*x; + *x = neg(*x); } } Ok(parts) @@ -831,8 +832,7 @@ struct Tally { } fn add(to: &mut Decimal, x: Decimal) -> Result<(), LedgerError> { - *to = to - .checked_add(x) + *to = crate::kernel::Amount::checked_add(*to, x) .ok_or_else(|| LedgerError::TooLargeToCompute("a vendor's payments for the year".into()))?; Ok(()) } @@ -1236,8 +1236,7 @@ fn untagged_payments( continue; } let [counts, _, unknown] = entry_buckets(ledger, e, roles)?; - let out_of_pocket = counts - .checked_add(unknown) + let out_of_pocket = crate::kernel::Amount::checked_add(counts, unknown) .ok_or_else(|| LedgerError::TooLargeToCompute("a payment".into()))?; if out_of_pocket <= Decimal::ZERO { continue; diff --git a/crates/ledger-core/src/k1.rs b/crates/ledger-core/src/k1.rs index 7949bdd9..b39e0fd0 100644 --- a/crates/ledger-core/src/k1.rs +++ b/crates/ledger-core/src/k1.rs @@ -68,7 +68,7 @@ //! ``` use crate::kernel::Amount; -use crate::money::{add_exact, sub_exact, sum_exact_of, sum_exact_try}; +use crate::money::{add_exact, neg, 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; @@ -314,7 +314,7 @@ pub(crate) fn entry_lines( "a member's distributions", )?; if !taken.is_zero() { - lines.push(line(i, K1Kind::Distribution, -taken)); + lines.push(line(i, K1Kind::Distribution, neg(taken))); } } Ok(lines) @@ -347,10 +347,7 @@ pub(crate) fn share_property( use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with}; let too_large = || LedgerError::TooLargeToCompute("a member's share of contributed property".into()); - let total = credits - .iter() - .try_fold(Decimal::ZERO, |t, c| t.checked_add(*c)) - .ok_or_else(too_large)?; + let total = crate::kernel::total_of(credits.iter(), |c| *c).ok_or_else(too_large)?; let whole = pool.min(total); if whole <= Decimal::ZERO || total <= Decimal::ZERO { return Ok(vec![Decimal::ZERO; credits.len()]); diff --git a/crates/ledger-core/src/kernel/entries.rs b/crates/ledger-core/src/kernel/entries.rs index 5753b5d6..5964b48c 100644 --- a/crates/ledger-core/src/kernel/entries.rs +++ b/crates/ledger-core/src/kernel/entries.rs @@ -50,6 +50,28 @@ pub trait Amount: Copy + Ord { fn checked_mul_rounded(self, rhs: Self) -> Option { self.checked_mul(rhs) } + /// `self + rhs` as the amount type adds, which for [`Decimal`] is + /// `rust_decimal`'s: exact where the sum fits 96 bits and scale 28, + /// otherwise rounded to what it holds. `None` only on overflow. + /// + /// The engine's rounding sum, beside its rounding product and its + /// rounding division, and for one use: a running total of rounded + /// shares (`whole x weight / total`, each a quotient of 28 significant + /// digits). Three thirds of 28 digits are not a sum 96 bits hold, and + /// the total they stand for was never an exact figure: the caller + /// rounds it to the places it means before a cent is taken from it + /// (`tax_capital`'s `RunningSplit`, INVARIANT 4). Nothing else calls + /// it; a sum of amounts is [`Amount::checked_add`], exact or refused. + /// A machine integer never rounds, so there it is `checked_add`. + fn checked_add_rounded(self, rhs: Self) -> Option { + self.checked_add(rhs) + } + /// `self - rhs` as the amount type subtracts: [`Amount::checked_add_rounded`]'s + /// other half, for taking a rounded share back out of such a running + /// total. For a machine integer it is `checked_sub`. + fn checked_sub_rounded(self, rhs: Self) -> Option { + self.checked_sub(rhs) + } /// `self * rhs`, computed exactly and rounded once to a whole multiple /// of `step` in `mode`; `None` when `step` is not positive or the /// result cannot be represented. @@ -142,6 +164,12 @@ impl Amount for Decimal { fn checked_mul_rounded(self, rhs: Self) -> Option { Decimal::checked_mul(self, rhs) } + fn checked_add_rounded(self, rhs: Self) -> Option { + Decimal::checked_add(self, rhs) + } + fn checked_sub_rounded(self, rhs: Self) -> Option { + Decimal::checked_sub(self, rhs) + } fn checked_mul_round_to_step(self, rhs: Self, step: Self, mode: Rounding) -> Option { if let Some(product) = super::decimal_exact::exact_mul(self, rhs) { return super::round::round_step(product, step, mode); diff --git a/crates/ledger-core/src/kernel/round.rs b/crates/ledger-core/src/kernel/round.rs index d108e20d..3e42c857 100644 --- a/crates/ledger-core/src/kernel/round.rs +++ b/crates/ledger-core/src/kernel/round.rs @@ -106,6 +106,36 @@ pub fn round_places(amount: Decimal, places: u32, mode: Rounding) -> Option Option { + if places > Decimal::MAX_SCALE { + return None; + } + let mut written = amount; + written.rescale(places); + (written == amount).then_some(written) +} + /// `amount` rounded to whole `currency` minor units in `mode`: cents for /// USD, whole yen for JPY, thousandths for KWD. A currency ISO 4217 gives /// no minor unit (gold, SDRs) is returned exactly, as the FX booking rule diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index c241f48e..b65aa856 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -6,6 +6,7 @@ //! is no other way to change the books, which is what makes the ledger an //! audit trail and what will make the future oracle harness trustworthy. +use crate::money::{add_in_range, neg, on_side}; use crate::schedules::{ self, AmortizationSchedule, NewRecurring, NewSchedule, RecurringEntry, RecurringId, ScheduleId, }; @@ -2369,9 +2370,11 @@ impl Ledger { for (i, l) in original.lines().iter().enumerate() { if let Some(tag) = self.line_docs.get(&(original.id(), i)) { // The mirror moves the document by the opposite. - let by = -tag.doc.counted(l.side, l.amount.amount); + let by = neg(tag.doc.counted(l.side, l.amount.amount)); match moves.iter_mut().find(|(d, _)| *d == tag.doc) { - Some((_, m)) => *m += by, + Some((_, m)) => { + *m = crate::money::add_exact(*m, by, "a document's movement in a reversal")? + } None => moves.push((tag.doc, by)), } } @@ -3439,11 +3442,13 @@ impl Ledger { ) -> Result { let too_large = || LedgerError::TooLargeToCompute(format!("asset {id}'s posted depreciation")); - assets::run_chain_entries(self, &self.depreciation_run_entries(id), reversals) - .into_iter() - .filter(|(d, _)| *d >= from && *d <= to) - .try_fold(Decimal::ZERO, |t, (_, a)| t.checked_add(a)) - .ok_or_else(too_large) + crate::kernel::total_of( + assets::run_chain_entries(self, &self.depreciation_run_entries(id), reversals) + .into_iter() + .filter(|(d, _)| *d >= from && *d <= to), + |(_, a)| a, + ) + .ok_or_else(too_large) } /// The run the books carry for an asset's month, if any: the first one @@ -3757,7 +3762,7 @@ impl Ledger { let mut sweep = |from: AccountId, into: AccountId, this: &Self| { // An equity balance (credit-normal) is −movement; zeroing it // moves exactly that much into the target. - let balance = -this.movement_through(from, period.end); + let balance = neg(this.movement_through(from, period.end)); if !balance.is_zero() { sweep_lines.push((from, into, balance)); } @@ -3830,7 +3835,7 @@ impl Ledger { // A sweep zeroes the source (opposite its balance) and moves // the balance into the target. for (from, into, balance) in sweep_lines { - post(self, from, -balance)?; + post(self, from, neg(balance))?; post(self, into, balance)?; } self.post_entry(entry)?; @@ -4005,10 +4010,10 @@ impl Ledger { regime.trued_up |= matches!(m.rule, periods::MemberRule::Cumulative { .. }) && p.closing_entry.is_some(); regime.order.clone_from(&m.members); - regime.closed += m.net; + regime.closed = add_in_range(regime.closed, m.net); for ((capital, _), part) in m.members.iter().zip(&m.parts) { if let Some(i) = members.iter().position(|(c, _)| c == capital) { - regime.given[i] += *part; + regime.given[i] = add_in_range(regime.given[i], *part); } } } @@ -4041,7 +4046,12 @@ impl Ledger { share, part, running, - exact: share * regime.closed, + // A share is positive and the shares sum to one + // (close_period_to_members), so the product is no + // larger than the total and Decimal holds it, rounded + // at its 28th digit where the factors carry more. + exact: crate::kernel::Amount::checked_mul_rounded(share, regime.closed) + .expect("a share of at most one of a total Decimal holds"), }, ) .collect(); @@ -4079,7 +4089,7 @@ impl Ledger { let mut total = Decimal::ZERO; for p in closed { match &p.member_close { - Some(r) if r.members == members => total += r.net, + Some(r) if r.members == members => total = add_in_range(total, r.net), _ => break, } } @@ -6347,7 +6357,8 @@ impl Ledger { return Ok(None); } let too_large = || LedgerError::TooLargeToCompute(format!("{doc}'s figures")); - let add = |a: Decimal, b: Decimal| a.checked_add(b).ok_or_else(too_large); + let add = + |a: Decimal, b: Decimal| crate::kernel::Amount::checked_add(a, b).ok_or_else(too_large); let (mut outstanding, mut paid, mut discounted, mut written_off) = (Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO); let lines = self.doc_lines(doc); @@ -6357,9 +6368,9 @@ impl Ledger { for l in lines.into_iter().filter(|l| l.date <= as_of) { outstanding = add(outstanding, l.amount)?; match l.movement { - arap::Movement::Payment => paid = add(paid, -l.amount)?, - arap::Movement::Discount => discounted = add(discounted, -l.amount)?, - arap::Movement::WriteOff => written_off = add(written_off, -l.amount)?, + arap::Movement::Payment => paid = add(paid, neg(l.amount))?, + arap::Movement::Discount => discounted = add(discounted, neg(l.amount))?, + arap::Movement::WriteOff => written_off = add(written_off, neg(l.amount))?, arap::Movement::Origin | arap::Movement::Adopted | arap::Movement::RoleMove => {} } } @@ -6411,12 +6422,14 @@ impl Ledger { /// payment needs that feature. Refused (TooLargeToCompute), never a /// panic, past exact arithmetic: replayed amounts are any size (BS-entry-4). pub fn payments_recorded(&self, doc: arap::DocRef) -> Result { - self.payment_events - .get(&doc) - .map_or(&[][..], Vec::as_slice) - .iter() - .try_fold(Decimal::ZERO, |sum, &a| sum.checked_add(a)) - .ok_or_else(|| LedgerError::TooLargeToCompute(format!("{doc}'s payments"))) + crate::kernel::total_of( + self.payment_events + .get(&doc) + .map_or(&[][..], Vec::as_slice) + .iter(), + |&a| a, + ) + .ok_or_else(|| LedgerError::TooLargeToCompute(format!("{doc}'s payments"))) } /// The payment entries that stand against a document now: each @@ -6457,7 +6470,7 @@ impl Ledger { .chain(extra.iter().copied()); for (date, amount) in moves { let day = by_date.entry(date).or_default(); - *day = day.checked_add(amount).ok_or_else(too_large)?; + *day = crate::kernel::Amount::checked_add(*day, amount).ok_or_else(too_large)?; } Ok(by_date.into_values().collect()) } @@ -6534,11 +6547,13 @@ impl Ledger { let too_large = || LedgerError::TooLargeToCompute(format!("{doc}'s figures")); let mut running = Decimal::ZERO; for l in lines.iter().filter(|l| l.date <= from) { - running = running.checked_add(l.amount).ok_or_else(too_large)?; + running = + crate::kernel::Amount::checked_add(running, l.amount).ok_or_else(too_large)?; } let mut room = running; for l in lines.iter().filter(|l| l.date > from) { - running = running.checked_add(l.amount).ok_or_else(too_large)?; + running = + crate::kernel::Amount::checked_add(running, l.amount).ok_or_else(too_large)?; room = room.min(running); } Ok(room) @@ -6730,9 +6745,10 @@ impl Ledger { }); } let room = self.payment_room(app.doc, params.date)?; - let applied = app.cash.checked_add(app.discount).ok_or_else(|| { - LedgerError::TooLargeToCompute(format!("{}'s settlement", app.doc)) - })?; + let applied = + crate::kernel::Amount::checked_add(app.cash, app.discount).ok_or_else(|| { + LedgerError::TooLargeToCompute(format!("{}'s settlement", app.doc)) + })?; if applied > room { return Err(LedgerError::Overpayment(applied, room)); } @@ -6754,9 +6770,7 @@ impl Ledger { // A fee above the cash is its own refusal; the kernel would also // answer `None` for it, with no way to say which of its refusals it // was. A sum that overflows is left to the kernel (too large). - if let Some(total_cash) = cash - .iter() - .try_fold(Decimal::ZERO, |sum, c| sum.checked_add(*c)) + if let Some(total_cash) = crate::kernel::total_of(cash.iter(), |c| *c) && fee_amount > total_cash { return Err(LedgerError::FeeAboveCash { @@ -6780,9 +6794,9 @@ impl Ledger { let mut total_discount = Decimal::ZERO; for app in ¶ms.applications { if app.discount > Decimal::ZERO { - total_discount = total_discount - .checked_add(app.discount) - .ok_or_else(|| LedgerError::TooLargeToCompute("the discounts".into()))?; + total_discount = + crate::kernel::Amount::checked_add(total_discount, app.discount) + .ok_or_else(|| LedgerError::TooLargeToCompute("the discounts".into()))?; } } let discount_account = if any_discount { @@ -7412,7 +7426,7 @@ impl Ledger { }; for l in self.doc_lines(doc).into_iter().filter(|l| l.date <= as_of) { let t = doc_totals.entry(l.account).or_default(); - *t = t.checked_add(l.amount).ok_or_else(too_large)?; + *t = crate::kernel::Amount::checked_add(*t, l.amount).ok_or_else(too_large)?; } if let Some(st) = self.doc_state(doc, as_of)? && (st.out_of_bounds() || st.status == arap::DocStatus::Unattached) @@ -7444,7 +7458,7 @@ impl Ledger { } else { Side::Credit }; - if side == plus { amount } else { -amount } + on_side(plus, side, amount) }; let mut out = Vec::new(); for (account, role) in accounts { @@ -7455,9 +7469,11 @@ impl Ledger { if l.account != account { continue; } - balance = balance - .checked_add(counted(role, l.side, l.amount.amount)) - .ok_or_else(too_large)?; + balance = crate::kernel::Amount::checked_add( + balance, + counted(role, l.side, l.amount.amount), + ) + .ok_or_else(too_large)?; if !self.line_docs.contains_key(&(e.id(), i)) { let top = self.reversal_chain(e.id())[0]; if !tops.contains(&(top, i)) { @@ -7480,12 +7496,15 @@ impl Ledger { continue; }; debug_assert!(n == 0 || e.reversal_of().is_some()); - net = net - .checked_add(counted(role, l.side, l.amount.amount)) - .ok_or_else(too_large)?; + net = crate::kernel::Amount::checked_add( + net, + counted(role, l.side, l.amount.amount), + ) + .ok_or_else(too_large)?; } if !net.is_zero() { - unattached_sum = unattached_sum.checked_add(net).ok_or_else(too_large)?; + unattached_sum = crate::kernel::Amount::checked_add(unattached_sum, net) + .ok_or_else(too_large)?; unattached.push(arap::UnattachedLine { entry: top, line: i, @@ -7522,10 +7541,8 @@ impl Ledger { let Ok(Some(st)) = self.doc_state(doc, NaiveDate::MAX) else { return; }; - let Some(settled) = st - .paid - .checked_add(st.discounted) - .and_then(|s| s.checked_add(st.written_off)) + let Some(settled) = crate::kernel::Amount::checked_add(st.paid, st.discounted) + .and_then(|s| crate::kernel::Amount::checked_add(s, st.written_off)) else { return; }; @@ -8190,18 +8207,14 @@ impl Ledger { continue; } // Signed in the account's normal side: positive = normal balance. - let signed = match (line.side, normal) { - (Side::Debit, Side::Debit) => line.amount.amount, - (Side::Credit, Side::Credit) => line.amount.amount, - (Side::Debit, Side::Credit) => -line.amount.amount, - (Side::Credit, Side::Debit) => -line.amount.amount, - }; - book += signed; + let signed = on_side(normal, line.side, line.amount.amount); + book = crate::money::add_exact(book, signed, "the account's book balance")?; if entry.date() > statement_date { continue; } if self.is_cleared(entry.id(), idx) { - cleared += signed; + cleared = + crate::money::add_exact(cleared, signed, "the account's cleared balance")?; } else { uncleared_lines.push(UnclearedLine { entry_id: entry.id(), @@ -8225,9 +8238,9 @@ impl Ledger { cleared }, statement_balance, - difference: cleared.checked_sub(statement_balance).ok_or_else(|| { - LedgerError::TooLargeToCompute("the reconciliation's difference".into()) - })?, + difference: crate::kernel::Amount::checked_sub(cleared, statement_balance).ok_or_else( + || LedgerError::TooLargeToCompute("the reconciliation's difference".into()), + )?, uncleared_lines, }) } @@ -8442,7 +8455,7 @@ impl Ledger { match l.employee { Some(p) => match paid.iter_mut().find(|(x, _)| *x == p) { Some((_, v)) => { - *v = v.checked_add(net).ok_or_else(|| { + *v = crate::kernel::Amount::checked_add(*v, net).ok_or_else(|| { LedgerError::TooLargeToCompute(format!("party {p}'s net pay")) })? } @@ -9209,11 +9222,10 @@ impl Ledger { .iter() .filter_map(|l| self.chart.get(l.account).map(|a| a.code.as_str())) .collect(); - let debits = e - .lines() - .iter() - .filter(|l| l.side == Side::Debit) - .try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount)) + let debits = + crate::kernel::total_of(e.lines().iter().filter(|l| l.side == Side::Debit), |l| { + l.amount.amount + }) .ok_or_else(|| LedgerError::TooLargeToCompute(format!("entry {entry}'s debits")))?; let approvals = self.conventions.approvals(entry); let key = crate::parties::name_key; diff --git a/crates/ledger-core/src/money.rs b/crates/ledger-core/src/money.rs index d1708084..23118077 100644 --- a/crates/ledger-core/src/money.rs +++ b/crates/ledger-core/src/money.rs @@ -4,7 +4,7 @@ //! [`Money`] arithmetic is checked: adding different currencies is an error, //! not a guess. -use crate::LedgerError; +use crate::{LedgerError, Side}; use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; use std::fmt; @@ -205,6 +205,43 @@ pub fn sub_exact(a: Decimal, b: Decimal, what: &str) -> Result Decimal { + crate::kernel::Amount::checked_neg(value).expect("Decimal negation is exact") +} + +/// A line's amount signed by its side ([`crate::kernel::signed`]): +/// a debit as it is, a credit negated. +pub(crate) fn signed_amount(side: Side, amount: Decimal) -> Decimal { + crate::kernel::signed(side, amount).expect("Decimal negation is exact") +} + +/// A line's amount counted from one side of an account: as it is when +/// the line is on `normal`, negated when it is on the other side. With +/// `normal` the account's normal side this is the line's effect on the +/// balance as a reader sees it. +pub(crate) fn on_side(normal: Side, side: Side, amount: Decimal) -> Decimal { + match normal { + Side::Debit => signed_amount(side, amount), + Side::Credit => signed_amount(crate::kernel::flip(side), amount), + } +} + +/// `a + b` for figures built from posted lines, where the sum is always +/// exact (BS-entry-3, BS-entry-4 bound every line). A sum that could not +/// be held exactly is a broken ledger, so it panics rather than round. +/// Anything a caller can make too large uses [`add_exact`] instead. +pub(crate) fn add_in_range(a: Decimal, b: Decimal) -> Decimal { + crate::kernel::Amount::checked_add(a, b).expect("posted lines are in range, so their sums are") +} + +/// `a - b` for figures built from posted lines: see [`add_in_range`]. +pub(crate) fn sub_in_range(a: Decimal, b: Decimal) -> Decimal { + crate::kernel::Amount::checked_sub(a, b).expect("posted lines are in range, so their sums are") +} + impl fmt::Debug for Money { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} {}", self.amount, self.currency) @@ -267,9 +304,10 @@ impl Steps { if self.scale == self.minor { return Some(d); } - let mut d = d.normalize(); + let d = d.normalize(); if d.scale() < self.minor { - d.rescale(self.minor); + // Trailing zeros only, so never refused. + return Some(crate::kernel::rescale_exact(d, self.minor).unwrap_or(d)); } Some(d) } @@ -293,6 +331,56 @@ mod tests { Decimal::new(cents, 2) } + /// The sign helpers against the plain rule they stand for, on both + /// sides and both signs: a line counts as it is on the named side and + /// negated on the other, and a debit is the plus side of `signed`. + #[test] + fn sign_helpers_follow_the_side() { + for amount in [d(0), d(1), d(-1), d(123_456), d(-999)] { + assert_eq!(neg(amount), -amount); + assert_eq!(signed_amount(Side::Debit, amount), amount); + assert_eq!(signed_amount(Side::Credit, amount), -amount); + for normal in [Side::Debit, Side::Credit] { + for side in [Side::Debit, Side::Credit] { + let plain = if side == normal { amount } else { -amount }; + let got = on_side(normal, side, amount); + assert_eq!(got, plain); + // Bit for bit, the sign of a zero included. + assert_eq!(got.is_sign_negative(), plain.is_sign_negative()); + assert_eq!(got.scale(), plain.scale()); + } + } + } + } + + /// The in-range sum and difference are the raw operators' figures, + /// scale and the sign of a zero included. + #[test] + fn in_range_arithmetic_is_the_raw_operators() { + let figures = [ + d(0), + -d(0), + d(1), + d(-1), + Decimal::new(5, 1), + d(123_456), + Decimal::new(-7, 4), + ]; + for a in figures { + for b in figures { + for (got, plain) in [(add_in_range(a, b), a + b), (sub_in_range(a, b), a - b)] { + assert_eq!(got, plain); + assert_eq!( + got.is_sign_negative(), + plain.is_sign_negative(), + "{a} and {b}" + ); + assert_eq!(got.scale(), plain.scale(), "{a} and {b}"); + } + } + } + } + #[test] fn checked_arithmetic() { assert_eq!( diff --git a/crates/ledger-core/src/parties.rs b/crates/ledger-core/src/parties.rs index 7cb0db7f..194019cc 100644 --- a/crates/ledger-core/src/parties.rs +++ b/crates/ledger-core/src/parties.rs @@ -917,11 +917,9 @@ impl Activity { match basis { Basis::Cash => (self.paid, self.received), Basis::All => ( - self.paid - .checked_add(self.paid_in_kind) + crate::kernel::Amount::checked_add(self.paid, self.paid_in_kind) .expect("activity_with keeps the all-basis sums exact"), - self.received - .checked_add(self.received_in_kind) + crate::kernel::Amount::checked_add(self.received, self.received_in_kind) .expect("activity_with keeps the all-basis sums exact"), ), } @@ -1152,8 +1150,10 @@ pub fn entry_flow( // sum is checked, and one past exact arithmetic is refused. let too_large = || crate::LedgerError::TooLargeToCompute(format!("entry {}'s money flow", entry.id())); - let plus = |a: Decimal, b: Decimal| a.checked_add(b).ok_or_else(too_large); - let minus = |a: Decimal, b: Decimal| a.checked_sub(b).ok_or_else(too_large); + let plus = + |a: Decimal, b: Decimal| crate::kernel::Amount::checked_add(a, b).ok_or_else(too_large); + let minus = + |a: Decimal, b: Decimal| crate::kernel::Amount::checked_sub(a, b).ok_or_else(too_large); let (mut cash_cr, mut cash_dr, mut liab_cr, mut liab_dr) = (Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO); for l in entry.lines() { @@ -1199,13 +1199,13 @@ pub fn entry_flow( let (part, rest) = match l.side { Side::Debit => { let take = a.min(down_left); - down_left -= take; - (take, a - take) + down_left = minus(down_left, take)?; + (take, minus(a, take)?) } Side::Credit => { let take = a.min(up_left); - up_left -= take; - (-take, -(a - take)) + up_left = minus(up_left, take)?; + (crate::money::neg(take), crate::money::neg(minus(a, take)?)) } }; match left.iter_mut().find(|(x, _)| *x == l.account) { @@ -1214,10 +1214,7 @@ pub fn entry_flow( } part } else { - match l.side { - Side::Debit => a, - Side::Credit => -a, - } + crate::money::signed_amount(l.side, a) }; add(&mut by, &mut order, l.account, part)?; } @@ -1226,17 +1223,18 @@ pub fn entry_flow( .map(|(_, v)| *v) .filter(|v| *v > Decimal::ZERO) .try_fold(Decimal::ZERO, &plus)?; - let owed_up = -left - .iter() - .map(|(_, v)| *v) - .filter(|v| *v < Decimal::ZERO) - .try_fold(Decimal::ZERO, &plus)?; + let owed_up = crate::money::neg( + left.iter() + .map(|(_, v)| *v) + .filter(|v| *v < Decimal::ZERO) + .try_fold(Decimal::ZERO, &plus)?, + ); let across = owed_down.min(owed_up); let mut across_left = across; for (account, v) in left { if v > Decimal::ZERO && !across_left.is_zero() { let take = v.min(across_left); - across_left -= take; + across_left = minus(across_left, take)?; add(&mut by, &mut order, account, take)?; } } @@ -1298,7 +1296,7 @@ pub fn flow( if v.is_zero() { rust_decimal::Decimal::ZERO } else { - -v + crate::money::neg(v) } }; Ok(EntryFlow { @@ -1395,19 +1393,22 @@ pub fn activity_with( // the root original's side; every total, the all-basis sums // included, stays exact or the entry counts nothing. let next = match t.counts_as { - Direction::Paid => a - .paid - .checked_add(p.cash) - .zip(a.paid_in_kind.checked_add(p.in_kind)) + Direction::Paid => crate::kernel::Amount::checked_add(a.paid, p.cash) + .zip(crate::kernel::Amount::checked_add( + a.paid_in_kind, + p.in_kind, + )) .map(|(c, k)| (c, k, a.received, a.received_in_kind)), - _ => a - .received - .checked_sub(p.cash) - .zip(a.received_in_kind.checked_sub(p.in_kind)) + _ => crate::kernel::Amount::checked_sub(a.received, p.cash) + .zip(crate::kernel::Amount::checked_sub( + a.received_in_kind, + p.in_kind, + )) .map(|(c, k)| (a.paid, a.paid_in_kind, c, k)), }; match next.filter(|(pc, pk, rc, rk)| { - pc.checked_add(*pk).is_some() && rc.checked_add(*rk).is_some() + crate::kernel::Amount::checked_add(*pc, *pk).is_some() + && crate::kernel::Amount::checked_add(*rc, *rk).is_some() }) { Some((pc, pk, rc, rk)) => { a.paid = pc; diff --git a/crates/ledger-core/src/payouts.rs b/crates/ledger-core/src/payouts.rs index b63ecbbb..f7070690 100644 --- a/crates/ledger-core/src/payouts.rs +++ b/crates/ledger-core/src/payouts.rs @@ -17,7 +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::money::{add_exact, neg, on_side, sub_exact, sum_exact_of}; use crate::{AccountId, AccountType, ChartOfAccounts, ClassId, LedgerError, Side}; use rust_decimal::Decimal; @@ -170,10 +170,7 @@ pub fn payout_plan( 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, - }, + |a| on_side(Side::Credit, a.side, a.amount), "the payout's adjustments", )?; let expected = add_exact( @@ -193,7 +190,12 @@ pub fn payout_plan( if payout.deposit > Decimal::ZERO { plan.push((payout.deposit_account, Side::Debit, payout.deposit, None)); } else if payout.deposit < Decimal::ZERO { - plan.push((payout.deposit_account, Side::Credit, -payout.deposit, None)); + plan.push(( + payout.deposit_account, + Side::Credit, + neg(payout.deposit), + None, + )); } plan.extend( payout diff --git a/crates/ledger-core/src/payroll.rs b/crates/ledger-core/src/payroll.rs index 4b581a77..2da38aea 100644 --- a/crates/ledger-core/src/payroll.rs +++ b/crates/ledger-core/src/payroll.rs @@ -177,17 +177,19 @@ pub fn payroll_entry_plan( // exact, or refused here as TooLargeToCompute, never a panic. let gross = crate::kernel::total_of(lines.iter(), |l| l.gross_pay).ok_or_else(too_large)?; let employer = crate::kernel::total_try(lines.iter(), |l| { - l.ss_employer.checked_add(l.medicare_employer) + crate::kernel::Amount::checked_add(l.ss_employer, l.medicare_employer) }) .ok_or_else(too_large)?; let federal = crate::kernel::total_of(lines.iter(), |l| l.federal_withholding).ok_or_else(too_large)?; let state = crate::kernel::total_of(lines.iter(), |l| l.state_withholding).ok_or_else(too_large)?; - let ss = crate::kernel::total_try(lines.iter(), |l| l.ss_employee.checked_add(l.ss_employer)) - .ok_or_else(too_large)?; + let ss = crate::kernel::total_try(lines.iter(), |l| { + crate::kernel::Amount::checked_add(l.ss_employee, l.ss_employer) + }) + .ok_or_else(too_large)?; let medicare = crate::kernel::total_try(lines.iter(), |l| { - l.medicare_employee.checked_add(l.medicare_employer) + crate::kernel::Amount::checked_add(l.medicare_employee, l.medicare_employer) }) .ok_or_else(too_large)?; let other = diff --git a/crates/ledger-core/src/periods.rs b/crates/ledger-core/src/periods.rs index 4de68e29..948395ec 100644 --- a/crates/ledger-core/src/periods.rs +++ b/crates/ledger-core/src/periods.rs @@ -14,6 +14,7 @@ //! through the *next* open period (or a reversal dated in an open period). use crate::LedgerError; +use crate::money::neg; use chrono::NaiveDate; use serde::{Deserialize, Serialize}; @@ -145,7 +146,11 @@ pub fn try_allocate( let magnitude = amount.abs(); let exact: Vec = shares .iter() - .map(|s| magnitude.checked_mul(*s).ok_or_else(too_large)) + .map(|s| { + // The rounding product, as this rule has always computed it + // (posted closes replay with it); the shares sum to one. + crate::kernel::Amount::checked_mul_rounded(magnitude, *s).ok_or_else(too_large) + }) .collect::>()?; let mut parts: Vec = exact .iter() @@ -157,13 +162,13 @@ pub fn try_allocate( let remainders: Vec = exact .iter() .zip(&parts) - .map(|(e, p)| e.checked_sub(*p).ok_or_else(too_large)) + .map(|(e, p)| crate::kernel::Amount::checked_sub(*e, *p).ok_or_else(too_large)) .collect::>()?; crate::kernel::apportion(magnitude, &mut parts, &remainders, Decimal::new(1, 2)) .ok_or_else(too_large)?; if amount.is_sign_negative() { for p in &mut parts { - *p = -*p; + *p = neg(*p); } } Ok(parts) @@ -197,8 +202,8 @@ pub fn try_allocate_last_absorbs( let mut parts: Vec<_> = shares .iter() .map(|s| { - amount - .checked_mul(*s) + // The rounding product: this rule is frozen for replay. + crate::kernel::Amount::checked_mul_rounded(amount, *s) .and_then(|p| round_places(p, 2, Rounding::HalfAwayFromZero)) .ok_or_else(too_large) }) @@ -270,7 +275,10 @@ pub fn allocate_cumulative( } let loss = total < Decimal::ZERO; let magnitude = total.abs().normalize(); - let given: Vec = given.iter().map(|&g| if loss { -g } else { g }).collect(); + let given: Vec = given + .iter() + .map(|&g| if loss { neg(g) } else { g }) + .collect(); let mut parts = Vec::with_capacity(shares.len()); let mut remainders = Vec::with_capacity(shares.len()); for share in shares { @@ -278,8 +286,7 @@ pub fn allocate_cumulative( // Exact exactly when Decimal kept every digit: a product it had to // round comes back with fewer places than its factors carry (a // zero product, which it returns without places, is exact). - let exact = magnitude - .checked_mul(share) + let exact = crate::kernel::Amount::checked_mul(magnitude, share) .filter(|e| e.is_zero() || e.scale() == magnitude.scale() + share.scale()) .ok_or_else(|| { LedgerError::TooLargeToCompute(format!( @@ -290,7 +297,11 @@ pub fn allocate_cumulative( LedgerError::TooLargeToCompute(format!("a member's share {share} of {magnitude}")) })?; parts.push(floor); - remainders.push(exact - floor); + remainders.push(crate::money::sub_exact( + exact, + floor, + "a member's share of the period's income", + )?); } crate::kernel::apportion_cumulative( magnitude, @@ -302,7 +313,7 @@ pub fn allocate_cumulative( .ok_or_else(|| LedgerError::TooLargeToCompute(format!("the members' shares of {total}")))?; if loss { for p in parts.iter_mut().filter(|p| !p.is_zero()) { - *p = -*p; + *p = neg(*p); } } Ok(parts) diff --git a/crates/ledger-core/src/reports.rs b/crates/ledger-core/src/reports.rs index 1a2f88da..f49deec1 100644 --- a/crates/ledger-core/src/reports.rs +++ b/crates/ledger-core/src/reports.rs @@ -4,7 +4,10 @@ //! (`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::money::{ + add_exact, add_in_range, neg, on_side, signed_amount, sub_exact, sub_in_range, sum_exact, + sum_exact_of, sum_exact_try, +}; use crate::{AccountType, Class, ClassId, JournalEntry, JournalLine, Ledger, LedgerError}; use chrono::NaiveDate; use rust_decimal::Decimal; @@ -92,7 +95,8 @@ fn trial_balance_where(ledger: &Ledger, include: &dyn Fn(&JournalEntry) -> bool) for line in entry.lines() { let signed = crate::kernel::signed(line.side, line.amount.amount) .expect("Decimal negation is exact"); - *movements.entry(line.account).or_default() += signed; + let slot = movements.entry(line.account).or_default(); + *slot = add_in_range(*slot, signed); } } let mut accounts: Vec<_> = ledger.chart().all().collect(); @@ -110,8 +114,8 @@ fn trial_balance_where(ledger: &Ledger, include: &dyn Fn(&JournalEntry) -> bool) continue; } let (debit, credit) = crate::kernel::columns(movement).expect("Decimal negation is exact"); - total_debits += debit; - total_credits += credit; + total_debits = add_in_range(total_debits, debit); + total_credits = add_in_range(total_credits, credit); lines.push(TrialBalanceLine { code: account.code.clone(), name: account.name.clone(), @@ -140,7 +144,7 @@ pub struct ProfitAndLoss { impl ProfitAndLoss { /// Revenue minus expenses. Positive is profit. pub fn net_income(&self) -> Decimal { - self.revenue - self.expenses + sub_in_range(self.revenue, self.expenses) } } @@ -262,11 +266,11 @@ fn profit_and_loss_where( if account.placeholder { continue; } - let signed = if line.side == account.account_type.normal_side() { - line.amount.amount - } else { - -line.amount.amount - }; + let signed = on_side( + account.account_type.normal_side(), + line.side, + line.amount.amount, + ); match account.account_type { AccountType::Revenue => revenue = add_exact(revenue, signed, "total revenue")?, AccountType::Expense => expenses = add_exact(expenses, signed, "total expenses")?, @@ -297,7 +301,7 @@ pub struct BalanceSheet { impl BalanceSheet { /// The accounting equation: assets == liabilities + equity, exactly. pub fn balanced(&self) -> bool { - self.assets == self.liabilities + self.equity + crate::kernel::Amount::checked_add(self.liabilities, self.equity) == Some(self.assets) } } @@ -362,7 +366,7 @@ pub struct ProfitAndLossStatement { impl ProfitAndLossStatement { /// Revenue minus expenses. Positive is profit. pub fn net_income(&self) -> Decimal { - self.total_revenue - self.total_expenses + sub_in_range(self.total_revenue, self.total_expenses) } } @@ -391,7 +395,8 @@ pub struct BalanceSheetStatement { impl BalanceSheetStatement { /// The accounting equation: assets == liabilities + equity, exactly. pub fn balanced(&self) -> bool { - self.total_assets == self.total_liabilities + self.total_equity + crate::kernel::Amount::checked_add(self.total_liabilities, self.total_equity) + == Some(self.total_assets) } } @@ -408,10 +413,7 @@ fn statement_lines( if !include(entry, line) { continue; } - let signed = match line.side { - crate::Side::Debit => line.amount.amount, - crate::Side::Credit => -line.amount.amount, - }; + let signed = signed_amount(line.side, line.amount.amount); let slot = movement.entry(line.account).or_default(); *slot = add_exact(*slot, signed, "an account's movement")?; } @@ -425,10 +427,8 @@ fn statement_lines( if account.placeholder || m.is_zero() { continue; } - let amount = match account.account_type.normal_side() { - crate::Side::Debit => m, - crate::Side::Credit => -m, - }; + let amount = crate::kernel::normal_balance(account.account_type, m) + .expect("Decimal negation is exact"); out.insert( account.code.clone(), ( @@ -594,7 +594,7 @@ impl ProjectToDate { /// Revenue less expenses: the project's contribution before overhead /// (WB-statement-7), since only its own tagged lines count. pub fn net(&self) -> Decimal { - self.revenue - self.expenses + sub_in_range(self.revenue, self.expenses) } /// Its contribution margin to date: [`contribution_margin_pct`] of @@ -627,15 +627,15 @@ impl ProjectToDate { /// 3. NEVER panics: None when the quotient can't be represented. /// ``` pub fn contribution_margin_pct(contribution: Decimal, revenue: Decimal) -> Option { - let mut x = crate::kernel::percent_of( + let x = crate::kernel::percent_of( contribution, revenue, Decimal::new(1, 1), crate::kernel::Rounding::HalfToEven, )?; - // Display padding only: the margin always prints its one place. - x.rescale(1); - Some(x) + // Display padding only: the margin always prints its one place. It + // is a whole number of tenths, so writing it with one changes nothing. + Some(crate::kernel::rescale_exact(x, 1).unwrap_or(x)) } /// The most months [`ProjectFigures::months`] holds: the period's last. @@ -690,12 +690,13 @@ pub fn project_figures( // before them). let mut running = months .iter() - .try_fold(to_date.net(), |t, m| t.checked_sub(m.net())) + .try_fold(to_date.net(), |t, m| { + crate::kernel::Amount::checked_sub(t, m.net()) + }) .ok_or(LedgerError::AmountOutOfRange)?; let mut months_net_to_date = Vec::with_capacity(months.len()); for m in &months { - running = running - .checked_add(m.net()) + running = crate::kernel::Amount::checked_add(running, m.net()) .ok_or(LedgerError::AmountOutOfRange)?; months_net_to_date.push(running); } @@ -758,21 +759,18 @@ pub fn project_entries(ledger: &Ledger, id: ClassId) -> Vec<(crate::EntryId, Dec let Some(account) = ledger.chart().get(line.account) else { continue; }; - let debit = matches!(line.side, crate::Side::Debit); match account.account_type { AccountType::Revenue => { - amount += if debit { - -line.amount.amount - } else { - line.amount.amount - } + amount = add_in_range( + amount, + on_side(crate::Side::Credit, line.side, line.amount.amount), + ); } AccountType::Expense => { - amount -= if debit { - line.amount.amount - } else { - -line.amount.amount - } + amount = sub_in_range( + amount, + on_side(crate::Side::Debit, line.side, line.amount.amount), + ); } _ => {} } @@ -952,10 +950,7 @@ pub fn general_ledger( for entry in &entries { let lines = entry.lines(); for (i, line) in lines.iter().enumerate() { - let signed = match line.side { - crate::Side::Debit => line.amount.amount, - crate::Side::Credit => -line.amount.amount, - }; + let signed = signed_amount(line.side, line.amount.amount); if entry.date() < start { let slot = begin.entry(line.account).or_default(); *slot = add_exact(*slot, signed, "an account's beginning balance")?; @@ -1005,15 +1000,15 @@ pub fn general_ledger( continue; } let normal = account.account_type.normal_side(); - let to_normal = |m: Decimal| if normal == crate::Side::Debit { m } else { -m }; - let beginning_balance = to_normal(begin_movement) + Decimal::ZERO; + let to_normal = |m: Decimal| on_side(normal, crate::Side::Debit, m); + let beginning_balance = add_in_range(to_normal(begin_movement), Decimal::ZERO); let mut balance = beginning_balance; 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 = add_exact( balance, - if side == normal { amount } else { -amount }, + on_side(normal, side, amount), "an account's running balance", )?; total_debits = add_exact(total_debits, p.debit, "an account's total debits")?; @@ -1602,7 +1597,7 @@ impl AssetRegister { /// don't carry yet (run `run_depreciation`); negative if the books /// carry more. pub fn unposted_depreciation(&self) -> Decimal { - self.total_accumulated_scheduled - self.ledger_accumulated + sub_in_range(self.total_accumulated_scheduled, self.ledger_accumulated) } /// Accumulated depreciation in the accounts that no held asset's runs @@ -1610,14 +1605,14 @@ impl AssetRegister { /// from a run; otherwise an entry made by hand (or a run reversed /// after its asset left the books) is in them. pub fn unattributed_accumulated(&self) -> Decimal { - self.ledger_accumulated - self.total_accumulated_posted + sub_in_range(self.ledger_accumulated, self.total_accumulated_posted) } /// Cost in the ledger's cost accounts that no held asset accounts for /// (equipment bought but not registered), or negative if registered /// cost isn't in the books. pub fn unregistered_cost(&self) -> Decimal { - self.ledger_cost - self.total_cost + sub_in_range(self.ledger_cost, self.total_cost) } } @@ -1656,9 +1651,7 @@ pub fn register_row( let book_value = if disposed.is_some() { Decimal::ZERO } else { - a.cost - .amount - .checked_sub(post) + crate::kernel::Amount::checked_sub(a.cost.amount, post) .ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s book value", a.id)))? }; Ok(Some(AssetRegisterRow { @@ -1745,23 +1738,18 @@ pub fn fixed_asset_register( cost_accounts.insert(a.cost_account); accum_accounts.insert(a.accum_depr_account); if row.disposed.is_none() { - cost = cost - .checked_add(row.cost) + cost = crate::kernel::Amount::checked_add(cost, row.cost) .ok_or_else(|| too_large("cost"))?; - scheduled = scheduled - .checked_add(row.accumulated_scheduled) + scheduled = crate::kernel::Amount::checked_add(scheduled, row.accumulated_scheduled) .ok_or_else(|| too_large("accumulated depreciation"))?; - posted_total = posted_total - .checked_add(row.accumulated_posted) + posted_total = crate::kernel::Amount::checked_add(posted_total, row.accumulated_posted) .ok_or_else(|| too_large("posted depreciation"))?; match row.depreciable_basis { Some(b) => { - depreciable_total = depreciable_total - .checked_add(b) + depreciable_total = crate::kernel::Amount::checked_add(depreciable_total, b) .ok_or_else(|| too_large("depreciable basis"))?; if let Some(b) = row.tax_basis_723 { - total_723 = total_723 - .checked_add(b) + total_723 = crate::kernel::Amount::checked_add(total_723, b) .ok_or_else(|| too_large("§723 basis"))?; } } @@ -1779,7 +1767,7 @@ pub fn fixed_asset_register( tb.lines .iter() .find(|l| &l.code == code) - .map(|l| l.debit - l.credit) + .map(|l| sub_in_range(l.debit, l.credit)) .unwrap_or(Decimal::ZERO) }; Ok(AssetRegister { @@ -1788,17 +1776,16 @@ pub fn fixed_asset_register( total_cost: cost, total_accumulated_scheduled: scheduled, total_accumulated_posted: posted_total, - total_book_value: cost - .checked_sub(posted_total) + total_book_value: crate::kernel::Amount::checked_sub(cost, posted_total) .ok_or_else(|| too_large("book value"))?, total_depreciable_basis: depreciable_total, total_tax_basis_723: total_723, missing_basis: missing, ledger_cost: sum_exact_of(&cost_accounts, |&id| net(id), "the ledger's asset cost")?, - ledger_accumulated: -sum_exact_of( + ledger_accumulated: neg(sum_exact_of( &accum_accounts, |&id| net(id), "the ledger's accumulated depreciation", - )?, + )?), }) } diff --git a/crates/ledger-core/src/schedules.rs b/crates/ledger-core/src/schedules.rs index f267e85a..93c6becb 100644 --- a/crates/ledger-core/src/schedules.rs +++ b/crates/ledger-core/src/schedules.rs @@ -365,17 +365,24 @@ fn present_as_rounded(parts: &mut [Decimal], total: Decimal, places: u32) { let Some(&first) = rest.first() else { return; }; + // `rescale_exact` refuses to round: a figure that is not a whole + // number of the places asked for (none is: `even_parts` rounded each + // to the step) would be left as the kernel gave it. let mut each = first; if each.scale() > places || each.is_zero() { - each.rescale(places); - debug_assert_eq!(each, first, "rescaling an amount never changes it"); + let written = kernel::rescale_exact(each, places); + debug_assert!(written.is_some(), "a month is a whole number of steps"); + each = written.unwrap_or(each); } // Subtracting a zero (a month that rounded to nothing) leaves the // total as it was, scale included; any other subtrahend widens it. if !each.is_zero() { - let before = *last; - last.rescale(total.scale().max(each.scale())); - debug_assert_eq!(*last, before, "rescaling an amount never changes it"); + let written = kernel::rescale_exact(*last, total.scale().max(each.scale())); + debug_assert!( + written.is_some(), + "the last month is the total less whole steps" + ); + *last = written.unwrap_or(*last); } for part in rest.iter_mut() { *part = each; @@ -668,13 +675,15 @@ impl AmortizationSchedule { /// The amount not yet recognized: the sum of the plan's unposted /// months. pub fn remaining(&self) -> Result { - self.plan()? - .into_iter() - .filter(|(d, _)| !self.posted.contains(d)) - .try_fold(Decimal::ZERO, |sum, (_, a)| sum.checked_add(a)) - .ok_or_else(|| { - LedgerError::TooLargeToCompute(format!("schedule {}'s remaining amount", self.id)) - }) + crate::kernel::total_of( + self.plan()? + .into_iter() + .filter(|(d, _)| !self.posted.contains(d)), + |(_, a)| a, + ) + .ok_or_else(|| { + LedgerError::TooLargeToCompute(format!("schedule {}'s remaining amount", self.id)) + }) } } @@ -808,8 +817,7 @@ pub fn validate_recurring_journaled( Side::Debit => &mut debits, Side::Credit => &mut credits, }; - *total = total - .checked_add(money.amount) + *total = crate::kernel::Amount::checked_add(*total, money.amount) .ok_or_else(|| LedgerError::TooLargeToCompute("the recurring entry's total".into()))?; } if debits != credits { diff --git a/crates/ledger-core/src/settings.rs b/crates/ledger-core/src/settings.rs index 126031ec..b7cb089e 100644 --- a/crates/ledger-core/src/settings.rs +++ b/crates/ledger-core/src/settings.rs @@ -850,10 +850,11 @@ pub fn parse_share(name: &str, s: &str) -> Result { let s = s.trim(); let bad = || format!("member {name}: share {s:?} must be like \"50%\" or \"0.5\""); let share = match s.strip_suffix('%') { - Some(pct) => decimal(pct.trim()) - .ok_or_else(bad)? - .checked_div(Decimal::from(100)) - .ok_or_else(bad)?, + Some(pct) => crate::kernel::Amount::checked_div( + decimal(pct.trim()).ok_or_else(bad)?, + Decimal::from(100), + ) + .ok_or_else(bad)?, None => decimal(s).ok_or_else(bad)?, }; if share <= Decimal::ZERO || share > Decimal::ONE { @@ -1404,9 +1405,7 @@ fn check_members(list: &[Value]) -> Result, String> { } } if !members.is_empty() { - let total = members - .iter() - .try_fold(Decimal::ZERO, |t, m| t.checked_add(m.share)) + let total = crate::kernel::total_of(members.iter(), |m| m.share) .ok_or("member shares are too large to add")?; if total != Decimal::ONE { return Err(format!("member shares sum to {total}, not 100%")); diff --git a/crates/ledger-core/src/shares.rs b/crates/ledger-core/src/shares.rs index a304ffc6..5374283c 100644 --- a/crates/ledger-core/src/shares.rs +++ b/crates/ledger-core/src/shares.rs @@ -128,6 +128,7 @@ pub use crate::kernel::Direction; use crate::kernel::{self, PartyTarget}; +use crate::money::{neg, on_side}; use crate::{AccountId, AccountType, EntryId, JournalEntry, Ledger, LedgerError, PartyId, Side}; use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; @@ -257,7 +258,12 @@ pub fn check_shares_journaled( )); } any_percent = true; - percent += p; + percent = crate::kernel::Amount::checked_add(percent, p).ok_or_else(|| { + format!( + "party {}'s percent has too many digits to add up exactly", + s.party + ) + })?; } Share::Derived => {} } @@ -275,9 +281,7 @@ fn too_large(what: String) -> crate::LedgerError { /// The sum of `values`, or None past exact arithmetic. fn checked_sum(values: impl IntoIterator) -> Option { - values - .into_iter() - .try_fold(Decimal::ZERO, |s, v| s.checked_add(v)) + crate::kernel::total(values) } /// Split `magnitude` (non-negative) by `weights` (positive, any sum): each @@ -407,7 +411,7 @@ fn original_target( kind(a) == Some(AccountType::Asset) && !money.cash.contains(&a) && Some(a) != receivables }; let add = |t: &mut Decimal, v: Decimal| -> Result<(), LedgerError> { - *t = t.checked_add(v).ok_or_else(past_exact)?; + *t = crate::kernel::Amount::checked_add(*t, v).ok_or_else(past_exact)?; Ok(()) }; let zero = Decimal::ZERO; @@ -528,12 +532,13 @@ pub fn split( let parts: Vec = named .iter() .map(|m| { - checked_sum(entry.lines().iter().filter(|l| on(m, l.account)).map(|l| { - match l.side { - Side::Credit => l.amount.amount, - Side::Debit => -l.amount.amount, - } - })) + checked_sum( + entry + .lines() + .iter() + .filter(|l| on(m, l.account)) + .map(|l| on_side(Side::Credit, l.side, l.amount.amount)), + ) .map(|s| s.abs()) }) .collect::>() @@ -576,7 +581,7 @@ pub fn split( let left: Vec = sizes .iter() .zip(&in_kind_sizes) - .map(|(s, k)| s.checked_sub(*k)) + .map(|(s, k)| crate::kernel::Amount::checked_sub(*s, *k)) .collect::>() .ok_or_else(past_exact)?; let cash_sizes = if cash == checked_sum(left.iter().copied()).ok_or_else(past_exact)? { @@ -587,7 +592,7 @@ pub fn split( share_by(cash, &left, &order).ok_or_else(past_exact)? }; let negative = target.amount < Decimal::ZERO; - let signed = |v: Decimal| if negative && !v.is_zero() { -v } else { v }; + let signed = |v: Decimal| if negative && !v.is_zero() { neg(v) } else { v }; Ok(shares .iter() .enumerate() diff --git a/crates/ledger-core/src/tax.rs b/crates/ledger-core/src/tax.rs index f8e37bb0..3d5e4d80 100644 --- a/crates/ledger-core/src/tax.rs +++ b/crates/ledger-core/src/tax.rs @@ -12,6 +12,7 @@ //! Scope is deliberate, like fixed assets: no tax depreciation (MACRS, //! Section 179, bonus), no basis computations, no filing. Not tax advice. +use crate::money::{neg, sub_in_range}; use crate::{AccountType, Ledger, LedgerError}; use chrono::NaiveDate; use rust_decimal::Decimal; @@ -513,21 +514,29 @@ pub struct TaxSummary { impl TaxSummary { /// Book net income of the categorized accounts. pub fn book_net(&self) -> Decimal { - sum(&self.income, |l| l.book) - - sum(&self.cost_of_goods, |l| l.book) - - sum(&self.deductions, |l| l.book) + sub_in_range( + sub_in_range( + sum(&self.income, |l| l.book), + sum(&self.cost_of_goods, |l| l.book), + ), + sum(&self.deductions, |l| l.book), + ) } /// Income less deductible amounts, before the CPA's other adjustments. pub fn tax_net(&self) -> Decimal { - sum(&self.income, |l| l.tax) - - sum(&self.cost_of_goods, |l| l.tax) - - sum(&self.deductions, |l| l.tax) + sub_in_range( + sub_in_range( + sum(&self.income, |l| l.tax), + sum(&self.cost_of_goods, |l| l.tax), + ), + sum(&self.deductions, |l| l.tax), + ) } } fn sum(lines: &[TaxSummaryLine], f: fn(&TaxSummaryLine) -> Decimal) -> Decimal { - lines.iter().map(f).sum() + crate::kernel::total_of(lines, f).expect("posted lines are in range, so their sums are") } /// A category's line while it is being built, with the exact `(book, @@ -570,7 +579,7 @@ pub fn tax_summary( // Income from an expense-type account (e.g. a contra) counts with // its sign flipped, so returns reduce receipts. let book = if c.kind == TaxKind::Income && account.account_type == AccountType::Expense { - -line.amount + neg(line.amount) } else { line.amount }; @@ -593,9 +602,7 @@ pub fn tax_summary( (&mut build.line, &mut build.shares) }; entry.accounts.push(name); - entry.book = entry - .book - .checked_add(book) + entry.book = crate::kernel::Amount::checked_add(entry.book, book) .ok_or_else(|| too_large("book amount"))?; shares.push((book, pct)); } diff --git a/crates/ledger-core/src/tax_capital.rs b/crates/ledger-core/src/tax_capital.rs index a3c29a45..98bf0546 100644 --- a/crates/ledger-core/src/tax_capital.rs +++ b/crates/ledger-core/src/tax_capital.rs @@ -80,6 +80,7 @@ use crate::k1::{K1Kind, K1Row, k1_detail}; use crate::money::sum_exact_of; +use crate::money::{neg, signed_amount}; use crate::reports::MemberCapital; use crate::{AccountId, AssetId, AssetStatus, EntryId, Ledger, LedgerError, Side}; use chrono::NaiveDate; @@ -120,16 +121,11 @@ fn disposal_depreciation( }) else { return Ok(Decimal::ZERO); }; - e.lines() - .iter() - .filter(|l| l.account == a.expense_account) - .try_fold(Decimal::ZERO, |t, l| { - t.checked_add(match l.side { - Side::Debit => l.amount.amount, - Side::Credit => -l.amount.amount, - }) - }) - .ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s depreciation", a.id))) + crate::kernel::total_of( + e.lines().iter().filter(|l| l.account == a.expense_account), + |l| signed_amount(l.side, l.amount.amount), + ) + .ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s depreciation", a.id))) } /// A figure the books can't know, with what they do have. @@ -437,10 +433,7 @@ impl RunningSplit { weights.len() ))); } - let sum = weights - .iter() - .try_fold(Decimal::ZERO, |t, w| t.checked_add(*w)) - .ok_or_else(too_large)?; + let sum = crate::kernel::total_of(weights.iter(), |w| *w).ok_or_else(too_large)?; Ok((sum > Decimal::ZERO).then_some(sum)) } @@ -469,11 +462,14 @@ impl RunningSplit { } let mut exact = self.exact.clone(); for (x, w) in exact.iter_mut().zip(weights) { - *x = x - .checked_add(Self::share(whole, *w, sum)?) + // A sum of rounded quotients, itself rounded where 96 bits + // end (INVARIANT 4 is what that leaves): three thirds of 28 + // digits are no exact Decimal, so the exact sum would refuse + // every split by thirds. + *x = crate::kernel::Amount::checked_add_rounded(*x, Self::share(whole, *w, sum)?) .ok_or_else(too_large)?; } - let total = self.total.checked_add(whole).ok_or_else(too_large)?; + let total = crate::kernel::Amount::checked_add(self.total, whole).ok_or_else(too_large)?; // A loss is rounded as its magnitude, then negated; at a running // whole of zero, by the sign of this whole (INVARIANT 2). let sign = if total < Decimal::ZERO || (total.is_zero() && whole < Decimal::ZERO) { @@ -485,7 +481,13 @@ impl RunningSplit { // rounded down to the cent, what rounding took its remainder. let snapped: Vec = exact .iter() - .map(|x| round_places(x * sign, EXACT_PLACES, Rounding::HalfToEven)) + .map(|x| { + round_places( + crate::kernel::Amount::checked_mul(*x, sign)?, + EXACT_PLACES, + Rounding::HalfToEven, + ) + }) .collect::>() .ok_or_else(too_large)?; let mut parts: Vec = snapped @@ -493,10 +495,20 @@ impl RunningSplit { .map(|x| round_places(*x, 2, Rounding::TowardNegativeInfinity)) .collect::>() .ok_or_else(too_large)?; - let remainders: Vec = snapped.iter().zip(&parts).map(|(x, p)| x - p).collect(); - let given: Vec = self.given.iter().map(|g| g * sign).collect(); + let remainders: Vec = snapped + .iter() + .zip(&parts) + .map(|(x, p)| crate::kernel::Amount::checked_sub(*x, *p)) + .collect::>() + .ok_or_else(too_large)?; + let given: Vec = self + .given + .iter() + .map(|g| crate::kernel::Amount::checked_mul(*g, sign)) + .collect::>() + .ok_or_else(too_large)?; crate::kernel::apportion_cumulative( - total * sign, + crate::kernel::Amount::checked_mul(total, sign).ok_or_else(too_large)?, &mut parts, &remainders, Decimal::new(1, 2), @@ -504,8 +516,8 @@ impl RunningSplit { ) .ok_or_else(too_large)?; for (p, g) in parts.iter_mut().zip(self.given.iter_mut()) { - *p *= sign; - *g = g.checked_add(*p).ok_or_else(too_large)?; + *p = crate::kernel::Amount::checked_mul(*p, sign).ok_or_else(too_large)?; + *g = crate::kernel::Amount::checked_add(*g, *p).ok_or_else(too_large)?; } self.exact = exact; self.total = total; @@ -538,12 +550,16 @@ impl RunningSplit { let mut exact = self.exact.clone(); let mut given = self.given.clone(); for i in 0..n { - exact[i] = exact[i] - .checked_sub(Self::share(whole, weights[i], sum)?) - .ok_or_else(too_large)?; - given[i] = given[i].checked_sub(parts[i]).ok_or_else(too_large)?; + // The rounding difference `split`'s sum is the other half of. + exact[i] = crate::kernel::Amount::checked_sub_rounded( + exact[i], + Self::share(whole, weights[i], sum)?, + ) + .ok_or_else(too_large)?; + given[i] = + crate::kernel::Amount::checked_sub(given[i], parts[i]).ok_or_else(too_large)?; } - self.total = self.total.checked_sub(whole).ok_or_else(too_large)?; + self.total = crate::kernel::Amount::checked_sub(self.total, whole).ok_or_else(too_large)?; self.exact = exact; self.given = given; Ok(()) @@ -611,21 +627,17 @@ fn entry_wholes( // Distributions are negative lines; weights are what each took. let taken: Vec = by_member(K1Kind::Distribution)? .into_iter() - .map(|d| -d) + .map(neg) .collect(); if taken.iter().any(|t| *t > Decimal::ZERO) { - let property = e - .lines() - .iter() - .filter(|l| { + let property = crate::kernel::total_of( + e.lines().iter().filter(|l| { l.side == Side::Credit && crate::k1::is_property_account(ledger, cash, l.account) - }) - .try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount)) - .ok_or_else(too_large)?; - let total_taken = taken - .iter() - .try_fold(Decimal::ZERO, |t, x| t.checked_add(*x)) - .ok_or_else(too_large)?; + }), + |l| l.amount.amount, + ) + .ok_or_else(too_large)?; + let total_taken = crate::kernel::total_of(taken.iter(), |x| *x).ok_or_else(too_large)?; let property = property.min(total_taken); if property > Decimal::ZERO { out.push((DISTRIBUTED, property, taken)); @@ -736,14 +748,13 @@ fn entry_property( entry: &crate::JournalEntry, cash: &[AccountId], ) -> Result { - let pool = entry - .lines() - .iter() - .filter(|l| { + let pool = crate::kernel::total_of( + entry.lines().iter().filter(|l| { l.side == Side::Debit && crate::k1::is_property_account(ledger, cash, l.account) - }) - .try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount)) - .ok_or_else(too_large)?; + }), + |l| l.amount.amount, + ) + .ok_or_else(too_large)?; // Prepaid accounts: those a prepaid-expense schedule amortizes, and no // registered asset carries its cost in (INVARIANT 6). let prepaid_account = |id: AccountId| { @@ -751,17 +762,16 @@ fn entry_property( s.kind == crate::schedules::ScheduleKind::PrepaidExpense && s.balance_account == id }) && !ledger.registered_assets().any(|a| a.cost_account == id) }; - let prepaid = entry - .lines() - .iter() - .filter(|l| { + let prepaid = crate::kernel::total_of( + entry.lines().iter().filter(|l| { l.side == Side::Debit && crate::k1::is_property_account(ledger, cash, l.account) && prepaid_account(l.account) - }) - .try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount)) - .ok_or_else(too_large)?; - let pool = pool.checked_sub(prepaid).ok_or_else(too_large)?; + }), + |l| l.amount.amount, + ) + .ok_or_else(too_large)?; + let pool = crate::kernel::Amount::checked_sub(pool, 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() @@ -772,11 +782,14 @@ fn entry_property( // Its book amount in the entry: the value at contribution, which // the books recorded (D-41), or the book cost. let value = a.fmv_at_contribution().unwrap_or(a.cost.amount); - linked = linked.checked_add(value).ok_or_else(too_large)?; + linked = crate::kernel::Amount::checked_add(linked, value).ok_or_else(too_large)?; match contributed { - Some(g) => big = big.checked_add(g).ok_or_else(too_large)?, + Some(g) => big = crate::kernel::Amount::checked_add(big, g).ok_or_else(too_large)?, // No basis, or a purchase's basis on a contribution: unknown. - None => unknown = unknown.checked_add(value).ok_or_else(too_large)?, + None => { + unknown = + crate::kernel::Amount::checked_add(unknown, value).ok_or_else(too_large)? + } } } if linked > pool { @@ -787,11 +800,11 @@ fn entry_property( mismatch: Some((linked, pool)), }); } - let rest = pool.checked_sub(linked).ok_or_else(too_large)?; + let rest = crate::kernel::Amount::checked_sub(pool, linked).ok_or_else(too_large)?; Ok(EntryProperty { built_in_gain: big, prepaid, - without_basis: unknown.checked_add(rest).ok_or_else(too_large)?, + without_basis: crate::kernel::Amount::checked_add(unknown, rest).ok_or_else(too_large)?, mismatch: None, }) } @@ -855,8 +868,9 @@ fn span( book: pp, }); } - big[i] = big[i].checked_add(g).ok_or_else(too_large)?; - without[i] = without[i].checked_add(w).ok_or_else(too_large)?; + big[i] = crate::kernel::Amount::checked_add(big[i], g).ok_or_else(too_large)?; + without[i] = + crate::kernel::Amount::checked_add(without[i], w).ok_or_else(too_large)?; if let Some((linked, property)) = p.mismatch { prop_open[i].push(Open::LinkedValueExceedsEntry { entry: id, @@ -873,7 +887,8 @@ fn span( for i in 0..n { let book = part.get(DISTRIBUTED, i); if !book.is_zero() { - distributed[i] = distributed[i].checked_add(book).ok_or_else(too_large)?; + distributed[i] = crate::kernel::Amount::checked_add(distributed[i], book) + .ok_or_else(too_large)?; dist_open[i].push(Open::PropertyDistribution { entry: id, book }); } } @@ -888,13 +903,15 @@ fn span( if a.in_service_date <= end && !gone_before { in_service = true; } - let d = ledger - .depreciation_posted_between(a.id, start, end)? - .checked_add(disposal_depreciation(ledger, a, start, end)?) - .ok_or_else(too_large)?; - book_depr = book_depr.checked_add(d).ok_or_else(too_large)?; + let d = crate::kernel::Amount::checked_add( + ledger.depreciation_posted_between(a.id, start, end)?, + disposal_depreciation(ledger, a, start, end)?, + ) + .ok_or_else(too_large)?; + book_depr = crate::kernel::Amount::checked_add(book_depr, d).ok_or_else(too_large)?; if a.basis.as_ref().is_some_and(|b| b.rule.is_contribution()) { - contributed_depr = contributed_depr.checked_add(d).ok_or_else(too_large)?; + contributed_depr = + crate::kernel::Amount::checked_add(contributed_depr, d).ok_or_else(too_large)?; } } if in_service || !book_depr.is_zero() { @@ -930,10 +947,8 @@ fn span( None => TaxLine::complete(book.beginning), }; let contributions_property = TaxLine { - known: book - .contributions_property - .checked_sub(big[i]) - .and_then(|x| x.checked_sub(without[i])) + known: crate::kernel::Amount::checked_sub(book.contributions_property, big[i]) + .and_then(|x| crate::kernel::Amount::checked_sub(x, without[i])) .ok_or_else(too_large)?, open: std::mem::take(&mut prop_open[i]), notes: std::mem::take(&mut prop_notes[i]), @@ -957,20 +972,16 @@ fn span( notes: Vec::new(), }; let distributions = TaxLine { - known: book - .distributions - .checked_sub(distributed[i]) + known: crate::kernel::Amount::checked_sub(book.distributions, distributed[i]) .ok_or_else(too_large)?, open: std::mem::take(&mut dist_open[i]), notes: Vec::new(), }; - let known = beginning - .known - .checked_add(book.contributions_cash) - .and_then(|x| x.checked_add(contributions_property.known)) - .and_then(|x| x.checked_add(net_income.known)) - .and_then(|x| x.checked_add(other.known)) - .and_then(|x| x.checked_sub(distributions.known)) + let known = crate::kernel::Amount::checked_add(beginning.known, book.contributions_cash) + .and_then(|x| crate::kernel::Amount::checked_add(x, contributions_property.known)) + .and_then(|x| crate::kernel::Amount::checked_add(x, net_income.known)) + .and_then(|x| crate::kernel::Amount::checked_add(x, other.known)) + .and_then(|x| crate::kernel::Amount::checked_sub(x, distributions.known)) .ok_or_else(too_large)?; let ending = TaxLine { known, @@ -987,9 +998,7 @@ fn span( notes: Vec::new(), }; let reconciliation = Reconciliation { - beginning: book - .beginning - .checked_sub(beginning.known) + beginning: crate::kernel::Amount::checked_sub(book.beginning, beginning.known) .ok_or_else(too_large)?, built_in_gain_704c: big[i], property_without_basis: without[i], diff --git a/crates/ledger-core/tests/bookspec/traceability.rs b/crates/ledger-core/tests/bookspec/traceability.rs index 524b6cd5..0668c3eb 100644 --- a/crates/ledger-core/tests/bookspec/traceability.rs +++ b/crates/ledger-core/tests/bookspec/traceability.rs @@ -2340,7 +2340,7 @@ fn every_claim_is_backed() { } assert_eq!( EXCEPTIONS.len(), - 15, + 16, "the kernel exception list changes only on purpose" ); // No ordinary function may fall through the right-law check: the @@ -2519,6 +2519,11 @@ const EXCEPTIONS: &[(&str, &str, &str)] = &[ "a Kani harness and a law", "it is the Decimal/currency wrapper around `round_step`; the harnesses and law 40 are round_step's, and the bridge carries them to Decimal", ), + ( + "rescale_exact", + "a Kani harness and a law", + "it adds or drops trailing zeros and refuses anything else, so it has no arithmetic for whole-number money to model (an i64 amount has no places); bridge `rescale_exact_never_changes_the_value` checks the value, the sign and the two refusals over Decimal's whole range", + ), ( "split_by_weights_with", "a Kani harness and a law", @@ -2532,8 +2537,9 @@ const EXCEPTIONS: &[(&str, &str, &str)] = &[ /// `split_by_weights_with` allocate, so every harness proves their /// fixed-array helper; `round_places`, `round_minor` and `fx_booked_minor` /// are Decimal wrappers whose law is the inner function's; `Direction::key` -/// is a wire name and `MonthPart::is_valid` a range predicate, with no law -/// at all. A new name here is a deliberate widening, never a silent hole. +/// is a wire name, `MonthPart::is_valid` a range predicate and +/// `rescale_exact` a change of trailing zeros, with no law at all. A new +/// name here is a deliberate widening, never a silent hole. const SKIPPED: &[&str] = &[ "movements", "reversal", @@ -2542,6 +2548,7 @@ const SKIPPED: &[&str] = &[ "round_places", "round_minor", "fx_booked_minor", + "rescale_exact", "split_by_weights_with", ]; diff --git a/crates/ledger-core/tests/kernel_bridge/decimal_exact.rs b/crates/ledger-core/tests/kernel_bridge/decimal_exact.rs index bf93ee2d..6f9f576e 100644 --- a/crates/ledger-core/tests/kernel_bridge/decimal_exact.rs +++ b/crates/ledger-core/tests/kernel_bridge/decimal_exact.rs @@ -125,6 +125,42 @@ proptest! { prop_assert_eq!(got.is_some(), representable(&exact), "{} - {}", a, b); } + /// The rounding sum and difference (a running total of rounded shares, + /// K-U11): `rust_decimal`'s own, to the digit and the scale; the exact + /// figure wherever exact arithmetic gives one; and where it rounds, + /// within half a unit of the last place it keeps. + #[test] + fn the_rounding_sum_is_the_exact_one_wherever_that_exists((a, b) in arb_pair()) { + for (got, old, exact_op, exact) in [ + ( + Amount::checked_add_rounded(a, b), + Decimal::checked_add(a, b), + Amount::checked_add(a, b), + rat(a) + rat(b), + ), + ( + Amount::checked_sub_rounded(a, b), + Decimal::checked_sub(a, b), + Amount::checked_sub(a, b), + rat(a) - rat(b), + ), + ] { + prop_assert_eq!(shown(got), shown(old), "{} and {}", a, b); + if exact_op.is_some() { + prop_assert_eq!(shown(got), shown(exact_op), "{} and {}", a, b); + } + if let Some(r) = got { + let off = rat(r) - exact; + let half_unit = BigRational::new( + BigInt::from(1u8), + BigInt::from(2u8) * BigInt::from(10u8).pow(r.scale()), + ); + let off = if off < BigRational::from_integer(BigInt::from(0u8)) { -off } else { off }; + prop_assert!(off <= half_unit, "{} and {} gave {}", a, b, r); + } + } + } + /// Multiply: the same laws. #[test] fn mul_is_exact_or_none((a, b) in arb_pair()) { diff --git a/crates/ledger-core/tests/kernel_bridge/round.rs b/crates/ledger-core/tests/kernel_bridge/round.rs index 4967fe52..389ba034 100644 --- a/crates/ledger-core/tests/kernel_bridge/round.rs +++ b/crates/ledger-core/tests/kernel_bridge/round.rs @@ -258,6 +258,73 @@ proptest! { prop_assert_eq!(got.to_string(), want.to_string()); } } + + /// `rescale_exact` changes how an amount is written, never the + /// amount. Over Decimal's whole range, against whole-number + /// arithmetic that shares nothing with it: it refuses exactly when + /// the amount is no whole multiple of 10^-places, and what it returns + /// is the same value with the same sign, at `places` places or, where + /// 96 bits cannot hold it that wide, as many as they can. + #[test] + fn rescale_exact_never_changes_the_value( + mantissa in prop_oneof![ + -(1i128 << 60)..=(1i128 << 60), + -MAX_MANTISSA..=MAX_MANTISSA, + (0u32..=27, -9i128..=9).prop_map(|(zeros, digit)| digit * 10i128.pow(zeros)), + ], + scale in 0u32..=28, + places in 0u32..=28, + ) { + use num_bigint::BigInt; + let amount = Decimal::try_from_i128_with_scale(mantissa, scale).expect("in Decimal's range"); + let whole_multiple = places >= scale || mantissa % 10i128.pow(scale - places) == 0; + let got = ledger_core::kernel::rescale_exact(amount, places); + prop_assert_eq!(got.is_some(), whole_multiple, "{} at {} places", amount, places); + if let Some(written) = got { + // The same number: both mantissas brought to 28 places. + let at_28 = |m: i128, s: u32| BigInt::from(m) * BigInt::from(10u8).pow(28 - s); + prop_assert_eq!(at_28(written.mantissa(), written.scale()), at_28(mantissa, scale)); + prop_assert_eq!(written.is_sign_negative(), amount.is_sign_negative()); + let no_room = written.mantissa().unsigned_abs() * 10 > MAX_MANTISSA.unsigned_abs(); + prop_assert!( + written.scale() == places || (written.scale() < places && no_room), + "{} written as {} at {} places", amount, written, places + ); + } + } +} + +/// Decimal's largest mantissa: 96 bits. +const MAX_MANTISSA: i128 = (1i128 << 96) - 1; + +/// `rescale_exact` at the edges, each row checked by hand: the places a +/// figure prints with, a zero's sign, and the two refusals. +#[test] +fn rescale_exact_at_the_edges() { + use ledger_core::kernel::rescale_exact; + let text = + |amount: &str, places: u32| rescale_exact(parse(amount), places).map(|d| d.to_string()); + assert_eq!(text("100", 1).as_deref(), Some("100.0")); + assert_eq!(text("0.250", 2).as_deref(), Some("0.25")); + assert_eq!(text("0", 2).as_deref(), Some("0.00")); + assert_eq!(text("12.5", 1).as_deref(), Some("12.5")); + assert_eq!(text("-3.10", 1).as_deref(), Some("-3.1")); + // A digit would be lost: refused, where `Decimal::rescale` rounds. + assert_eq!(text("0.255", 2), None); + assert_eq!(text("-0.001", 2), None); + assert_eq!(text("1", 29), None); + // A negative zero keeps its sign and takes the places (a schedule's + // posted month is compared as text on replay). + let minus_zero = rescale_exact(-Decimal::ZERO, 2).unwrap(); + assert!(minus_zero.is_zero() && minus_zero.is_sign_negative()); + assert_eq!(minus_zero.scale(), 2); + // No room for two more places in 96 bits: as many as fit, the value + // untouched. + let wide = Decimal::from_i128_with_scale(MAX_MANTISSA, 0); + assert_eq!(rescale_exact(wide, 2), Some(wide)); + assert_eq!(rescale_exact(wide, 2).unwrap().scale(), 0); + let nearly = Decimal::from_i128_with_scale(MAX_MANTISSA / 10, 0); + assert_eq!(rescale_exact(nearly, 2).unwrap().scale(), 1); } /// The edge table, each row checked by hand. diff --git a/crates/ledger-core/tests/tax_capital.proptest-regressions b/crates/ledger-core/tests/tax_capital.proptest-regressions index 45fdd12b..08f7ae82 100644 --- a/crates/ledger-core/tests/tax_capital.proptest-regressions +++ b/crates/ledger-core/tests/tax_capital.proptest-regressions @@ -5,3 +5,4 @@ # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. cc 56101dd675399c931df47369972f415782f4cd0e6ea874c37ef655b9961b69cb # shrinks to n = 2, splits = [(28343, [4, 2, 0, 0]), (27468, [0, 1, 0, 0]), (82432, [2, 4, 0, 0]), (-19139, [1, 2, 0, 0])] +cc 9d3652b30f1cf76da6d8dad78a402ff774ddf30ea760574a8c1ebed15e684684 # shrinks to n = 2, splits = [(1, [4, 2, 0, 0], 1), (990, [0, 1, 0, 0], 1)] diff --git a/docs/proofs/k-u11.md b/docs/proofs/k-u11.md new file mode 100644 index 00000000..c976086c --- /dev/null +++ b/docs/proofs/k-u11.md @@ -0,0 +1,153 @@ +# K-U11: no Decimal arithmetic outside the kernel (ledger-core) + +Bar item 1 of `AGENTS.md` says money arithmetic lives in `kernel/` and +nowhere else. Until this unit nothing checked it, and it was not true. + +## What was measured + +`scripts/raw-decimal-arith.sh ` asks the compiler. It runs clippy +twice over the package's own source (tests and proof harnesses are not +compiled; `src/kernel/` is where arithmetic belongs), once flagging every +arithmetic operator and once with `Decimal` allowed, and prints the places +that drop out: those are the `Decimal` ones. It also prints every call to +one of rust_decimal's own arithmetic or rounding methods (`checked_add`, +`checked_mul`, `round_dp`, `rescale`, ...) and every `Iterator::sum` or +`product`. A call such as `a.checked_add(b)` on a `Decimal` is +rust_decimal's method even with the kernel's `Amount` in scope, since an +inherent method wins over a trait's; reading the source does not show +which one runs, and the compiler does. + +At 8ad55e82a it listed **210 places in ledger-core**. Two kinds of fault +sat behind them: + +- a raw operator (`+`, `-`, `*`, unary `-`) panics when the result does + not fit; +- rust_decimal's operators and its `checked_*` methods both return a + rounded answer when the exact one needs more than 96 bits, and say + nothing (K-U10, `docs/proofs/k-u10.md`). + +## What was done + +| Sites | Now | +|---|---| +| 199 | the kernel's `Amount` methods by their full path, `kernel::total` and `total_of` for hand-rolled sums, `kernel::normal_balance`, and `money.rs`'s helpers over the kernel: `neg`, `signed_amount`, `on_side` (a line's sign, said once), `add_in_range` and `sub_in_range` (sums of posted lines, exact by BS-entry-3 and BS-entry-4), `add_exact` and `sub_exact` (anything a caller can make too large: a `TooLargeToCompute`) | +| 2 | `Money::checked_add` and `checked_sub`: exact or `TooLargeToCompute` (K-U10a) | +| 3 | the frozen close rules (`periods::try_allocate`, `try_allocate_last_absorbs`) and `Ledger::member_close_split`: `Amount::checked_mul_rounded`, the product they have always computed, by name. Posted closes replay with the first two, so not a digit of them may move | +| 2 | the audit's check of a close (`audit::check_split`): the bound and the drift through `Amount`. A bound or a drift exact arithmetic cannot hold is raised as a finding, never passed | +| 4 | `kernel::rescale_exact`, new: see below | + +Two sites among the 199 were then moved again, on evidence (see "What +exact arithmetic refused"): the K-1 worksheet's running total adds and +subtracts through `Amount::checked_add_rounded` and `checked_sub_rounded`. + +The first 199 were rewritten by a script from the compiler's own line and +column for each site, so no site was copied by hand. The ones that needed +a decision are in that commit's message (a balance sheet that cannot add +liabilities and equity is not balanced; a template's shares, a party's +percents and a reconciliation's balances refuse where they panicked). + +No figure moves: every site computes what it computed. What changes is +the edge: a result past exact arithmetic is refused where it panicked or +was rounded. + +## What exact arithmetic refused + +The script ran before K-U10 landed, when `Amount::checked_add` on a +`Decimal` was rust_decimal's rounding sum. K-U10 made it exact or `None`, +and after the merge one test failed: +`tax_capital::tests::thirds_summed_are_the_cents_they_are`, with +`TooLargeToCompute("a member's tax-basis capital")`. + +The cause is not a wrong figure. A member's "exact" running total in the +K-1 worksheet (`tax_capital::RunningSplit`) is a sum of shares, each +`whole x weight / sum`, a quotient of 28 significant digits. Two thirds of +28 digits each do not add to a number 96 bits hold, so the exact sum +refuses every split by thirds. rust_decimal's sum rounded it at the last +digit, and INVARIANT 4 of that type was written for exactly that: the +total is snapped to ten places before a cent is taken from it. + +A sum of rounded quotients is a rounded figure by construction, as a +share's product is (K-U10, `checked_mul_rounded`). So the kernel names +that sum too: `Amount::checked_add_rounded` and `checked_sub_rounded`, +rust_decimal's own for `Decimal` and the plain operation for a machine +integer, called by `RunningSplit::split` and `unsplit` and by nothing +else. The bridge property +`the_rounding_sum_is_the_exact_one_wherever_that_exists` +(`tests/kernel_bridge/decimal_exact.rs`) checks, over `Decimal`'s whole +range: it is rust_decimal's figure to the digit and the scale, it is the +exact figure wherever exact arithmetic gives one, and where it rounds it +is within half a unit of the last place it keeps. + +Every other place that makes a figure of more than ten places outside the +kernel was then read for the same fault, since a test only catches the +ones it reaches: + +| Place | What happens to the long figure next | +|---|---| +| `form1099::vendor_part` (`share_of`) | rounded to the cent on the next line | +| `form1099::split_share` (`share_floor_with`) | floors and remainders stay inside the kernel (`apportion`) | +| `settings::parse_share` (a percent over 100) | summed by `kernel::total_of`; shares that sum to one never pass 10^28 at 28 places, so a valid set is never refused, and one that does not sum to one was refused before | +| `reports::contribution_margin_pct` (`percent_of`) | already rounded to one place by the kernel | +| `Ledger::member_close_split` (`checked_mul_rounded`) | read only by the audit, whose difference is raised as a finding when exact arithmetic cannot hold it | +| `tax_capital::RunningSplit` (`share_of`) | the case above | + +## `kernel::rescale_exact` + +Four places changed how many decimal places a figure is written with: +a contribution margin always prints one place ("100.0"), a schedule's +months print at the currency's places (the kernel returns 0.250 as it +came, the plan has always shown 0.25, and a posted month is compared as +text on replay), and `Money`'s step count prints the minor places. Each +called `Decimal::rescale`, which rounds half away from zero when asked for +fewer places than the value has. None of the four ever asked for that, +and a debug assertion said so; nothing stopped the next one. + +`rescale_exact(amount, places)` adds or drops trailing zeros and returns +`None` for anything else. It is the only place outside the kernel's own +rounding that writes a scale. + +It has no Kani harness and no Lean theorem, and is the sixteenth entry in +the traceability gate's exception list, for this reason: whole-number +money has no places, so there is nothing for an `i64` harness or a law +over the rationals to state. What carries it instead: + +| Bridge property (`tests/kernel_bridge/round.rs`) | Checks | +|---|---| +| `rescale_exact_never_changes_the_value` | over Decimal's whole range (96-bit mantissas, every scale and every target from 0 to 28), against whole-number arithmetic that shares no code with it: `None` exactly when the amount is no whole multiple of 10^-places; a result is the same number with the same sign, at `places` places or, where 96 bits cannot hold it that wide, as many as they can | +| `rescale_exact_at_the_edges` | the figures the four call sites print, a negative zero (it keeps its sign and takes the places), the refusals, and the largest mantissa | + +## The gate + +`just kernel-only` runs the detector over the crates named in the +justfile's `kernel_only_crates`, and the lint part of `just check` runs +it, so a new raw operator or rust_decimal method on a `Decimal` outside +the kernel fails the build. The list is ledger-core and the four outer +crates that were already at zero (ledger-cli, ledger-host, ledger-reader, +ledger-vault); the other six join it as K-U12 brings each to zero, and a +crate never leaves it. A waiver is an +`#[allow(clippy::arithmetic_side_effects)]` or +`#[allow(clippy::disallowed_methods)]` with a `reason`, and the detector +counts them on its last line so one cannot slip in unseen. There are none +in ledger-core. + +## What this does not show + +- That each site calls the *right* kernel function. The detector shows + that arithmetic goes through the kernel, not that a sum or product which + should round was not made exact (a refusal where there was a figure) or + the reverse. The engine's tests and the properties check the figures, + and they found one (above). Every multiplication and division outside + the kernel was read for this unit (eleven, listed by + `grep -n "Amount::checked_mul\|Amount::checked_div"`), and every place + a long figure is made (the table above). A sum of figures a caller + supplies with more than ten places each (settings, a template's shares) + is refused where exact arithmetic cannot hold it; that is K-U10's rule, + not a regression, and no such sum is rounded later. +- The K-1 worksheet's running split is still a prelude outside the kernel + (`plan/2026-11-09_TRIAGE.md`, P2.7): its rounding sum has a bridge + property, and the split built on it has no Kani harness or Lean theorem + yet. +- `Decimal::abs`, `normalize` and comparisons are not arithmetic and are + not flagged: none can round or overflow. +- Integer arithmetic on counts, indexes and step counts (`i128` steps in + `Steps`, day counts) is outside this detector. diff --git a/docs/testing.md b/docs/testing.md index 75db0e0e..277d16f9 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -28,6 +28,7 @@ promise. | Fuzzing | crash, hang, broken books (4); for `fuzz_store_replay` (validly chained journals with fuzz-chosen events): books that open must verify, and the viewer must accept exactly what the writer does | `fuzz/fuzz_targets/`, corpora in `fuzz/corpus/` | `just fuzz ` | 10 min each | weekly | | Miri | undefined behavior in our use of dependencies (4) | the core's unit, bridge, invariant tests (the exhaustive calendar walk aside) | `just miri` | ~4 min | on demand | | Golden | `tests/golden/fixture_company.json` (5) | `invariants.rs` | `just check` | <1s | every change | +| Kernel only | no `Decimal` arithmetic outside `src/kernel/`: no raw operator, none of rust_decimal's own arithmetic or rounding methods, no `Iterator::sum` (AGENTS.md, bar item 1; the proofs are about the kernel only) | `scripts/raw-decimal-arith.sh`, which asks clippy twice and compares; the crates held at zero are the justfile's `kernel_only_crates` (ledger-core, ledger-cli, ledger-host, ledger-reader, ledger-vault; the other six join as K-U12 brings each to zero) | `just kernel-only` (in `just check`, the lint part) | ~1 min warm, a few minutes cold (two clippy runs of the crate) | every change. A waiver is an `#[allow]` with a `reason`; the last line counts them, and ledger-core has none | | Dependencies | no crate in the lock file with a known vulnerability (RustSec) or yanked; none under a licence that does not fit MIT OR Apache-2.0; none from a source `deny.toml` does not name; none of our own unmaintained (4) | `deny.toml`, each exception with its reason and date | `just deny` (in `just check`, the lint part) | seconds, needs the network | every change, and weekly (`scheduled.yml`), since an advisory is published when it is, not when we push. First run, 2026-11-09: 23 advisories; closed by upgrades (quick-xml, rusqlite, rust_xlsxwriter, rmcp, rustls, tokio, zstd, pulldown-cmark) but two, lived with in `deny.toml` | | Notices | every crate the program links and every font it embeds, with the licence text each asks to travel with (1, the licence itself) | `THIRD-PARTY-NOTICES.txt`, written by cargo-about from `ledger-cli`'s manifest, by `scripts/notices-packaged.py` (the crates' own licence files, where cargo-about could only give a licence's standard text with a placeholder for the copyright line) and from the licence files beside the fonts | `just notices`; `just notices-check` (in `just check`, the lint part) | ~2 min (12 CPU-minutes: it reads every crate's files for licence text) | every change that touches a dependency or a font. `just notices` writes the file; `just notices-check` fails when a dependency changed and the file was not regenerated, and the fix is `just notices` and committing the result | | Benchmarks | a baseline (6) | `ledger-core/benches/books.rs`, `ledger-store/benches/store.rs` | `just bench` | ~2 min | none (no budget, by decision) | diff --git a/docs/verification.md b/docs/verification.md index 3c8feb66..2caf1fe5 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -1065,6 +1065,17 @@ kernel. What the proofs and their reviews found, beyond the tidying: never refused; they now prove both, from the rational alone. One refusal remains by design: a product that is not exact, rounded to a step of 27 or 28 places. `docs/proofs/k-u10.md` has the account. +- **No `Decimal` arithmetic outside the kernel, checked by the compiler + (K-U11).** Bar item 1 was a rule nothing enforced: 210 places in + ledger-core added, negated, multiplied or summed a `Decimal` outside + `kernel/`, by raw operators (which panic) or by rust_decimal's own + `checked_*` methods (which round silently). All go through the kernel + now and `just kernel-only`, in the lint part of `just check`, fails on + a new one. It found one more rounding figure to name: a running total + of 28-digit shares (`checked_add_rounded`), which exact addition + refused for every split by thirds. `kernel::rescale_exact` is the one + place a figure's written places change, and it refuses to round. + `docs/proofs/k-u11.md` has the account. - **The sweep changed no posted figure.** Every golden and existing test passed unchanged. `round_places` reproduces `round_dp_with_strategy` to the character except a negative-zero input (which no call site can @@ -1124,13 +1135,16 @@ Be precise about the claims: `checked_sub` and `checked_mul` for `Decimal` are exact or `None` (`tests/kernel_bridge/decimal_exact.rs`: `Some` exactly when the exact result is a `Decimal`), and a foreign amount at a rate is rounded once - from the exact product. Two operations round, each by name: + from the exact product. Three operations round, each by name: `checked_div` at 28 significant digits (K-U3's `finding_the_quotients_rounding_can_cross_a_step`, K-U5's `the_edges` - at `Decimal::MAX / 2`) and a share's `checked_mul_rounded`. Neither - edge is reachable by a posted line (the line cap is 10^15, and - schedules refuse totals of `EXACT_LIMIT` or more), so the laws hold at - the engine's inputs. Not proved by Kani: the 256-bit helpers, which + at `Decimal::MAX / 2`), a share's `checked_mul_rounded`, and a running + total of such shares, `checked_add_rounded` and `checked_sub_rounded` + (K-U11: the K-1 worksheet's running split, whose thirds of 28 digits + are no exact sum; `docs/proofs/k-u11.md`). Neither edge of the first + two is reachable by a posted line (the line cap is 10^15, and schedules + refuse totals of `EXACT_LIMIT` or more), so the laws hold at the + engine's inputs. Not proved by Kani: the 256-bit helpers, which rest on the bridge properties and unit tests against `num_bigint`. - **The FX overflow harness proves two concrete cases, not every overflow.** `fx_booked_refuses_overflow` proves `i64::MAX × 2` and diff --git a/justfile b/justfile index fafaf61d..3b01c422 100644 --- a/justfile +++ b/justfile @@ -37,6 +37,7 @@ check-shard shard: cargo clippy --workspace --all-targets -- -D warnings RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --quiet just server-only + just kernel-only just check-shards-agree just deny just notices-check @@ -58,6 +59,23 @@ check-shard shard: ;; esac +# The crates with no Decimal arithmetic outside the kernel. A crate joins +# this list when its count reaches zero (K-U12) and never leaves it. +kernel_only_crates := "ledger-core ledger-cli ledger-host ledger-reader ledger-vault" + +# Money arithmetic lives in the kernel and nowhere else (AGENTS.md, bar +# item 1). The compiler is asked (scripts/raw-decimal-arith.sh): a raw +# operator on a Decimal, one of rust_decimal's own arithmetic or rounding +# methods, or an Iterator::sum outside `src/kernel/` fails. Those panic or +# round where the kernel's operations are exact or refuse (K-U10), and the +# proofs are about the kernel only. +kernel-only: + #!/usr/bin/env bash + set -euo pipefail + for crate in {{kernel_only_crates}}; do + scripts/raw-decimal-arith.sh "$crate" + done + # What every dependency must be (deny.toml): free of known vulnerabilities # (the RustSec database, fetched now), not yanked, under a licence that # fits MIT OR Apache-2.0, and from crates.io or the bookspec repository.