merge: the tools', the exports' and the imports' Decimal arithmetic goes through the kernel (K-U12)

Fifty places in ledger-mcp (19), ledger-import (18) and ledger-package
(13), now zero. Signs come from money::neg, signed_amount and on_side;
sums of posted figures from the kernel's exact total and add_in_range /
sub_in_range; the checked sums that already had a "too large" outcome
keep it and now get it from the exact operation, where rust_decimal's
own would have rounded and gone on.

No figure changes. What is not a plain sign or sum:

- A template's equal shares (100 / n, to two places, the last taking the
  remainder) are the same three steps through the kernel; no owners now
  gives no shares where the raw division panicked (no caller can ask).
- The exports' money and share text padded to two places with
  Decimal::rescale, which can round; kernel::rescale_exact cannot.
- The tools' own profit and loss by class signs each line with
  money::on_side, one statement of the rule the two matches spelled out.
- The payment summary adds what was deposited after the engine has
  accepted the settlement (on the books or on a probe), so those figures
  are in range.

Worker: Claude Sonnet 5.5, high effort, from a per-site table. The diff
was read line by line against the table; the detector and the three
suites were run again here before the crates joined kernel_only_crates.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude committed 2026-11-10 00:45:21 -07:00
commit a167766dd4
18 files changed
+94 -69

No files matched your search

