fix(core): Decimal arithmetic in ledger-core goes through the kernel (K-U11a)

Bar item 1: money arithmetic lives in kernel/ and nowhere else.
scripts/raw-decimal-arith.sh listed 210 places in ledger-core that did
not: raw +, -, * and unary minus (which panic past Decimal's range), and
checked_add / checked_sub / checked_mul / checked_div calls that
resolved to rust_decimal's inherent methods (which round silently past
28 digits) and not to the kernel's Amount. 199 of them now call the
kernel: Amount's methods by their full path, total / total_of for the
hand-rolled sums, normal_balance, and money.rs's sign and in-range
helpers.

The rewrite was done by a script from the compiler's own line and
column for each site, so no site was copied by hand; the few that
needed a decision are explicit:
- a balance sheet that cannot add liabilities and equity is not
  balanced (it panicked);
- a template's shares, a party's percents, a reconciliation's book and
  cleared balances and a reversal's document movements refuse with
  TooLargeToCompute or their own message where they panicked;
- tax_capital's split refuses where a product by the sign could not be
  taken, and collects its remainders as Options.
No figure moves: every site computes what it computed, by the same
operations in the same order.

Left, each for a named reason (the detector prints these 11):
money.rs 139 and 150 and periods.rs 149 and 202 (K-U10a rewrites them),
audit.rs 355 and 511 (V-D3 is in them), ledger.rs 4048 (a share times
the closed total: checked_mul_rounded, with K-U10a), and four rescale
calls (money.rs 302, reports.rs 637, schedules.rs 370 and 377) that
need a kernel function of their own.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude committed 2026-11-09 17:22:17 -07:00
1 parent e0c78a783b
commit 32725fb669
19 files changed
+401 -394

No files matched your search

+18 -13
View File
@@ -128,6 +128,7 @@
pub use crate::kernel::Direction;
use crate::kernel::{self, PartyTarget};
use crate::money::{neg, on_side};
use crate::{AccountId, AccountType, EntryId, JournalEntry, Ledger, LedgerError, PartyId, Side};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
@@ -257,7 +258,12 @@ pub fn check_shares_journaled(
));
}
any_percent = true;
percent += p;
percent = crate::kernel::Amount::checked_add(percent, p).ok_or_else(|| {
format!(
"party {}'s percent has too many digits to add up exactly",
s.party
)
})?;
}
Share::Derived => {}
}
@@ -275,9 +281,7 @@ fn too_large(what: String) -> crate::LedgerError {
/// The sum of `values`, or None past exact arithmetic.
fn checked_sum(values: impl IntoIterator<Item = Decimal>) -> Option<Decimal> {
values
.into_iter()
.try_fold(Decimal::ZERO, |s, v| s.checked_add(v))
crate::kernel::total(values)
}
/// Split `magnitude` (non-negative) by `weights` (positive, any sum): each
@@ -407,7 +411,7 @@ fn original_target(
kind(a) == Some(AccountType::Asset) && !money.cash.contains(&a) && Some(a) != receivables
};
let add = |t: &mut Decimal, v: Decimal| -> Result<(), LedgerError> {
*t = t.checked_add(v).ok_or_else(past_exact)?;
*t = crate::kernel::Amount::checked_add(*t, v).ok_or_else(past_exact)?;
Ok(())
};
let zero = Decimal::ZERO;
@@ -528,12 +532,13 @@ pub fn split(
let parts: Vec<Decimal> = named
.iter()
.map(|m| {
checked_sum(entry.lines().iter().filter(|l| on(m, l.account)).map(|l| {
match l.side {
Side::Credit => l.amount.amount,
Side::Debit => -l.amount.amount,
}
}))
checked_sum(
entry
.lines()
.iter()
.filter(|l| on(m, l.account))
.map(|l| on_side(Side::Credit, l.side, l.amount.amount)),
)
.map(|s| s.abs())
})
.collect::<Option<_>>()
@@ -576,7 +581,7 @@ pub fn split(
let left: Vec<Decimal> = sizes
.iter()
.zip(&in_kind_sizes)
.map(|(s, k)| s.checked_sub(*k))
.map(|(s, k)| crate::kernel::Amount::checked_sub(*s, *k))
.collect::<Option<_>>()
.ok_or_else(past_exact)?;
let cash_sizes = if cash == checked_sum(left.iter().copied()).ok_or_else(past_exact)? {
@@ -587,7 +592,7 @@ pub fn split(
share_by(cash, &left, &order).ok_or_else(past_exact)?
};
let negative = target.amount < Decimal::ZERO;
let signed = |v: Decimal| if negative && !v.is_zero() { -v } else { v };
let signed = |v: Decimal| if negative && !v.is_zero() { neg(v) } else { v };
Ok(shares
.iter()
.enumerate()