merge: no Decimal arithmetic outside the kernel in ledger-core (K-U11a)

AGENTS.md's bar item 1 says money arithmetic lives in kernel/ and nowhere
else. The compiler-driven detector listed 210 places in ledger-core that
broke it: raw operators that panic when a result does not fit, and
rust_decimal's own methods, which round silently past 96 bits. All 210
now go through the kernel, and `just kernel-only` in the lint part of
`just check` holds ledger-core and the four outer crates already at zero
(ledger-cli, ledger-host, ledger-reader, ledger-vault) there.

No figure moves. What changes is the edge: a result exact arithmetic
cannot hold is refused where it panicked or was rounded.

What the unit found: once K-U10 made the kernel's sum exact, the K-1
worksheet's running total of 28-digit shares refused every split by
thirds. That sum is a rounded figure by construction, so the kernel now
names it (Amount::checked_add_rounded, checked_sub_rounded), with a
bridge property; every other maker of a long figure outside the kernel
was read for the same fault. Four places that changed a figure's written
places through Decimal::rescale, which can round, now call
kernel::rescale_exact, which cannot.

Checked on the branch: the detector at 0 for the five crates, the whole
ledger-core suite (1362 passed), clippy with -D warnings, and the
workspace compiles. docs/proofs/k-u11.md is the account.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude committed 2026-11-09 23:29:15 -07:00
commit 411c3aae16
31 files changed
+880 -397

No files matched your search

