From 7d525d392e17b847aeab771fca11ee026ae04b22 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 23:27:23 -0700 Subject: [PATCH] refactor(core): the last eleven Decimal sites go through the kernel (K-U11a) The detector now reads zero for ledger-core. These eleven waited for K-U10's exact operations, since each needed a decision the first 199 did not: - The frozen close rules (periods::try_allocate and try_allocate_last_absorbs) and Ledger::member_close_split multiply a share by a total. That product is a rounded figure by construction (a share of 27 places), and posted closes replay through the first two, so not a digit may move: they call Amount::checked_mul_rounded, the product they have always computed, by name. - The audit's check of a close (check_split) computes its bound and each member's drift through Amount. A bound or a drift that exact arithmetic cannot hold is raised as a finding, never passed as clean. - Four places changed how many decimal places a figure is written with (a contribution margin's one place, a schedule's months at the currency's places, Money's step count). Each called Decimal::rescale, which rounds half away from zero when asked for fewer places than the value has. None of them asked for that, and only a debug assertion said so. kernel::rescale_exact adds or drops trailing zeros and returns None for anything else, so a figure's written places can change and its value cannot. rescale_exact has no Kani harness and no Lean theorem: whole-number money has no places, so there is nothing for an i64 harness or a law over the rationals to state. It is the sixteenth listed exception of the traceability gate, and two bridge tests carry it instead: a property over Decimal's whole range against whole-number arithmetic that shares no code with it (None exactly when the amount is no whole multiple of the step; a result is the same number with the same sign), and a table of the figures the four call sites print. No figure moves. The full ledger-core suite passes. Co-Authored-By: Claude --- crates/ledger-core/src/audit.rs | 28 +++++--- crates/ledger-core/src/kernel/round.rs | 30 +++++++++ crates/ledger-core/src/ledger.rs | 7 +- crates/ledger-core/src/money.rs | 5 +- crates/ledger-core/src/periods.rs | 10 ++- crates/ledger-core/src/reports.rs | 8 +-- crates/ledger-core/src/schedules.rs | 17 +++-- .../tests/bookspec/traceability.rs | 13 +++- .../ledger-core/tests/kernel_bridge/round.rs | 67 +++++++++++++++++++ 9 files changed, 158 insertions(+), 27 deletions(-) diff --git a/crates/ledger-core/src/audit.rs b/crates/ledger-core/src/audit.rs index 7d4053dc..c570406e 100644 --- a/crates/ledger-core/src/audit.rs +++ b/crates/ledger-core/src/audit.rs @@ -36,7 +36,7 @@ use serde::Serialize; use crate::evidence::{Policy, Requirement}; use crate::settings::Settings; -use crate::{AccountType, DocStatus, EntryId, EntryStatus, Ledger, PeriodStatus, Side}; +use crate::{AccountType, DocStatus, EntryId, EntryStatus, Ledger, PeriodStatus}; /// How much a finding matters. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)] @@ -350,10 +350,7 @@ fn closed_net(ledger: &Ledger, through: NaiveDate) -> Option { let Some(a) = ledger.chart().get(l.account) else { continue; }; - let signed = match l.side { - Side::Debit => l.amount.amount, - Side::Credit => -l.amount.amount, - }; + let signed = crate::money::signed_amount(l.side, l.amount.amount); if matches!(a.account_type, AccountType::Revenue | AccountType::Expense) { net = crate::kernel::Amount::checked_add(net, signed)?; } @@ -536,16 +533,29 @@ pub fn check_split( trued_up: bool, ) -> Vec { // B(n) as derived above: (n-1)*u/2, floored at u. `unit` is a power - // of ten and n is small, so the product and the halving are exact. + // of ten and n is small, so the product and the halving are exact. A + // bound exact arithmetic could not hold (no real unit and member + // count reach it) falls to the floor, the stricter of the two: the + // audit then raises a drift it might have allowed, never hides one. let legacy_bound = { let others = Decimal::new(split.len().saturating_sub(1) as i64, 0); - let last = others * unit / Decimal::new(2, 0); - if last > unit { last } else { unit } + match crate::kernel::Amount::checked_mul(others, unit) + .and_then(|product| crate::kernel::Amount::checked_div_exact(product, Decimal::TWO)) + { + Some(last) if last > unit => last, + _ => unit, + } }; split .iter() .filter(|m| { - let drift = (m.running - m.exact).abs(); + // A difference exact arithmetic cannot hold is no drift + // under a unit: raised. + let Some(drift) = + crate::kernel::Amount::checked_sub(m.running, m.exact).map(|d| d.abs()) + else { + return true; + }; if trued_up { drift >= unit } else { diff --git a/crates/ledger-core/src/kernel/round.rs b/crates/ledger-core/src/kernel/round.rs index d108e20d..3e42c857 100644 --- a/crates/ledger-core/src/kernel/round.rs +++ b/crates/ledger-core/src/kernel/round.rs @@ -106,6 +106,36 @@ pub fn round_places(amount: Decimal, places: u32, mode: Rounding) -> Option Option { + if places > Decimal::MAX_SCALE { + return None; + } + let mut written = amount; + written.rescale(places); + (written == amount).then_some(written) +} + /// `amount` rounded to whole `currency` minor units in `mode`: cents for /// USD, whole yen for JPY, thousandths for KWD. A currency ISO 4217 gives /// no minor unit (gold, SDRs) is returned exactly, as the FX booking rule diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index 5f7150f3..b65aa856 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -4046,7 +4046,12 @@ impl Ledger { share, part, running, - exact: share * regime.closed, + // A share is positive and the shares sum to one + // (close_period_to_members), so the product is no + // larger than the total and Decimal holds it, rounded + // at its 28th digit where the factors carry more. + exact: crate::kernel::Amount::checked_mul_rounded(share, regime.closed) + .expect("a share of at most one of a total Decimal holds"), }, ) .collect(); diff --git a/crates/ledger-core/src/money.rs b/crates/ledger-core/src/money.rs index c0461931..23118077 100644 --- a/crates/ledger-core/src/money.rs +++ b/crates/ledger-core/src/money.rs @@ -304,9 +304,10 @@ impl Steps { if self.scale == self.minor { return Some(d); } - let mut d = d.normalize(); + let d = d.normalize(); if d.scale() < self.minor { - d.rescale(self.minor); + // Trailing zeros only, so never refused. + return Some(crate::kernel::rescale_exact(d, self.minor).unwrap_or(d)); } Some(d) } diff --git a/crates/ledger-core/src/periods.rs b/crates/ledger-core/src/periods.rs index 23af6a92..948395ec 100644 --- a/crates/ledger-core/src/periods.rs +++ b/crates/ledger-core/src/periods.rs @@ -146,7 +146,11 @@ pub fn try_allocate( let magnitude = amount.abs(); let exact: Vec = shares .iter() - .map(|s| magnitude.checked_mul(*s).ok_or_else(too_large)) + .map(|s| { + // The rounding product, as this rule has always computed it + // (posted closes replay with it); the shares sum to one. + crate::kernel::Amount::checked_mul_rounded(magnitude, *s).ok_or_else(too_large) + }) .collect::>()?; let mut parts: Vec = exact .iter() @@ -198,8 +202,8 @@ pub fn try_allocate_last_absorbs( let mut parts: Vec<_> = shares .iter() .map(|s| { - amount - .checked_mul(*s) + // The rounding product: this rule is frozen for replay. + crate::kernel::Amount::checked_mul_rounded(amount, *s) .and_then(|p| round_places(p, 2, Rounding::HalfAwayFromZero)) .ok_or_else(too_large) }) diff --git a/crates/ledger-core/src/reports.rs b/crates/ledger-core/src/reports.rs index ae05996a..f49deec1 100644 --- a/crates/ledger-core/src/reports.rs +++ b/crates/ledger-core/src/reports.rs @@ -627,15 +627,15 @@ impl ProjectToDate { /// 3. NEVER panics: None when the quotient can't be represented. /// ``` pub fn contribution_margin_pct(contribution: Decimal, revenue: Decimal) -> Option { - let mut x = crate::kernel::percent_of( + let x = crate::kernel::percent_of( contribution, revenue, Decimal::new(1, 1), crate::kernel::Rounding::HalfToEven, )?; - // Display padding only: the margin always prints its one place. - x.rescale(1); - Some(x) + // Display padding only: the margin always prints its one place. It + // is a whole number of tenths, so writing it with one changes nothing. + Some(crate::kernel::rescale_exact(x, 1).unwrap_or(x)) } /// The most months [`ProjectFigures::months`] holds: the period's last. diff --git a/crates/ledger-core/src/schedules.rs b/crates/ledger-core/src/schedules.rs index 1b084e66..93c6becb 100644 --- a/crates/ledger-core/src/schedules.rs +++ b/crates/ledger-core/src/schedules.rs @@ -365,17 +365,24 @@ fn present_as_rounded(parts: &mut [Decimal], total: Decimal, places: u32) { let Some(&first) = rest.first() else { return; }; + // `rescale_exact` refuses to round: a figure that is not a whole + // number of the places asked for (none is: `even_parts` rounded each + // to the step) would be left as the kernel gave it. let mut each = first; if each.scale() > places || each.is_zero() { - each.rescale(places); - debug_assert_eq!(each, first, "rescaling an amount never changes it"); + let written = kernel::rescale_exact(each, places); + debug_assert!(written.is_some(), "a month is a whole number of steps"); + each = written.unwrap_or(each); } // Subtracting a zero (a month that rounded to nothing) leaves the // total as it was, scale included; any other subtrahend widens it. if !each.is_zero() { - let before = *last; - last.rescale(total.scale().max(each.scale())); - debug_assert_eq!(*last, before, "rescaling an amount never changes it"); + let written = kernel::rescale_exact(*last, total.scale().max(each.scale())); + debug_assert!( + written.is_some(), + "the last month is the total less whole steps" + ); + *last = written.unwrap_or(*last); } for part in rest.iter_mut() { *part = each; diff --git a/crates/ledger-core/tests/bookspec/traceability.rs b/crates/ledger-core/tests/bookspec/traceability.rs index 524b6cd5..0668c3eb 100644 --- a/crates/ledger-core/tests/bookspec/traceability.rs +++ b/crates/ledger-core/tests/bookspec/traceability.rs @@ -2340,7 +2340,7 @@ fn every_claim_is_backed() { } assert_eq!( EXCEPTIONS.len(), - 15, + 16, "the kernel exception list changes only on purpose" ); // No ordinary function may fall through the right-law check: the @@ -2519,6 +2519,11 @@ const EXCEPTIONS: &[(&str, &str, &str)] = &[ "a Kani harness and a law", "it is the Decimal/currency wrapper around `round_step`; the harnesses and law 40 are round_step's, and the bridge carries them to Decimal", ), + ( + "rescale_exact", + "a Kani harness and a law", + "it adds or drops trailing zeros and refuses anything else, so it has no arithmetic for whole-number money to model (an i64 amount has no places); bridge `rescale_exact_never_changes_the_value` checks the value, the sign and the two refusals over Decimal's whole range", + ), ( "split_by_weights_with", "a Kani harness and a law", @@ -2532,8 +2537,9 @@ const EXCEPTIONS: &[(&str, &str, &str)] = &[ /// `split_by_weights_with` allocate, so every harness proves their /// fixed-array helper; `round_places`, `round_minor` and `fx_booked_minor` /// are Decimal wrappers whose law is the inner function's; `Direction::key` -/// is a wire name and `MonthPart::is_valid` a range predicate, with no law -/// at all. A new name here is a deliberate widening, never a silent hole. +/// is a wire name, `MonthPart::is_valid` a range predicate and +/// `rescale_exact` a change of trailing zeros, with no law at all. A new +/// name here is a deliberate widening, never a silent hole. const SKIPPED: &[&str] = &[ "movements", "reversal", @@ -2542,6 +2548,7 @@ const SKIPPED: &[&str] = &[ "round_places", "round_minor", "fx_booked_minor", + "rescale_exact", "split_by_weights_with", ]; diff --git a/crates/ledger-core/tests/kernel_bridge/round.rs b/crates/ledger-core/tests/kernel_bridge/round.rs index 4967fe52..389ba034 100644 --- a/crates/ledger-core/tests/kernel_bridge/round.rs +++ b/crates/ledger-core/tests/kernel_bridge/round.rs @@ -258,6 +258,73 @@ proptest! { prop_assert_eq!(got.to_string(), want.to_string()); } } + + /// `rescale_exact` changes how an amount is written, never the + /// amount. Over Decimal's whole range, against whole-number + /// arithmetic that shares nothing with it: it refuses exactly when + /// the amount is no whole multiple of 10^-places, and what it returns + /// is the same value with the same sign, at `places` places or, where + /// 96 bits cannot hold it that wide, as many as they can. + #[test] + fn rescale_exact_never_changes_the_value( + mantissa in prop_oneof![ + -(1i128 << 60)..=(1i128 << 60), + -MAX_MANTISSA..=MAX_MANTISSA, + (0u32..=27, -9i128..=9).prop_map(|(zeros, digit)| digit * 10i128.pow(zeros)), + ], + scale in 0u32..=28, + places in 0u32..=28, + ) { + use num_bigint::BigInt; + let amount = Decimal::try_from_i128_with_scale(mantissa, scale).expect("in Decimal's range"); + let whole_multiple = places >= scale || mantissa % 10i128.pow(scale - places) == 0; + let got = ledger_core::kernel::rescale_exact(amount, places); + prop_assert_eq!(got.is_some(), whole_multiple, "{} at {} places", amount, places); + if let Some(written) = got { + // The same number: both mantissas brought to 28 places. + let at_28 = |m: i128, s: u32| BigInt::from(m) * BigInt::from(10u8).pow(28 - s); + prop_assert_eq!(at_28(written.mantissa(), written.scale()), at_28(mantissa, scale)); + prop_assert_eq!(written.is_sign_negative(), amount.is_sign_negative()); + let no_room = written.mantissa().unsigned_abs() * 10 > MAX_MANTISSA.unsigned_abs(); + prop_assert!( + written.scale() == places || (written.scale() < places && no_room), + "{} written as {} at {} places", amount, written, places + ); + } + } +} + +/// Decimal's largest mantissa: 96 bits. +const MAX_MANTISSA: i128 = (1i128 << 96) - 1; + +/// `rescale_exact` at the edges, each row checked by hand: the places a +/// figure prints with, a zero's sign, and the two refusals. +#[test] +fn rescale_exact_at_the_edges() { + use ledger_core::kernel::rescale_exact; + let text = + |amount: &str, places: u32| rescale_exact(parse(amount), places).map(|d| d.to_string()); + assert_eq!(text("100", 1).as_deref(), Some("100.0")); + assert_eq!(text("0.250", 2).as_deref(), Some("0.25")); + assert_eq!(text("0", 2).as_deref(), Some("0.00")); + assert_eq!(text("12.5", 1).as_deref(), Some("12.5")); + assert_eq!(text("-3.10", 1).as_deref(), Some("-3.1")); + // A digit would be lost: refused, where `Decimal::rescale` rounds. + assert_eq!(text("0.255", 2), None); + assert_eq!(text("-0.001", 2), None); + assert_eq!(text("1", 29), None); + // A negative zero keeps its sign and takes the places (a schedule's + // posted month is compared as text on replay). + let minus_zero = rescale_exact(-Decimal::ZERO, 2).unwrap(); + assert!(minus_zero.is_zero() && minus_zero.is_sign_negative()); + assert_eq!(minus_zero.scale(), 2); + // No room for two more places in 96 bits: as many as fit, the value + // untouched. + let wide = Decimal::from_i128_with_scale(MAX_MANTISSA, 0); + assert_eq!(rescale_exact(wide, 2), Some(wide)); + assert_eq!(rescale_exact(wide, 2).unwrap().scale(), 0); + let nearly = Decimal::from_i128_with_scale(MAX_MANTISSA / 10, 0); + assert_eq!(rescale_exact(nearly, 2).unwrap().scale(), 1); } /// The edge table, each row checked by hand.