merge: every report and book total goes through the kernel's checked sum (K-U4; branch t3/kernel-checked-totals, bc81b849; reviewed)

periods.rs conflicted with K-U2: the frozen replay rules delegate to
K-U4's checked twins, whose rounding now goes through K-U2's
round_places (so every rounding stays in the kernel); no figure changes.
The K-U4 note gains the review's list of bounded raw sums left, and the
caveat that the twin test checks delegation (the review's independent
20,000-case comparison found the twins identical).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-11-08 17:09:27 -07:00
commit 57d86b1920
25 files changed
+1184 -229

No files matched your search

+1 -3
View File
@@ -1064,9 +1064,7 @@ pub struct Invoice {
/// line as written (rules.md B-28), so its lines are bounded only by what
/// the version that wrote it checked.
pub fn document_total(lines: &[DocumentLine], what: &str) -> Result<Decimal, LedgerError> {
lines
.iter()
.try_fold(Decimal::ZERO, |sum, l| sum.checked_add(l.amount))
crate::kernel::total_of(lines, |l| l.amount)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{what}'s total")))
}
+12 -6
View File
@@ -333,7 +333,9 @@ pub fn check_equation(bs: &crate::reports::BalanceSheetStatement) -> Option<Find
/// Net income moved to equity by the closes dated through `through`:
/// revenue closed less expenses closed, read off the closing entries'
/// lines.
fn closed_net(ledger: &Ledger, through: NaiveDate) -> Decimal {
/// `None` when the sum is past exact arithmetic (the check is skipped, as
/// `articulation` skips a statement it cannot make).
fn closed_net(ledger: &Ledger, through: NaiveDate) -> Option<Decimal> {
let mut net = Decimal::ZERO;
for id in ledger.closing_entry_ids() {
let Some(e) = ledger.get_entry(id) else {
@@ -351,11 +353,11 @@ fn closed_net(ledger: &Ledger, through: NaiveDate) -> Decimal {
Side::Credit => -l.amount.amount,
};
if matches!(a.account_type, AccountType::Revenue | AccountType::Expense) {
net += signed;
net = crate::kernel::Amount::checked_add(net, signed)?;
}
}
}
net
Some(net)
}
fn articulation(ledger: &Ledger, through: NaiveDate) -> Option<Finding> {
@@ -369,7 +371,7 @@ fn articulation(ledger: &Ledger, through: NaiveDate) -> Option<Finding> {
check_articulation(
pnl.net_income(),
bs.current_earnings,
closed_net(ledger, through),
closed_net(ledger, through)?,
)
}
@@ -380,7 +382,8 @@ pub fn check_articulation(
current_earnings: Decimal,
closed: Decimal,
) -> Option<Finding> {
(net_income != current_earnings + closed).then(|| {
let explained = crate::kernel::Amount::checked_add(current_earnings, closed)?;
(net_income != explained).then(|| {
Finding::new(
"pnl_not_articulated",
Subject::Books,
@@ -522,7 +525,10 @@ fn schedules(ledger: &Ledger, through: NaiveDate) -> Vec<Finding> {
}
};
if let Some((first, _)) = months.first() {
let total: Decimal = months.iter().map(|(_, a)| *a).sum();
let total = crate::kernel::total_of(&months, |&(_, a)| a).map_or_else(
|| "a sum too large to compute".to_string(),
|t| t.to_string(),
);
out.push(Finding::new(
"schedule_behind",
Subject::Schedule(s.id),
+5 -7
View File
@@ -704,9 +704,7 @@ fn entry_buckets(
}
fn sum3(b: [Decimal; 3]) -> Result<Decimal, LedgerError> {
b[0].checked_add(b[1])
.and_then(|s| s.checked_add(b[2]))
.ok_or_else(|| LedgerError::TooLargeToCompute("a payment's buckets".into()))
kernel::total(b).ok_or_else(|| LedgerError::TooLargeToCompute("a payment's buckets".into()))
}
/// The vendor's part of `payment` when the entry names several parties:
@@ -768,13 +766,13 @@ fn split_share(b: [Decimal; 3], v: Decimal) -> Result<[Decimal; 3], LedgerError>
let mut part =
kernel::round_places(q, 2, kernel::Rounding::TowardZero).ok_or_else(too_large)?;
while times(part)? > num {
part -= cent;
part = part.checked_sub(cent).ok_or_else(too_large)?;
}
while times(part + cent)? <= num {
part += cent;
while times(part.checked_add(cent).ok_or_else(too_large)?)? <= num {
part = part.checked_add(cent).ok_or_else(too_large)?;
}
// The remainder, over the common denominator ap.
rems[i] = num - times(part)?;
rems[i] = num.checked_sub(times(part)?).ok_or_else(too_large)?;
parts[i] = part;
}
kernel::apportion(av, &mut parts, &rems, cent).ok_or_else(too_large)?;
+63 -34
View File
@@ -66,6 +66,8 @@
//! 3001 1,500): 1,500.00 property each, no cash.
//! ```
use crate::kernel::Amount;
use crate::money::{add_exact, sub_exact, sum_exact_of, sum_exact_try};
use crate::reports::{MemberCapital, members_equity};
use crate::{AccountId, AccountType, EntryId, Ledger, LedgerError, PartyId, Side};
use chrono::NaiveDate;
@@ -178,10 +180,16 @@ pub fn k1_detail(
{
if closings.contains(&e.id()) {
for (i, m) in members.iter().enumerate() {
let effect: Decimal = std::iter::once(m.capital_account)
.chain(m.distribution_account)
.map(|a| side_sum(e, Side::Credit, a) - side_sum(e, Side::Debit, a))
.sum();
let effect = sum_exact_try(
std::iter::once(m.capital_account).chain(m.distribution_account),
|a| {
Amount::checked_sub(
side_sum(e, Side::Credit, a).ok()?,
side_sum(e, Side::Debit, a).ok()?,
)
},
"a member's closing effect",
)?;
if !effect.is_zero() {
lines.push(K1Line {
member: i,
@@ -195,12 +203,12 @@ pub fn k1_detail(
}
lines.extend(entry_lines(ledger, e, members, cash, places)?);
}
let total = |i: usize, k: K1Kind| -> Decimal {
lines
.iter()
.filter(|l| l.member == i && l.kind == k)
.map(|l| l.amount)
.sum()
let total = |i: usize, k: K1Kind| -> Result<Decimal, LedgerError> {
sum_exact_of(
lines.iter().filter(|l| l.member == i && l.kind == k),
|l| l.amount,
"a member's K-1 contributions",
)
};
let rows = me
.members
@@ -211,30 +219,40 @@ pub fn k1_detail(
// Each entry's property is at most that member's credit in it,
// and contributions are those credits' sum: property never
// exceeds contributions, and is never negative.
let prop = total(i, K1Kind::PropertyContribution);
K1Row {
let prop = total(i, K1Kind::PropertyContribution)?;
Ok(K1Row {
name: col.name,
share: m.share,
beginning: col.beginning,
contributions_cash: col.contributions - prop,
contributions_cash: sub_exact(
col.contributions,
prop,
"a member's cash contributions",
)?,
contributions_property: prop,
net_income: col.net_income,
distributions: col.distributions,
other: col.other,
ending: col.ending,
}
})
})
.collect();
.collect::<Result<_, LedgerError>>()?;
Ok(K1Detail { rows, lines })
}
/// Σ of an entry's lines on `account`, on `side`.
fn side_sum(e: &crate::JournalEntry, side: Side, account: AccountId) -> Decimal {
e.lines()
.iter()
.filter(|l| l.side == side && l.account == account)
.map(|l| l.amount.amount)
.sum()
fn side_sum(
e: &crate::JournalEntry,
side: Side,
account: AccountId,
) -> Result<Decimal, LedgerError> {
sum_exact_of(
e.lines()
.iter()
.filter(|l| l.side == side && l.account == account),
|l| l.amount.amount,
"an entry's lines on an account",
)
}
/// One entry's contribution and distribution lines, as [`k1_detail`]
@@ -256,33 +274,44 @@ pub(crate) fn entry_lines(
kind,
amount,
};
let pool: Decimal = e
.lines()
.iter()
.filter(|l| l.side == Side::Debit && is_property_account(ledger, cash, l.account))
.map(|l| l.amount.amount)
.sum();
let pool = sum_exact_of(
e.lines()
.iter()
.filter(|l| l.side == Side::Debit && is_property_account(ledger, cash, l.account)),
|l| l.amount.amount,
"an entry's property debits",
)?;
// Contributions are credits to capital (members_equity's).
let credits: Vec<Decimal> = members
.iter()
.map(|m| side_sum(e, Side::Credit, m.capital_account))
.collect();
.collect::<Result<_, _>>()?;
let takes = share_property(pool, &credits, places)?;
let mut lines = Vec::new();
for (i, m) in members.iter().enumerate() {
let (credit, take) = (credits[i], takes[i]);
if !(credit - take).is_zero() {
lines.push(line(i, K1Kind::CashContribution, credit - take));
let cash_part = sub_exact(credit, take, "a member's cash contribution")?;
if !cash_part.is_zero() {
lines.push(line(i, K1Kind::CashContribution, cash_part));
}
if !take.is_zero() {
lines.push(line(i, K1Kind::PropertyContribution, take));
}
// Distributions: debits to capital, net debits to the
// distributions account (members_equity's).
let taken = side_sum(e, Side::Debit, m.capital_account)
+ m.distribution_account.map_or(Decimal::ZERO, |d| {
side_sum(e, Side::Debit, d) - side_sum(e, Side::Credit, d)
});
let from_distributions = match m.distribution_account {
None => Decimal::ZERO,
Some(d) => sub_exact(
side_sum(e, Side::Debit, d)?,
side_sum(e, Side::Credit, d)?,
"a member's distributions",
)?,
};
let taken = add_exact(
side_sum(e, Side::Debit, m.capital_account)?,
from_distributions,
"a member's distributions",
)?;
if !taken.is_zero() {
lines.push(line(i, K1Kind::Distribution, -taken));
}
+85 -3
View File
@@ -1,5 +1,87 @@
//! U4: totals, exact checked sums for books and reports (kernel sweep).
//!
//! Empty in U0: the unit adds its arithmetic here, in this file alone, so
//! no two sweep units ever edit the same file. The module root re-exports
//! it, keeping every path `crate::kernel::foo`.
//! The sum of a collection of money figures, in one place. A raw `Decimal`
//! `+`, `+=` or `.sum()` panics at `Decimal::MAX`; these return `None`
//! instead, so the caller can refuse with `TooLargeToCompute` and never
//! crash a book (rules.md B-28: a replayed journal line is accepted "of
//! any size", so a restored figure is the realistic path to the edge).
//! The signed sum of `(Side, amount)` lines is [`super::net`] and the pair
//! of columns [`super::totals`]; they were here first and stay the one
//! copy of that shape.
use super::Amount;
/// The exact sum of some figures: `None` the moment a running sum cannot
/// be represented, never a wrapped, rounded or panicking one.
///
/// ```text
/// GOAL: a book's or report's total is the exact sum of its figures, or
/// refused; no total is ever rounded, wrapped or a crash.
/// SOURCE: docs/spec/rules.md B-21 (amounts are exact; rounding is
/// confined to returns), B-28 (replayed lines are accepted "of any
/// size"; no input may reach a panic); bookspec BS-entry-3,
/// BS-entry-4; CONVENTION.
/// INVARIANTS:
/// 1. total([]) = Some(0).
/// 2. Some(s): s is the exact mathematical sum of the figures (every
/// running sum was representable, so no step lost anything).
/// 3. total(a ++ b) = total(a) + total(b) whenever the combined run
/// never leaves the representable range (always for amounts within
/// the line range and a few thousand of them). At the very edge the
/// sum is order dependent by design: [MAX, 1, -1] is None while
/// [MAX, -1, 1] is Some(MAX), because each step must be exact.
/// 4. None on overflow; NEVER a rounded or wrapped result, never a
/// panic. (Exactness is `Amount::checked_add`'s: `rust_decimal`
/// rounds sub-unit dust when a sum lands on `Decimal::MAX`; see
/// docs/proofs/k-u4.md, finding 1.)
/// ```
pub fn total<T: Amount>(values: impl IntoIterator<Item = T>) -> Option<T> {
let mut sum = T::ZERO;
for value in values {
sum = sum.checked_add(value)?;
}
Some(sum)
}
/// The exact sum of a figure drawn from each item (`f` of each), the shape
/// of `iter().map(f).sum()`: `total(map(f, items))`.
///
/// ```text
/// GOAL: the sum of a mapped field (a row's amount, a member's share) is
/// the exact sum of the mapping, or refused.
/// SOURCE: docs/spec/rules.md B-21, B-28; bookspec BS-entry-3,
/// BS-entry-4; CONVENTION.
/// INVARIANTS:
/// 1. total_of(items, f) = total(f(item) for item in items), exactly.
/// 2. None on overflow; NEVER a rounded or wrapped result.
/// ```
pub fn total_of<T: Amount, I>(
values: impl IntoIterator<Item = I>,
f: impl FnMut(I) -> T,
) -> Option<T> {
total(values.into_iter().map(f))
}
/// [`total_of`] for a mapping that can itself fail (a difference of two
/// figures, `c - d`, that may not be representable): `None` when `f` is
/// `None` for any item or the running sum overflows.
///
/// ```text
/// GOAL: the sum of a derived figure (a column's contributions less its
/// distributions) is exact, or refused.
/// SOURCE: docs/spec/rules.md B-21, B-28; bookspec BS-entry-3,
/// BS-entry-4; CONVENTION.
/// INVARIANTS:
/// 1. total_try(items, f) = Some(Σ f(item)) exactly when every f(item)
/// is Some and every running sum is representable; otherwise None.
/// ```
pub fn total_try<T: Amount, I>(
values: impl IntoIterator<Item = I>,
mut f: impl FnMut(I) -> Option<T>,
) -> Option<T> {
let mut sum = T::ZERO;
for value in values {
sum = sum.checked_add(f(value)?)?;
}
Some(sum)
}
+25 -9
View File
@@ -3822,17 +3822,26 @@ impl Ledger {
let shares: Vec<Decimal> = members.iter().map(|m| m.share).collect();
Ok(match to {
CloseTo::MembersLastAbsorbs(_) => (
periods::allocate_last_absorbs(net, &shares),
periods::try_allocate_last_absorbs(net, &shares)?,
MemberRule::LastAbsorbs,
),
CloseTo::MembersPerClose(_) => (periods::allocate(net, &shares), MemberRule::PerClose),
CloseTo::MembersPerClose(_) => {
(periods::try_allocate(net, &shares)?, MemberRule::PerClose)
}
CloseTo::MembersRun(_) => {
// The run rule: what the run gives each member with this
// close, less what it gave them before.
let before = self.member_close_run(&member_key(members));
let after = periods::allocate(before + net, &shares);
let prior = periods::allocate(before, &shares);
let parts = after.iter().zip(&prior).map(|(a, p)| a - p).collect();
let after = periods::try_allocate(
crate::money::add_exact(before, net, "the members' close run")?,
&shares,
)?;
let prior = periods::try_allocate(before, &shares)?;
let parts = after
.iter()
.zip(&prior)
.map(|(a, p)| crate::money::sub_exact(*a, *p, "the members' close run"))
.collect::<Result<_, _>>()?;
(parts, MemberRule::Run)
}
_ => {
@@ -3842,7 +3851,11 @@ impl Ledger {
let parts = if posts {
regime.allocate(
&key,
regime.closed + net,
crate::money::add_exact(
regime.closed,
net,
"the members' closed earnings",
)?,
&regime.given,
self.base_currency.allocation_places(),
)?
@@ -4045,7 +4058,8 @@ impl Ledger {
"a count of members closes starts at close 1 or later, not 0".into(),
));
}
let total: Decimal = members.iter().map(|m| m.share).sum();
let total =
crate::money::sum_exact_of(members, |m| m.share, "the members' shares")?;
if members.is_empty()
|| total != Decimal::ONE
|| members.iter().any(|m| m.share <= Decimal::ZERO)
@@ -6397,7 +6411,8 @@ impl Ledger {
return Err(LedgerError::TooLargeToCompute(format!("{doc}'s figures")));
}
};
let owed: Decimal = after[..=i].iter().sum();
let owed =
crate::money::sum_exact(after[..=i].iter().copied(), &format!("{doc}'s figures"))?;
let on = grid[i];
let payments: Vec<String> = self
.standing_payments(doc)
@@ -8416,7 +8431,8 @@ impl Ledger {
.ok_or(LedgerError::UnknownAccount(cash_account))?;
self.check_controls(&PAYROLL)?;
let payables = self.payroll_tax_payables();
let total: Decimal = payables.iter().map(|(_, b)| *b).sum();
let total =
crate::money::sum_exact_of(&payables, |(_, b)| *b, "the payroll taxes payable")?;
if total.is_zero() {
return Err(LedgerError::NothingToRemit);
}
+45
View File
@@ -153,6 +153,51 @@ impl Money {
}
}
/// The exact sum of some figures ([`crate::kernel::total`]), or
/// `TooLargeToCompute` naming `what` when a running sum cannot be held:
/// the engine's way to total a column without a raw `.sum()` that would
/// panic at `Decimal::MAX` (rules.md B-21, B-28).
pub fn sum_exact(
values: impl IntoIterator<Item = Decimal>,
what: &str,
) -> Result<Decimal, LedgerError> {
crate::kernel::total(values).ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string()))
}
/// [`sum_exact`] over a figure drawn from each item
/// ([`crate::kernel::total_of`]).
pub fn sum_exact_of<I>(
values: impl IntoIterator<Item = I>,
f: impl FnMut(I) -> Decimal,
what: &str,
) -> Result<Decimal, LedgerError> {
crate::kernel::total_of(values, f)
.ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string()))
}
/// [`sum_exact`] over a derived figure that can itself be unrepresentable
/// ([`crate::kernel::total_try`]).
pub fn sum_exact_try<I>(
values: impl IntoIterator<Item = I>,
f: impl FnMut(I) -> Option<Decimal>,
what: &str,
) -> Result<Decimal, LedgerError> {
crate::kernel::total_try(values, f)
.ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string()))
}
/// `a + b` exactly, or `TooLargeToCompute` naming `what` (a checked `+`).
pub fn add_exact(a: Decimal, b: Decimal, what: &str) -> Result<Decimal, LedgerError> {
crate::kernel::Amount::checked_add(a, b)
.ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string()))
}
/// `a - b` exactly, or `TooLargeToCompute` naming `what` (a checked `-`).
pub fn sub_exact(a: Decimal, b: Decimal, what: &str) -> Result<Decimal, LedgerError> {
crate::kernel::Amount::checked_sub(a, b)
.ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string()))
}
impl fmt::Debug for Money {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.amount, self.currency)
+15 -10
View File
@@ -17,6 +17,7 @@
//! no platform: callers (or a format-specific parser) supply the numbers
//! from the payout statement, which is the entry's receipt.
use crate::money::{add_exact, sub_exact, sum_exact_of};
use crate::{AccountId, AccountType, ChartOfAccounts, ClassId, LedgerError, Side};
use rust_decimal::Decimal;
@@ -165,23 +166,27 @@ pub fn payout_plan(
for a in &payout.adjustments {
check(a.account, a.amount, "adjustment", &[])?;
}
let gross: Decimal = payout.revenue.iter().map(|l| l.amount).sum();
let fees: Decimal = payout.fees.iter().map(|l| l.amount).sum();
let adjustments: Decimal = payout
.adjustments
.iter()
.map(|a| match a.side {
let gross = sum_exact_of(&payout.revenue, |l| l.amount, "the payout's revenue")?;
let fees = sum_exact_of(&payout.fees, |l| l.amount, "the payout's fees")?;
let adjustments = sum_exact_of(
&payout.adjustments,
|a| match a.side {
Side::Credit => a.amount,
Side::Debit => -a.amount,
})
.sum();
let expected = gross - fees + adjustments;
},
"the payout's adjustments",
)?;
let expected = add_exact(
sub_exact(gross, fees, "the payout's total")?,
adjustments,
"the payout's total",
)?;
if expected != payout.deposit {
return bad(format!(
"payout doesn't reconcile: gross {gross} − fees {fees} + adjustments \
{adjustments} = {expected}, but the deposit is {} (off by {})",
payout.deposit,
payout.deposit - expected
sub_exact(payout.deposit, expected, "the payout's difference")?
));
}
let mut plan = Vec::new();
+44 -9
View File
@@ -124,9 +124,25 @@ pub fn allocate(
amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal],
) -> Vec<rust_decimal::Decimal> {
try_allocate(amount, shares)
.expect("shares sum to 1, so the shortfall is under one cent per member")
}
/// [`allocate`], refusing with `TooLargeToCompute` instead of panicking
/// when a share of `amount` is beyond exact arithmetic (a replayed close
/// carries a journaled amount of any size, rules.md B-28). The same split,
/// to the cent, for every amount [`allocate`] accepts.
pub fn try_allocate(
amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal],
) -> Result<Vec<rust_decimal::Decimal>, LedgerError> {
use rust_decimal::Decimal;
let too_large = || LedgerError::TooLargeToCompute(format!("the members' shares of {amount}"));
let magnitude = amount.abs();
let exact: Vec<Decimal> = shares.iter().map(|s| magnitude * s).collect();
let exact: Vec<Decimal> = shares
.iter()
.map(|s| magnitude.checked_mul(*s).ok_or_else(too_large))
.collect::<Result<_, _>>()?;
let mut parts: Vec<Decimal> = exact
.iter()
.map(|e| {
@@ -134,15 +150,19 @@ pub fn allocate(
.expect("a cent place of a representable amount is representable")
})
.collect();
let remainders: Vec<Decimal> = exact.iter().zip(&parts).map(|(e, p)| e - p).collect();
let remainders: Vec<Decimal> = exact
.iter()
.zip(&parts)
.map(|(e, p)| e.checked_sub(*p).ok_or_else(too_large))
.collect::<Result<_, _>>()?;
crate::kernel::apportion(magnitude, &mut parts, &remainders, Decimal::new(1, 2))
.expect("shares sum to 1, so the shortfall is under one cent per member");
.ok_or_else(too_large)?;
if amount.is_sign_negative() {
for p in &mut parts {
*p = -*p;
}
}
parts
Ok(parts)
}
/// The rule closes used before 2026-10-13: each share rounded half away
@@ -152,16 +172,31 @@ pub fn allocate_last_absorbs(
amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal],
) -> Vec<rust_decimal::Decimal> {
try_allocate_last_absorbs(amount, shares).expect("allocated amounts are in range")
}
/// [`allocate_last_absorbs`], refusing with `TooLargeToCompute` instead of
/// panicking when `amount × share` or the plug is beyond exact arithmetic
/// (replay of a legacy close with a huge journaled amount, rules.md B-28).
/// The same split, to the cent, for every amount [`allocate_last_absorbs`]
/// accepts: this is the frozen rule, only its overflow now an error.
pub fn try_allocate_last_absorbs(
amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal],
) -> Result<Vec<rust_decimal::Decimal>, LedgerError> {
use crate::kernel::{Rounding, round_places};
let too_large = || LedgerError::TooLargeToCompute(format!("the members' shares of {amount}"));
let mut parts: Vec<_> = shares
.iter()
.map(|s| {
round_places(amount * s, 2, Rounding::HalfAwayFromZero)
.expect("a cent place of a representable amount is representable")
amount
.checked_mul(*s)
.and_then(|p| round_places(p, 2, Rounding::HalfAwayFromZero))
.ok_or_else(too_large)
})
.collect();
crate::kernel::plug_last(amount, &mut parts).expect("allocated amounts are in range");
parts
.collect::<Result<_, _>>()?;
crate::kernel::plug_last(amount, &mut parts).ok_or_else(too_large)?;
Ok(parts)
}
/// What one members close gives each member: [`allocate`]'s split of the
+126 -3
View File
@@ -1,5 +1,128 @@
//! U4 proof harnesses: exact totals (kernel sweep).
//!
//! Empty in U0: the unit adds its Kani harnesses here; `just prove` scans
//! every file in `proofs/`, so a harness needs no change to the module
//! root or the recipe.
//! `kernel::total`, `total_of` and `total_try` on `i64` (the engine runs
//! the same code on `Decimal`; `tests/kernel_bridge/total.rs` checks the
//! two agree). Fixed arrays throughout: no symbolic-length `Vec`, no
//! `copy_from_slice` (model-checking/kani#4904).
use super::{N, any_amount, any_side, wide};
use crate::Side;
use crate::kernel::{self, Amount};
/// Most figures in each of the two runs `total_append` joins.
const A: usize = 3;
fn any_count(max: usize) -> usize {
let n: usize = kani::any();
kani::assume(n <= max);
n
}
/// The exact sum of some `i64`s, in `i128`, the specification.
fn spec_sum(values: &[i64]) -> i128 {
values.iter().map(|&v| i128::from(v)).sum()
}
/// No figures total to zero, for `total`, `total_of` and `total_try`.
#[kani::proof]
fn total_empty_is_zero() {
let none: [i64; 0] = [];
assert_eq!(kernel::total(none), Some(0));
assert_eq!(kernel::total_of(none, |v: i64| v), Some(0));
assert_eq!(kernel::total_try(none, Some), Some(0));
}
/// A run appended to another totals to the sum of their totals: for any
/// in-range runs `a` and `b`, `total(a ++ b) = total(a) + total(b)`, and
/// all three are `Some` (the combined run never leaves the range).
#[kani::proof]
#[kani::unwind(8)]
fn total_append() {
let a_values: [i64; A] = core::array::from_fn(|_| any_amount());
let b_values: [i64; A] = core::array::from_fn(|_| any_amount());
let a = &a_values[..any_count(A)];
let b = &b_values[..any_count(A)];
// The concatenation, into a fixed array (no growth, no copy_from_slice).
let mut both = [0i64; 2 * A];
let mut at = 0;
for &v in a.iter().chain(b.iter()) {
both[at] = v;
at += 1;
}
let ta = kernel::total(a.iter().copied()).expect("in-range amounts never overflow");
let tb = kernel::total(b.iter().copied()).expect("in-range amounts never overflow");
let tab = kernel::total(both[..at].iter().copied()).expect("in-range amounts never overflow");
assert_eq!(Some(tab), ta.checked_add(tb));
kani::cover!(
!a.is_empty() && !b.is_empty() && tab != 0,
"two non-empty runs"
);
}
/// A total is exact whenever it exists, for *any* `i64` figures (the edge
/// included): `Some(s)` means `s` is the true sum, and `total` agrees with
/// a plain left-to-right checked fold.
#[kani::proof]
#[kani::unwind(5)]
fn total_is_sound() {
let all: [i64; 4] = core::array::from_fn(|_| kani::any());
let values = &all[..any_count(4)];
if let Some(s) = kernel::total(values.iter().copied()) {
assert_eq!(i128::from(s), spec_sum(values));
kani::cover!(values.len() > 1 && s != 0, "a nonempty exact total");
}
}
/// A total over a mapped figure is the sum of the mapping: with the line's
/// signed amount as the map, `total_of` is `net` (the signed sum of the
/// lines), and it is the exact sum of the signed amounts.
#[kani::proof]
#[kani::unwind(6)]
fn total_of_is_map_sum() {
let lines: [(Side, i64); N] = core::array::from_fn(|_| (any_side(), any_amount()));
let used = &lines[..any_count(N)];
let by_map = kernel::total_of(used.iter().copied(), |(side, amount)| {
kernel::signed(side, amount).expect("an in-range amount negates")
})
.expect("in-range amounts never overflow");
let spec: i64 = used.iter().map(|&(s, a)| wide(s, a)).sum();
assert_eq!(by_map, spec);
assert_eq!(Some(by_map), kernel::net(used.iter().copied()));
kani::cover!(used.len() > 1 && by_map != 0, "a nonzero signed sum");
}
/// A total over a fallible mapping (a difference of two figures) is the sum
/// of the differences, and `None` when a difference is not representable.
#[kani::proof]
#[kani::unwind(6)]
fn total_try_is_map_sum() {
let pairs: [(i64, i64); N] = core::array::from_fn(|_| (any_amount(), any_amount()));
let used = &pairs[..any_count(N)];
let got = kernel::total_try(used.iter().copied(), |(c, d)| c.checked_sub(d))
.expect("in-range differences never overflow");
let spec: i64 = used.iter().map(|&(c, d)| c - d).sum();
assert_eq!(got, spec);
kani::cover!(used.len() > 1 && got != 0, "a nonzero sum of differences");
// A mapping that fails fails the whole total, wherever it is.
let failing = kernel::total_try(used.iter().copied(), |_| None::<i64>);
assert_eq!(failing.is_none(), !used.is_empty());
}
/// Overflow is `None`, never a wrap: for any two `i64`s, their total
/// exists exactly when the true sum fits, and the overflow case is reached.
#[kani::proof]
fn total_overflow_is_none() {
let a: i64 = kani::any();
let b: i64 = kani::any();
let true_sum = i128::from(a) + i128::from(b);
let fits = true_sum >= i128::from(i64::MIN) && true_sum <= i128::from(i64::MAX);
let got = kernel::total([a, b]);
assert_eq!(got.is_some(), fits);
if let Some(s) = got {
assert_eq!(i128::from(s), true_sum);
}
kani::cover!(!fits && true_sum > 0, "overflow past the maximum");
kani::cover!(!fits && true_sum < 0, "overflow past the minimum");
kani::cover!(fits && a != 0 && b != 0, "an ordinary sum");
}
+145 -67
View File
@@ -4,6 +4,7 @@
//! (`docs/oracle.md`) diffs: the same fixture books through two engines must
//! produce byte-identical [`snapshot`] output.
use crate::money::{add_exact, sub_exact, sum_exact, sum_exact_of, sum_exact_try};
use crate::{AccountType, Class, ClassId, JournalEntry, JournalLine, Ledger, LedgerError};
use chrono::NaiveDate;
use rust_decimal::Decimal;
@@ -267,8 +268,8 @@ fn profit_and_loss_where(
-line.amount.amount
};
match account.account_type {
AccountType::Revenue => revenue += signed,
AccountType::Expense => expenses += signed,
AccountType::Revenue => revenue = add_exact(revenue, signed, "total revenue")?,
AccountType::Expense => expenses = add_exact(expenses, signed, "total expenses")?,
_ => {}
}
}
@@ -311,14 +312,16 @@ pub fn balance_sheet(ledger: &Ledger) -> Result<BalanceSheet, LedgerError> {
}
let balance = ledger.account_balance(account.id)?;
match account.account_type {
AccountType::Asset => assets += balance,
AccountType::Liability => liabilities += balance,
AccountType::Equity => equity += balance,
AccountType::Asset => assets = add_exact(assets, balance, "total assets")?,
AccountType::Liability => {
liabilities = add_exact(liabilities, balance, "total liabilities")?
}
AccountType::Equity => equity = add_exact(equity, balance, "total equity")?,
AccountType::Revenue | AccountType::Expense => {}
}
}
let current_earnings = unclosed_earnings(ledger)?.net_income();
equity += current_earnings;
equity = add_exact(equity, current_earnings, "total equity")?;
Ok(BalanceSheet {
assets,
liabilities,
@@ -409,7 +412,8 @@ fn statement_lines(
crate::Side::Debit => line.amount.amount,
crate::Side::Credit => -line.amount.amount,
};
*movement.entry(line.account).or_default() += signed;
let slot = movement.entry(line.account).or_default();
*slot = add_exact(*slot, signed, "an account's movement")?;
}
}
let mut out = BTreeMap::new();
@@ -514,8 +518,8 @@ fn profit_and_loss_counted(
_ => {}
}
}
let total_revenue = revenue.iter().map(|l| l.amount).sum();
let total_expenses = expenses.iter().map(|l| l.amount).sum();
let total_revenue = sum_exact_of(&revenue, |l| l.amount, "total revenue")?;
let total_expenses = sum_exact_of(&expenses, |l| l.amount, "total expenses")?;
Ok((
ProfitAndLossStatement {
start,
@@ -820,13 +824,21 @@ pub fn balance_sheet_as_of(
AccountType::Asset => assets.push(line),
AccountType::Liability => liabilities.push(line),
AccountType::Equity => equity.push(line),
AccountType::Revenue => current_earnings += line.amount,
AccountType::Expense => current_earnings -= line.amount,
AccountType::Revenue => {
current_earnings = add_exact(current_earnings, line.amount, "current earnings")?
}
AccountType::Expense => {
current_earnings = sub_exact(current_earnings, line.amount, "current earnings")?
}
}
}
let total_assets = assets.iter().map(|l| l.amount).sum();
let total_liabilities = liabilities.iter().map(|l| l.amount).sum();
let total_equity = equity.iter().map(|l| l.amount).sum::<Decimal>() + current_earnings;
let total_assets = sum_exact_of(&assets, |l| l.amount, "total assets")?;
let total_liabilities = sum_exact_of(&liabilities, |l| l.amount, "total liabilities")?;
let total_equity = add_exact(
sum_exact_of(&equity, |l| l.amount, "total equity")?,
current_earnings,
"total equity",
)?;
Ok(BalanceSheetStatement {
as_of,
assets,
@@ -949,7 +961,8 @@ pub fn general_ledger(
crate::Side::Credit => -line.amount.amount,
};
if entry.date() < start {
*begin.entry(line.account).or_default() += signed;
let slot = begin.entry(line.account).or_default();
*slot = add_exact(*slot, signed, "an account's beginning balance")?;
continue;
}
if entry.date() > end {
@@ -1002,9 +1015,13 @@ pub fn general_ledger(
let (mut total_debits, mut total_credits) = (Decimal::ZERO, Decimal::ZERO);
let mut posted = Vec::with_capacity(lines.len());
for (side, amount, mut p) in lines {
balance += if side == normal { amount } else { -amount };
total_debits += p.debit;
total_credits += p.credit;
balance = add_exact(
balance,
if side == normal { amount } else { -amount },
"an account's running balance",
)?;
total_debits = add_exact(total_debits, p.debit, "an account's total debits")?;
total_credits = add_exact(total_credits, p.credit, "an account's total credits")?;
p.balance = balance;
posted.push(p);
}
@@ -1184,7 +1201,7 @@ pub fn members_equity(
return Err(LedgerError::InvalidMembers("no members given".to_string()));
}
let shares: Vec<Decimal> = members.iter().map(|m| m.share).collect();
let total_share: Decimal = shares.iter().sum();
let total_share = sum_exact(shares.iter().copied(), "the members' shares")?;
if total_share != Decimal::ONE || shares.iter().any(|s| *s <= Decimal::ZERO) {
return Err(LedgerError::InvalidMembers(format!(
"member shares must be positive and sum to 1, got {total_share}"
@@ -1214,23 +1231,23 @@ pub fn members_equity(
let end_bs = balance_sheet_as_of(ledger, end)?;
// Capital account balances before the period, and their movement in it.
let capital_before = |id: crate::AccountId| -> Decimal {
let capital_before = |id: crate::AccountId| -> Result<Decimal, LedgerError> {
let mut m = Decimal::ZERO;
for e in ledger.posted_entries().filter(|e| e.date() < start) {
for l in e.lines().iter().filter(|l| l.account == id) {
match l.side {
crate::Side::Credit => m += l.amount.amount,
crate::Side::Debit => m -= l.amount.amount,
}
m = match l.side {
crate::Side::Credit => add_exact(m, l.amount.amount, "a member's capital")?,
crate::Side::Debit => sub_exact(m, l.amount.amount, "a member's capital")?,
};
}
}
m
Ok(m)
};
// Contributions and distributions move a capital account; a closing
// entry allocating earnings into it is income, already counted below.
let closings = ledger.closing_entry_ids();
let cancelled = cancelled_in_span(ledger, start, end);
let flows = |id: crate::AccountId| -> (Decimal, Decimal) {
let flows = |id: crate::AccountId| -> Result<(Decimal, Decimal), LedgerError> {
let (mut credits, mut debits) = (Decimal::ZERO, Decimal::ZERO);
for e in ledger.posted_entries().filter(|e| {
e.date() >= start
@@ -1240,35 +1257,48 @@ pub fn members_equity(
}) {
for l in e.lines().iter().filter(|l| l.account == id) {
match l.side {
crate::Side::Credit => credits += l.amount.amount,
crate::Side::Debit => debits += l.amount.amount,
crate::Side::Credit => {
credits = add_exact(credits, l.amount.amount, "a member's contributions")?
}
crate::Side::Debit => {
debits = add_exact(debits, l.amount.amount, "a member's distributions")?
}
}
}
}
(credits, debits)
Ok((credits, debits))
};
// A member's capital is their capital account plus their distributions
// account (a debit balance, so it reduces capital).
let capital: Vec<Decimal> = members
.iter()
.map(|m| {
capital_before(m.capital_account)
+ m.distribution_account.map_or(Decimal::ZERO, capital_before)
add_exact(
capital_before(m.capital_account)?,
m.distribution_account
.map_or(Ok(Decimal::ZERO), capital_before)?,
"a member's capital",
)
})
.collect();
.collect::<Result<_, _>>()?;
// (contributions, distributions): credits to capital are
// contributions; debits to capital and net debits to the distributions
// account are distributions.
let flow: Vec<(Decimal, Decimal)> = members
.iter()
.map(|m| {
let (credits, debits) = flows(m.capital_account);
let (credits, debits) = flows(m.capital_account)?;
let (dc, dd) = m
.distribution_account
.map_or((Decimal::ZERO, Decimal::ZERO), flows);
(credits, debits + dd - dc)
.map_or(Ok((Decimal::ZERO, Decimal::ZERO)), flows)?;
let distributions = sub_exact(
add_exact(debits, dd, "a member's distributions")?,
dc,
"a member's distributions",
)?;
Ok((credits, distributions))
})
.collect();
.collect::<Result<_, LedgerError>>()?;
// Everything in equity that isn't a capital account is partnership
// earnings not yet distributed. Each member's share of it is allocated
@@ -1276,26 +1306,30 @@ pub fn members_equity(
// depends on which statement shows it: one statement's ending is the
// next one's beginning, to the minor unit (a capital account is one
// running balance: Treas. Reg. §1.704-1(b)(2)(iv)(b)).
let capital_through = |id: crate::AccountId, through: NaiveDate| -> Decimal {
let mut m = Decimal::ZERO;
for e in ledger.posted_entries().filter(|e| e.date() <= through) {
for l in e.lines().iter().filter(|l| l.account == id) {
match l.side {
crate::Side::Credit => m += l.amount.amount,
crate::Side::Debit => m -= l.amount.amount,
let capital_through =
|id: crate::AccountId, through: NaiveDate| -> Result<Decimal, LedgerError> {
let mut m = Decimal::ZERO;
for e in ledger.posted_entries().filter(|e| e.date() <= through) {
for l in e.lines().iter().filter(|l| l.account == id) {
m = match l.side {
crate::Side::Credit => add_exact(m, l.amount.amount, "a member's capital")?,
crate::Side::Debit => sub_exact(m, l.amount.amount, "a member's capital")?,
};
}
}
}
m
};
Ok(m)
};
let capital_end: Vec<Decimal> = members
.iter()
.map(|m| {
capital_through(m.capital_account, end)
+ m.distribution_account
.map_or(Decimal::ZERO, |d| capital_through(d, end))
add_exact(
capital_through(m.capital_account, end)?,
m.distribution_account
.map_or(Ok(Decimal::ZERO), |d| capital_through(d, end))?,
"a member's capital",
)
})
.collect();
.collect::<Result<_, _>>()?;
// As of a date, a member's share of the earnings not yet in capital is
// what the next members close would give them of it: their split of
// everything closed to these members and shares (the regime's closes
@@ -1313,38 +1347,76 @@ pub fn members_equity(
let nothing = vec![Decimal::ZERO; members.len()];
let unclosed_share = |undistributed: Decimal, regime: &crate::ledger::Regime| {
let closed = regime.allocate(&key, regime.closed, &nothing, places)?;
regime.allocate(&key, regime.closed + undistributed, &closed, places)
let whole = add_exact(regime.closed, undistributed, "the members' closed earnings")?;
regime.allocate(&key, whole, &closed, places)
};
let end_regime = ledger.members_regime(&key, Some(end));
let begin_alloc = unclosed_share(
begin_bs.total_equity - capital.iter().sum::<Decimal>(),
sub_exact(
begin_bs.total_equity,
sum_exact(capital.iter().copied(), "the members' capital")?,
"the members' undistributed earnings",
)?,
&ledger.members_regime(&key, Some(day_before)),
)?;
let end_alloc = unclosed_share(
end_bs.total_equity - capital_end.iter().sum::<Decimal>(),
sub_exact(
end_bs.total_equity,
sum_exact(capital_end.iter().copied(), "the members' capital")?,
"the members' undistributed earnings",
)?,
&end_regime,
)?;
let explained = flow.iter().map(|(c, d)| c - d).sum::<Decimal>() + pnl.net_income();
let explained = add_exact(
sum_exact_try(
flow.iter(),
|&(c, d)| crate::kernel::Amount::checked_sub(c, d),
"the members' net contributions",
)?,
pnl.net_income(),
"the period's explained equity",
)?;
// "Other" is split anew on each statement, its tied unit to the member
// the count as of `end` lists first, as the ending's are: a reorder of
// the members in the settings moves no cent between their other (and
// so their income) either.
let other_alloc = end_regime.allocate(
&key,
end_bs.total_equity - begin_bs.total_equity - explained,
sub_exact(
sub_exact(
end_bs.total_equity,
begin_bs.total_equity,
"the change in equity",
)?,
explained,
"the change in equity",
)?,
&nothing,
places,
)?;
let mut cols = Vec::with_capacity(members.len());
for (i, m) in members.iter().enumerate() {
let beginning = capital[i] + begin_alloc[i];
let ending = capital_end[i] + end_alloc[i];
let beginning = add_exact(capital[i], begin_alloc[i], "a member's beginning capital")?;
let ending = add_exact(capital_end[i], end_alloc[i], "a member's ending capital")?;
let (contributions, distributions) = flow[i];
// The member's income is what the roll-forward leaves: their share
// of the period's income, give or take the rounding cent that keeps
// the running balance exact. The members' incomes sum to net income.
let income = ending - beginning - contributions + distributions - other_alloc[i];
let too_large = "a member's income";
let income = sub_exact(
add_exact(
sub_exact(
sub_exact(ending, beginning, too_large)?,
contributions,
too_large,
)?,
distributions,
too_large,
)?,
other_alloc[i],
too_large,
)?;
cols.push(MemberEquityColumn {
name: m.name.clone(),
beginning: zero_clean(beginning),
@@ -1355,15 +1427,17 @@ pub fn members_equity(
ending: zero_clean(ending),
});
}
let sum = |f: fn(&MemberEquityColumn) -> Decimal| cols.iter().map(f).sum::<Decimal>();
let sum = |f: fn(&MemberEquityColumn) -> Decimal| {
sum_exact_of(&cols, f, "the members' equity totals")
};
let total = MemberEquityColumn {
name: "Total".to_string(),
beginning: sum(|c| c.beginning),
contributions: sum(|c| c.contributions),
net_income: sum(|c| c.net_income),
distributions: sum(|c| c.distributions),
other: sum(|c| c.other),
ending: sum(|c| c.ending),
beginning: sum(|c| c.beginning)?,
contributions: sum(|c| c.contributions)?,
net_income: sum(|c| c.net_income)?,
distributions: sum(|c| c.distributions)?,
other: sum(|c| c.other)?,
ending: sum(|c| c.ending)?,
};
debug_assert_eq!(total.ending, end_bs.total_equity);
Ok(MembersEquityStatement {
@@ -1724,7 +1798,11 @@ pub fn fixed_asset_register(
total_depreciable_basis: depreciable_total,
total_tax_basis_723: total_723,
missing_basis: missing,
ledger_cost: cost_accounts.iter().map(|&id| net(id)).sum(),
ledger_accumulated: -accum_accounts.iter().map(|&id| net(id)).sum::<Decimal>(),
ledger_cost: sum_exact_of(&cost_accounts, |&id| net(id), "the ledger's asset cost")?,
ledger_accumulated: -sum_exact_of(
&accum_accounts,
|&id| net(id),
"the ledger's accumulated depreciation",
)?,
})
}
+21 -18
View File
@@ -79,6 +79,7 @@
//! ```
use crate::k1::{K1Kind, K1Row, k1_detail};
use crate::money::sum_exact_of;
use crate::reports::MemberCapital;
use crate::{AccountId, AssetId, AssetStatus, EntryId, Ledger, LedgerError, Side};
use chrono::NaiveDate;
@@ -586,19 +587,19 @@ fn entry_wholes(
n: usize,
cash: &[AccountId],
) -> Result<Vec<Whole>, LedgerError> {
let by_member = |kind| -> Vec<Decimal> {
let by_member = |kind| -> Result<Vec<Decimal>, LedgerError> {
(0..n)
.map(|i| {
lines
.iter()
.filter(|l| l.member == i && l.kind == kind)
.map(|l| l.amount)
.sum()
sum_exact_of(
lines.iter().filter(|l| l.member == i && l.kind == kind),
|l| l.amount,
"a member's K-1 lines",
)
})
.collect()
};
let mut out = Vec::new();
let takes = by_member(K1Kind::PropertyContribution);
let takes = by_member(K1Kind::PropertyContribution)?;
if takes.iter().any(|t| !t.is_zero()) {
let p = entry_property(ledger, e, cash)?;
out.push((BUILT_IN_GAIN, p.built_in_gain, takes.clone()));
@@ -606,7 +607,7 @@ fn entry_wholes(
out.push((PREPAID, p.prepaid, takes));
}
// Distributions are negative lines; weights are what each took.
let taken: Vec<Decimal> = by_member(K1Kind::Distribution)
let taken: Vec<Decimal> = by_member(K1Kind::Distribution)?
.into_iter()
.map(|d| -d)
.collect();
@@ -757,7 +758,7 @@ fn entry_property(
})
.try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount))
.ok_or_else(too_large)?;
let pool = pool - prepaid;
let pool = pool.checked_sub(prepaid).ok_or_else(too_large)?;
let (mut linked, mut big, mut unknown) = (Decimal::ZERO, Decimal::ZERO, Decimal::ZERO);
for a in ledger
.registered_assets()
@@ -783,7 +784,7 @@ fn entry_property(
mismatch: Some((linked, pool)),
});
}
let rest = pool - linked;
let rest = pool.checked_sub(linked).ok_or_else(too_large)?;
Ok(EntryProperty {
built_in_gain: big,
prepaid,
@@ -818,21 +819,23 @@ fn span(
}
for id in entries {
let e = ledger.get_entry(id).ok_or(LedgerError::UnknownEntry(id))?;
let lines = |kind| -> Vec<Decimal> {
let lines = |kind| -> Result<Vec<Decimal>, LedgerError> {
(0..n)
.map(|i| {
detail
.lines
.iter()
.filter(|l| l.entry == id && l.member == i && l.kind == kind)
.map(|l| l.amount)
.sum()
sum_exact_of(
detail
.lines
.iter()
.filter(|l| l.entry == id && l.member == i && l.kind == kind),
|l| l.amount,
"a member's K-1 lines",
)
})
.collect()
};
let none = EntryParts::default();
let part = parts.get(&id).unwrap_or(&none);
let takes = lines(K1Kind::PropertyContribution);
let takes = lines(K1Kind::PropertyContribution)?;
if takes.iter().any(|t| !t.is_zero()) {
let p = entry_property(ledger, e, cash)?;
// Only the members with property in the entry have a part of