+12 -11
View File
@@ -6,6 +6,7 @@
//! are built from the same posted entries and statements as everything //! 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. //! 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::reports::profit_and_loss_for_period;
use crate::{AccountId, AccountType, Ledger, LedgerError, Side}; use crate::{AccountId, AccountType, Ledger, LedgerError, Side};
use chrono::{Datelike, Days, Months, NaiveDate}; use chrono::{Datelike, Days, Months, NaiveDate};
@@ -84,11 +85,11 @@ pub fn balance_series(
let Some(account) = ledger.chart().get(line.account) else { let Some(account) = ledger.chart().get(line.account) else {
continue; continue;
}; };
let signed = if line.side == account.account_type.normal_side() { let signed = on_side(
line.amount.amount account.account_type.normal_side(),
} else { line.side,
-line.amount.amount line.amount.amount,
}; );
postings.push((entry.date(), signed)); postings.push((entry.date(), signed));
} }
} }
@@ -98,7 +99,7 @@ pub fn balance_series(
let mut i = 0; let mut i = 0;
for date in dates { for date in dates {
while i < postings.len() && postings[i].0 <= *date { while i < postings.len() && postings[i].0 <= *date {
running += postings[i].1; running = add_in_range(running, postings[i].1);
i += 1; i += 1;
} }
out.push(running); out.push(running);
@@ -137,7 +138,7 @@ pub struct IntervalPnl {
impl IntervalPnl { impl IntervalPnl {
/// Revenue minus expenses. /// Revenue minus expenses.
pub fn net(&self) -> Decimal { 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; let mut net = Decimal::ZERO;
for line in entry.lines().iter().filter(|l| set.contains(&l.account)) { for line in entry.lines().iter().filter(|l| set.contains(&l.account)) {
match line.side { match line.side {
Side::Debit => net += line.amount.amount, Side::Debit => net = add_in_range(net, line.amount.amount),
Side::Credit => net -= line.amount.amount, Side::Credit => net = sub_in_range(net, line.amount.amount),
} }
} }
if net > Decimal::ZERO { if net > Decimal::ZERO {
slot.2 += net; slot.2 = add_in_range(slot.2, net);
} else { } else {
slot.3 -= net; slot.3 = sub_in_range(slot.3, net);
} }
} }
out out
+3 -6
View File
@@ -145,11 +145,7 @@ impl DocRef {
/// A line's amount as this document counts it: plus on /// A line's amount as this document counts it: plus on
/// [`Self::owed_side`], minus on the other. /// [`Self::owed_side`], minus on the other.
pub fn counted(self, side: crate::Side, amount: Decimal) -> Decimal { pub fn counted(self, side: crate::Side, amount: Decimal) -> Decimal {
if side == self.owed_side() { crate::money::on_side(self.owed_side(), side, amount)
amount
} else {
-amount
}
} }
} }
@@ -1368,7 +1364,8 @@ impl AgingRow {
/// Add `other`'s buckets to this row's; refused past exact arithmetic. /// Add `other`'s buckets to this row's; refused past exact arithmetic.
pub(crate) fn add(&mut self, other: &AgingRow) -> Result<(), LedgerError> { pub(crate) fn add(&mut self, other: &AgingRow) -> Result<(), LedgerError> {
let too_large = || LedgerError::TooLargeToCompute(format!("{}'s aging", self.name)); 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) = ( let (current, days_30, days_60, days_90, days_90_plus) = (
sum(self.current, other.current)?, sum(self.current, other.current)?,
sum(self.days_30, other.days_30)?, sum(self.days_30, other.days_30)?,
+16 -24
View File
@@ -22,6 +22,7 @@
//! the §704(c) built-in gain or loss at contribution. //! the §704(c) built-in gain or loss at contribution.
use crate::money::Steps; use crate::money::Steps;
use crate::money::neg;
use crate::{ use crate::{
AccountId, AccountType, ChartOfAccounts, EntryId, EntryStatus, Ledger, LedgerError, Money, AccountId, AccountType, ChartOfAccounts, EntryId, EntryStatus, Ledger, LedgerError, Money,
kernel, kernel,
@@ -684,10 +685,8 @@ fn schedule_months(asset: &Asset, through: NaiveDate) -> Result<Vec<MonthLine>,
} }
let too_large = let too_large =
|| LedgerError::TooLargeToCompute(format!("asset {}'s depreciation schedule", asset.id)); || LedgerError::TooLargeToCompute(format!("asset {}'s depreciation schedule", asset.id));
let depreciable = asset let depreciable =
.cost crate::kernel::Amount::checked_sub(asset.cost.amount, asset.salvage_value.amount)
.amount
.checked_sub(asset.salvage_value.amount)
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
if depreciable <= Decimal::ZERO { if depreciable <= Decimal::ZERO {
return Ok(Vec::new()); return Ok(Vec::new());
@@ -721,10 +720,7 @@ fn schedule_months(asset: &Asset, through: NaiveDate) -> Result<Vec<MonthLine>,
period: format!("{:04}-{:02}", p.year, p.month), period: format!("{:04}-{:02}", p.year, p.month),
amount: steps.decimal(through_k - charged).ok_or_else(too_large)?, amount: steps.decimal(through_k - charged).ok_or_else(too_large)?,
accumulated, accumulated,
book_value: asset book_value: crate::kernel::Amount::checked_sub(asset.cost.amount, accumulated)
.cost
.amount
.checked_sub(accumulated)
.ok_or_else(too_large)?, .ok_or_else(too_large)?,
}, },
}); });
@@ -760,10 +756,10 @@ pub fn accumulated_scheduled_through(
/// [`crate::Ledger::accumulated_posted`] (the register's and the tools' /// [`crate::Ledger::accumulated_posted`] (the register's and the tools'
/// `book_value`, BS-asset-3). /// `book_value`, BS-asset-3).
pub fn scheduled_book_value(asset: &Asset, as_of: NaiveDate) -> Result<Decimal, LedgerError> { pub fn scheduled_book_value(asset: &Asset, as_of: NaiveDate) -> Result<Decimal, LedgerError> {
asset crate::kernel::Amount::checked_sub(
.cost asset.cost.amount,
.amount accumulated_scheduled_through(asset, as_of)?,
.checked_sub(accumulated_scheduled_through(asset, as_of)?) )
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s book value", asset.id))) .ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s book value", asset.id)))
} }
@@ -839,7 +835,7 @@ pub(crate) fn run_chain_entries(
.get_entry(id) .get_entry(id)
.filter(|x| x.status() == EntryStatus::Posted) .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(); link = reversals.get(&id).copied();
adds = !adds; adds = !adds;
@@ -929,8 +925,7 @@ pub fn run_amounts(
RunAmount { RunAmount {
amount, amount,
scheduled: own, scheduled: own,
over: g over: crate::kernel::Amount::checked_sub(g, s)
.checked_sub(s)
.map_or(Decimal::ZERO, |o| o.max(Decimal::ZERO)), .map_or(Decimal::ZERO, |o| o.max(Decimal::ZERO)),
}, },
) )
@@ -981,7 +976,7 @@ fn cumulatives(
li += 1; li += 1;
} }
while let Some(r) = runs.get(ri).filter(|r| (r.year, r.month) <= (y, m)) { 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; ri += 1;
} }
months.push((y, m)); months.push((y, m));
@@ -1096,8 +1091,7 @@ pub fn catch_up_room(
let too_large = let too_large =
|| LedgerError::TooLargeToCompute(format!("asset {}'s depreciation run", asset.id)); || LedgerError::TooLargeToCompute(format!("asset {}'s depreciation run", asset.id));
let c = cumulatives(asset, (year, month), latest, &lines, posted)?; let c = cumulatives(asset, (year, month), latest, &lines, posted)?;
let over = c.carried[0] let over = crate::kernel::Amount::checked_sub(c.carried[0], c.scheduled[0])
.checked_sub(c.scheduled[0])
.ok_or_else(too_large)? .ok_or_else(too_large)?
.max(Decimal::ZERO); .max(Decimal::ZERO);
Ok(RunAmount { Ok(RunAmount {
@@ -1154,15 +1148,13 @@ pub fn disposal_amounts(
check_disposal(asset, proceeds)?; check_disposal(asset, proceeds)?;
let accumulated = accumulated_scheduled_through(asset, date)?; let accumulated = accumulated_scheduled_through(asset, date)?;
let too_large = || LedgerError::TooLargeToCompute(format!("asset {}'s disposal", asset.id)); let too_large = || LedgerError::TooLargeToCompute(format!("asset {}'s disposal", asset.id));
let book = asset let book =
.cost crate::kernel::Amount::checked_sub(asset.cost.amount, accumulated).ok_or_else(too_large)?;
.amount
.checked_sub(accumulated)
.ok_or_else(too_large)?;
Ok(DisposalAmounts { Ok(DisposalAmounts {
book_value: book, book_value: book,
accumulated, 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)?,
}) })
} }
+19 -9
View File
@@ -36,7 +36,7 @@ use serde::Serialize;
use crate::evidence::{Policy, Requirement}; use crate::evidence::{Policy, Requirement};
use crate::settings::Settings; 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. /// How much a finding matters.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
@@ -350,10 +350,7 @@ fn closed_net(ledger: &Ledger, through: NaiveDate) -> Option<Decimal> {
let Some(a) = ledger.chart().get(l.account) else { let Some(a) = ledger.chart().get(l.account) else {
continue; continue;
}; };
let signed = match l.side { let signed = crate::money::signed_amount(l.side, l.amount.amount);
Side::Debit => l.amount.amount,
Side::Credit => -l.amount.amount,
};
if matches!(a.account_type, AccountType::Revenue | AccountType::Expense) { if matches!(a.account_type, AccountType::Revenue | AccountType::Expense) {
net = crate::kernel::Amount::checked_add(net, signed)?; net = crate::kernel::Amount::checked_add(net, signed)?;
} }
@@ -536,16 +533,29 @@ pub fn check_split(
trued_up: bool, trued_up: bool,
) -> Vec<Finding> { ) -> Vec<Finding> {
// B(n) as derived above: (n-1)*u/2, floored at u. `unit` is a power // 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 legacy_bound = {
let others = Decimal::new(split.len().saturating_sub(1) as i64, 0); let others = Decimal::new(split.len().saturating_sub(1) as i64, 0);
let last = others * unit / Decimal::new(2, 0); match crate::kernel::Amount::checked_mul(others, unit)
if last > unit { last } else { unit } .and_then(|product| crate::kernel::Amount::checked_div_exact(product, Decimal::TWO))
{
Some(last) if last > unit => last,
_ => unit,
}
}; };
split split
.iter() .iter()
.filter(|m| { .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 { if trued_up {
drift >= unit drift >= unit
} else { } else {
+24 -28
View File
@@ -12,6 +12,7 @@
//! falls, what a member or lender paid for the company, pairs reversals, //! falls, what a member or lender paid for the company, pairs reversals,
//! names the kinds and checks the result foots. //! 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 std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use chrono::NaiveDate; use chrono::NaiveDate;
@@ -405,7 +406,7 @@ impl CashFlowStatement {
for l in self.lines(section) { for l in self.lines(section) {
match out.last_mut() { match out.last_mut() {
Some(k) if k.kind == l.kind => { 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); k.entries.push(l.entry);
} }
_ => out.push(CashFlowKind { _ => out.push(CashFlowKind {
@@ -643,8 +644,7 @@ pub fn role_problems(
/// cannot fail on posted entries): the sections sum to the change in /// cannot fail on posted entries): the sections sum to the change in
/// cash, or nothing is produced. /// cash, or nothing is produced.
pub fn foot(sections_sum: Decimal, net_change: Decimal) -> Result<CashFlowFooting, LedgerError> { pub fn foot(sections_sum: Decimal, net_change: Decimal) -> Result<CashFlowFooting, LedgerError> {
let difference = sections_sum let difference = crate::kernel::Amount::checked_sub(sections_sum, net_change)
.checked_sub(net_change)
.ok_or_else(|| too_large("the cash flow statement's footing"))?; .ok_or_else(|| too_large("the cash flow statement's footing"))?;
if !difference.is_zero() { if !difference.is_zero() {
return Err(LedgerError::CashFlowDoesNotFoot { return Err(LedgerError::CashFlowDoesNotFoot {
@@ -665,14 +665,11 @@ fn too_large(what: &str) -> LedgerError {
} }
fn add(a: Decimal, b: Decimal, what: &str) -> Result<Decimal, LedgerError> { fn add(a: Decimal, b: Decimal, what: &str) -> Result<Decimal, LedgerError> {
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 { fn signed(side: Side, amount: Decimal) -> Decimal {
match side { signed_amount(side, amount)
Side::Debit => amount,
Side::Credit => -amount,
}
} }
/// What a line part belongs to within its section: the kind its cash is /// 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<BillSplits, LedgerE
if l.side == Side::Credit && left > Decimal::ZERO && operating_liability(l.account)? { if l.side == Side::Credit && left > Decimal::ZERO && operating_liability(l.account)? {
let part = left.min(l.amount.amount); let part = left.min(l.amount.amount);
out.parts.insert((b.id(), i), (part, bucket.clone())); 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: // Each payment pays the equipment part first, in the order paid:
@@ -1085,13 +1082,13 @@ fn bill_splits(roles: &Roles<'_>, chains: &Chains) -> Result<BillSplits, LedgerE
// paid nothing for good: its reversal unpays it on the reversal's // paid nothing for good: its reversal unpays it on the reversal's
// date, and it leaves the equipment part for the payment that // date, and it leaves the equipment part for the payment that
// stands (P4b.2 gap 6: it used to keep it, as the bill did). // stands (P4b.2 gap 6: it used to keep it, as the bill did).
let mut owed = equipment - left; let mut owed = sub_in_range(equipment, left);
let payments = ledger let payments = ledger
.doc_lines(crate::DocRef::Bill(bill.id)) .doc_lines(crate::DocRef::Bill(bill.id))
.into_iter() .into_iter()
.filter(|l| l.movement == crate::Movement::Payment && !l.reversal); .filter(|l| l.movement == crate::Movement::Payment && !l.reversal);
for pl in payments { for pl in payments {
let (pay, amount) = (pl.entry, -pl.amount); let (pay, amount) = (pl.entry, neg(pl.amount));
let Some(p) = ledger.get_entry(pay) else { let Some(p) = ledger.get_entry(pay) else {
continue; continue;
}; };
@@ -1107,20 +1104,20 @@ fn bill_splits(roles: &Roles<'_>, chains: &Chains) -> Result<BillSplits, LedgerE
let paid = out.paid.entry(b.id()).or_default(); let paid = out.paid.entry(b.id()).or_default();
paid.push((p.date(), part)); paid.push((p.date(), part));
// Its reversal unpays it; a reinstatement pays it again. // Its reversal unpays it; a reinstatement pays it again.
let mut undo = -part; let mut undo = neg(part);
let mut cur = p.id(); let mut cur = p.id();
while let Some(&r) = chains.reversed_by.get(&cur) { while let Some(&r) = chains.reversed_by.get(&cur) {
let Some(re) = ledger.get_entry(r).filter(|_| r > cur) else { let Some(re) = ledger.get_entry(r).filter(|_| r > cur) else {
break; break;
}; };
paid.push((re.date(), undo)); paid.push((re.date(), undo));
undo = -undo; undo = neg(undo);
cur = r; cur = r;
} }
if ledger.in_effect(p.id()) { 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.clone()
}); });
} }
part.amount = amount - inv; part.amount = sub_in_range(amount, inv);
if part.amount.is_zero() { if part.amount.is_zero() {
continue; continue;
} }
@@ -1401,7 +1398,7 @@ fn analyse<'a>(
if total > Decimal::ZERO { if total > Decimal::ZERO {
inflow = add(inflow, total, "an entry's exchange")?; inflow = add(inflow, total, "an entry's exchange")?;
} else { } else {
outflow = add(outflow, -total, "an entry's exchange")?; outflow = add(outflow, neg(total), "an entry's exchange")?;
} }
} }
if !total.is_zero() { if !total.is_zero() {
@@ -1427,7 +1424,7 @@ fn analyse<'a>(
if m > Decimal::ZERO { if m > Decimal::ZERO {
debits = add(debits, m, "an entry's exchange")?; debits = add(debits, m, "an entry's exchange")?;
} else { } 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) let exchanged = kernel::exchanged(debits, credits, inflow, outflow)
@@ -1490,9 +1487,9 @@ impl Chains {
fn negated(f: &EntryFlows<Decimal>) -> EntryFlows<Decimal> { fn negated(f: &EntryFlows<Decimal>) -> EntryFlows<Decimal> {
EntryFlows { EntryFlows {
cash: -f.cash, cash: neg(f.cash),
flows: f.flows.map(|x| -x), flows: f.flows.map(neg),
noncash: f.noncash.map(|x| -x), noncash: f.noncash.map(neg),
} }
} }
@@ -1526,8 +1523,8 @@ fn pairs(kept: &[Analysed<'_>]) -> HashSet<EntryId> {
r.kinds[k].len() == x.kinds[k].len() r.kinds[k].len() == x.kinds[k].len()
&& r.kinds[k].iter().zip(&x.kinds[k]).all(|(rk, xk)| { && r.kinds[k].iter().zip(&x.kinds[k]).all(|(rk, xk)| {
rk.bucket == xk.bucket rk.bucket == xk.bucket
&& rk.cash == -xk.cash && rk.cash == neg(xk.cash)
&& rk.on_behalf == -xk.on_behalf && rk.on_behalf == neg(xk.on_behalf)
}) })
}); });
if mirror { if mirror {
@@ -1968,7 +1965,7 @@ pub fn cash_flow(
{ {
for &(date, part) in paid { for &(date, part) in paid {
if date <= params.end { if date <= params.end {
exchanged -= part; exchanged = sub_in_range(exchanged, part);
} }
} }
exchanged = exchanged.max(Decimal::ZERO); exchanged = exchanged.max(Decimal::ZERO);
@@ -2017,8 +2014,7 @@ pub fn cash_flow(
} }
} }
} }
let net_change_in_cash = cash_ending let net_change_in_cash = crate::kernel::Amount::checked_sub(cash_ending, cash_beginning)
.checked_sub(cash_beginning)
.ok_or_else(|| too_large("the change in cash"))?; .ok_or_else(|| too_large("the change in cash"))?;
let sections_sum = add( let sections_sum = add(
add(totals[0], totals[1], "the sections' sum")?, add(totals[0], totals[1], "the sections' sum")?,
@@ -2072,7 +2068,7 @@ fn reconcile(
let (mut g, mut dep) = (Decimal::ZERO, Decimal::ZERO); let (mut g, mut dep) = (Decimal::ZERO, Decimal::ZERO);
for p in &a.parts { for p in &a.parts {
if p.pl { 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 p.flow == Flow::Investing {
if roles.depreciation.contains(&p.account) { if roles.depreciation.contains(&p.account) {
dep = add(dep, p.signed(), WHAT)?; dep = add(dep, p.signed(), WHAT)?;
@@ -2204,7 +2200,7 @@ fn reconcile(
if up { "Increase in" } else { "Decrease in" }, if up { "Increase in" } else { "Decrease in" },
named(&code) named(&code)
), ),
amount: -movement, amount: neg(movement),
account: Some(code), account: Some(code),
entries: Vec::new(), entries: Vec::new(),
}); });
+10 -4
View File
@@ -779,10 +779,16 @@ fn check_template(t: &Template) -> Result<Template, String> {
l.share l.share
) )
})?; })?;
match l.side { let side_total = match l.side {
Side::Debit => debit += share, Side::Debit => &mut debit,
Side::Credit => credit += share, 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)?; let account = line_text(&format!("template line {n} account"), &l.account, 64)?;
if account.starts_with('{') && slot(&account).is_none() { if account.starts_with('{') && slot(&account).is_none() {
return Err(format!( return Err(format!(
+5 -6
View File
@@ -200,11 +200,10 @@ impl Policy {
/// total past exact arithmetic is refused (TooLargeToCompute), never /// total past exact arithmetic is refused (TooLargeToCompute), never
/// a panic. /// a panic.
pub fn entry_debits(entry: &JournalEntry) -> Result<Decimal, LedgerError> { pub fn entry_debits(entry: &JournalEntry) -> Result<Decimal, LedgerError> {
entry crate::kernel::total_of(
.lines() entry.lines().iter().filter(|l| l.side == Side::Debit),
.iter() |l| l.amount.amount,
.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()))) .ok_or_else(|| LedgerError::TooLargeToCompute(format!("entry {}'s debits", entry.id())))
} }
@@ -343,7 +342,7 @@ impl Policy {
// A sum past exact arithmetic is past the threshold. // A sum past exact arithmetic is past the threshold.
total = Self::entry_debits(other) total = Self::entry_debits(other)
.ok() .ok()
.and_then(|d| total.checked_add(d)) .and_then(|d| crate::kernel::Amount::checked_add(total, d))
.unwrap_or(Decimal::MAX); .unwrap_or(Decimal::MAX);
} }
if !group.is_empty() && total > self.threshold { if !group.is_empty() && total > self.threshold {
+4 -5
View File
@@ -37,6 +37,7 @@
//! them and the report takes an override. Confirm with the CPA. //! them and the report takes an override. Confirm with the CPA.
use crate::kernel::{self, Bucket, PayRole, Tag}; use crate::kernel::{self, Bucket, PayRole, Tag};
use crate::money::neg;
use crate::settings::Source; use crate::settings::Source;
use crate::{AccountId, AccountType, EntryId, Ledger, LedgerError, VendorId}; use crate::{AccountId, AccountType, EntryId, Ledger, LedgerError, VendorId};
use chrono::{Datelike, NaiveDate}; 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)?; kernel::apportion(av, &mut parts, &rems, cent).ok_or_else(too_large)?;
if v.is_sign_negative() { if v.is_sign_negative() {
for x in parts.iter_mut().filter(|x| !x.is_zero()) { for x in parts.iter_mut().filter(|x| !x.is_zero()) {
*x = -*x; *x = neg(*x);
} }
} }
Ok(parts) Ok(parts)
@@ -831,8 +832,7 @@ struct Tally {
} }
fn add(to: &mut Decimal, x: Decimal) -> Result<(), LedgerError> { fn add(to: &mut Decimal, x: Decimal) -> Result<(), LedgerError> {
*to = to *to = crate::kernel::Amount::checked_add(*to, x)
.checked_add(x)
.ok_or_else(|| LedgerError::TooLargeToCompute("a vendor's payments for the year".into()))?; .ok_or_else(|| LedgerError::TooLargeToCompute("a vendor's payments for the year".into()))?;
Ok(()) Ok(())
} }
@@ -1236,8 +1236,7 @@ fn untagged_payments(
continue; continue;
} }
let [counts, _, unknown] = entry_buckets(ledger, e, roles)?; let [counts, _, unknown] = entry_buckets(ledger, e, roles)?;
let out_of_pocket = counts let out_of_pocket = crate::kernel::Amount::checked_add(counts, unknown)
.checked_add(unknown)
.ok_or_else(|| LedgerError::TooLargeToCompute("a payment".into()))?; .ok_or_else(|| LedgerError::TooLargeToCompute("a payment".into()))?;
if out_of_pocket <= Decimal::ZERO { if out_of_pocket <= Decimal::ZERO {
continue; continue;
+3 -6
View File
@@ -68,7 +68,7 @@
//! ``` //! ```
use crate::kernel::Amount; 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::reports::{MemberCapital, members_equity};
use crate::{AccountId, AccountType, EntryId, Ledger, LedgerError, PartyId, Side}; use crate::{AccountId, AccountType, EntryId, Ledger, LedgerError, PartyId, Side};
use chrono::NaiveDate; use chrono::NaiveDate;
@@ -314,7 +314,7 @@ pub(crate) fn entry_lines(
"a member's distributions", "a member's distributions",
)?; )?;
if !taken.is_zero() { if !taken.is_zero() {
lines.push(line(i, K1Kind::Distribution, -taken)); lines.push(line(i, K1Kind::Distribution, neg(taken)));
} }
} }
Ok(lines) Ok(lines)
@@ -347,10 +347,7 @@ pub(crate) fn share_property(
use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with}; use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with};
let too_large = let too_large =
|| LedgerError::TooLargeToCompute("a member's share of contributed property".into()); || LedgerError::TooLargeToCompute("a member's share of contributed property".into());
let total = credits let total = crate::kernel::total_of(credits.iter(), |c| *c).ok_or_else(too_large)?;
.iter()
.try_fold(Decimal::ZERO, |t, c| t.checked_add(*c))
.ok_or_else(too_large)?;
let whole = pool.min(total); let whole = pool.min(total);
if whole <= Decimal::ZERO || total <= Decimal::ZERO { if whole <= Decimal::ZERO || total <= Decimal::ZERO {
return Ok(vec![Decimal::ZERO; credits.len()]); return Ok(vec![Decimal::ZERO; credits.len()]);
+28
View File
@@ -50,6 +50,28 @@ pub trait Amount: Copy + Ord {
fn checked_mul_rounded(self, rhs: Self) -> Option<Self> { fn checked_mul_rounded(self, rhs: Self) -> Option<Self> {
self.checked_mul(rhs) 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> {
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> {
self.checked_sub(rhs)
}
/// `self * rhs`, computed exactly and rounded once to a whole multiple /// `self * rhs`, computed exactly and rounded once to a whole multiple
/// of `step` in `mode`; `None` when `step` is not positive or the /// of `step` in `mode`; `None` when `step` is not positive or the
/// result cannot be represented. /// result cannot be represented.
@@ -142,6 +164,12 @@ impl Amount for Decimal {
fn checked_mul_rounded(self, rhs: Self) -> Option<Self> { fn checked_mul_rounded(self, rhs: Self) -> Option<Self> {
Decimal::checked_mul(self, rhs) Decimal::checked_mul(self, rhs)
} }
fn checked_add_rounded(self, rhs: Self) -> Option<Self> {
Decimal::checked_add(self, rhs)
}
fn checked_sub_rounded(self, rhs: Self) -> Option<Self> {
Decimal::checked_sub(self, rhs)
}
fn checked_mul_round_to_step(self, rhs: Self, step: Self, mode: Rounding) -> Option<Self> { fn checked_mul_round_to_step(self, rhs: Self, step: Self, mode: Rounding) -> Option<Self> {
if let Some(product) = super::decimal_exact::exact_mul(self, rhs) { if let Some(product) = super::decimal_exact::exact_mul(self, rhs) {
return super::round::round_step(product, step, mode); return super::round::round_step(product, step, mode);
+30
View File
@@ -106,6 +106,36 @@ pub fn round_places(amount: Decimal, places: u32, mode: Rounding) -> Option<Deci
Some(rounded) Some(rounded)
} }
/// `amount` written with `places` decimal places, when that changes no
/// digit of its value: trailing zeros are added or dropped, nothing else.
/// This is how a figure is given the places it prints with (a margin of
/// "100.0", a month of "0.25" that the kernel returned as 0.250), and it
/// is the one such place: `Decimal::rescale` rounds half away from zero
/// when asked for fewer places than the value has, silently, and this
/// refuses instead.
///
/// ```text
/// GOAL: change how many places an amount is written with, never the
/// amount.
/// SOURCE: BS-ledger-1 (law 40: a whole multiple of the step is its own
/// rounding in every mode, so writing it at the step's places
/// rounds nothing).
/// INVARIANTS:
/// 1. A result equals `amount`, and keeps its sign (a zero's too).
/// 2. None exactly when `amount` is no whole multiple of 10^(−places)
/// (it would have to be rounded), or `places` is past Decimal's 28.
/// 3. A result carries `places` places, or, where Decimal's 96 bits
/// cannot hold the amount that wide, as many as they can hold.
/// ```
pub fn rescale_exact(amount: Decimal, places: u32) -> Option<Decimal> {
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 /// `amount` rounded to whole `currency` minor units in `mode`: cents for
/// USD, whole yen for JPY, thousandths for KWD. A currency ISO 4217 gives /// 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 /// no minor unit (gold, SDRs) is returned exactly, as the FX booking rule
+65 -53
View File
@@ -6,6 +6,7 @@
//! is no other way to change the books, which is what makes the ledger an //! 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. //! audit trail and what will make the future oracle harness trustworthy.
use crate::money::{add_in_range, neg, on_side};
use crate::schedules::{ use crate::schedules::{
self, AmortizationSchedule, NewRecurring, NewSchedule, RecurringEntry, RecurringId, ScheduleId, self, AmortizationSchedule, NewRecurring, NewSchedule, RecurringEntry, RecurringId, ScheduleId,
}; };
@@ -2369,9 +2370,11 @@ impl Ledger {
for (i, l) in original.lines().iter().enumerate() { for (i, l) in original.lines().iter().enumerate() {
if let Some(tag) = self.line_docs.get(&(original.id(), i)) { if let Some(tag) = self.line_docs.get(&(original.id(), i)) {
// The mirror moves the document by the opposite. // 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) { 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)), None => moves.push((tag.doc, by)),
} }
} }
@@ -3439,10 +3442,12 @@ impl Ledger {
) -> Result<Decimal, LedgerError> { ) -> Result<Decimal, LedgerError> {
let too_large = let too_large =
|| LedgerError::TooLargeToCompute(format!("asset {id}'s posted depreciation")); || LedgerError::TooLargeToCompute(format!("asset {id}'s posted depreciation"));
crate::kernel::total_of(
assets::run_chain_entries(self, &self.depreciation_run_entries(id), reversals) assets::run_chain_entries(self, &self.depreciation_run_entries(id), reversals)
.into_iter() .into_iter()
.filter(|(d, _)| *d >= from && *d <= to) .filter(|(d, _)| *d >= from && *d <= to),
.try_fold(Decimal::ZERO, |t, (_, a)| t.checked_add(a)) |(_, a)| a,
)
.ok_or_else(too_large) .ok_or_else(too_large)
} }
@@ -3757,7 +3762,7 @@ impl Ledger {
let mut sweep = |from: AccountId, into: AccountId, this: &Self| { let mut sweep = |from: AccountId, into: AccountId, this: &Self| {
// An equity balance (credit-normal) is −movement; zeroing it // An equity balance (credit-normal) is −movement; zeroing it
// moves exactly that much into the target. // 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() { if !balance.is_zero() {
sweep_lines.push((from, into, balance)); sweep_lines.push((from, into, balance));
} }
@@ -3830,7 +3835,7 @@ impl Ledger {
// A sweep zeroes the source (opposite its balance) and moves // A sweep zeroes the source (opposite its balance) and moves
// the balance into the target. // the balance into the target.
for (from, into, balance) in sweep_lines { for (from, into, balance) in sweep_lines {
post(self, from, -balance)?; post(self, from, neg(balance))?;
post(self, into, balance)?; post(self, into, balance)?;
} }
self.post_entry(entry)?; self.post_entry(entry)?;
@@ -4005,10 +4010,10 @@ impl Ledger {
regime.trued_up |= matches!(m.rule, periods::MemberRule::Cumulative { .. }) regime.trued_up |= matches!(m.rule, periods::MemberRule::Cumulative { .. })
&& p.closing_entry.is_some(); && p.closing_entry.is_some();
regime.order.clone_from(&m.members); 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) { for ((capital, _), part) in m.members.iter().zip(&m.parts) {
if let Some(i) = members.iter().position(|(c, _)| c == capital) { 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, share,
part, part,
running, 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(); .collect();
@@ -4079,7 +4089,7 @@ impl Ledger {
let mut total = Decimal::ZERO; let mut total = Decimal::ZERO;
for p in closed { for p in closed {
match &p.member_close { 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, _ => break,
} }
} }
@@ -6347,7 +6357,8 @@ impl Ledger {
return Ok(None); return Ok(None);
} }
let too_large = || LedgerError::TooLargeToCompute(format!("{doc}'s figures")); 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) = let (mut outstanding, mut paid, mut discounted, mut written_off) =
(Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO); (Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO);
let lines = self.doc_lines(doc); let lines = self.doc_lines(doc);
@@ -6357,9 +6368,9 @@ impl Ledger {
for l in lines.into_iter().filter(|l| l.date <= as_of) { for l in lines.into_iter().filter(|l| l.date <= as_of) {
outstanding = add(outstanding, l.amount)?; outstanding = add(outstanding, l.amount)?;
match l.movement { match l.movement {
arap::Movement::Payment => paid = add(paid, -l.amount)?, arap::Movement::Payment => paid = add(paid, neg(l.amount))?,
arap::Movement::Discount => discounted = add(discounted, -l.amount)?, arap::Movement::Discount => discounted = add(discounted, neg(l.amount))?,
arap::Movement::WriteOff => written_off = add(written_off, -l.amount)?, arap::Movement::WriteOff => written_off = add(written_off, neg(l.amount))?,
arap::Movement::Origin | arap::Movement::Adopted | arap::Movement::RoleMove => {} arap::Movement::Origin | arap::Movement::Adopted | arap::Movement::RoleMove => {}
} }
} }
@@ -6411,11 +6422,13 @@ impl Ledger {
/// payment needs that feature. Refused (TooLargeToCompute), never a /// payment needs that feature. Refused (TooLargeToCompute), never a
/// panic, past exact arithmetic: replayed amounts are any size (BS-entry-4). /// panic, past exact arithmetic: replayed amounts are any size (BS-entry-4).
pub fn payments_recorded(&self, doc: arap::DocRef) -> Result<Decimal, LedgerError> { pub fn payments_recorded(&self, doc: arap::DocRef) -> Result<Decimal, LedgerError> {
crate::kernel::total_of(
self.payment_events self.payment_events
.get(&doc) .get(&doc)
.map_or(&[][..], Vec::as_slice) .map_or(&[][..], Vec::as_slice)
.iter() .iter(),
.try_fold(Decimal::ZERO, |sum, &a| sum.checked_add(a)) |&a| a,
)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{doc}'s payments"))) .ok_or_else(|| LedgerError::TooLargeToCompute(format!("{doc}'s payments")))
} }
@@ -6457,7 +6470,7 @@ impl Ledger {
.chain(extra.iter().copied()); .chain(extra.iter().copied());
for (date, amount) in moves { for (date, amount) in moves {
let day = by_date.entry(date).or_default(); 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()) Ok(by_date.into_values().collect())
} }
@@ -6534,11 +6547,13 @@ impl Ledger {
let too_large = || LedgerError::TooLargeToCompute(format!("{doc}'s figures")); let too_large = || LedgerError::TooLargeToCompute(format!("{doc}'s figures"));
let mut running = Decimal::ZERO; let mut running = Decimal::ZERO;
for l in lines.iter().filter(|l| l.date <= from) { 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; let mut room = running;
for l in lines.iter().filter(|l| l.date > from) { 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); room = room.min(running);
} }
Ok(room) Ok(room)
@@ -6730,7 +6745,8 @@ impl Ledger {
}); });
} }
let room = self.payment_room(app.doc, params.date)?; let room = self.payment_room(app.doc, params.date)?;
let applied = app.cash.checked_add(app.discount).ok_or_else(|| { let applied =
crate::kernel::Amount::checked_add(app.cash, app.discount).ok_or_else(|| {
LedgerError::TooLargeToCompute(format!("{}'s settlement", app.doc)) LedgerError::TooLargeToCompute(format!("{}'s settlement", app.doc))
})?; })?;
if applied > room { if applied > room {
@@ -6754,9 +6770,7 @@ impl Ledger {
// A fee above the cash is its own refusal; the kernel would also // 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 // 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). // was. A sum that overflows is left to the kernel (too large).
if let Some(total_cash) = cash if let Some(total_cash) = crate::kernel::total_of(cash.iter(), |c| *c)
.iter()
.try_fold(Decimal::ZERO, |sum, c| sum.checked_add(*c))
&& fee_amount > total_cash && fee_amount > total_cash
{ {
return Err(LedgerError::FeeAboveCash { return Err(LedgerError::FeeAboveCash {
@@ -6780,8 +6794,8 @@ impl Ledger {
let mut total_discount = Decimal::ZERO; let mut total_discount = Decimal::ZERO;
for app in &params.applications { for app in &params.applications {
if app.discount > Decimal::ZERO { if app.discount > Decimal::ZERO {
total_discount = total_discount total_discount =
.checked_add(app.discount) crate::kernel::Amount::checked_add(total_discount, app.discount)
.ok_or_else(|| LedgerError::TooLargeToCompute("the discounts".into()))?; .ok_or_else(|| LedgerError::TooLargeToCompute("the discounts".into()))?;
} }
} }
@@ -7412,7 +7426,7 @@ impl Ledger {
}; };
for l in self.doc_lines(doc).into_iter().filter(|l| l.date <= as_of) { for l in self.doc_lines(doc).into_iter().filter(|l| l.date <= as_of) {
let t = doc_totals.entry(l.account).or_default(); 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)? if let Some(st) = self.doc_state(doc, as_of)?
&& (st.out_of_bounds() || st.status == arap::DocStatus::Unattached) && (st.out_of_bounds() || st.status == arap::DocStatus::Unattached)
@@ -7444,7 +7458,7 @@ impl Ledger {
} else { } else {
Side::Credit Side::Credit
}; };
if side == plus { amount } else { -amount } on_side(plus, side, amount)
}; };
let mut out = Vec::new(); let mut out = Vec::new();
for (account, role) in accounts { for (account, role) in accounts {
@@ -7455,8 +7469,10 @@ impl Ledger {
if l.account != account { if l.account != account {
continue; continue;
} }
balance = balance balance = crate::kernel::Amount::checked_add(
.checked_add(counted(role, l.side, l.amount.amount)) balance,
counted(role, l.side, l.amount.amount),
)
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
if !self.line_docs.contains_key(&(e.id(), i)) { if !self.line_docs.contains_key(&(e.id(), i)) {
let top = self.reversal_chain(e.id())[0]; let top = self.reversal_chain(e.id())[0];
@@ -7480,12 +7496,15 @@ impl Ledger {
continue; continue;
}; };
debug_assert!(n == 0 || e.reversal_of().is_some()); debug_assert!(n == 0 || e.reversal_of().is_some());
net = net net = crate::kernel::Amount::checked_add(
.checked_add(counted(role, l.side, l.amount.amount)) net,
counted(role, l.side, l.amount.amount),
)
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
} }
if !net.is_zero() { 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 { unattached.push(arap::UnattachedLine {
entry: top, entry: top,
line: i, line: i,
@@ -7522,10 +7541,8 @@ impl Ledger {
let Ok(Some(st)) = self.doc_state(doc, NaiveDate::MAX) else { let Ok(Some(st)) = self.doc_state(doc, NaiveDate::MAX) else {
return; return;
}; };
let Some(settled) = st let Some(settled) = crate::kernel::Amount::checked_add(st.paid, st.discounted)
.paid .and_then(|s| crate::kernel::Amount::checked_add(s, st.written_off))
.checked_add(st.discounted)
.and_then(|s| s.checked_add(st.written_off))
else { else {
return; return;
}; };
@@ -8190,18 +8207,14 @@ impl Ledger {
continue; continue;
} }
// Signed in the account's normal side: positive = normal balance. // Signed in the account's normal side: positive = normal balance.
let signed = match (line.side, normal) { let signed = on_side(normal, line.side, line.amount.amount);
(Side::Debit, Side::Debit) => line.amount.amount, book = crate::money::add_exact(book, signed, "the account's book balance")?;
(Side::Credit, Side::Credit) => line.amount.amount,
(Side::Debit, Side::Credit) => -line.amount.amount,
(Side::Credit, Side::Debit) => -line.amount.amount,
};
book += signed;
if entry.date() > statement_date { if entry.date() > statement_date {
continue; continue;
} }
if self.is_cleared(entry.id(), idx) { if self.is_cleared(entry.id(), idx) {
cleared += signed; cleared =
crate::money::add_exact(cleared, signed, "the account's cleared balance")?;
} else { } else {
uncleared_lines.push(UnclearedLine { uncleared_lines.push(UnclearedLine {
entry_id: entry.id(), entry_id: entry.id(),
@@ -8225,9 +8238,9 @@ impl Ledger {
cleared cleared
}, },
statement_balance, statement_balance,
difference: cleared.checked_sub(statement_balance).ok_or_else(|| { difference: crate::kernel::Amount::checked_sub(cleared, statement_balance).ok_or_else(
LedgerError::TooLargeToCompute("the reconciliation's difference".into()) || LedgerError::TooLargeToCompute("the reconciliation's difference".into()),
})?, )?,
uncleared_lines, uncleared_lines,
}) })
} }
@@ -8442,7 +8455,7 @@ impl Ledger {
match l.employee { match l.employee {
Some(p) => match paid.iter_mut().find(|(x, _)| *x == p) { Some(p) => match paid.iter_mut().find(|(x, _)| *x == p) {
Some((_, v)) => { 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")) LedgerError::TooLargeToCompute(format!("party {p}'s net pay"))
})? })?
} }
@@ -9209,11 +9222,10 @@ impl Ledger {
.iter() .iter()
.filter_map(|l| self.chart.get(l.account).map(|a| a.code.as_str())) .filter_map(|l| self.chart.get(l.account).map(|a| a.code.as_str()))
.collect(); .collect();
let debits = e let debits =
.lines() crate::kernel::total_of(e.lines().iter().filter(|l| l.side == Side::Debit), |l| {
.iter() l.amount.amount
.filter(|l| l.side == Side::Debit) })
.try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount))
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("entry {entry}'s debits")))?; .ok_or_else(|| LedgerError::TooLargeToCompute(format!("entry {entry}'s debits")))?;
let approvals = self.conventions.approvals(entry); let approvals = self.conventions.approvals(entry);
let key = crate::parties::name_key; let key = crate::parties::name_key;
+91 -3
View File
@@ -4,7 +4,7 @@
//! [`Money`] arithmetic is checked: adding different currencies is an error, //! [`Money`] arithmetic is checked: adding different currencies is an error,
//! not a guess. //! not a guess.
use crate::LedgerError; use crate::{LedgerError, Side};
use rust_decimal::Decimal; use rust_decimal::Decimal;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt; use std::fmt;
@@ -205,6 +205,43 @@ pub fn sub_exact(a: Decimal, b: Decimal, what: &str) -> Result<Decimal, LedgerEr
.ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string())) .ok_or_else(|| LedgerError::TooLargeToCompute(what.to_string()))
} }
/// `-value`, through the kernel. A `Decimal`'s negation is always exact,
/// so this never fails (a zero comes back as a negative zero, bit for bit
/// what a raw `-` gives).
pub(crate) fn neg(value: Decimal) -> 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 { impl fmt::Debug for Money {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.amount, self.currency) write!(f, "{} {}", self.amount, self.currency)
@@ -267,9 +304,10 @@ impl Steps {
if self.scale == self.minor { if self.scale == self.minor {
return Some(d); return Some(d);
} }
let mut d = d.normalize(); let d = d.normalize();
if d.scale() < self.minor { 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) Some(d)
} }
@@ -293,6 +331,56 @@ mod tests {
Decimal::new(cents, 2) 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] #[test]
fn checked_arithmetic() { fn checked_arithmetic() {
assert_eq!( assert_eq!(
+29 -28
View File
@@ -917,11 +917,9 @@ impl Activity {
match basis { match basis {
Basis::Cash => (self.paid, self.received), Basis::Cash => (self.paid, self.received),
Basis::All => ( Basis::All => (
self.paid crate::kernel::Amount::checked_add(self.paid, self.paid_in_kind)
.checked_add(self.paid_in_kind)
.expect("activity_with keeps the all-basis sums exact"), .expect("activity_with keeps the all-basis sums exact"),
self.received crate::kernel::Amount::checked_add(self.received, self.received_in_kind)
.checked_add(self.received_in_kind)
.expect("activity_with keeps the all-basis sums exact"), .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. // sum is checked, and one past exact arithmetic is refused.
let too_large = let too_large =
|| crate::LedgerError::TooLargeToCompute(format!("entry {}'s money flow", entry.id())); || 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 plus =
let minus = |a: Decimal, b: Decimal| a.checked_sub(b).ok_or_else(too_large); |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) = let (mut cash_cr, mut cash_dr, mut liab_cr, mut liab_dr) =
(Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO); (Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO);
for l in entry.lines() { for l in entry.lines() {
@@ -1199,13 +1199,13 @@ pub fn entry_flow(
let (part, rest) = match l.side { let (part, rest) = match l.side {
Side::Debit => { Side::Debit => {
let take = a.min(down_left); let take = a.min(down_left);
down_left -= take; down_left = minus(down_left, take)?;
(take, a - take) (take, minus(a, take)?)
} }
Side::Credit => { Side::Credit => {
let take = a.min(up_left); let take = a.min(up_left);
up_left -= take; up_left = minus(up_left, take)?;
(-take, -(a - take)) (crate::money::neg(take), crate::money::neg(minus(a, take)?))
} }
}; };
match left.iter_mut().find(|(x, _)| *x == l.account) { match left.iter_mut().find(|(x, _)| *x == l.account) {
@@ -1214,10 +1214,7 @@ pub fn entry_flow(
} }
part part
} else { } else {
match l.side { crate::money::signed_amount(l.side, a)
Side::Debit => a,
Side::Credit => -a,
}
}; };
add(&mut by, &mut order, l.account, part)?; add(&mut by, &mut order, l.account, part)?;
} }
@@ -1226,17 +1223,18 @@ pub fn entry_flow(
.map(|(_, v)| *v) .map(|(_, v)| *v)
.filter(|v| *v > Decimal::ZERO) .filter(|v| *v > Decimal::ZERO)
.try_fold(Decimal::ZERO, &plus)?; .try_fold(Decimal::ZERO, &plus)?;
let owed_up = -left let owed_up = crate::money::neg(
.iter() left.iter()
.map(|(_, v)| *v) .map(|(_, v)| *v)
.filter(|v| *v < Decimal::ZERO) .filter(|v| *v < Decimal::ZERO)
.try_fold(Decimal::ZERO, &plus)?; .try_fold(Decimal::ZERO, &plus)?,
);
let across = owed_down.min(owed_up); let across = owed_down.min(owed_up);
let mut across_left = across; let mut across_left = across;
for (account, v) in left { for (account, v) in left {
if v > Decimal::ZERO && !across_left.is_zero() { if v > Decimal::ZERO && !across_left.is_zero() {
let take = v.min(across_left); let take = v.min(across_left);
across_left -= take; across_left = minus(across_left, take)?;
add(&mut by, &mut order, account, take)?; add(&mut by, &mut order, account, take)?;
} }
} }
@@ -1298,7 +1296,7 @@ pub fn flow(
if v.is_zero() { if v.is_zero() {
rust_decimal::Decimal::ZERO rust_decimal::Decimal::ZERO
} else { } else {
-v crate::money::neg(v)
} }
}; };
Ok(EntryFlow { Ok(EntryFlow {
@@ -1395,19 +1393,22 @@ pub fn activity_with(
// the root original's side; every total, the all-basis sums // the root original's side; every total, the all-basis sums
// included, stays exact or the entry counts nothing. // included, stays exact or the entry counts nothing.
let next = match t.counts_as { let next = match t.counts_as {
Direction::Paid => a Direction::Paid => crate::kernel::Amount::checked_add(a.paid, p.cash)
.paid .zip(crate::kernel::Amount::checked_add(
.checked_add(p.cash) a.paid_in_kind,
.zip(a.paid_in_kind.checked_add(p.in_kind)) p.in_kind,
))
.map(|(c, k)| (c, k, a.received, a.received_in_kind)), .map(|(c, k)| (c, k, a.received, a.received_in_kind)),
_ => a _ => crate::kernel::Amount::checked_sub(a.received, p.cash)
.received .zip(crate::kernel::Amount::checked_sub(
.checked_sub(p.cash) a.received_in_kind,
.zip(a.received_in_kind.checked_sub(p.in_kind)) p.in_kind,
))
.map(|(c, k)| (a.paid, a.paid_in_kind, c, k)), .map(|(c, k)| (a.paid, a.paid_in_kind, c, k)),
}; };
match next.filter(|(pc, pk, rc, rk)| { 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)) => { Some((pc, pk, rc, rk)) => {
a.paid = pc; a.paid = pc;
+8 -6
View File
@@ -17,7 +17,7 @@
//! no platform: callers (or a format-specific parser) supply the numbers //! no platform: callers (or a format-specific parser) supply the numbers
//! from the payout statement, which is the entry's receipt. //! 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 crate::{AccountId, AccountType, ChartOfAccounts, ClassId, LedgerError, Side};
use rust_decimal::Decimal; 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 fees = sum_exact_of(&payout.fees, |l| l.amount, "the payout's fees")?;
let adjustments = sum_exact_of( let adjustments = sum_exact_of(
&payout.adjustments, &payout.adjustments,
|a| match a.side { |a| on_side(Side::Credit, a.side, a.amount),
Side::Credit => a.amount,
Side::Debit => -a.amount,
},
"the payout's adjustments", "the payout's adjustments",
)?; )?;
let expected = add_exact( let expected = add_exact(
@@ -193,7 +190,12 @@ pub fn payout_plan(
if payout.deposit > Decimal::ZERO { if payout.deposit > Decimal::ZERO {
plan.push((payout.deposit_account, Side::Debit, payout.deposit, None)); plan.push((payout.deposit_account, Side::Debit, payout.deposit, None));
} else if payout.deposit < Decimal::ZERO { } 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( plan.extend(
payout payout
+5 -3
View File
@@ -177,17 +177,19 @@ pub fn payroll_entry_plan(
// exact, or refused here as TooLargeToCompute, never a panic. // 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 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| { 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)?; .ok_or_else(too_large)?;
let federal = let federal =
crate::kernel::total_of(lines.iter(), |l| l.federal_withholding).ok_or_else(too_large)?; crate::kernel::total_of(lines.iter(), |l| l.federal_withholding).ok_or_else(too_large)?;
let state = let state =
crate::kernel::total_of(lines.iter(), |l| l.state_withholding).ok_or_else(too_large)?; 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)) 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)?; .ok_or_else(too_large)?;
let medicare = crate::kernel::total_try(lines.iter(), |l| { 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)?; .ok_or_else(too_large)?;
let other = let other =
+21 -10
View File
@@ -14,6 +14,7 @@
//! through the *next* open period (or a reversal dated in an open period). //! through the *next* open period (or a reversal dated in an open period).
use crate::LedgerError; use crate::LedgerError;
use crate::money::neg;
use chrono::NaiveDate; use chrono::NaiveDate;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -145,7 +146,11 @@ pub fn try_allocate(
let magnitude = amount.abs(); let magnitude = amount.abs();
let exact: Vec<Decimal> = shares let exact: Vec<Decimal> = shares
.iter() .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::<Result<_, _>>()?; .collect::<Result<_, _>>()?;
let mut parts: Vec<Decimal> = exact let mut parts: Vec<Decimal> = exact
.iter() .iter()
@@ -157,13 +162,13 @@ pub fn try_allocate(
let remainders: Vec<Decimal> = exact let remainders: Vec<Decimal> = exact
.iter() .iter()
.zip(&parts) .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::<Result<_, _>>()?; .collect::<Result<_, _>>()?;
crate::kernel::apportion(magnitude, &mut parts, &remainders, Decimal::new(1, 2)) crate::kernel::apportion(magnitude, &mut parts, &remainders, Decimal::new(1, 2))
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
if amount.is_sign_negative() { if amount.is_sign_negative() {
for p in &mut parts { for p in &mut parts {
*p = -*p; *p = neg(*p);
} }
} }
Ok(parts) Ok(parts)
@@ -197,8 +202,8 @@ pub fn try_allocate_last_absorbs(
let mut parts: Vec<_> = shares let mut parts: Vec<_> = shares
.iter() .iter()
.map(|s| { .map(|s| {
amount // The rounding product: this rule is frozen for replay.
.checked_mul(*s) crate::kernel::Amount::checked_mul_rounded(amount, *s)
.and_then(|p| round_places(p, 2, Rounding::HalfAwayFromZero)) .and_then(|p| round_places(p, 2, Rounding::HalfAwayFromZero))
.ok_or_else(too_large) .ok_or_else(too_large)
}) })
@@ -270,7 +275,10 @@ pub fn allocate_cumulative(
} }
let loss = total < Decimal::ZERO; let loss = total < Decimal::ZERO;
let magnitude = total.abs().normalize(); let magnitude = total.abs().normalize();
let given: Vec<Decimal> = given.iter().map(|&g| if loss { -g } else { g }).collect(); let given: Vec<Decimal> = given
.iter()
.map(|&g| if loss { neg(g) } else { g })
.collect();
let mut parts = Vec::with_capacity(shares.len()); let mut parts = Vec::with_capacity(shares.len());
let mut remainders = Vec::with_capacity(shares.len()); let mut remainders = Vec::with_capacity(shares.len());
for share in shares { for share in shares {
@@ -278,8 +286,7 @@ pub fn allocate_cumulative(
// Exact exactly when Decimal kept every digit: a product it had to // Exact exactly when Decimal kept every digit: a product it had to
// round comes back with fewer places than its factors carry (a // round comes back with fewer places than its factors carry (a
// zero product, which it returns without places, is exact). // zero product, which it returns without places, is exact).
let exact = magnitude let exact = crate::kernel::Amount::checked_mul(magnitude, share)
.checked_mul(share)
.filter(|e| e.is_zero() || e.scale() == magnitude.scale() + share.scale()) .filter(|e| e.is_zero() || e.scale() == magnitude.scale() + share.scale())
.ok_or_else(|| { .ok_or_else(|| {
LedgerError::TooLargeToCompute(format!( LedgerError::TooLargeToCompute(format!(
@@ -290,7 +297,11 @@ pub fn allocate_cumulative(
LedgerError::TooLargeToCompute(format!("a member's share {share} of {magnitude}")) LedgerError::TooLargeToCompute(format!("a member's share {share} of {magnitude}"))
})?; })?;
parts.push(floor); 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( crate::kernel::apportion_cumulative(
magnitude, magnitude,
@@ -302,7 +313,7 @@ pub fn allocate_cumulative(
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("the members' shares of {total}")))?; .ok_or_else(|| LedgerError::TooLargeToCompute(format!("the members' shares of {total}")))?;
if loss { if loss {
for p in parts.iter_mut().filter(|p| !p.is_zero()) { for p in parts.iter_mut().filter(|p| !p.is_zero()) {
*p = -*p; *p = neg(*p);
} }
} }
Ok(parts) Ok(parts)
+55 -68
View File
@@ -4,7 +4,10 @@
//! (`docs/oracle.md`) diffs: the same fixture books through two engines must //! (`docs/oracle.md`) diffs: the same fixture books through two engines must
//! produce byte-identical [`snapshot`] output. //! 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 crate::{AccountType, Class, ClassId, JournalEntry, JournalLine, Ledger, LedgerError};
use chrono::NaiveDate; use chrono::NaiveDate;
use rust_decimal::Decimal; use rust_decimal::Decimal;
@@ -92,7 +95,8 @@ fn trial_balance_where(ledger: &Ledger, include: &dyn Fn(&JournalEntry) -> bool)
for line in entry.lines() { for line in entry.lines() {
let signed = crate::kernel::signed(line.side, line.amount.amount) let signed = crate::kernel::signed(line.side, line.amount.amount)
.expect("Decimal negation is exact"); .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(); let mut accounts: Vec<_> = ledger.chart().all().collect();
@@ -110,8 +114,8 @@ fn trial_balance_where(ledger: &Ledger, include: &dyn Fn(&JournalEntry) -> bool)
continue; continue;
} }
let (debit, credit) = crate::kernel::columns(movement).expect("Decimal negation is exact"); let (debit, credit) = crate::kernel::columns(movement).expect("Decimal negation is exact");
total_debits += debit; total_debits = add_in_range(total_debits, debit);
total_credits += credit; total_credits = add_in_range(total_credits, credit);
lines.push(TrialBalanceLine { lines.push(TrialBalanceLine {
code: account.code.clone(), code: account.code.clone(),
name: account.name.clone(), name: account.name.clone(),
@@ -140,7 +144,7 @@ pub struct ProfitAndLoss {
impl ProfitAndLoss { impl ProfitAndLoss {
/// Revenue minus expenses. Positive is profit. /// Revenue minus expenses. Positive is profit.
pub fn net_income(&self) -> Decimal { 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 { if account.placeholder {
continue; continue;
} }
let signed = if line.side == account.account_type.normal_side() { let signed = on_side(
line.amount.amount account.account_type.normal_side(),
} else { line.side,
-line.amount.amount line.amount.amount,
}; );
match account.account_type { match account.account_type {
AccountType::Revenue => revenue = add_exact(revenue, signed, "total revenue")?, AccountType::Revenue => revenue = add_exact(revenue, signed, "total revenue")?,
AccountType::Expense => expenses = add_exact(expenses, signed, "total expenses")?, AccountType::Expense => expenses = add_exact(expenses, signed, "total expenses")?,
@@ -297,7 +301,7 @@ pub struct BalanceSheet {
impl BalanceSheet { impl BalanceSheet {
/// The accounting equation: assets == liabilities + equity, exactly. /// The accounting equation: assets == liabilities + equity, exactly.
pub fn balanced(&self) -> bool { 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 { impl ProfitAndLossStatement {
/// Revenue minus expenses. Positive is profit. /// Revenue minus expenses. Positive is profit.
pub fn net_income(&self) -> Decimal { 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 { impl BalanceSheetStatement {
/// The accounting equation: assets == liabilities + equity, exactly. /// The accounting equation: assets == liabilities + equity, exactly.
pub fn balanced(&self) -> bool { 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) { if !include(entry, line) {
continue; continue;
} }
let signed = match line.side { let signed = signed_amount(line.side, line.amount.amount);
crate::Side::Debit => line.amount.amount,
crate::Side::Credit => -line.amount.amount,
};
let slot = movement.entry(line.account).or_default(); let slot = movement.entry(line.account).or_default();
*slot = add_exact(*slot, signed, "an account's movement")?; *slot = add_exact(*slot, signed, "an account's movement")?;
} }
@@ -425,10 +427,8 @@ fn statement_lines(
if account.placeholder || m.is_zero() { if account.placeholder || m.is_zero() {
continue; continue;
} }
let amount = match account.account_type.normal_side() { let amount = crate::kernel::normal_balance(account.account_type, m)
crate::Side::Debit => m, .expect("Decimal negation is exact");
crate::Side::Credit => -m,
};
out.insert( out.insert(
account.code.clone(), account.code.clone(),
( (
@@ -594,7 +594,7 @@ impl ProjectToDate {
/// Revenue less expenses: the project's contribution before overhead /// Revenue less expenses: the project's contribution before overhead
/// (WB-statement-7), since only its own tagged lines count. /// (WB-statement-7), since only its own tagged lines count.
pub fn net(&self) -> Decimal { 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 /// 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. /// 3. NEVER panics: None when the quotient can't be represented.
/// ``` /// ```
pub fn contribution_margin_pct(contribution: Decimal, revenue: Decimal) -> Option<Decimal> { pub fn contribution_margin_pct(contribution: Decimal, revenue: Decimal) -> Option<Decimal> {
let mut x = crate::kernel::percent_of( let x = crate::kernel::percent_of(
contribution, contribution,
revenue, revenue,
Decimal::new(1, 1), Decimal::new(1, 1),
crate::kernel::Rounding::HalfToEven, crate::kernel::Rounding::HalfToEven,
)?; )?;
// Display padding only: the margin always prints its one place. // Display padding only: the margin always prints its one place. It
x.rescale(1); // is a whole number of tenths, so writing it with one changes nothing.
Some(x) Some(crate::kernel::rescale_exact(x, 1).unwrap_or(x))
} }
/// The most months [`ProjectFigures::months`] holds: the period's last. /// The most months [`ProjectFigures::months`] holds: the period's last.
@@ -690,12 +690,13 @@ pub fn project_figures(
// before them). // before them).
let mut running = months let mut running = months
.iter() .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)?; .ok_or(LedgerError::AmountOutOfRange)?;
let mut months_net_to_date = Vec::with_capacity(months.len()); let mut months_net_to_date = Vec::with_capacity(months.len());
for m in &months { for m in &months {
running = running running = crate::kernel::Amount::checked_add(running, m.net())
.checked_add(m.net())
.ok_or(LedgerError::AmountOutOfRange)?; .ok_or(LedgerError::AmountOutOfRange)?;
months_net_to_date.push(running); 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 { let Some(account) = ledger.chart().get(line.account) else {
continue; continue;
}; };
let debit = matches!(line.side, crate::Side::Debit);
match account.account_type { match account.account_type {
AccountType::Revenue => { AccountType::Revenue => {
amount += if debit { amount = add_in_range(
-line.amount.amount amount,
} else { on_side(crate::Side::Credit, line.side, line.amount.amount),
line.amount.amount );
}
} }
AccountType::Expense => { AccountType::Expense => {
amount -= if debit { amount = sub_in_range(
line.amount.amount amount,
} else { on_side(crate::Side::Debit, line.side, line.amount.amount),
-line.amount.amount );
}
} }
_ => {} _ => {}
} }
@@ -952,10 +950,7 @@ pub fn general_ledger(
for entry in &entries { for entry in &entries {
let lines = entry.lines(); let lines = entry.lines();
for (i, line) in lines.iter().enumerate() { for (i, line) in lines.iter().enumerate() {
let signed = match line.side { let signed = signed_amount(line.side, line.amount.amount);
crate::Side::Debit => line.amount.amount,
crate::Side::Credit => -line.amount.amount,
};
if entry.date() < start { if entry.date() < start {
let slot = begin.entry(line.account).or_default(); let slot = begin.entry(line.account).or_default();
*slot = add_exact(*slot, signed, "an account's beginning balance")?; *slot = add_exact(*slot, signed, "an account's beginning balance")?;
@@ -1005,15 +1000,15 @@ pub fn general_ledger(
continue; continue;
} }
let normal = account.account_type.normal_side(); let normal = account.account_type.normal_side();
let to_normal = |m: Decimal| if normal == crate::Side::Debit { m } else { -m }; let to_normal = |m: Decimal| on_side(normal, crate::Side::Debit, m);
let beginning_balance = to_normal(begin_movement) + Decimal::ZERO; let beginning_balance = add_in_range(to_normal(begin_movement), Decimal::ZERO);
let mut balance = beginning_balance; let mut balance = beginning_balance;
let (mut total_debits, mut total_credits) = (Decimal::ZERO, Decimal::ZERO); let (mut total_debits, mut total_credits) = (Decimal::ZERO, Decimal::ZERO);
let mut posted = Vec::with_capacity(lines.len()); let mut posted = Vec::with_capacity(lines.len());
for (side, amount, mut p) in lines { for (side, amount, mut p) in lines {
balance = add_exact( balance = add_exact(
balance, balance,
if side == normal { amount } else { -amount }, on_side(normal, side, amount),
"an account's running balance", "an account's running balance",
)?; )?;
total_debits = add_exact(total_debits, p.debit, "an account's total debits")?; 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 /// don't carry yet (run `run_depreciation`); negative if the books
/// carry more. /// carry more.
pub fn unposted_depreciation(&self) -> Decimal { 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 /// 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 /// from a run; otherwise an entry made by hand (or a run reversed
/// after its asset left the books) is in them. /// after its asset left the books) is in them.
pub fn unattributed_accumulated(&self) -> Decimal { 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 /// Cost in the ledger's cost accounts that no held asset accounts for
/// (equipment bought but not registered), or negative if registered /// (equipment bought but not registered), or negative if registered
/// cost isn't in the books. /// cost isn't in the books.
pub fn unregistered_cost(&self) -> Decimal { 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() { let book_value = if disposed.is_some() {
Decimal::ZERO Decimal::ZERO
} else { } else {
a.cost crate::kernel::Amount::checked_sub(a.cost.amount, post)
.amount
.checked_sub(post)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s book value", a.id)))? .ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s book value", a.id)))?
}; };
Ok(Some(AssetRegisterRow { Ok(Some(AssetRegisterRow {
@@ -1745,23 +1738,18 @@ pub fn fixed_asset_register(
cost_accounts.insert(a.cost_account); cost_accounts.insert(a.cost_account);
accum_accounts.insert(a.accum_depr_account); accum_accounts.insert(a.accum_depr_account);
if row.disposed.is_none() { if row.disposed.is_none() {
cost = cost cost = crate::kernel::Amount::checked_add(cost, row.cost)
.checked_add(row.cost)
.ok_or_else(|| too_large("cost"))?; .ok_or_else(|| too_large("cost"))?;
scheduled = scheduled scheduled = crate::kernel::Amount::checked_add(scheduled, row.accumulated_scheduled)
.checked_add(row.accumulated_scheduled)
.ok_or_else(|| too_large("accumulated depreciation"))?; .ok_or_else(|| too_large("accumulated depreciation"))?;
posted_total = posted_total posted_total = crate::kernel::Amount::checked_add(posted_total, row.accumulated_posted)
.checked_add(row.accumulated_posted)
.ok_or_else(|| too_large("posted depreciation"))?; .ok_or_else(|| too_large("posted depreciation"))?;
match row.depreciable_basis { match row.depreciable_basis {
Some(b) => { Some(b) => {
depreciable_total = depreciable_total depreciable_total = crate::kernel::Amount::checked_add(depreciable_total, b)
.checked_add(b)
.ok_or_else(|| too_large("depreciable basis"))?; .ok_or_else(|| too_large("depreciable basis"))?;
if let Some(b) = row.tax_basis_723 { if let Some(b) = row.tax_basis_723 {
total_723 = total_723 total_723 = crate::kernel::Amount::checked_add(total_723, b)
.checked_add(b)
.ok_or_else(|| too_large("§723 basis"))?; .ok_or_else(|| too_large("§723 basis"))?;
} }
} }
@@ -1779,7 +1767,7 @@ pub fn fixed_asset_register(
tb.lines tb.lines
.iter() .iter()
.find(|l| &l.code == code) .find(|l| &l.code == code)
.map(|l| l.debit - l.credit) .map(|l| sub_in_range(l.debit, l.credit))
.unwrap_or(Decimal::ZERO) .unwrap_or(Decimal::ZERO)
}; };
Ok(AssetRegister { Ok(AssetRegister {
@@ -1788,17 +1776,16 @@ pub fn fixed_asset_register(
total_cost: cost, total_cost: cost,
total_accumulated_scheduled: scheduled, total_accumulated_scheduled: scheduled,
total_accumulated_posted: posted_total, total_accumulated_posted: posted_total,
total_book_value: cost total_book_value: crate::kernel::Amount::checked_sub(cost, posted_total)
.checked_sub(posted_total)
.ok_or_else(|| too_large("book value"))?, .ok_or_else(|| too_large("book value"))?,
total_depreciable_basis: depreciable_total, total_depreciable_basis: depreciable_total,
total_tax_basis_723: total_723, total_tax_basis_723: total_723,
missing_basis: missing, missing_basis: missing,
ledger_cost: sum_exact_of(&cost_accounts, |&id| net(id), "the ledger's asset cost")?, 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, &accum_accounts,
|&id| net(id), |&id| net(id),
"the ledger's accumulated depreciation", "the ledger's accumulated depreciation",
)?, )?),
}) })
} }
+17 -9
View File
@@ -365,17 +365,24 @@ fn present_as_rounded(parts: &mut [Decimal], total: Decimal, places: u32) {
let Some(&first) = rest.first() else { let Some(&first) = rest.first() else {
return; 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; let mut each = first;
if each.scale() > places || each.is_zero() { if each.scale() > places || each.is_zero() {
each.rescale(places); let written = kernel::rescale_exact(each, places);
debug_assert_eq!(each, first, "rescaling an amount never changes it"); 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 // Subtracting a zero (a month that rounded to nothing) leaves the
// total as it was, scale included; any other subtrahend widens it. // total as it was, scale included; any other subtrahend widens it.
if !each.is_zero() { if !each.is_zero() {
let before = *last; let written = kernel::rescale_exact(*last, total.scale().max(each.scale()));
last.rescale(total.scale().max(each.scale())); debug_assert!(
debug_assert_eq!(*last, before, "rescaling an amount never changes it"); written.is_some(),
"the last month is the total less whole steps"
);
*last = written.unwrap_or(*last);
} }
for part in rest.iter_mut() { for part in rest.iter_mut() {
*part = each; *part = each;
@@ -668,10 +675,12 @@ impl AmortizationSchedule {
/// The amount not yet recognized: the sum of the plan's unposted /// The amount not yet recognized: the sum of the plan's unposted
/// months. /// months.
pub fn remaining(&self) -> Result<Decimal, LedgerError> { pub fn remaining(&self) -> Result<Decimal, LedgerError> {
crate::kernel::total_of(
self.plan()? self.plan()?
.into_iter() .into_iter()
.filter(|(d, _)| !self.posted.contains(d)) .filter(|(d, _)| !self.posted.contains(d)),
.try_fold(Decimal::ZERO, |sum, (_, a)| sum.checked_add(a)) |(_, a)| a,
)
.ok_or_else(|| { .ok_or_else(|| {
LedgerError::TooLargeToCompute(format!("schedule {}'s remaining amount", self.id)) LedgerError::TooLargeToCompute(format!("schedule {}'s remaining amount", self.id))
}) })
@@ -808,8 +817,7 @@ pub fn validate_recurring_journaled(
Side::Debit => &mut debits, Side::Debit => &mut debits,
Side::Credit => &mut credits, Side::Credit => &mut credits,
}; };
*total = total *total = crate::kernel::Amount::checked_add(*total, money.amount)
.checked_add(money.amount)
.ok_or_else(|| LedgerError::TooLargeToCompute("the recurring entry's total".into()))?; .ok_or_else(|| LedgerError::TooLargeToCompute("the recurring entry's total".into()))?;
} }
if debits != credits { if debits != credits {
+5 -6
View File
@@ -850,9 +850,10 @@ pub fn parse_share(name: &str, s: &str) -> Result<Decimal, String> {
let s = s.trim(); let s = s.trim();
let bad = || format!("member {name}: share {s:?} must be like \"50%\" or \"0.5\""); let bad = || format!("member {name}: share {s:?} must be like \"50%\" or \"0.5\"");
let share = match s.strip_suffix('%') { let share = match s.strip_suffix('%') {
Some(pct) => decimal(pct.trim()) Some(pct) => crate::kernel::Amount::checked_div(
.ok_or_else(bad)? decimal(pct.trim()).ok_or_else(bad)?,
.checked_div(Decimal::from(100)) Decimal::from(100),
)
.ok_or_else(bad)?, .ok_or_else(bad)?,
None => decimal(s).ok_or_else(bad)?, None => decimal(s).ok_or_else(bad)?,
}; };
@@ -1404,9 +1405,7 @@ fn check_members(list: &[Value]) -> Result<Vec<Member>, String> {
} }
} }
if !members.is_empty() { if !members.is_empty() {
let total = members let total = crate::kernel::total_of(members.iter(), |m| m.share)
.iter()
.try_fold(Decimal::ZERO, |t, m| t.checked_add(m.share))
.ok_or("member shares are too large to add")?; .ok_or("member shares are too large to add")?;
if total != Decimal::ONE { if total != Decimal::ONE {
return Err(format!("member shares sum to {total}, not 100%")); return Err(format!("member shares sum to {total}, not 100%"));
+18 -13
View File
@@ -128,6 +128,7 @@
pub use crate::kernel::Direction; pub use crate::kernel::Direction;
use crate::kernel::{self, PartyTarget}; use crate::kernel::{self, PartyTarget};
use crate::money::{neg, on_side};
use crate::{AccountId, AccountType, EntryId, JournalEntry, Ledger, LedgerError, PartyId, Side}; use crate::{AccountId, AccountType, EntryId, JournalEntry, Ledger, LedgerError, PartyId, Side};
use rust_decimal::Decimal; use rust_decimal::Decimal;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -257,7 +258,12 @@ pub fn check_shares_journaled(
)); ));
} }
any_percent = true; 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 => {} Share::Derived => {}
} }
@@ -275,9 +281,7 @@ fn too_large(what: String) -> crate::LedgerError {
/// The sum of `values`, or None past exact arithmetic. /// The sum of `values`, or None past exact arithmetic.
fn checked_sum(values: impl IntoIterator<Item = Decimal>) -> Option<Decimal> { fn checked_sum(values: impl IntoIterator<Item = Decimal>) -> Option<Decimal> {
values crate::kernel::total(values)
.into_iter()
.try_fold(Decimal::ZERO, |s, v| s.checked_add(v))
} }
/// Split `magnitude` (non-negative) by `weights` (positive, any sum): each /// 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 kind(a) == Some(AccountType::Asset) && !money.cash.contains(&a) && Some(a) != receivables
}; };
let add = |t: &mut Decimal, v: Decimal| -> Result<(), LedgerError> { 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(()) Ok(())
}; };
let zero = Decimal::ZERO; let zero = Decimal::ZERO;
@@ -528,12 +532,13 @@ pub fn split(
let parts: Vec<Decimal> = named let parts: Vec<Decimal> = named
.iter() .iter()
.map(|m| { .map(|m| {
checked_sum(entry.lines().iter().filter(|l| on(m, l.account)).map(|l| { checked_sum(
match l.side { entry
Side::Credit => l.amount.amount, .lines()
Side::Debit => -l.amount.amount, .iter()
} .filter(|l| on(m, l.account))
})) .map(|l| on_side(Side::Credit, l.side, l.amount.amount)),
)
.map(|s| s.abs()) .map(|s| s.abs())
}) })
.collect::<Option<_>>() .collect::<Option<_>>()
@@ -576,7 +581,7 @@ pub fn split(
let left: Vec<Decimal> = sizes let left: Vec<Decimal> = sizes
.iter() .iter()
.zip(&in_kind_sizes) .zip(&in_kind_sizes)
.map(|(s, k)| s.checked_sub(*k)) .map(|(s, k)| crate::kernel::Amount::checked_sub(*s, *k))
.collect::<Option<_>>() .collect::<Option<_>>()
.ok_or_else(past_exact)?; .ok_or_else(past_exact)?;
let cash_sizes = if cash == checked_sum(left.iter().copied()).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)? share_by(cash, &left, &order).ok_or_else(past_exact)?
}; };
let negative = target.amount < Decimal::ZERO; 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 Ok(shares
.iter() .iter()
.enumerate() .enumerate()
+18 -11
View File
@@ -12,6 +12,7 @@
//! Scope is deliberate, like fixed assets: no tax depreciation (MACRS, //! Scope is deliberate, like fixed assets: no tax depreciation (MACRS,
//! Section 179, bonus), no basis computations, no filing. Not tax advice. //! Section 179, bonus), no basis computations, no filing. Not tax advice.
use crate::money::{neg, sub_in_range};
use crate::{AccountType, Ledger, LedgerError}; use crate::{AccountType, Ledger, LedgerError};
use chrono::NaiveDate; use chrono::NaiveDate;
use rust_decimal::Decimal; use rust_decimal::Decimal;
@@ -513,21 +514,29 @@ pub struct TaxSummary {
impl TaxSummary { impl TaxSummary {
/// Book net income of the categorized accounts. /// Book net income of the categorized accounts.
pub fn book_net(&self) -> Decimal { pub fn book_net(&self) -> Decimal {
sum(&self.income, |l| l.book) sub_in_range(
- sum(&self.cost_of_goods, |l| l.book) sub_in_range(
- sum(&self.deductions, |l| l.book) 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. /// Income less deductible amounts, before the CPA's other adjustments.
pub fn tax_net(&self) -> Decimal { pub fn tax_net(&self) -> Decimal {
sum(&self.income, |l| l.tax) sub_in_range(
- sum(&self.cost_of_goods, |l| l.tax) sub_in_range(
- sum(&self.deductions, |l| l.tax) 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 { 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, /// 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 // Income from an expense-type account (e.g. a contra) counts with
// its sign flipped, so returns reduce receipts. // its sign flipped, so returns reduce receipts.
let book = if c.kind == TaxKind::Income && account.account_type == AccountType::Expense { let book = if c.kind == TaxKind::Income && account.account_type == AccountType::Expense {
-line.amount neg(line.amount)
} else { } else {
line.amount line.amount
}; };
@@ -593,9 +602,7 @@ pub fn tax_summary(
(&mut build.line, &mut build.shares) (&mut build.line, &mut build.shares)
}; };
entry.accounts.push(name); entry.accounts.push(name);
entry.book = entry entry.book = crate::kernel::Amount::checked_add(entry.book, book)
.book
.checked_add(book)
.ok_or_else(|| too_large("book amount"))?; .ok_or_else(|| too_large("book amount"))?;
shares.push((book, pct)); shares.push((book, pct));
} }
+89 -80
View File
@@ -80,6 +80,7 @@
use crate::k1::{K1Kind, K1Row, k1_detail}; use crate::k1::{K1Kind, K1Row, k1_detail};
use crate::money::sum_exact_of; use crate::money::sum_exact_of;
use crate::money::{neg, signed_amount};
use crate::reports::MemberCapital; use crate::reports::MemberCapital;
use crate::{AccountId, AssetId, AssetStatus, EntryId, Ledger, LedgerError, Side}; use crate::{AccountId, AssetId, AssetStatus, EntryId, Ledger, LedgerError, Side};
use chrono::NaiveDate; use chrono::NaiveDate;
@@ -120,15 +121,10 @@ fn disposal_depreciation(
}) else { }) else {
return Ok(Decimal::ZERO); return Ok(Decimal::ZERO);
}; };
e.lines() crate::kernel::total_of(
.iter() e.lines().iter().filter(|l| l.account == a.expense_account),
.filter(|l| l.account == a.expense_account) |l| signed_amount(l.side, l.amount.amount),
.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))) .ok_or_else(|| LedgerError::TooLargeToCompute(format!("asset {}'s depreciation", a.id)))
} }
@@ -437,10 +433,7 @@ impl RunningSplit {
weights.len() weights.len()
))); )));
} }
let sum = weights let sum = crate::kernel::total_of(weights.iter(), |w| *w).ok_or_else(too_large)?;
.iter()
.try_fold(Decimal::ZERO, |t, w| t.checked_add(*w))
.ok_or_else(too_large)?;
Ok((sum > Decimal::ZERO).then_some(sum)) Ok((sum > Decimal::ZERO).then_some(sum))
} }
@@ -469,11 +462,14 @@ impl RunningSplit {
} }
let mut exact = self.exact.clone(); let mut exact = self.exact.clone();
for (x, w) in exact.iter_mut().zip(weights) { for (x, w) in exact.iter_mut().zip(weights) {
*x = x // A sum of rounded quotients, itself rounded where 96 bits
.checked_add(Self::share(whole, *w, sum)?) // 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)?; .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 // A loss is rounded as its magnitude, then negated; at a running
// whole of zero, by the sign of this whole (INVARIANT 2). // whole of zero, by the sign of this whole (INVARIANT 2).
let sign = if total < Decimal::ZERO || (total.is_zero() && whole < Decimal::ZERO) { 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. // rounded down to the cent, what rounding took its remainder.
let snapped: Vec<Decimal> = exact let snapped: Vec<Decimal> = exact
.iter() .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::<Option<_>>() .collect::<Option<_>>()
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
let mut parts: Vec<Decimal> = snapped let mut parts: Vec<Decimal> = snapped
@@ -493,10 +495,20 @@ impl RunningSplit {
.map(|x| round_places(*x, 2, Rounding::TowardNegativeInfinity)) .map(|x| round_places(*x, 2, Rounding::TowardNegativeInfinity))
.collect::<Option<_>>() .collect::<Option<_>>()
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
let remainders: Vec<Decimal> = snapped.iter().zip(&parts).map(|(x, p)| x - p).collect(); let remainders: Vec<Decimal> = snapped
let given: Vec<Decimal> = self.given.iter().map(|g| g * sign).collect(); .iter()
.zip(&parts)
.map(|(x, p)| crate::kernel::Amount::checked_sub(*x, *p))
.collect::<Option<_>>()
.ok_or_else(too_large)?;
let given: Vec<Decimal> = self
.given
.iter()
.map(|g| crate::kernel::Amount::checked_mul(*g, sign))
.collect::<Option<_>>()
.ok_or_else(too_large)?;
crate::kernel::apportion_cumulative( crate::kernel::apportion_cumulative(
total * sign, crate::kernel::Amount::checked_mul(total, sign).ok_or_else(too_large)?,
&mut parts, &mut parts,
&remainders, &remainders,
Decimal::new(1, 2), Decimal::new(1, 2),
@@ -504,8 +516,8 @@ impl RunningSplit {
) )
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
for (p, g) in parts.iter_mut().zip(self.given.iter_mut()) { for (p, g) in parts.iter_mut().zip(self.given.iter_mut()) {
*p *= sign; *p = crate::kernel::Amount::checked_mul(*p, sign).ok_or_else(too_large)?;
*g = g.checked_add(*p).ok_or_else(too_large)?; *g = crate::kernel::Amount::checked_add(*g, *p).ok_or_else(too_large)?;
} }
self.exact = exact; self.exact = exact;
self.total = total; self.total = total;
@@ -538,12 +550,16 @@ impl RunningSplit {
let mut exact = self.exact.clone(); let mut exact = self.exact.clone();
let mut given = self.given.clone(); let mut given = self.given.clone();
for i in 0..n { for i in 0..n {
exact[i] = exact[i] // The rounding difference `split`'s sum is the other half of.
.checked_sub(Self::share(whole, weights[i], sum)?) exact[i] = crate::kernel::Amount::checked_sub_rounded(
exact[i],
Self::share(whole, weights[i], sum)?,
)
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
given[i] = given[i].checked_sub(parts[i]).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.exact = exact;
self.given = given; self.given = given;
Ok(()) Ok(())
@@ -611,21 +627,17 @@ fn entry_wholes(
// Distributions are negative lines; weights are what each took. // 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() .into_iter()
.map(|d| -d) .map(neg)
.collect(); .collect();
if taken.iter().any(|t| *t > Decimal::ZERO) { if taken.iter().any(|t| *t > Decimal::ZERO) {
let property = e let property = crate::kernel::total_of(
.lines() e.lines().iter().filter(|l| {
.iter()
.filter(|l| {
l.side == Side::Credit && crate::k1::is_property_account(ledger, cash, l.account) 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)) |l| 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)?; .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); let property = property.min(total_taken);
if property > Decimal::ZERO { if property > Decimal::ZERO {
out.push((DISTRIBUTED, property, taken)); out.push((DISTRIBUTED, property, taken));
@@ -736,13 +748,12 @@ fn entry_property(
entry: &crate::JournalEntry, entry: &crate::JournalEntry,
cash: &[AccountId], cash: &[AccountId],
) -> Result<EntryProperty, LedgerError> { ) -> Result<EntryProperty, LedgerError> {
let pool = entry let pool = crate::kernel::total_of(
.lines() entry.lines().iter().filter(|l| {
.iter()
.filter(|l| {
l.side == Side::Debit && crate::k1::is_property_account(ledger, cash, l.account) 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)) |l| l.amount.amount,
)
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
// Prepaid accounts: those a prepaid-expense schedule amortizes, and no // Prepaid accounts: those a prepaid-expense schedule amortizes, and no
// registered asset carries its cost in (INVARIANT 6). // registered asset carries its cost in (INVARIANT 6).
@@ -751,17 +762,16 @@ fn entry_property(
s.kind == crate::schedules::ScheduleKind::PrepaidExpense && s.balance_account == id s.kind == crate::schedules::ScheduleKind::PrepaidExpense && s.balance_account == id
}) && !ledger.registered_assets().any(|a| a.cost_account == id) }) && !ledger.registered_assets().any(|a| a.cost_account == id)
}; };
let prepaid = entry let prepaid = crate::kernel::total_of(
.lines() entry.lines().iter().filter(|l| {
.iter()
.filter(|l| {
l.side == Side::Debit l.side == Side::Debit
&& crate::k1::is_property_account(ledger, cash, l.account) && crate::k1::is_property_account(ledger, cash, l.account)
&& prepaid_account(l.account) && prepaid_account(l.account)
}) }),
.try_fold(Decimal::ZERO, |t, l| t.checked_add(l.amount.amount)) |l| l.amount.amount,
)
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
let pool = pool.checked_sub(prepaid).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); let (mut linked, mut big, mut unknown) = (Decimal::ZERO, Decimal::ZERO, Decimal::ZERO);
for a in ledger for a in ledger
.registered_assets() .registered_assets()
@@ -772,11 +782,14 @@ fn entry_property(
// Its book amount in the entry: the value at contribution, which // Its book amount in the entry: the value at contribution, which
// the books recorded (D-41), or the book cost. // the books recorded (D-41), or the book cost.
let value = a.fmv_at_contribution().unwrap_or(a.cost.amount); 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 { 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. // 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 { if linked > pool {
@@ -787,11 +800,11 @@ fn entry_property(
mismatch: Some((linked, pool)), 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 { Ok(EntryProperty {
built_in_gain: big, built_in_gain: big,
prepaid, 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, mismatch: None,
}) })
} }
@@ -855,8 +868,9 @@ fn span(
book: pp, book: pp,
}); });
} }
big[i] = big[i].checked_add(g).ok_or_else(too_large)?; big[i] = crate::kernel::Amount::checked_add(big[i], g).ok_or_else(too_large)?;
without[i] = without[i].checked_add(w).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 { if let Some((linked, property)) = p.mismatch {
prop_open[i].push(Open::LinkedValueExceedsEntry { prop_open[i].push(Open::LinkedValueExceedsEntry {
entry: id, entry: id,
@@ -873,7 +887,8 @@ fn span(
for i in 0..n { for i in 0..n {
let book = part.get(DISTRIBUTED, i); let book = part.get(DISTRIBUTED, i);
if !book.is_zero() { 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 }); dist_open[i].push(Open::PropertyDistribution { entry: id, book });
} }
} }
@@ -888,13 +903,15 @@ fn span(
if a.in_service_date <= end && !gone_before { if a.in_service_date <= end && !gone_before {
in_service = true; in_service = true;
} }
let d = ledger let d = crate::kernel::Amount::checked_add(
.depreciation_posted_between(a.id, start, end)? ledger.depreciation_posted_between(a.id, start, end)?,
.checked_add(disposal_depreciation(ledger, a, start, end)?) disposal_depreciation(ledger, a, start, end)?,
)
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
book_depr = book_depr.checked_add(d).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()) { 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() { if in_service || !book_depr.is_zero() {
@@ -930,10 +947,8 @@ fn span(
None => TaxLine::complete(book.beginning), None => TaxLine::complete(book.beginning),
}; };
let contributions_property = TaxLine { let contributions_property = TaxLine {
known: book known: crate::kernel::Amount::checked_sub(book.contributions_property, big[i])
.contributions_property .and_then(|x| crate::kernel::Amount::checked_sub(x, without[i]))
.checked_sub(big[i])
.and_then(|x| x.checked_sub(without[i]))
.ok_or_else(too_large)?, .ok_or_else(too_large)?,
open: std::mem::take(&mut prop_open[i]), open: std::mem::take(&mut prop_open[i]),
notes: std::mem::take(&mut prop_notes[i]), notes: std::mem::take(&mut prop_notes[i]),
@@ -957,20 +972,16 @@ fn span(
notes: Vec::new(), notes: Vec::new(),
}; };
let distributions = TaxLine { let distributions = TaxLine {
known: book known: crate::kernel::Amount::checked_sub(book.distributions, distributed[i])
.distributions
.checked_sub(distributed[i])
.ok_or_else(too_large)?, .ok_or_else(too_large)?,
open: std::mem::take(&mut dist_open[i]), open: std::mem::take(&mut dist_open[i]),
notes: Vec::new(), notes: Vec::new(),
}; };
let known = beginning let known = crate::kernel::Amount::checked_add(beginning.known, book.contributions_cash)
.known .and_then(|x| crate::kernel::Amount::checked_add(x, contributions_property.known))
.checked_add(book.contributions_cash) .and_then(|x| crate::kernel::Amount::checked_add(x, net_income.known))
.and_then(|x| x.checked_add(contributions_property.known)) .and_then(|x| crate::kernel::Amount::checked_add(x, other.known))
.and_then(|x| x.checked_add(net_income.known)) .and_then(|x| crate::kernel::Amount::checked_sub(x, distributions.known))
.and_then(|x| x.checked_add(other.known))
.and_then(|x| x.checked_sub(distributions.known))
.ok_or_else(too_large)?; .ok_or_else(too_large)?;
let ending = TaxLine { let ending = TaxLine {
known, known,
@@ -987,9 +998,7 @@ fn span(
notes: Vec::new(), notes: Vec::new(),
}; };
let reconciliation = Reconciliation { let reconciliation = Reconciliation {
beginning: book beginning: crate::kernel::Amount::checked_sub(book.beginning, beginning.known)
.beginning
.checked_sub(beginning.known)
.ok_or_else(too_large)?, .ok_or_else(too_large)?,
built_in_gain_704c: big[i], built_in_gain_704c: big[i],
property_without_basis: without[i], property_without_basis: without[i],
@@ -2340,7 +2340,7 @@ fn every_claim_is_backed() {
} }
assert_eq!( assert_eq!(
EXCEPTIONS.len(), EXCEPTIONS.len(),
15, 16,
"the kernel exception list changes only on purpose" "the kernel exception list changes only on purpose"
); );
// No ordinary function may fall through the right-law check: the // 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", "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", "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", "split_by_weights_with",
"a Kani harness and a law", "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 /// `split_by_weights_with` allocate, so every harness proves their
/// fixed-array helper; `round_places`, `round_minor` and `fx_booked_minor` /// fixed-array helper; `round_places`, `round_minor` and `fx_booked_minor`
/// are Decimal wrappers whose law is the inner function's; `Direction::key` /// 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 /// is a wire name, `MonthPart::is_valid` a range predicate and
/// at all. A new name here is a deliberate widening, never a silent hole. /// `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] = &[ const SKIPPED: &[&str] = &[
"movements", "movements",
"reversal", "reversal",
@@ -2542,6 +2548,7 @@ const SKIPPED: &[&str] = &[
"round_places", "round_places",
"round_minor", "round_minor",
"fx_booked_minor", "fx_booked_minor",
"rescale_exact",
"split_by_weights_with", "split_by_weights_with",
]; ];
@@ -125,6 +125,42 @@ proptest! {
prop_assert_eq!(got.is_some(), representable(&exact), "{} - {}", a, b); 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. /// Multiply: the same laws.
#[test] #[test]
fn mul_is_exact_or_none((a, b) in arb_pair()) { fn mul_is_exact_or_none((a, b) in arb_pair()) {
@@ -258,6 +258,73 @@ proptest! {
prop_assert_eq!(got.to_string(), want.to_string()); 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. /// The edge table, each row checked by hand.
@@ -5,3 +5,4 @@
# It is recommended to check this file in to source control so that # It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases. # 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 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)]
+153
View File
@@ -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 <package>` 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.
+1
View File
@@ -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 <target> <secs>` | 10 min each | weekly | | 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 <target> <secs>` | 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 | | 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 | | 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` | | 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 | | 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) | | Benchmarks | a baseline (6) | `ledger-core/benches/books.rs`, `ledger-store/benches/store.rs` | `just bench` | ~2 min | none (no budget, by decision) |
+19 -5
View File
@@ -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 never refused; they now prove both, from the rational alone. One
refusal remains by design: a product that is not exact, rounded to a 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. 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 - **The sweep changed no posted figure.** Every golden and existing test
passed unchanged. `round_places` reproduces `round_dp_with_strategy` to passed unchanged. `round_places` reproduces `round_dp_with_strategy` to
the character except a negative-zero input (which no call site can 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` `checked_sub` and `checked_mul` for `Decimal` are exact or `None`
(`tests/kernel_bridge/decimal_exact.rs`: `Some` exactly when the exact (`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 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 `checked_div` at 28 significant digits (K-U3's
`finding_the_quotients_rounding_can_cross_a_step`, K-U5's `the_edges` `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 at `Decimal::MAX / 2`), a share's `checked_mul_rounded`, and a running
edge is reachable by a posted line (the line cap is 10^15, and total of such shares, `checked_add_rounded` and `checked_sub_rounded`
schedules refuse totals of `EXACT_LIMIT` or more), so the laws hold at (K-U11: the K-1 worksheet's running split, whose thirds of 28 digits
the engine's inputs. Not proved by Kani: the 256-bit helpers, which 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`. rest on the bridge properties and unit tests against `num_bigint`.
- **The FX overflow harness proves two concrete cases, not every - **The FX overflow harness proves two concrete cases, not every
overflow.** `fx_booked_refuses_overflow` proves `i64::MAX × 2` and overflow.** `fx_booked_refuses_overflow` proves `i64::MAX × 2` and
+18
View File
@@ -37,6 +37,7 @@ check-shard shard:
cargo clippy --workspace --all-targets -- -D warnings cargo clippy --workspace --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --quiet RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --quiet
just server-only just server-only
just kernel-only
just check-shards-agree just check-shards-agree
just deny just deny
just notices-check just notices-check
@@ -58,6 +59,23 @@ check-shard shard:
;; ;;
esac 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 # What every dependency must be (deny.toml): free of known vulnerabilities
# (the RustSec database, fetched now), not yanked, under a licence that # (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. # fits MIT OR Apache-2.0, and from crates.io or the bookspec repository.