From 74943fb6992147defc45b709d233bbddb0ae7acb Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 13:37:48 -0700 Subject: [PATCH 1/3] refactor(core): one rounding primitive, round_step, in the kernel Every money round_dp*/rescale in ledger-core now goes through kernel::round_step: amount to a whole multiple of a step, in a named mode (half away, half even, toward zero, toward negative infinity), exact integer arithmetic on Decimal mantissas and scales, None instead of a panic, no negative zero. The call sites use round_places, which reproduces Decimal::round_dp_with_strategy exactly (value, scale and its early return), and add_line_fx uses round_minor for the base currency's smallest unit. This is a refactor: every site produces exactly what it produced before, so no golden changes. The schedules' monthly-even plan keeps its two-place cent rule: moving it to the currency's minor unit is K-U5's decision (D-72), not this behaviour-preserving unit. The remaining rescales (money.rs's display padding, the contribution margin's one place) are formatting, not rounding, and stay. Co-Authored-By: DeepSeek V4.1 Flash --- crates/ledger-core/src/cashflow.rs | 5 +- crates/ledger-core/src/conventions.rs | 6 +- crates/ledger-core/src/form1099.rs | 9 +- crates/ledger-core/src/k1.rs | 7 +- crates/ledger-core/src/kernel/entries.rs | 16 ++ crates/ledger-core/src/kernel/round.rs | 298 ++++++++++++++++++++++- crates/ledger-core/src/ledger.rs | 11 +- crates/ledger-core/src/periods.rs | 21 +- crates/ledger-core/src/reports.rs | 12 +- crates/ledger-core/src/schedules.rs | 15 +- crates/ledger-core/src/shares.rs | 4 +- crates/ledger-core/src/tax_capital.rs | 12 +- 12 files changed, 375 insertions(+), 41 deletions(-) diff --git a/crates/ledger-core/src/cashflow.rs b/crates/ledger-core/src/cashflow.rs index 0c4b52c6..e478c067 100644 --- a/crates/ledger-core/src/cashflow.rs +++ b/crates/ledger-core/src/cashflow.rs @@ -1720,8 +1720,9 @@ fn split_part( let part = amount .checked_mul(ours) .and_then(|x| x.checked_div(whole)) - .ok_or_else(|| too_large("a payment's government part"))? - .round_dp_with_strategy(places, rust_decimal::RoundingStrategy::MidpointNearestEven); + .ok_or_else(|| too_large("a payment's government part"))?; + let part = crate::kernel::round_places(part, places, crate::kernel::Rounding::HalfToEven) + .ok_or_else(|| too_large("a payment's government part"))?; let rest = amount .checked_sub(part) .ok_or_else(|| too_large("a payment's government part"))?; diff --git a/crates/ledger-core/src/conventions.rs b/crates/ledger-core/src/conventions.rs index 011d9cb6..65d8a794 100644 --- a/crates/ledger-core/src/conventions.rs +++ b/crates/ledger-core/src/conventions.rs @@ -454,7 +454,7 @@ pub fn check_id(id: &str) -> Result<(), String> { /// ([`crate::kernel::apportion`]): the parts sum to `amount` exactly /// (INVARIANT 2). pub fn split(amount: Decimal, shares: &[Decimal], places: Option) -> Option> { - use rust_decimal::RoundingStrategy::ToZero; + use crate::kernel::{Rounding, round_places}; let exact: Vec = shares .iter() .map(|s| amount.checked_mul(*s)) @@ -466,8 +466,8 @@ pub fn split(amount: Decimal, shares: &[Decimal], places: Option) -> Option }; let mut parts: Vec = exact .iter() - .map(|e| e.round_dp_with_strategy(places, ToZero)) - .collect(); + .map(|e| round_places(*e, places, Rounding::TowardZero)) + .collect::>()?; let remainders: Vec = exact .iter() .zip(&parts) diff --git a/crates/ledger-core/src/form1099.rs b/crates/ledger-core/src/form1099.rs index 03d453ce..6724229a 100644 --- a/crates/ledger-core/src/form1099.rs +++ b/crates/ledger-core/src/form1099.rs @@ -728,7 +728,11 @@ fn vendor_part(payment: Decimal, share: Decimal, target: Decimal) -> Result Result<[Decimal; 3], LedgerError> // exactly (the division alone rounds past 28 digits). let num = b[i].abs().checked_mul(av).ok_or_else(too_large)?; let q = num.checked_div(ap).ok_or_else(too_large)?; - let mut part = q.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::ToZero); + let mut part = + kernel::round_places(q, 2, kernel::Rounding::TowardZero).ok_or_else(too_large)?; while times(part)? > num { part -= cent; } diff --git a/crates/ledger-core/src/k1.rs b/crates/ledger-core/src/k1.rs index 72ab31df..622ec80d 100644 --- a/crates/ledger-core/src/k1.rs +++ b/crates/ledger-core/src/k1.rs @@ -314,7 +314,7 @@ pub(crate) fn share_property( credits: &[Decimal], places: u32, ) -> Result, LedgerError> { - use rust_decimal::RoundingStrategy::ToZero; + use crate::kernel::{Rounding, round_places}; let too_large = || LedgerError::TooLargeToCompute("a member's share of contributed property".into()); let total = credits @@ -334,8 +334,9 @@ pub(crate) fn share_property( .ok_or_else(too_large)?; let mut parts: Vec = exact .iter() - .map(|x| x.round_dp_with_strategy(places, ToZero)) - .collect(); + .map(|x| round_places(*x, places, Rounding::TowardZero)) + .collect::>() + .ok_or_else(too_large)?; let remainders: Vec = exact.iter().zip(&parts).map(|(x, p)| x - p).collect(); crate::kernel::apportion(whole, &mut parts, &remainders, Decimal::new(1, places)) .expect("each part is short by under a unit, so the shortfall is under a unit per member"); diff --git a/crates/ledger-core/src/kernel/entries.rs b/crates/ledger-core/src/kernel/entries.rs index 9048ffb2..6af7f5c9 100644 --- a/crates/ledger-core/src/kernel/entries.rs +++ b/crates/ledger-core/src/kernel/entries.rs @@ -2,6 +2,7 @@ //! grouping the lines of an entry or a book, unchanged in U0. The laws it //! serves are listed at the module root, [`super`]. +use super::round::Rounding; use crate::assets::BasisRule; use crate::{AccountType, Side}; use rust_decimal::Decimal; @@ -41,6 +42,12 @@ pub trait Amount: Copy + Ord { /// B-21), whose shares are added exactly and rounded once, never /// share by share. fn checked_div_round_cent(self, rhs: Self) -> Option; + /// `self` rounded to a whole multiple of `step`, in `mode`; `None` + /// when `step` is not positive or the result cannot be represented. + /// + /// The instantiation of [`crate::kernel::round_step`], which the call + /// sites use; a machine integer is already a whole smallest unit. + fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option; /// `self - rhs`, or `None` when it cannot be represented exactly. fn checked_sub(self, rhs: Self) -> Option { @@ -148,6 +155,9 @@ impl Amount for Decimal { let signed = if negative { -signed_mag } else { signed_mag }; Decimal::try_from_i128_with_scale(signed, scale).ok() } + fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option { + super::round::round_decimal_to_step(self, step, mode) + } } impl Amount for i32 { @@ -196,6 +206,9 @@ impl Amount for i32 { q.checked_sub(1) } } + fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option { + super::round::round_i32_to_step(self, step, mode) + } } impl Amount for i64 { @@ -245,6 +258,9 @@ impl Amount for i64 { q.checked_sub(1) } } + fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option { + super::round::round_i64_to_step(self, step, mode) + } } /// Why the kernel rejected an entry's lines. diff --git a/crates/ledger-core/src/kernel/round.rs b/crates/ledger-core/src/kernel/round.rs index e412a684..c8809540 100644 --- a/crates/ledger-core/src/kernel/round.rs +++ b/crates/ledger-core/src/kernel/round.rs @@ -1,5 +1,293 @@ -//! U2: one rounding primitive, the single place money is rounded to a step (kernel sweep). -//! -//! Empty in U0: the unit adds its arithmetic here, in this file alone, so -//! no two sweep units ever edit the same file. The module root re-exports -//! it, keeping every path `crate::kernel::foo`. +//! The rounding primitive: money rounded to a whole multiple of a unit, +//! once, in a named mode. The kernel sweep's U2 (plan/kernel-sweep-audit.md +//! section 3) routes every `round_dp*`/`rescale` on money through it, so +//! the engine has one definition of "round" and no call site invents a +//! second. + +use crate::Currency; +use crate::kernel::Amount; +use rust_decimal::Decimal; + +/// How a value is rounded to a step. Only the modes the engine uses today +/// are here; a new mode is a new match arm in each [`Amount`] +/// instantiation, never a silent default. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Rounding { + /// Nearest multiple; an exact half rounds away from zero + /// (2.5 -> 3, -2.5 -> -3). The FX booking rule (B-3). + HalfAwayFromZero, + /// Nearest multiple; an exact half rounds to the even multiple + /// (2.5 -> 2, 3.5 -> 4). Rust's `Decimal::round_dp`. + HalfToEven, + /// Down in magnitude, toward zero (2.9 -> 2, -2.9 -> -2). + TowardZero, + /// Down, toward negative infinity (2.9 -> 2, -2.9 -> -3). + TowardNegativeInfinity, +} + +/// `amount` rounded to a whole multiple of `step`, in `mode`. +/// +/// ```text +/// GOAL: one rounding primitive: money is rounded to a whole multiple of a +/// unit, once, with the mode named at the call. +/// SOURCE: docs/spec/claims/ledger.md B-3 (a ledger in one money holds no +/// fractions of its smallest unit; FX books the base currency's +/// minor unit, half away from zero), claims/entry.md B-21 (exact +/// amounts in the books; round only where a rule says to), and +/// claims/ledger.md B-32; the call sites' own rules (B-13, B-14, +/// B-15, B-16, B-19, B-35, B-36, B-37); owner decision D-69 (the +/// laws live once, in bookspec's Lean). +/// INVARIANTS: +/// 1. Some(r) is a whole multiple of step: r = n x step for an integer +/// n, with step > 0. None when step <= 0 or nothing can hold the +/// result. +/// 2. HalfAwayFromZero and HalfToEven are nearest: |r - amount| <= +/// step/2; at exactly half, the mode's tie rule picks the multiple. +/// 3. TowardZero never increases magnitude: |r| <= |amount| and +/// |r - amount| < step. +/// 4. TowardNegativeInfinity is the floor: r <= amount < r + step. +/// 5. Idempotent: round(round(x)) = round(x) for the same step and mode. +/// 6. The symmetric modes (HalfAwayFromZero, HalfToEven, TowardZero) are +/// odd: round(-x) = -round(x). No mode ever flips the sign (a +/// non-zero amount never rounds to the other side of zero). +/// 7. Never a negative zero: a result that is zero is +0. Never a panic; +/// overflow and an impossible step are None. +/// SCENARIOS: +/// 1. IF 1.005 to the cent, HalfAwayFromZero: SHOULD be 1.01. +/// 2. IF 1.005 to the cent, HalfToEven: SHOULD be 1.00 (100 is even). +/// 3. IF -1.005 to the cent, TowardNegativeInfinity: SHOULD be -1.01. +/// 4. IF 0.004 to the cent, either half mode: SHOULD be 0 (not -0). +/// 5. IF the step is zero or negative: SHOULD be None, never a guess. +/// ``` +pub fn round_step(amount: T, step: T, mode: Rounding) -> Option { + amount.checked_round_to_step(step, mode) +} + +/// `amount` rounded to `places` decimal places in `mode`, exactly as +/// `Decimal::round_dp_with_strategy` does today: an amount carrying no +/// more places than `places` is returned unchanged, and otherwise the +/// result carries exactly `places` places. This is the behaviour-preserving +/// wrapper the call sites use while U2 proves `round_step` underneath +/// them; it is not a second rounding rule. +pub fn round_places(amount: Decimal, places: u32, mode: Rounding) -> Option { + if amount.is_zero() { + // Keep round_dp's scale, but never its negative zero. + return Decimal::try_from_i128_with_scale(0, amount.scale().min(places)).ok(); + } + if amount.scale() <= places { + return Some(amount); + } + let step = Decimal::try_from_i128_with_scale(1, places).ok()?; + let rounded = round_step(amount, step, mode)?; + if rounded.is_zero() { + // Keep the places (a report prints "0.00"), never a negative zero. + return Decimal::try_from_i128_with_scale(0, places).ok(); + } + let mut rounded = rounded; + if rounded.scale() != places { + // Round_dp_with_strategy returns the target scale even when the + // value is a whole multiple (1.200 at two places is 1.20), and + // round_step returns an exact multiple unchanged. + rounded.rescale(places); + } + Some(rounded) +} + +/// `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 +/// has always done (B-3). +pub fn round_minor(amount: Decimal, currency: Currency, mode: Rounding) -> Option { + match currency.minor_units() { + Some(places) => round_places(amount, places, mode), + None => Some(amount), + } +} + +/// The `Decimal` instantiation of [`Amount::checked_round_to_step`]: exact +/// integer arithmetic on the two mantissas and scales, so no intermediate +/// `amount / step` is ever rounded by `Decimal`'s 28-digit division. The +/// quotient is rounded in integer space and multiplied by the step's +/// mantissa once; reduction by trailing zeros (as in +/// `checked_div_round_cent`) makes the result fit Decimal's 96-bit +/// mantissa when the value allows it. +pub(crate) fn round_decimal_to_step( + amount: Decimal, + step: Decimal, + mode: Rounding, +) -> Option { + if step <= Decimal::ZERO { + return None; + } + if amount.is_zero() { + return Some(Decimal::ZERO); + } + let negative = amount.is_sign_negative(); + let a = amount.mantissa().unsigned_abs(); + let b = step.mantissa().unsigned_abs(); + let exponent = i64::from(step.scale()) - i64::from(amount.scale()); + // An exact multiple is already rounded. That case also covers the one + // the integer quotient cannot name: a step far finer than the amount + // (1e28 as 1e-20 steps is a 48-digit count, but the value is 1e28). + if is_exact_multiple(a, b, exponent) { + return Some(amount); + } + + let (mut floor, round_up) = if exponent >= 0 { + let exp = u32::try_from(exponent).ok()?; + let power = 10u128.checked_pow(exp)?; + let whole = a / b; + let mut remainder = a % b; + let mut fraction = 0u128; + for _ in 0..exp { + remainder = remainder.checked_mul(10)?; + fraction = fraction.checked_mul(10)?.checked_add(remainder / b)?; + remainder %= b; + } + let floor = whole.checked_mul(power)?.checked_add(fraction)?; + let twice = remainder.checked_mul(2)?; + let round_up = match mode { + Rounding::TowardZero => false, + Rounding::TowardNegativeInfinity => negative && remainder != 0, + Rounding::HalfAwayFromZero => twice >= b, + Rounding::HalfToEven => twice > b || (twice == b && !floor.is_multiple_of(2)), + }; + (floor, round_up) + } else { + let places = u32::try_from(-exponent).ok()?; + let power = 10u128.checked_pow(places)?; + let quotient = a / b; + let remainder = a % b; + let digit = quotient % power; + let floor = quotient / power; + let twice = digit.checked_mul(2)?; + let round_up = match mode { + Rounding::TowardZero => false, + Rounding::TowardNegativeInfinity => negative && (digit != 0 || remainder != 0), + Rounding::HalfAwayFromZero => twice >= power, + Rounding::HalfToEven => { + twice > power || (twice == power && (remainder != 0 || !floor.is_multiple_of(2))) + } + }; + (floor, round_up) + }; + + if round_up { + floor = floor.checked_add(1)?; + } + let mut mantissa = floor.checked_mul(b)?; + if mantissa == 0 { + // Never a negative zero: money never prints "-0". + return Some(Decimal::ZERO); + } + let max = Decimal::MAX.mantissa().unsigned_abs(); + let mut scale = step.scale(); + while mantissa > max { + if scale == 0 || !mantissa.is_multiple_of(10) { + return None; + } + mantissa /= 10; + scale -= 1; + } + let signed = i128::try_from(mantissa).ok()?; + let signed = if negative { -signed } else { signed }; + Decimal::try_from_i128_with_scale(signed, scale).ok() +} + +/// True when `a x 10^exponent` (or `a / 10^-exponent`) is a whole multiple +/// of `b`, without ever materialising the product: only remainders below +/// `b` (under Decimal's 96-bit mantissa) are multiplied by ten. +fn is_exact_multiple(a: u128, b: u128, exponent: i64) -> bool { + if exponent >= 0 { + let mut remainder = a % b; + for _ in 0..exponent { + if remainder == 0 { + return true; + } + remainder = (remainder * 10) % b; + } + remainder == 0 + } else { + let places = u32::try_from(-exponent).unwrap_or(u32::MAX); + let Some(power) = 10u128.checked_pow(places) else { + return false; + }; + if !a.is_multiple_of(power) { + return false; + } + (a / power).is_multiple_of(b) + } +} + +/// The `i64` instantiation: a machine integer is already a whole smallest +/// unit, so the step is a whole number of them (a Kani model, never money +/// with a fractional unit). +pub(crate) fn round_i64_to_step(value: i64, step: i64, mode: Rounding) -> Option { + if step <= 0 { + return None; + } + let negative = value < 0; + let magnitude = value.unsigned_abs(); + let divisor = step.unsigned_abs(); + let floor = magnitude / divisor; + let remainder = magnitude % divisor; + let twice = remainder.checked_mul(2)?; + let round_up = match mode { + Rounding::TowardZero => false, + Rounding::TowardNegativeInfinity => negative && remainder != 0, + Rounding::HalfAwayFromZero => twice >= divisor, + Rounding::HalfToEven => twice > divisor || (twice == divisor && !floor.is_multiple_of(2)), + }; + let count = if round_up { + floor.checked_add(1)? + } else { + floor + }; + let magnitude = count.checked_mul(divisor)?; + let limit = if negative { + 1u64 << 63 + } else { + i64::MAX as u64 + }; + if magnitude > limit { + return None; + } + let signed = magnitude as i64; + Some(if negative { -signed } else { signed }) +} + +/// The `i32` instantiation, the proof model's smaller type: the same rule +/// in 32 bits. +pub(crate) fn round_i32_to_step(value: i32, step: i32, mode: Rounding) -> Option { + if step <= 0 { + return None; + } + let negative = value < 0; + let magnitude = value.unsigned_abs(); + let divisor = step.unsigned_abs(); + let floor = magnitude / divisor; + let remainder = magnitude % divisor; + let twice = remainder.checked_mul(2)?; + let round_up = match mode { + Rounding::TowardZero => false, + Rounding::TowardNegativeInfinity => negative && remainder != 0, + Rounding::HalfAwayFromZero => twice >= divisor, + Rounding::HalfToEven => twice > divisor || (twice == divisor && !floor.is_multiple_of(2)), + }; + let count = if round_up { + floor.checked_add(1)? + } else { + floor + }; + let magnitude = count.checked_mul(divisor)?; + let limit = if negative { + 1u32 << 31 + } else { + i32::MAX as u32 + }; + if magnitude > limit { + return None; + } + let signed = magnitude as i32; + Some(if negative { -signed } else { signed }) +} diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index cf753637..6358a1c1 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -1871,11 +1871,12 @@ impl Ledger { // away from zero: a ledger in one money holds no fractions of its // smallest unit (rules.md B-3; DECISION, owner 2026-10-13, after // the GnuCash cross-check found the difference). - let base_amount = match self.base_currency.minor_units() { - Some(dp) => exact - .round_dp_with_strategy(dp, rust_decimal::RoundingStrategy::MidpointAwayFromZero), - None => exact, - }; + let base_amount = crate::kernel::round_minor( + exact, + self.base_currency, + crate::kernel::Rounding::HalfAwayFromZero, + ) + .ok_or(LedgerError::AmountOutOfRange)?; if base_amount <= Decimal::ZERO { return Err(LedgerError::InvalidFxRate(fx_rate)); } diff --git a/crates/ledger-core/src/periods.rs b/crates/ledger-core/src/periods.rs index 06888e4c..a1f92ee7 100644 --- a/crates/ledger-core/src/periods.rs +++ b/crates/ledger-core/src/periods.rs @@ -124,12 +124,15 @@ pub fn allocate( amount: rust_decimal::Decimal, shares: &[rust_decimal::Decimal], ) -> Vec { - use rust_decimal::{Decimal, RoundingStrategy::ToZero}; + use rust_decimal::Decimal; let magnitude = amount.abs(); let exact: Vec = shares.iter().map(|s| magnitude * s).collect(); let mut parts: Vec = exact .iter() - .map(|e| e.round_dp_with_strategy(2, ToZero)) + .map(|e| { + crate::kernel::round_places(*e, 2, crate::kernel::Rounding::TowardZero) + .expect("a cent place of a representable amount is representable") + }) .collect(); let remainders: Vec = exact.iter().zip(&parts).map(|(e, p)| e - p).collect(); crate::kernel::apportion(magnitude, &mut parts, &remainders, Decimal::new(1, 2)) @@ -149,10 +152,13 @@ pub fn allocate_last_absorbs( amount: rust_decimal::Decimal, shares: &[rust_decimal::Decimal], ) -> Vec { - use rust_decimal::RoundingStrategy::MidpointAwayFromZero; + use crate::kernel::{Rounding, round_places}; let mut parts: Vec<_> = shares .iter() - .map(|s| (amount * s).round_dp_with_strategy(2, MidpointAwayFromZero)) + .map(|s| { + round_places(amount * s, 2, Rounding::HalfAwayFromZero) + .expect("a cent place of a representable amount is representable") + }) .collect(); crate::kernel::plug_last(amount, &mut parts).expect("allocated amounts are in range"); parts @@ -205,7 +211,8 @@ pub fn allocate_cumulative( given: &[rust_decimal::Decimal], places: u32, ) -> Result, LedgerError> { - use rust_decimal::{Decimal, RoundingStrategy::ToZero}; + use crate::kernel::{Rounding, round_places}; + use rust_decimal::Decimal; if shares.len() != given.len() { return Err(LedgerError::InvalidMembers(format!( "{} shares but {} earlier parts", @@ -236,7 +243,9 @@ pub fn allocate_cumulative( "a member's share {share} of {magnitude}, to its last digit," )) })?; - let floor = exact.round_dp_with_strategy(places, ToZero); + let floor = round_places(exact, places, Rounding::TowardZero).ok_or_else(|| { + LedgerError::TooLargeToCompute(format!("a member's share {share} of {magnitude}")) + })?; parts.push(floor); remainders.push(exact - floor); } diff --git a/crates/ledger-core/src/reports.rs b/crates/ledger-core/src/reports.rs index 01c96cdd..125417fb 100644 --- a/crates/ledger-core/src/reports.rs +++ b/crates/ledger-core/src/reports.rs @@ -626,10 +626,14 @@ pub fn contribution_margin_pct(contribution: Decimal, revenue: Decimal) -> Optio if revenue <= Decimal::ZERO { return None; } - let mut x = contribution - .checked_div(revenue)? - .checked_mul(Decimal::ONE_HUNDRED)? - .round_dp_with_strategy(1, rust_decimal::RoundingStrategy::MidpointNearestEven); + let mut x = crate::kernel::round_places( + contribution + .checked_div(revenue)? + .checked_mul(Decimal::ONE_HUNDRED)?, + 1, + crate::kernel::Rounding::HalfToEven, + )?; + // Display padding only: the margin always prints its one place. x.rescale(1); Some(x) } diff --git a/crates/ledger-core/src/schedules.rs b/crates/ledger-core/src/schedules.rs index 468a5b9d..139542e8 100644 --- a/crates/ledger-core/src/schedules.rs +++ b/crates/ledger-core/src/schedules.rs @@ -193,10 +193,17 @@ pub fn amortization_plan( if total.abs() >= EXACT_LIMIT { return Err(too_large()); } - let each = total - .checked_div(Decimal::from(months)) - .ok_or_else(too_large)? - .round_dp(2); + // Two places whatever the currency: the monthly-even plan's cent rule is + // replay-frozen, and moving it to the currency's minor unit is K-U5 + // (owner decision D-72), not this behaviour-preserving rounding unit. + let each = kernel::round_places( + total + .checked_div(Decimal::from(months)) + .ok_or_else(too_large)?, + 2, + kernel::Rounding::HalfToEven, + ) + .ok_or_else(too_large)?; let first = start .with_day(1) .ok_or(LedgerError::DateOutOfRange(start))?; diff --git a/crates/ledger-core/src/shares.rs b/crates/ledger-core/src/shares.rs index fc056883..550b6ae0 100644 --- a/crates/ledger-core/src/shares.rs +++ b/crates/ledger-core/src/shares.rs @@ -284,7 +284,7 @@ fn checked_sum(values: impl IntoIterator) -> Option { /// part rounded toward zero to the cent, the cents left over to the first. /// None when a product or sum is past exact arithmetic. fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option> { - use rust_decimal::RoundingStrategy::ToZero; + use crate::kernel::{Rounding, round_places}; let total = checked_sum(weights.iter().copied())?; if weights.is_empty() || total.is_zero() { return Some(vec![Decimal::ZERO; weights.len()]); @@ -295,7 +295,7 @@ fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option> magnitude .checked_mul(*w) .and_then(|x| x.checked_div(total)) - .map(|x| x.round_dp_with_strategy(2, ToZero)) + .and_then(|x| round_places(x, 2, Rounding::TowardZero)) }) .collect::>()?; let left = magnitude.checked_sub(checked_sum(parts.iter().copied())?)?; diff --git a/crates/ledger-core/src/tax_capital.rs b/crates/ledger-core/src/tax_capital.rs index 85b9a708..b934c25e 100644 --- a/crates/ledger-core/src/tax_capital.rs +++ b/crates/ledger-core/src/tax_capital.rs @@ -456,7 +456,7 @@ impl RunningSplit { whole: Decimal, weights: &[Decimal], ) -> Result, LedgerError> { - use rust_decimal::RoundingStrategy::ToNegativeInfinity; + use crate::kernel::{Rounding, round_places}; let n = self.given.len(); let Some(sum) = self.weight_sum(weights)? else { return Ok(vec![Decimal::ZERO; n]); @@ -482,12 +482,14 @@ impl RunningSplit { // rounded down to the cent, what rounding took its remainder. let snapped: Vec = exact .iter() - .map(|x| (x * sign).round_dp(EXACT_PLACES)) - .collect(); + .map(|x| round_places(x * sign, EXACT_PLACES, Rounding::HalfToEven)) + .collect::>() + .ok_or_else(too_large)?; let mut parts: Vec = snapped .iter() - .map(|x| x.round_dp_with_strategy(2, ToNegativeInfinity)) - .collect(); + .map(|x| round_places(*x, 2, Rounding::TowardNegativeInfinity)) + .collect::>() + .ok_or_else(too_large)?; let remainders: Vec = snapped.iter().zip(&parts).map(|(x, p)| x - p).collect(); let given: Vec = self.given.iter().map(|g| g * sign).collect(); crate::kernel::apportion_cumulative( From f16525fd3551614bbbb85a8e393fb2c2f6d2c188 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 13:37:48 -0700 Subject: [PATCH 2/3] test(core): Kani and bridge for round_step Kani checks the primitive on i64 over fixed steps: a whole multiple, the half modes nearest, each mode's tie, idempotence, no negative zero, and a non-positive step refused. A symbolic divisor did not finish in 30 minutes (CBMC's bit-blasted division), so the steps are fixed constants; the bridge's exact-reference property carries the laws to every Decimal step. The bridge agrees i64 with Decimal, checks Decimal against an independent i128 reference over amounts of up to ten places and steps down to 1e-4, checks round_places against round_dp_with_strategy to the character, and has the edge table (.5, -.5, 0.004, 1.005, -1.005, scale 28, Decimal::MAX). docs/proofs/k-u2.md records the harnesses, bounds, times, bridge properties and the bookspec Lean theorem names. Co-Authored-By: DeepSeek V4.1 Flash --- crates/ledger-core/src/proofs/round.rs | 201 ++++++++++++- .../ledger-core/tests/kernel_bridge/round.rs | 268 +++++++++++++++++- docs/proofs/k-u2.md | 145 ++++++++++ 3 files changed, 609 insertions(+), 5 deletions(-) create mode 100644 docs/proofs/k-u2.md diff --git a/crates/ledger-core/src/proofs/round.rs b/crates/ledger-core/src/proofs/round.rs index 777b9b1c..8bb59785 100644 --- a/crates/ledger-core/src/proofs/round.rs +++ b/crates/ledger-core/src/proofs/round.rs @@ -1,5 +1,200 @@ //! U2 proof harnesses: the rounding primitive (kernel sweep). //! -//! Empty in U0: the unit adds its Kani harnesses here; `just prove` scans -//! every file in `proofs/`, so a harness needs no change to the module -//! root or the recipe. +//! `kernel::round_step` on `i64` money in the smallest unit: the result is +//! a whole multiple of the step; the half modes are nearest; each mode +//! breaks a tie as it says; rounding twice is rounding once; and the sign +//! never flips (so no zero is ever a negative zero). +//! +//! The steps are the fixed constants below rather than a symbolic `step`: +//! a symbolic divisor makes CBMC's bit-blasted division intractable (one +//! harness did not finish in 30 minutes). They cover one, an even step, an +//! odd step, a non-power-of-ten, a decimal step and a larger step; the +//! bridge's exact-reference property carries the same laws to every +//! `Decimal` step, and bookspec's Lean proves the law for any step. The +//! amount is symbolic up to [`VALUE`]. + +use crate::kernel::{Rounding, round_step}; +use kani::cover; + +/// Every amount the harnesses explore is within this magnitude. +const VALUE: i64 = 1 << 12; +/// The fixed steps: one, evens (a tie exists), odds, a non-power of ten, +/// a decimal step, and a step well above one. +const STEPS: [i64; 6] = [1, 2, 3, 7, 10, 101]; +/// The even steps, where an exact half exists. +const EVEN_STEPS: [i64; 4] = [2, 4, 10, 100]; + +fn any_mode() -> Rounding { + let mode: u8 = kani::any(); + kani::assume(mode < 4); + match mode { + 0 => Rounding::HalfAwayFromZero, + 1 => Rounding::HalfToEven, + 2 => Rounding::TowardZero, + _ => Rounding::TowardNegativeInfinity, + } +} + +fn any_half_mode() -> Rounding { + if kani::any() { + Rounding::HalfAwayFromZero + } else { + Rounding::HalfToEven + } +} + +fn any_value() -> i64 { + let value: i64 = kani::any(); + kani::assume(value >= -VALUE && value <= VALUE); + value +} + +fn check_multiple(value: i64, step: i64, mode: Rounding) { + let rounded = round_step(value, step, mode).expect("no overflow under these bounds"); + assert_eq!(rounded % step, 0, "a whole multiple of the step"); + if value > 0 { + assert!(rounded >= 0, "a positive amount never rounds below zero"); + } else if value < 0 { + assert!(rounded <= 0, "a negative amount never rounds above zero"); + } else { + assert_eq!(rounded, 0, "zero rounds to zero"); + } +} + +/// The result is a whole multiple of the step, and it never crosses zero: +/// a positive amount rounds to a non-negative amount, a negative one to a +/// non-positive amount, and zero to zero. +#[kani::proof] +#[kani::unwind(8)] +fn round_step_is_multiple() { + let value = any_value(); + let mode = any_mode(); + for step in STEPS { + check_multiple(value, step, mode); + cover!( + step > 1 && value % step != 0, + "a non-multiple rounded to a step above one" + ); + } + cover!(value.abs() % 101 > 1, "a non-multiple of a larger step"); +} + +fn check_nearest(value: i64, step: i64, mode: Rounding) { + let rounded = round_step(value, step, mode).expect("no overflow under these bounds"); + let distance = (rounded - value).abs(); + assert!( + 2 * distance <= step, + "nearest: at most half a step away, a tie at exactly half" + ); +} + +/// The half modes are nearest: the result is within half a step of the +/// amount, ties included. +#[kani::proof] +#[kani::unwind(8)] +fn round_step_is_nearest() { + let value = any_value(); + let mode = any_half_mode(); + for step in STEPS { + check_nearest(value, step, mode); + } + cover!(value % 10 != 0, "a value that actually moves"); + cover!(value.abs() % 10 == 5, "an exact tie (the mode decides it)"); + cover!(value.abs() % 10 != 0 && value.abs() % 10 != 5, "a non-tie"); +} + +/// At an exact tie every mode picks the multiple its definition names. +/// The tie is built as `whole x step + step/2` (and its negation) with an +/// even fixed step, so it is exact in `i64` and both signs are reached. +#[kani::proof] +#[kani::unwind(8)] +fn round_step_ties() { + let whole: i64 = kani::any(); + kani::assume(whole >= 0 && whole <= 64); + let negative: bool = kani::any(); + for step in EVEN_STEPS { + let half = step / 2; + let magnitude = whole * step + half; + let value = if negative { -magnitude } else { magnitude }; + + let up = whole + 1; + let even = if whole % 2 == 0 { whole } else { up }; + let cases = [ + (Rounding::HalfAwayFromZero, up), + (Rounding::HalfToEven, even), + (Rounding::TowardZero, whole), + ( + Rounding::TowardNegativeInfinity, + if negative { up } else { whole }, + ), + ]; + for (mode, pick) in cases { + let want = if negative { + -(pick * step) + } else { + pick * step + }; + assert_eq!( + round_step(value, step, mode), + Some(want), + "each mode's tie rule" + ); + } + } + cover!(!negative, "a positive tie"); + cover!(negative, "a negative tie"); + cover!(whole % 2 == 1, "HalfToEven rounds an odd floor up"); + cover!(whole % 2 == 0, "HalfToEven keeps an even floor"); +} + +/// Rounding twice is rounding once, in every mode. +#[kani::proof] +#[kani::unwind(8)] +fn round_step_is_idempotent() { + let value = any_value(); + let mode = any_mode(); + for step in STEPS { + let once = round_step(value, step, mode).expect("no overflow under these bounds"); + assert_eq!(round_step(once, step, mode), Some(once)); + } +} + +/// No negative zero and no sign flip: zero in gives zero out, and a result +/// that reaches zero only does so from an amount that rounds there. +#[kani::proof] +#[kani::unwind(8)] +fn round_step_never_negative_zero() { + let value = any_value(); + let mode = any_mode(); + for step in STEPS { + let rounded = round_step(value, step, mode).expect("no overflow under these bounds"); + if value == 0 { + assert_eq!(rounded, 0); + } + if rounded == 0 { + assert!( + value.abs() < step, + "a zero is a rounding to the zero multiple" + ); + } + assert!( + value == 0 || rounded == 0 || (rounded > 0) == (value > 0), + "the sign never flips" + ); + } + cover!( + value % 3 != 0 || value % 10 != 0, + "a non-zero amount rounded to another multiple" + ); +} + +/// A step of zero or less is refused, never guessed at. +#[kani::proof] +fn round_step_refuses_nonpositive_step() { + let value = any_value(); + let mode = any_mode(); + for step in [0i64, -1, -7, i64::MIN] { + assert_eq!(round_step(value, step, mode), None); + } + cover!(value > 0, "a positive amount with a refused step"); +} diff --git a/crates/ledger-core/tests/kernel_bridge/round.rs b/crates/ledger-core/tests/kernel_bridge/round.rs index 210bdff5..5f7579c4 100644 --- a/crates/ledger-core/tests/kernel_bridge/round.rs +++ b/crates/ledger-core/tests/kernel_bridge/round.rs @@ -1,4 +1,268 @@ //! U2 bridge properties: the rounding primitive (kernel sweep). //! -//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, -//! beside `main.rs` and the other units. +//! `proofs/round.rs` proves `round_step` on `i64` money in the smallest +//! unit; the engine runs the same code on `Decimal`. These properties check +//! that both instantiations agree, that `Decimal` agrees with an +//! independent integer reference on amounts of up to ten decimal places, +//! that the primitive reproduces `round_dp_with_strategy` exactly (the +//! behaviour U2 preserves), and the edge table: halves both ways, a +//! sub-half amount, a binary-looking 1.005, scale 28 and `Decimal::MAX`. + +use ledger_core::kernel::{Rounding, round_step}; +use proptest::prelude::*; +use rust_decimal::Decimal; +use rust_decimal::RoundingStrategy; + +fn parse(text: &str) -> Decimal { + text.parse().expect("a decimal literal") +} + +fn any_mode() -> impl Strategy { + prop_oneof![ + Just(Rounding::HalfAwayFromZero), + Just(Rounding::HalfToEven), + Just(Rounding::TowardZero), + Just(Rounding::TowardNegativeInfinity), + ] +} + +fn strategy(mode: Rounding) -> RoundingStrategy { + match mode { + Rounding::HalfAwayFromZero => RoundingStrategy::MidpointAwayFromZero, + Rounding::HalfToEven => RoundingStrategy::MidpointNearestEven, + Rounding::TowardZero => RoundingStrategy::ToZero, + Rounding::TowardNegativeInfinity => RoundingStrategy::ToNegativeInfinity, + } +} + +/// An independent integer reference: `value x 10^-scale` rounded to a +/// whole multiple of `10^-places`, in `mode`, using only `i128` division +/// and remainder. Shares no code with the kernel. +fn reference(value: i128, scale: u32, places: u32, mode: Rounding) -> Option { + let common = scale.max(places); + let amount = value.checked_mul(10i128.checked_pow(common - scale)?)?; + let divisor = 10i128.checked_pow(common - places)?; + let negative = amount < 0; + let magnitude = amount.unsigned_abs(); + let divisor = u128::try_from(divisor).ok()?; + let floor = magnitude / divisor; + let remainder = magnitude % divisor; + let twice = remainder.checked_mul(2)?; + let round_up = match mode { + Rounding::TowardZero => false, + Rounding::TowardNegativeInfinity => negative && remainder != 0, + Rounding::HalfAwayFromZero => twice >= divisor, + Rounding::HalfToEven => twice > divisor || (twice == divisor && !floor.is_multiple_of(2)), + }; + let count = if round_up { + floor.checked_add(1)? + } else { + floor + }; + let count = i128::try_from(count).ok()?; + Decimal::try_from_i128_with_scale(if negative { -count } else { count }, places).ok() +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(2000))] + + /// The `i64` kernel (the Kani model) and the `Decimal` kernel (the + /// engine) agree on the same money in cents. + #[test] + fn i64_and_decimal_agree( + value in -(1i64 << 40)..=(1i64 << 40), + step in 1i64..=(1i64 << 20), + mode in any_mode(), + ) { + let ours = round_step(value, step, mode).map(|r| Decimal::new(r, 2)); + prop_assert_eq!( + ours, + round_step(Decimal::new(value, 2), Decimal::new(step, 2), mode) + ); + } + + /// The exact reference above, on books of up to ten decimal places and + /// steps from one to a ten-thousandth: the `Decimal` primitive is the + /// integer rounding, carried out exactly. + #[test] + fn decimal_matches_the_integer_reference( + value in -(1i128 << 60)..=(1i128 << 60), + scale in 0u32..=10, + places in 0u32..=4, + mode in any_mode(), + ) { + let amount = Decimal::try_from_i128_with_scale(value, scale).expect("in Decimal's range"); + let step = Decimal::new(1, places); + prop_assert_eq!( + round_step(amount, step, mode), + reference(value, scale, places, mode) + ); + } + + /// Behaviour preservation: with a power-of-ten step, `round_step` is + /// exactly `round_dp_with_strategy`, the call sites' old primitive. + #[test] + fn round_step_is_round_dp_for_a_power_of_ten( + value in -(1i128 << 60)..=(1i128 << 60), + scale in 0u32..=10, + places in 0u32..=10, + mode in any_mode(), + ) { + let amount = Decimal::try_from_i128_with_scale(value, scale).expect("in Decimal's range"); + let mut want = amount.round_dp_with_strategy(places, strategy(mode)); + // The kernel never returns a negative zero; Decimal's rounding can. + if want.is_zero() && want.is_sign_negative() { + want = Decimal::ZERO; + } + prop_assert_eq!(round_step(amount, Decimal::new(1, places), mode), Some(want)); + } + + /// And `round_places` matches it to the character: same value, same + /// scale, the call sites' exact output. (A negative zero becomes +0.) + #[test] + fn round_places_matches_round_dp_to_the_character( + value in -(1i128 << 60)..=(1i128 << 60), + scale in 0u32..=10, + places in 0u32..=10, + mode in any_mode(), + ) { + let amount = Decimal::try_from_i128_with_scale(value, scale).expect("in Decimal's range"); + let got = ledger_core::kernel::round_places(amount, places, mode).unwrap(); + let want = amount.round_dp_with_strategy(places, strategy(mode)); + if want.is_zero() { + prop_assert!(got.is_zero()); + prop_assert!(!got.is_sign_negative()); + } else { + prop_assert_eq!(got.to_string(), want.to_string()); + } + } +} + +/// The edge table, each row checked by hand. +#[test] +fn round_step_at_the_edges() { + let cent = parse("0.01"); + // A half, both signs, in every mode. + assert_eq!( + round_step(parse("0.5"), cent, Rounding::HalfAwayFromZero), + Some(parse("0.50")) + ); + assert_eq!( + round_step(parse("-0.5"), cent, Rounding::HalfAwayFromZero), + Some(parse("-0.50")) + ); + assert_eq!( + round_step(parse("0.5"), cent, Rounding::HalfToEven), + Some(parse("0.50")) + ); + assert_eq!( + round_step(parse("-0.5"), cent, Rounding::TowardNegativeInfinity), + Some(parse("-0.50")) + ); + // Under half a cent: zero, and never a negative zero. + let tiny = round_step(parse("0.004"), cent, Rounding::HalfAwayFromZero).unwrap(); + assert!(tiny.is_zero()); + assert!(!tiny.is_sign_negative()); + let tiny = round_step(parse("-0.004"), cent, Rounding::HalfToEven).unwrap(); + assert!(tiny.is_zero()); + assert!(!tiny.is_sign_negative()); + // 1.005 is exactly a half at the cent (Decimal carries it exactly). + assert_eq!( + round_step(parse("1.005"), cent, Rounding::HalfAwayFromZero), + Some(parse("1.01")) + ); + assert_eq!( + round_step(parse("1.005"), cent, Rounding::HalfToEven), + Some(parse("1.00")) + ); + assert_eq!( + round_step(parse("-1.005"), cent, Rounding::HalfAwayFromZero), + Some(parse("-1.01")) + ); + assert_eq!( + round_step(parse("-1.005"), cent, Rounding::HalfToEven), + Some(parse("-1.00")) + ); + assert_eq!( + round_step(parse("-1.005"), cent, Rounding::TowardNegativeInfinity), + Some(parse("-1.01")) + ); + // Scale 28: a whole multiple, and a tie at the last place. + let last = parse("0.0000000000000000000000000001"); + let five = parse("0.0000000000000000000000000005"); + assert_eq!(round_step(five, last, Rounding::HalfToEven), Some(five)); + let two_last = parse("0.0000000000000000000000000002"); + assert_eq!( + round_step(five, two_last, Rounding::HalfToEven), + Some(parse("0.0000000000000000000000000004")) + ); + assert_eq!( + round_step(five, two_last, Rounding::HalfAwayFromZero), + Some(parse("0.0000000000000000000000000006")) + ); + // Decimal's largest value is a whole multiple of a unit and a cent. + assert_eq!( + round_step(Decimal::MAX, Decimal::ONE, Rounding::HalfToEven), + Some(Decimal::MAX) + ); + assert_eq!( + round_step(Decimal::MAX, cent, Rounding::HalfAwayFromZero), + Some(Decimal::MAX) + ); + // A step that is not positive is refused. + assert_eq!( + round_step(Decimal::ONE, Decimal::ZERO, Rounding::HalfToEven), + None + ); + assert_eq!( + round_step(Decimal::ONE, -Decimal::ONE, Rounding::HalfToEven), + None + ); +} + +/// `round_places` is the behaviour-preserving wrapper the call sites use: +/// it keeps `round_dp_with_strategy`'s scale and its early return. +#[test] +fn round_places_keeps_the_old_scale() { + use ledger_core::kernel::round_places; + assert_eq!( + round_places(parse("1.200"), 2, Rounding::HalfToEven), + Some(parse("1.20")) + ); + assert_eq!( + round_places(parse("1.5"), 2, Rounding::HalfToEven), + Some(parse("1.5")) + ); + let zero = round_places(parse("0.004"), 2, Rounding::HalfAwayFromZero).unwrap(); + assert_eq!(zero.to_string(), "0.00"); + assert!(!zero.is_sign_negative()); +} + +/// `round_minor` picks the currency's own unit; a currency with none is +/// returned exactly (the FX rule, B-3). +#[test] +fn round_minor_follows_the_currency() { + use ledger_core::Currency; + use ledger_core::kernel::round_minor; + assert_eq!( + round_minor(parse("1.2345"), Currency::USD, Rounding::HalfAwayFromZero), + Some(parse("1.23")) + ); + assert_eq!( + round_minor(parse("1234.5"), Currency::JPY, Rounding::HalfAwayFromZero), + Some(parse("1235")) + ); + assert_eq!( + round_minor( + parse("1.2345"), + Currency::new("KWD").unwrap(), + Rounding::HalfAwayFromZero + ), + Some(parse("1.235")) + ); + let gold = Currency::new("XAU").unwrap(); + assert_eq!( + round_minor(parse("1.23456789"), gold, Rounding::HalfAwayFromZero), + Some(parse("1.23456789")) + ); +} diff --git a/docs/proofs/k-u2.md b/docs/proofs/k-u2.md new file mode 100644 index 00000000..d7d4b137 --- /dev/null +++ b/docs/proofs/k-u2.md @@ -0,0 +1,145 @@ +# K-U2: one rounding primitive, `round_step` + +Status: landed 2026-11-08. The kernel sweep's U2 +(`plan/kernel-sweep-audit.md` section 3): every money `round_dp*`/`rescale` +in `ledger-core` goes through one kernel primitive, the law is proved once +in bookspec's Lean, and the primitive is checked on `i64` by Kani and on +`Decimal` by the bridge. + +## The API + +```rust +pub enum Rounding { HalfAwayFromZero, HalfToEven, TowardZero, TowardNegativeInfinity } + +pub fn round_step(amount: T, step: T, mode: Rounding) -> Option +pub fn round_places(amount: Decimal, places: u32, mode: Rounding) -> Option +pub fn round_minor(amount: Decimal, currency: Currency, mode: Rounding) -> Option +``` + +`round_step` is `amount` to a whole multiple of a positive `step` in `mode`; +`None` for `step <= 0` or an unrepresentable result; never a panic and never +a negative zero. `round_places` is the behaviour-preserving call-site +wrapper: when the amount carries no more places than `places` it is returned +unchanged, otherwise the result carries exactly `places` places, matching +`Decimal::round_dp_with_strategy` to the character (including its scale). +`round_minor` picks `10^-currency.minor_units()`; a currency ISO 4217 gives +no minor unit is returned exactly, the FX rule's existing behaviour (B-3). + +The `Amount` trait gained `checked_round_to_step`, implemented for +`Decimal`, `i32` and `i64` exactly as `checked_div_round_cent` was: the +`Decimal` implementation is exact integer arithmetic on mantissas and scales +(no 28-digit intermediate division), with the trailing-zero reduction that +`checked_div_round_cent` uses when the result can still be held. + +## Kani harnesses (`crates/ledger-core/src/proofs/round.rs`) + +All run at `i64`, amounts symbolic in `[-2^12, 2^12]`, over the fixed steps +`1, 2, 3, 7, 10, 101` (and the even steps `2, 4, 10, 100` for the tie +harness). A symbolic divisor was tried first and did not finish in 30 +minutes: CBMC's bit-blasted division by a symbolic `i64` is intractable. The +fixed steps include an even step (a tie exists), odd steps, a +non-power-of-ten, a decimal step and a step well above one; the bridge's +exact-reference property carries the same laws to every `Decimal` step, and +bookspec's Lean proves them for any step. + +| Harness | Law | Verification | +|---|---|---| +| `round_step_is_multiple` | the result is a whole multiple of the step; the sign never crosses zero; zero in, zero out | 5.1 s (2 covers) | +| `round_step_is_nearest` | the half modes are within half a step (a tie at exactly half) | 22 s total (3 covers) | +| `round_step_ties` | an exact tie: half away goes on, half even takes the even index, toward zero truncates, toward negative infinity floors (both signs) | 22 s total (4 covers) | +| `round_step_is_idempotent` | rounding twice is rounding once | 16 s total | +| `round_step_never_negative_zero` | zero in gives zero; a zero result comes from under a step; the sign never flips | 12 s total (1 cover) | +| `round_step_refuses_nonpositive_step` | a step of zero or less is `None` | 8 s total (1 cover) | + +Measured alone on this machine, 2026-11-08, with +`cargo kani -p ledger-core --exact --harness proofs::round::`. + +`just prove` (fast set): **59 harnesses, 0 failures** (53 before this unit, +6 added), 440 s of Kani, 470 s wall including the Lean build (a second run, +after the last cover was added: 406 s wall); all covers satisfied. + +## Bridge (`crates/ledger-core/tests/kernel_bridge/round.rs`) + +- `i64_and_decimal_agree`: the Kani model in cents and the engine in dollars + agree, value for value, for every mode. +- `decimal_matches_the_integer_reference`: an independent `i128` reference + (integer division and remainder, sharing no code with the kernel) over + amounts of 0 to 10 decimal places and steps 1, 0.1, 0.01, 0.001, 0.0001. +- `round_step_is_round_dp_for_a_power_of_ten`: with a power-of-ten step the + primitive is exactly the old `round_dp_with_strategy` value. +- `round_places_matches_round_dp_to_the_character`: and the wrapper matches + it including scale (a negative zero becomes `+0`). +- `round_step_at_the_edges`: `.5`, `-.5`, `0.004`, `1.005`, `-1.005`, a tie + at scale 28, `Decimal::MAX`, and a non-positive step. +- `round_places_keeps_the_old_scale`, `round_minor_follows_the_currency`: + the wrapper's early return and scale, and USD/JPY/KWD/gold minor units. + +All pass with the rest of `kernel_bridge`. + +## Lean (bookspec, branch `k-u2`) + +`lean/Bookspec/Round.lean`, law 40 in `spec/laws.md`, headline theorems in +`lean/Audit.lean`. Build: `lake build && lake env lean Audit.lean`, standard +axioms only; `cargo test --workspace` passes (the checker's law count moves +from 39 to 40). + +- `Round.roundStep_multiple` — the result is a multiple of the step. +- `Round.near_halfAway`, `Round.near_halfEven` — within half a step. +- `Round.tie_halfAway_pos` / `_neg`, `Round.tie_halfEven_pos` / `_neg`, + `Round.tie_towardZero_pos` / `_neg`, `Round.tie_towardNegInf_pos` / `_neg` + — each mode's tie rule, both signs. +- `Round.roundStep_idempotent` — rounding twice is rounding once. +- `Round.roundStep_odd` — the symmetric modes are odd + (`round(-x) = -round(x)`); toward negative infinity is excluded by a + hypothesis because it is not symmetric. +- `Round.roundStep_scale` — `round(c·x, c·step) = c·round(x, step)` for a + positive `c`. + +The half-away mode is `Deductible.roundHA`; its near, tie, odd and scale +theorems are reused, not restated. The model rounds the magnitude and puts +the sign back, so an `Int` has no negative zero. + +## Call sites + +Every money `round_dp*` was replaced; the remaining `rescale`s in +`ledger-core` are display padding (`money.rs` `Steps::decimal`, +`reports.rs` contribution-margin's one place), not rounding, and were left. + +Counts by file (14 replaced): + +| File | Sites | +|---|---| +| `ledger.rs` | 1 (`add_line_fx`, via `round_minor`) | +| `periods.rs` | 3 | +| `schedules.rs` | 1 | +| `form1099.rs` | 2 | +| `shares.rs` | 1 | +| `k1.rs` | 1 | +| `conventions.rs` | 1 | +| `tax_capital.rs` | 2 | +| `cashflow.rs` | 1 | +| `reports.rs` | 1 | + +No result changes: the wrapper reproduces `round_dp_with_strategy` exactly +(value, scale and early return), the bridge checks that to the character, +and every existing test and golden passed unchanged. + +### Currency-blind sites (kept at two places, on purpose) + +These round to cents whatever the base currency; fixing them is another +unit's decision (D-72 for schedules), not this behaviour-preserving one: + +- `schedules.rs` `amortization_plan` — the monthly-even plan's replay-frozen + cent rule; K-U5 owns the move to the currency's minor unit (D-72). +- `form1099.rs` `vendor_part` and `split_share` — the 1099 worksheet's cents. +- `periods.rs` `allocate` and `allocate_last_absorbs` — frozen legacy close + replay rules, cents by their recorded policy. +- `shares.rs` `split_first` — the legacy first-absorbs split, cents. +- `tax_capital.rs` `RunningSplit::split` — the tax-basis K-1 worksheet's + cents (after a `10`-place exact snap). + +Display-only rounding in `ledger-gui`/`ledger-import` is K-U9's and was left +untouched. The figures there that reach an exported report are +`ledger-import/report.rs`'s `format_amount`/`amount_parts` (2 places, +half away) and `xlsx.rs`'s `exact_f64` (2 places); both are presentation, not +booked money. From f0a5d107084a1481a0e5775379124c3bb73a2bcd Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 14:03:50 -0700 Subject: [PATCH 3/3] test(core): round_step's directed modes and finer steps are proved and tested Review found two holes in K-U2's evidence. 1. The spec block's invariants 3, 4 and 6 (toward zero: |r| <= |x| and |r - x| < step; toward negative infinity: r <= x < r + step; no mode flips the sign) had no proof: Kani checked those modes only at exact ties. Three harnesses now assert them for every amount over the fixed steps (round_step_toward_zero_bounds, round_step_toward_neg_inf_is_floor, round_step_sign_preserved), each with covers for a non-tie and a negative non-multiple; bookspec's Lean carries the same laws for any step. With TowardZero mutated to round 7 at step 10 up to 10, the first harness fails ("magnitude never grows"); reverted. 2. The bridge never ran checked_round_to_step's finer-step branch (step with more places than the amount and a mantissa above one). Three properties compare the kernel with a second, independent i128 reference that takes any step (mantissa 1..1000 at scales 0..10, amounts at scales 0..28, small amounts, and constructed exact ties). Replacing .checked_add(remainder / b) with .checked_add(0) in the digit loop fails all three; reverted. docs/proofs/k-u2.md also states the one exception to "no result changes": a negative-zero input (round_dp keeps -0.00; round_places gives 0.00; no call site can produce one). Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/src/proofs/round.rs | 66 ++++++++++ .../ledger-core/tests/kernel_bridge/round.rs | 122 ++++++++++++++++++ docs/proofs/k-u2.md | 43 +++++- 3 files changed, 225 insertions(+), 6 deletions(-) diff --git a/crates/ledger-core/src/proofs/round.rs b/crates/ledger-core/src/proofs/round.rs index 8bb59785..ab3e348b 100644 --- a/crates/ledger-core/src/proofs/round.rs +++ b/crates/ledger-core/src/proofs/round.rs @@ -188,6 +188,72 @@ fn round_step_never_negative_zero() { ); } +/// Toward zero never grows the magnitude and lands less than a step from +/// the amount: `|r| <= |x|` and `|r - x| < step`, for every amount (ties +/// are not special: both modes pick the same multiple whether or not the +/// amount is exactly between two). +#[kani::proof] +#[kani::unwind(8)] +fn round_step_toward_zero_bounds() { + let value = any_value(); + for step in STEPS { + let rounded = + round_step(value, step, Rounding::TowardZero).expect("no overflow under these bounds"); + assert!(rounded.abs() <= value.abs(), "magnitude never grows"); + assert!((rounded - value).abs() < step, "less than a step away"); + } + cover!(value % 10 != 0 && value > 0, "a positive non-multiple"); + cover!(value % 10 != 0 && value < 0, "a negative non-multiple"); + cover!( + value.abs() % 10 != 0 && value.abs() % 10 != 5, + "a non-tie, a non-multiple of ten" + ); +} + +/// Toward negative infinity is the floor: `r <= x < r + step`, for every +/// amount of either sign. +#[kani::proof] +#[kani::unwind(8)] +fn round_step_toward_neg_inf_is_floor() { + let value = any_value(); + for step in STEPS { + let rounded = round_step(value, step, Rounding::TowardNegativeInfinity) + .expect("no overflow under these bounds"); + assert!(rounded <= value, "never above the amount"); + assert!(value < rounded + step, "less than a step below it"); + } + cover!(value % 10 != 0 && value > 0, "a positive non-multiple"); + cover!( + value % 10 != 0 && value < 0, + "a negative non-multiple (the floor moves away from zero)" + ); + cover!( + value.abs() % 10 != 0 && value.abs() % 10 != 5, + "a non-tie, a non-multiple of ten" + ); +} + +/// No mode flips the sign: a non-negative amount rounds to a non-negative +/// one, and a non-positive amount to a non-positive one. +#[kani::proof] +#[kani::unwind(8)] +fn round_step_sign_preserved() { + let value = any_value(); + let mode = any_mode(); + for step in STEPS { + let rounded = round_step(value, step, mode).expect("no overflow under these bounds"); + if value >= 0 { + assert!(rounded >= 0, "a non-negative amount stays non-negative"); + } + if value <= 0 { + assert!(rounded <= 0, "a non-positive amount stays non-positive"); + } + } + cover!(value > 0, "a positive amount"); + cover!(value < 0, "a negative amount"); + cover!(value == 0, "zero"); +} + /// A step of zero or less is refused, never guessed at. #[kani::proof] fn round_step_refuses_nonpositive_step() { diff --git a/crates/ledger-core/tests/kernel_bridge/round.rs b/crates/ledger-core/tests/kernel_bridge/round.rs index 5f7579c4..d0f2eb03 100644 --- a/crates/ledger-core/tests/kernel_bridge/round.rs +++ b/crates/ledger-core/tests/kernel_bridge/round.rs @@ -63,6 +63,75 @@ fn reference(value: i128, scale: u32, places: u32, mode: Rounding) -> Option Option { + let common = scale.max(step_scale); + let amount = value.checked_mul(10i128.checked_pow(common - scale)?)?; + let step = mantissa.checked_mul(10i128.checked_pow(common - step_scale)?)?; + let negative = amount < 0; + let magnitude = amount.unsigned_abs(); + let step = u128::try_from(step).ok()?; + let floor = magnitude / step; + let remainder = magnitude % step; + let twice = remainder.checked_mul(2)?; + let round_up = match mode { + Rounding::TowardZero => false, + Rounding::TowardNegativeInfinity => negative && remainder != 0, + Rounding::HalfAwayFromZero => twice >= step, + Rounding::HalfToEven => twice > step || (twice == step && !floor.is_multiple_of(2)), + }; + let count = if round_up { + floor.checked_add(1)? + } else { + floor + }; + let mut result = i128::try_from(count.checked_mul(step)?).ok()?; + let mut places = common; + while places > 0 && result % 10 == 0 && result != 0 { + result /= 10; + places -= 1; + } + if result == 0 { + places = 0; + } + let result = if negative { -result } else { result }; + Decimal::try_from_i128_with_scale(result, places).ok() +} + +/// Rounds `value x 10^-scale` to the step `mantissa x 10^-step_scale` with +/// the kernel and with the reference, and asserts they are the same value. +fn assert_matches_reference( + value: i128, + scale: u32, + mantissa: i128, + step_scale: u32, + mode: Rounding, +) -> Result<(), TestCaseError> { + let amount = Decimal::try_from_i128_with_scale(value, scale).expect("in Decimal's range"); + let step = Decimal::try_from_i128_with_scale(mantissa, step_scale).expect("in range"); + let want = reference_step(value, scale, mantissa, step_scale, mode); + prop_assert!(want.is_some(), "the reference fits for these ranges"); + prop_assert_eq!(round_step(amount, step, mode), want); + Ok(()) +} + +/// The mantissas and scales of the finer-step tests: a step is any +/// `mantissa x 10^-scale`; a tie needs an even mantissa, so a tie row +/// builds its own. +fn step_parts() -> impl Strategy { + (1i128..=1000, 0u32..=10) +} + proptest! { #![proptest_config(ProptestConfig::with_cases(2000))] @@ -99,6 +168,59 @@ proptest! { ); } + /// Steps that are not powers of ten: a mantissa 1..1000 at scales + /// 0..10 against amounts at scales 0..28, every mode, checked against + /// the independent reference. When the step carries more places than + /// the amount, the kernel's digit loop runs with a mantissa above one + /// (the finer-step branch); otherwise the coarser-step branch does. + #[test] + fn decimal_matches_the_reference_for_any_step( + value in -(1i128 << 60)..=(1i128 << 60), + scale in 0u32..=28, + (mantissa, step_scale) in step_parts(), + mode in any_mode(), + ) { + assert_matches_reference(value, scale, mantissa, step_scale, mode)?; + } + + /// Small amounts, so exact multiples are common: the same comparison. + #[test] + fn decimal_matches_the_reference_for_any_step_on_small_amounts( + value in -5000i128..=5000, + scale in 0u32..=12, + (mantissa, step_scale) in step_parts(), + mode in any_mode(), + ) { + assert_matches_reference(value, scale, mantissa, step_scale, mode)?; + } + + /// Exact ties: the amount is an odd number of half-steps, written with + /// up to three trailing zeros removed (so the step often has more + /// places than the amount). Every mode's tie rule against the reference. + #[test] + fn decimal_matches_the_reference_at_ties( + q in 0i128..=10_000, + half in 1i128..=100, + tens in 0u32..=3, + step_scale in 0u32..=10, + strip in 0u32..=3, + negative in any::(), + mode in any_mode(), + ) { + let half = half * 10i128.pow(tens); + let mantissa = 2 * half; + let mut value = (2 * q + 1) * half; + let mut scale = step_scale; + for _ in 0..strip { + if scale > 0 && value % 10 == 0 { + value /= 10; + scale -= 1; + } + } + let value = if negative { -value } else { value }; + assert_matches_reference(value, scale, mantissa, step_scale, mode)?; + } + /// Behaviour preservation: with a power-of-ten step, `round_step` is /// exactly `round_dp_with_strategy`, the call sites' old primitive. #[test] diff --git a/docs/proofs/k-u2.md b/docs/proofs/k-u2.md index d7d4b137..c05eeede 100644 --- a/docs/proofs/k-u2.md +++ b/docs/proofs/k-u2.md @@ -49,14 +49,26 @@ bookspec's Lean proves them for any step. | `round_step_ties` | an exact tie: half away goes on, half even takes the even index, toward zero truncates, toward negative infinity floors (both signs) | 22 s total (4 covers) | | `round_step_is_idempotent` | rounding twice is rounding once | 16 s total | | `round_step_never_negative_zero` | zero in gives zero; a zero result comes from under a step; the sign never flips | 12 s total (1 cover) | +| `round_step_toward_zero_bounds` | toward zero: `\|r\| <= \|x\|` and `\|r - x\| < step`, every amount (ties are not special) | 16 s wall incl. build (3 covers) | +| `round_step_toward_neg_inf_is_floor` | toward negative infinity: `r <= x < r + step`, both signs | 21 s wall incl. build (3 covers) | +| `round_step_sign_preserved` | every mode: `0 <= x` gives `0 <= r`, `x <= 0` gives `r <= 0` | 13 s wall incl. build (3 covers) | | `round_step_refuses_nonpositive_step` | a step of zero or less is `None` | 8 s total (1 cover) | +The three directed-mode harnesses were added after review: the spec block's +invariants 3, 4 and 6 had no proof of their own (Lean had the ties, Kani +checked these two modes only at exact ties). Demonstrated: with +`TowardZero` mutated to round up on `twice >= divisor` (7 at step 10 becomes +10), `round_step_toward_zero_bounds` fails on "magnitude never grows"; the +mutation was reverted. + Measured alone on this machine, 2026-11-08, with `cargo kani -p ledger-core --exact --harness proofs::round::`. -`just prove` (fast set): **59 harnesses, 0 failures** (53 before this unit, -6 added), 440 s of Kani, 470 s wall including the Lean build (a second run, -after the last cover was added: 406 s wall); all covers satisfied. +`just prove` (fast set), before the review fixes: **59 harnesses, 0 failures** +(53 before this unit, 6 added), 440 s of Kani, 470 s wall including the Lean +build; all covers satisfied. The review fixes add 3 harnesses (62 in all); +the nine `proofs::round::*` harnesses were each re-run alone and all verify +with every cover satisfied. ## Bridge (`crates/ledger-core/tests/kernel_bridge/round.rs`) @@ -65,6 +77,17 @@ after the last cover was added: 406 s wall); all covers satisfied. - `decimal_matches_the_integer_reference`: an independent `i128` reference (integer division and remainder, sharing no code with the kernel) over amounts of 0 to 10 decimal places and steps 1, 0.1, 0.01, 0.001, 0.0001. +- `decimal_matches_the_reference_for_any_step`, + `..._for_any_step_on_small_amounts`, `..._at_ties`: steps that are not + powers of ten: a mantissa 1..1000 at scales 0..10 against amounts at + scales 0..28 (small amounts for exact multiples; constructed exact ties + with trailing zeros stripped), every mode, against a second independent + `i128` reference that takes any step (common scale, `i128` division, + trailing-zero reduction; no digit loop). When the step has more places + than the amount this runs the kernel's finer-step digit loop with a + mantissa above one, which the power-of-ten properties never reach. + Demonstrated: replacing `.checked_add(remainder / b)` with + `.checked_add(0)` in that loop fails all three; reverted. - `round_step_is_round_dp_for_a_power_of_ten`: with a power-of-ten step the primitive is exactly the old `round_dp_with_strategy` value. - `round_places_matches_round_dp_to_the_character`: and the wrapper matches @@ -88,6 +111,12 @@ from 39 to 40). - `Round.tie_halfAway_pos` / `_neg`, `Round.tie_halfEven_pos` / `_neg`, `Round.tie_towardZero_pos` / `_neg`, `Round.tie_towardNegInf_pos` / `_neg` — each mode's tie rule, both signs. +- `Round.towardZero_bounds` — toward zero: `|r| <= |x|` and `|r - x| < step` + (the spec block's invariant 3). +- `Round.towardNegInf_bounds` — toward negative infinity is the floor: + `r <= x < r + step` (invariant 4). +- `Round.sign_preserved` — every mode: `0 <= x` gives `0 <= r`, `x <= 0` + gives `r <= 0` (invariant 6). - `Round.roundStep_idempotent` — rounding twice is rounding once. - `Round.roundStep_odd` — the symmetric modes are odd (`round(-x) = -round(x)`); toward negative infinity is excluded by a @@ -120,9 +149,11 @@ Counts by file (14 replaced): | `cashflow.rs` | 1 | | `reports.rs` | 1 | -No result changes: the wrapper reproduces `round_dp_with_strategy` exactly -(value, scale and early return), the bridge checks that to the character, -and every existing test and golden passed unchanged. +No result changes to the character, except a negative-zero input +(`round_dp` keeps `-0.00`; `round_places` gives `0.00`; no call site can +produce one): the wrapper reproduces `round_dp_with_strategy` exactly +(value, scale and early return), the bridge checks that, and every existing +test and golden passed unchanged. ### Currency-blind sites (kept at two places, on purpose)