+2 -2
View File
@@ -118,7 +118,7 @@ pub fn parse_bank_csv_with(
4 => {
// Money out in the third column, money in in the fourth.
match (!fields[2].is_empty(), !fields[3].is_empty()) {
(true, false) => -parse_amount(fields[2])?,
(true, false) => ledger_core::money::neg(parse_amount(fields[2])?),
(false, true) => parse_amount(fields[3])?,
(false, false) => Decimal::ZERO,
(true, true) => {
@@ -227,7 +227,7 @@ fn parse_amount(s: &str) -> Result<Decimal, BankCsvError> {
return Err(bad());
}
if neg {
amount = -amount;
amount = ledger_core::money::neg(amount);
}
Ok(amount)
}
+1 -4
View File
@@ -994,10 +994,7 @@ pub fn journal_to_iif(
/// Debit positive, credit negative (Intuit: "Debit amounts are always
/// positive, credit amounts are always negative").
fn signed(side: Side, amount: Decimal) -> Decimal {
match side {
Side::Debit => amount,
Side::Credit => -amount,
}
ledger_core::money::signed_amount(side, amount)
}
/// Two decimal places, no thousands separators.
+1 -1
View File
@@ -266,7 +266,7 @@ pub fn template_data(doc: &InvoiceDoc) -> Result<serde_json::Value, PdfError> {
"total": dollars(doc.total),
"settled": doc.settled.iter().map(|(label, a)| serde_json::json!({
"label": label,
"amount": dollars(-*a),
"amount": dollars(ledger_core::money::neg(*a)),
})).collect::<Vec<_>>(),
"balance_label": "Balance due",
"balance": dollars(doc.balance),
+28 -9
View File
@@ -13,6 +13,8 @@
use chrono::{Datelike, NaiveDate};
use ledger_core::RETAINED_EARNINGS_CODE;
use ledger_core::kernel::total_of;
use ledger_core::money::{add_in_range, sub_in_range};
use ledger_core::reports::{
BalanceSheetStatement, CashFlowSection, CashFlowStatement, MembersEquityStatement,
ProfitAndLossStatement, StatementLine, TrialBalance,
@@ -275,9 +277,14 @@ pub fn balance_sheet(
.iter()
.map(|l| one(RowKind::Line, format!("{} {}", l.code, l.name), l.amount)),
);
let retained: Decimal = retained.iter().map(|l| l.amount).sum::<Decimal>()
+ bs.current_earnings
- earnings.net_income_ytd;
let retained: Decimal = sub_in_range(
add_in_range(
total_of(retained.iter(), |l| l.amount)
.expect("figures drawn from the books are in range, so their sum is"),
bs.current_earnings,
),
earnings.net_income_ytd,
);
if !retained.is_zero() {
rows.push(one(RowKind::Line, "Retained earnings", retained));
}
@@ -288,7 +295,7 @@ pub fn balance_sheet(
));
} else {
rows.extend(account_lines(&bs.equity));
let prior = bs.current_earnings - earnings.unclosed;
let prior = sub_in_range(bs.current_earnings, earnings.unclosed);
if !prior.is_zero() {
rows.push(one(
RowKind::Line,
@@ -307,7 +314,7 @@ pub fn balance_sheet(
rows.push(one(
RowKind::Total,
format!("Total liabilities and {}", equity_name.to_lowercase()),
bs.total_liabilities + bs.total_equity,
add_in_range(bs.total_liabilities, bs.total_equity),
));
statement(
"Balance Sheet",
@@ -482,7 +489,11 @@ pub fn members_equity(me: &MembersEquityStatement) -> Statement {
row(RowKind::Line, "Beginning balance", pick(&|c| c.beginning)),
row(RowKind::Line, "Contributions", pick(&|c| c.contributions)),
row(RowKind::Line, "Net income (loss)", pick(&|c| c.net_income)),
row(RowKind::Line, "Distributions", pick(&|c| -c.distributions)),
row(
RowKind::Line,
"Distributions",
pick(&|c| ledger_core::money::neg(c.distributions)),
),
];
if !me.total.other.is_zero() {
rows.push(row(RowKind::Line, "Other changes", pick(&|c| c.other)));
@@ -501,7 +512,13 @@ pub fn members_equity(me: &MembersEquityStatement) -> Statement {
/// difference where they disagree (meals at 50%, penalties at 0%), and any
/// account still needing a category.
pub fn tax_summary(ts: &ledger_core::TaxSummary) -> Statement {
let diff = |b: Decimal, t: Decimal| if b == t { None } else { Some(b - t) };
let diff = |b: Decimal, t: Decimal| {
if b == t {
None
} else {
Some(sub_in_range(b, t))
}
};
let lines = |ls: &[ledger_core::TaxSummaryLine]| -> Vec<Row> {
ls.iter()
.map(|l| {
@@ -519,8 +536,10 @@ pub fn tax_summary(ts: &ledger_core::TaxSummary) -> Statement {
.collect()
};
let total = |kind, label: &str, ls: &[ledger_core::TaxSummaryLine]| {
let b: Decimal = ls.iter().map(|l| l.book).sum();
let t: Decimal = ls.iter().map(|l| l.tax).sum();
let b: Decimal = total_of(ls.iter(), |l| l.book)
.expect("figures drawn from the books are in range, so their sum is");
let t: Decimal = total_of(ls.iter(), |l| l.tax)
.expect("figures drawn from the books are in range, so their sum is");
row(kind, label, vec![Some(b), Some(t), diff(b, t)])
};
let mut rows = vec![section("Income")];
+9 -2
View File
@@ -115,10 +115,17 @@ fn acct(code: &str, name: &str, t: &str, tax: Option<&str>) -> ChartRow {
/// Equal shares for `n` owners as percents to two places, the last
/// absorbing the remainder so they sum to exactly 100.
fn equal_shares(n: usize) -> Vec<Decimal> {
let each = (Decimal::from(100) / Decimal::from(n as u64)).round_dp(2);
use ledger_core::kernel::{Amount, Rounding, round_places, total};
let hundred = Decimal::from(100);
let Some(each) = Amount::checked_div(hundred, Decimal::from(n as u64))
.and_then(|q| round_places(q, 2, Rounding::HalfToEven))
else {
return Vec::new(); // no owners: no shares (the raw `/` panicked here)
};
let mut v = vec![each; n];
if let Some((last, rest)) = v.split_last_mut() {
*last = Decimal::from(100) - rest.iter().sum::<Decimal>();
let given = total(rest.iter().copied()).expect("fewer than a hundred percent, n times");
*last = Amount::checked_sub(hundred, given).expect("a hundred minus the shares given fits");
}
v
}
+2 -2
View File
@@ -387,11 +387,11 @@ fn general_journal(
match line.side {
ledger_core::Side::Debit => {
number(sheet, row, 5, line.amount.amount, &f.plain)?;
debits += line.amount.amount;
debits = ledger_core::money::add_in_range(debits, line.amount.amount);
}
ledger_core::Side::Credit => {
number(sheet, row, 6, line.amount.amount, &f.plain)?;
credits += line.amount.amount;
credits = ledger_core::money::add_in_range(credits, line.amount.amount);
}
}
row += 1;
+1 -5
View File
@@ -1343,11 +1343,7 @@ fn preview_lines_for(
.account_balance(*account_id)
.map_err(|e| e.to_string())?;
let normal = account.account_type.normal_side();
let delta = if *side == normal {
amount.amount
} else {
-amount.amount
};
let delta = ledger_core::money::on_side(normal, *side, amount.amount);
let after =
ledger_core::money::add_exact(before, delta, "the account's balance after the line")
.map_err(|e| e.to_string())?;
+6 -3
View File
@@ -150,7 +150,7 @@ fn basis_out(a: &ledger_core::Asset) -> Result<Option<AssetBasisOut>, String> {
sec704c_1c_note: loss.map(|l| {
format!(
"a built-in loss of {}: it counts only for the contributing member(s); for the others the basis is treated as the value at contribution (IRC §704(c)(1)(C))",
money(-l)
money(ledger_core::money::neg(l))
)
}),
sec704c_method: b.sec704c_method.map(|m| m.key().to_string()),
@@ -748,7 +748,10 @@ impl BooksServer {
accumulated_posted: figure(|r| r.accumulated_posted),
accumulated_scheduled_through: figure(|r| r.accumulated_scheduled),
unposted_depreciation: figure(|r| {
r.accumulated_scheduled - r.accumulated_posted
ledger_core::money::sub_in_range(
r.accumulated_scheduled,
r.accumulated_posted,
)
}),
book_value: figure(|r| r.book_value),
schedule_error,
@@ -930,7 +933,7 @@ impl BooksServer {
proceeds.amount,
preview.catch_up_depreciation,
if preview.gain_loss < Decimal::ZERO {
-preview.gain_loss
ledger_core::money::neg(preview.gain_loss)
} else {
Decimal::ZERO
},
+2 -2
View File
@@ -7,6 +7,7 @@
use super::*;
use ledger_core::Terms;
use ledger_core::arap::{self, PartySnapshot};
use ledger_core::kernel::Amount;
/// A document's id.
fn doc_id(doc: ledger_core::DocRef) -> u64 {
@@ -934,8 +935,7 @@ impl BooksServer {
if !keep {
continue;
}
owed = owed
.checked_add(st.outstanding)
owed = Amount::checked_add(owed, st.outstanding)
.ok_or("the total is too large to compute")?;
rows.push((
due,
+1 -1
View File
@@ -330,7 +330,7 @@ impl BooksServer {
links: g.link.iter().map(|s| subject_out(&store, *s)).collect(),
})
.collect();
let withdrawn = out_groups.iter().map(|g| g.withdraw.len()).sum();
let withdrawn = out_groups.iter().flat_map(|g| g.withdraw.iter()).count();
let digest = self.preview_of(
&store,
"books.consolidate_duplicates",
+5 -2
View File
@@ -7,6 +7,7 @@
use super::*;
use ledger_core::InstrumentId;
use ledger_core::kernel::Amount;
use ledger_store::StoreError;
/// The book's id, as the commands given to agents name it: its folder's
@@ -462,7 +463,7 @@ pub(crate) fn checked_sum(
) -> Result<Decimal, String> {
values.into_iter().try_fold(Decimal::ZERO, |sum, v| {
let v = v.map_err(|e| e.to_string())?;
sum.checked_add(v).ok_or_else(|| {
Amount::checked_add(sum, v).ok_or_else(|| {
ledger_core::LedgerError::TooLargeToCompute(what.to_string()).to_string()
})
})
@@ -548,7 +549,9 @@ pub(crate) fn lines_settled(entry: &JournalEntry) -> bool {
.lines()
.iter()
.filter(|l| l.side == s)
.try_fold(Decimal::ZERO, |sum, l| sum.checked_add(l.amount.amount))
.try_fold(Decimal::ZERO, |sum, l| {
Amount::checked_add(sum, l.amount.amount)
})
};
match (side(Side::Debit), side(Side::Credit)) {
(Some(debits), Some(credits)) => !entry.lines().is_empty() && debits == credits,
+14 -19
View File
@@ -4,6 +4,7 @@
//! Split whole out of `server.rs` (plan/served.md 8.2 U0a).
use super::*;
use ledger_core::money::{add_in_range, sub_in_range};
/// What the digest lists from the control check: each line on a control
/// account that is no document's, and each document needing attention.
@@ -37,18 +38,15 @@ fn movement_over(
.iter()
.flat_map(|e| e.lines())
.filter(|l| l.account == account),
|l| match l.side {
Side::Debit => l.amount.amount,
Side::Credit => -l.amount.amount,
},
|l| ledger_core::money::signed_amount(l.side, l.amount.amount),
"an account's movement",
)
.map_err(|e| e.to_string())?;
let account = ledger.chart().get(account).expect("account exists");
Ok(match account.account_type.normal_side() {
Side::Debit => movement,
Side::Credit => -movement,
})
Ok(ledger_core::money::signed_amount(
account.account_type.normal_side(),
movement,
))
}
fn lines_out(lines: &[ledger_core::StatementLine]) -> Vec<StatementLineOut> {
@@ -1057,19 +1055,16 @@ impl BooksServer {
Some(a) => a,
_ => continue,
};
let signed = match line.side {
Side::Debit => line.amount.amount,
Side::Credit => -line.amount.amount,
};
// Normal-side positive.
let normal = match account.account_type.normal_side() {
Side::Debit => signed,
Side::Credit => -signed,
};
let normal = ledger_core::money::on_side(
account.account_type.normal_side(),
line.side,
line.amount.amount,
);
let acc = by_class.entry(line.class_id).or_default();
match account.account_type {
AccountType::Revenue => acc.revenue += normal,
AccountType::Expense => acc.expenses += normal,
AccountType::Revenue => acc.revenue = add_in_range(acc.revenue, normal),
AccountType::Expense => acc.expenses = add_in_range(acc.expenses, normal),
_ => {}
}
}
@@ -1099,7 +1094,7 @@ impl BooksServer {
class,
revenue: money(acc.revenue),
expenses: money(acc.expenses),
net_income: money(acc.revenue - acc.expenses),
net_income: money(sub_in_range(acc.revenue, acc.expenses)),
})
.collect();
Ok(Json(ProfitAndLossByClassOut {
+5 -4
View File
@@ -6,6 +6,7 @@
//! there and this slice's do not collide (plan/served.md 8.2 P4b S6).
use super::*;
use ledger_core::money::{add_in_range, sub_in_range};
/// A document as the payment tools and the agings name it ("invoice:7",
/// "bill:12").
@@ -257,7 +258,7 @@ fn payment_out(
let mut documents = Vec::with_capacity(params.applications.len());
let mut deposited = Decimal::ZERO;
for app in &params.applications {
deposited += app.cash;
deposited = add_in_range(deposited, app.cash);
let st = ledger
.doc_state(app.doc, chrono::NaiveDate::MAX)
.map_err(|e| e.to_string())?
@@ -270,7 +271,7 @@ fn payment_out(
});
}
let fee = params.fee.as_ref().map_or(Decimal::ZERO, |f| f.amount);
deposited -= fee;
deposited = sub_in_range(deposited, fee);
let (remaining, status) = match documents.as_slice() {
[one] => (Some(one.outstanding.clone()), Some(one.status.clone())),
_ => (None, None),
@@ -413,7 +414,7 @@ impl BooksServer {
Some((by, max)) if by >= as_of => (
Some(by.to_string()),
Some(money(max)),
Some(money(st.outstanding - max)),
Some(money(sub_in_range(st.outstanding, max))),
),
_ => (None, None, None),
};
@@ -438,7 +439,7 @@ impl BooksServer {
let mut by_date = Vec::new();
let mut running = Decimal::ZERO;
for (bill, owed) in &bills {
running += owed;
running = add_in_range(running, *owed);
match by_date.last_mut() {
Some(DueDateTotalOut { date, amount }) if *date == bill.due_date => {
*amount = money(running);
+11 -7
View File
@@ -100,6 +100,7 @@
use std::collections::{BTreeSet, HashMap, HashSet};
use chrono::{Datelike, NaiveDate};
use ledger_core::kernel::Amount;
use ledger_core::parties::MoneyAccounts;
use ledger_core::{
AccountId, AccountType, AssetId, DocRef, DocStatus, EntryId, EntryStatus, Ledger, LedgerError,
@@ -344,7 +345,7 @@ pub fn find_with(
if missing.len() > 3 {
let total = missing
.iter()
.try_fold(Decimal::ZERO, |t, e| t.checked_add(e.amount?));
.try_fold(Decimal::ZERO, |t, e| Amount::checked_add(t, e.amount?));
let list: Vec<String> = missing
.iter()
.map(|e| format!("{} ({}, {})", e.id, e.description, e.date))
@@ -428,7 +429,7 @@ pub fn find_with(
if !due.is_empty() {
let Some(total) = due
.iter()
.try_fold(Decimal::ZERO, |t, (_, a)| t.checked_add(*a))
.try_fold(Decimal::ZERO, |t, (_, a)| Amount::checked_add(t, *a))
else {
out.push(cant_compute(
format!("Amortization schedule \"{}\"", s.description),
@@ -704,7 +705,10 @@ pub fn find_with(
.map(|r| {
[r.days_60, r.days_90, r.days_90_plus]
.into_iter()
.try_fold(r.days_30, Decimal::checked_add)
.try_fold(
r.days_30,
<Decimal as ledger_core::kernel::Amount>::checked_add,
)
.ok_or_else(too_large)
})
.collect::<Result<Vec<_>, _>>()?
@@ -713,7 +717,7 @@ pub fn find_with(
.collect();
let total = late
.iter()
.try_fold(Decimal::ZERO, |t, d| t.checked_add(*d))
.try_fold(Decimal::ZERO, |t, d| Amount::checked_add(t, *d))
.ok_or_else(too_large)?;
Ok::<_, LedgerError>((late.len(), total))
};
@@ -870,7 +874,7 @@ pub fn find_with(
};
match lines
.iter()
.try_fold(Decimal::ZERO, |t, l| t.checked_sub(l.amount))
.try_fold(Decimal::ZERO, |t, l| Amount::checked_sub(t, l.amount))
{
Some(amount) => written_off.push((inv.id, inv.number.clone(), last.date, amount)),
None => out.push(cant_compute(
@@ -1133,7 +1137,7 @@ pub fn find_with(
(
format!(
"{} of registered assets not in the books",
dollars(-unregistered)
dollars(ledger_core::money::neg(unregistered))
),
"Registered assets cost more than their cost accounts hold: a purchase entry may be missing.",
)
@@ -1864,7 +1868,7 @@ fn paid_this_year(
.max(today);
let end = last.min(NaiveDate::from_ymd_opt(today.year(), 12, 31).expect("valid"));
let a = ledger_core::parties::activity_with(ledger, party, (start, end), money, members);
a.paid - a.received
ledger_core::money::sub_in_range(a.paid, a.received)
}
/// A figure the books can't compute (BS-entry-4: books an earlier
+1 -1
View File
@@ -269,7 +269,7 @@ pub fn invoice_document(
{
label.push_str(&format!(" · ref {r}"));
}
settled.push((label, -l.amount));
settled.push((label, ledger_core::money::neg(l.amount)));
last_paid = Some(l.date);
}
for (label, amount) in [
+2 -2
View File
@@ -135,7 +135,7 @@ pub fn tax_basis_csv(ledger: &Ledger, names: &[String], tc: &TaxCapital) -> Stri
Some(t) => [
money(book),
money(t),
money(book - t),
money(ledger_core::money::sub_in_range(book, t)),
"tax basis".into(),
note,
],
@@ -244,7 +244,7 @@ pub fn tax_basis_csv(ledger: &Ledger, names: &[String], tc: &TaxCapital) -> Stri
name,
"Reconciliation: less property distributed, at book",
recon(
Some(-r.property_distributed),
Some(ledger_core::money::neg(r.property_distributed)),
"the company's adjusted tax basis in it is the CPA's",
),
);
+2 -2
View File
@@ -27,7 +27,7 @@ pub fn money(n: Decimal) -> String {
// is what drops a negative zero.
let mut n = ledger_import::round_display(n, n.scale().max(2));
if n.scale() < 2 {
n.rescale(2);
n = ledger_core::kernel::rescale_exact(n, 2).unwrap_or(n);
}
n.to_string()
}
@@ -47,7 +47,7 @@ pub fn share_text(n: Decimal) -> String {
let mut n = n.normalize();
n = ledger_import::round_display(n, n.scale().max(2));
if n.scale() < 2 {
n.rescale(2);
n = ledger_core::kernel::rescale_exact(n, 2).unwrap_or(n);
}
n.to_string()
}
+1 -1
View File
@@ -268,7 +268,7 @@ fn notes_for(ledger: &Ledger, r: &ledger_core::Vendor1099Report) -> Vec<String>
for p in &r.other_receipts {
// Money in is negative; its reversal gives it back.
let what = if p.amount < Decimal::ZERO {
format!("received {} from", money(-p.amount))
format!("received {} from", money(ledger_core::money::neg(p.amount)))
} else {
format!("reversed {} received from", money(p.amount))
};