diff --git a/crates/ledger-core/src/kernel/allocate.rs b/crates/ledger-core/src/kernel/allocate.rs index c5896d80..eedc3734 100644 --- a/crates/ledger-core/src/kernel/allocate.rs +++ b/crates/ledger-core/src/kernel/allocate.rs @@ -9,7 +9,10 @@ //! division, so a `Decimal` quotient is rounded at 28 significant digits //! (and a machine integer's is truncated), never an exact rational. //! Multiplication is not exact either at `Decimal`'s 96-bit mantissa: -//! `checked_mul` rounds the product there. Every invariant below is +//! `checked_mul_rounded` rounds the product there, and this module uses +//! it by name wherever a rounded product is the figure meant (the +//! kernel's `checked_mul` is exact or refused, K-U10, and would refuse a +//! share by a percent of 27 places). Every invariant below is //! stated of that computation, and of the parts after the named leftover //! policy, which do sum to the whole exactly. See `docs/proofs/k-u3.md` //! for the edges where a product's or a quotient's rounding can change a diff --git a/crates/ledger-core/src/kernel/decimal_exact.rs b/crates/ledger-core/src/kernel/decimal_exact.rs index 101df0e8..847f7920 100644 --- a/crates/ledger-core/src/kernel/decimal_exact.rs +++ b/crates/ledger-core/src/kernel/decimal_exact.rs @@ -201,8 +201,14 @@ fn product_is_exact(a: Decimal, b: Decimal, product: Decimal) -> bool { /// rounded one. `None` when the product is too large to hold with those /// digits: the figure times 10^(step places + 2) must fit 96 bits, so a /// figure past about 7.9e26 at a whole-unit step, 7.9e24 at a cent (10^9 -/// times a journal line's cap). A zero product is exact and never gets -/// here. +/// times a journal line's cap). For the same reason a step of 27 or 28 +/// places is always `None` here: `Decimal` ends at 28 places, so there is +/// no place below such a step for the real digit and the sticky one. That +/// refuses some figures whose rounded result `Decimal` could hold (1e-28 +/// squared to a step of 1e-27 is zero); a refusal, never a guess, and no +/// currency's step is within twenty places of it (pinned in the bridge: +/// `a_step_of_27_places_refuses_a_product_that_is_not_exact`). A zero +/// product is exact and never gets here. pub(super) fn mul_for_rounding(a: Decimal, b: Decimal, step_scale: u32) -> Option { let negative = (a.mantissa() < 0) != (b.mantissa() < 0); let mut digits = Wide::mul_wide(a.mantissa().unsigned_abs(), b.mantissa().unsigned_abs()); diff --git a/crates/ledger-core/src/kernel/entries.rs b/crates/ledger-core/src/kernel/entries.rs index 0200e7d9..5753b5d6 100644 --- a/crates/ledger-core/src/kernel/entries.rs +++ b/crates/ledger-core/src/kernel/entries.rs @@ -58,7 +58,12 @@ pub trait Amount: Copy + Ord { /// For [`Decimal`] the exact product may need more than 96 bits (ten /// places each, D-75, is twenty places, and past 7.9e8 the mantissa /// passes `Decimal`'s): it is held wider than `Decimal` for the one - /// rounding, never rounded early and then again. + /// rounding, never rounded early and then again. Two refusals come + /// with that, both far from any books: a product that is not exact + /// and is past about 7.9e26 divided by 10^(the step's places), and a + /// product that is not exact at a step of 27 or 28 places (the + /// rounding needs two places below the step, and `Decimal` ends at + /// 28). An exact product is rounded at any step. fn checked_mul_round_to_step(self, rhs: Self, step: Self, mode: Rounding) -> Option { super::round::round_step(self.checked_mul(rhs)?, step, mode) } diff --git a/crates/ledger-core/src/kernel/ratio.rs b/crates/ledger-core/src/kernel/ratio.rs index a4ad2719..e49218e4 100644 --- a/crates/ledger-core/src/kernel/ratio.rs +++ b/crates/ledger-core/src/kernel/ratio.rs @@ -31,8 +31,8 @@ use super::{Amount, Rounding, round_step, share_of}; /// 1. Some(r) is round_step(part / whole × 100, step, mode), computed /// division first and then the multiplication, the order every call /// site used before U6. For Decimal the quotient is exact while it -/// fits 28 significant digits and the product while it fits the -/// 96-bit mantissa; either operation rounds at that edge (K-U10). +/// fits 28 significant digits and rounds past them; the product by +/// 100 is exact or refused, never rounded (K-U10). /// For a machine integer the division truncates toward zero. /// 2. None when whole <= 0, step <= 0, or a quotient, product or /// rounded result is not representable. Never a panic. diff --git a/crates/ledger-core/tests/kernel_bridge/decimal_exact.rs b/crates/ledger-core/tests/kernel_bridge/decimal_exact.rs index da6accce..bf93ee2d 100644 --- a/crates/ledger-core/tests/kernel_bridge/decimal_exact.rs +++ b/crates/ledger-core/tests/kernel_bridge/decimal_exact.rs @@ -14,6 +14,12 @@ //! compared as strings (value and scale): nothing exact moves. //! 3. Where the old result was rounded, the kernel returns `None`. //! 4. Where the old result was `None`, so is the kernel's. +//! 5. `Some` exactly when the exact result is a `Decimal` at all (a +//! mantissa under 2^96 at some scale of 0 to 28), decided from the +//! rational alone, with none of `rust_decimal`'s arithmetic: nothing +//! representable is refused. Laws 2 to 4 compare with `rust_decimal`; +//! this one does not, so it would catch `rust_decimal` rounding a +//! result it could have held. //! //! And over the posted range (BS-entry-4's line cap and ten places) the //! kernel equals the old for every input. @@ -41,6 +47,21 @@ fn expected(old: Option, exact: &BigRational) -> Option { old.filter(|o| rat(*o) == *exact) } +/// Whether an exact rational is a `Decimal`: `m x 10^-s` with `|m| < 2^96` +/// and `s <= 28`. The fewest places that make it whole are tried in turn; +/// more places only make the mantissa longer. +fn representable(q: &BigRational) -> bool { + let ten = BigRational::from_integer(BigInt::from(10u8)); + let mut scaled = q.clone(); + for _ in 0..=28 { + if scaled.is_integer() { + return scaled.numer().magnitude().bits() <= 96; + } + scaled *= &ten; + } + false +} + /// Any `Decimal`: mantissas across the whole 96 bits (small, near the /// top, trailing zeros) at every scale. fn arb_decimal() -> impl Strategy { @@ -87,6 +108,7 @@ proptest! { prop_assert_eq!(rat(r), exact.clone(), "{} + {} is rounded", a, b); } prop_assert_eq!(shown(got), shown(expected(old, &exact))); + prop_assert_eq!(got.is_some(), representable(&exact), "{} + {}", a, b); } /// Subtract: the same laws, against `rust_decimal`'s own subtraction @@ -100,6 +122,7 @@ proptest! { prop_assert_eq!(rat(r), exact.clone(), "{} - {} is rounded", a, b); } prop_assert_eq!(shown(got), shown(expected(old, &exact))); + prop_assert_eq!(got.is_some(), representable(&exact), "{} - {}", a, b); } /// Multiply: the same laws. @@ -112,6 +135,7 @@ proptest! { prop_assert_eq!(rat(r), exact.clone(), "{} x {} is rounded", a, b); } prop_assert_eq!(shown(got), shown(expected(old, &exact))); + prop_assert_eq!(got.is_some(), representable(&exact), "{} x {}", a, b); } /// Whatever the kernel refuses, `rust_decimal` either refused or @@ -216,6 +240,52 @@ proptest! { } } +proptest! { + #![proptest_config(ProptestConfig::with_cases(24))] + + /// The same over thousands of lines, where the total's mantissa comes + /// near 2^96 (5,000 lines of 10^15 at ten places is 5e28 of 7.9e28): + /// every step is `rust_decimal`'s, and none is refused. + #[test] + fn posted_range_running_totals_of_thousands_of_lines_are_unchanged( + lines in proptest::collection::vec(arb_line_amount(), 4000..=5000), + same_sign in any::(), + ) { + let mut old = Decimal::ZERO; + let mut new = Decimal::ZERO; + for l in lines { + let l = if same_sign { l.abs() } else { l }; + old = Decimal::checked_add(old, l).expect("posted sums fit"); + new = Amount::checked_add(new, l).expect("posted sums stay exact"); + prop_assert_eq!(shown(Some(new)), shown(Some(old))); + } + } +} + +/// Where a running total stops being exact: 7,922 lines of the largest +/// ten-place amount under the cap (999999999999999.9999999999, a mantissa +/// of 10^25 - 1) sum exactly; the next one passes 2^96 at ten places. +/// `rust_decimal` drops a place and rounds; the kernel refuses. +#[test] +fn a_running_total_is_refused_where_it_would_first_round() { + let line = Decimal::from_i128_with_scale(10i128.pow(25) - 1, 10); + assert!(line.in_line_range()); + let mut old = Decimal::ZERO; + let mut new = Decimal::ZERO; + for n in 1..=7_922 { + old = Decimal::checked_add(old, line).unwrap(); + new = Amount::checked_add(new, line).unwrap_or_else(|| panic!("line {n} is exact")); + assert_eq!(shown(Some(new)), shown(Some(old)), "line {n}"); + } + assert_eq!( + rat(new), + rat(line) * BigRational::from_integer(BigInt::from(7_922)) + ); + let rounded = Decimal::checked_add(old, line).unwrap(); + assert_ne!(rat(rounded), rat(old) + rat(line), "rust_decimal rounds"); + assert_eq!(Amount::checked_add(new, line), None); +} + /// The K-U4 canary, flipped: a sum within one unit of `Decimal::MAX` /// that `rust_decimal` rounds is refused, and the exact ones stand. #[test] @@ -376,16 +446,18 @@ proptest! { #![proptest_config(ProptestConfig::with_cases(30000))] /// `checked_mul_round_to_step` is the exact product rounded once, in - /// every mode, at the steps the books use (one, a cent, a mill) and - /// at steps of 5 and 25 of them, + /// every mode, at the steps the books use (one, a cent, a mill), at + /// steps of 5 and 25 of them, and at steps of any number of places, /// whether or not the exact product fits 96 bits, ties and signs - /// included; `None` only for a figure past about 10^23 (the real digits, the - /// sticky digit and the step's places must fit 96 bits). + /// included. `None` only where the kernel says so: the figure times + /// 10^(the step's places + 2) does not fit 96 bits (one real digit + /// below the step and the sticky digit have no room), or the step has + /// 27 or 28 places (no room below it at all). #[test] fn the_fx_product_is_rounded_once_from_the_exact_one( foreign in arb_ten_place(26), rate in arb_ten_place(14), - places in 0u32..=3, + places in prop_oneof![4 => 0u32..=3, 1 => 0u32..=28], unit in prop_oneof![Just(1i128), Just(5i128), Just(25i128)], mode in arb_mode(), negative in any::(), @@ -395,15 +467,24 @@ proptest! { // half steps sit one place below it, where the kept digit is real. let step = Decimal::from_i128_with_scale(unit, places); let got = Amount::checked_mul_round_to_step(foreign, rate, step, mode); - let count = round_rational(&(rat(foreign) * rat(rate) / rat(step)), mode); + let exact = rat(foreign) * rat(rate); + let count = round_rational(&(exact.clone() / rat(step)), mode); let want = BigRational::from_integer(count) * rat(step); match got { Some(g) => prop_assert_eq!(rat(g), want, "{} x {} to {} places, {:?}", foreign, rate, places, mode), - None => prop_assert!( - want.numer().magnitude() / want.denom().magnitude() - > BigInt::from(10u8).pow(23).magnitude().clone(), - "{} x {} refused though it is only {}", foreign, rate, want - ), + None => { + // The digits the rounding needs: the figure to one place + // below the step, then the sticky digit. + let step_places = step.normalize().scale(); + let needed = (exact.clone() + * BigRational::from_integer(BigInt::from(10u8).pow(step_places + 2))) + .to_integer(); + let room = (BigInt::from(1u8) << 96u32) - BigInt::from(10u8); + prop_assert!( + step_places >= 27 || *needed.magnitude() >= *room.magnitude(), + "{} x {} to a step of {} refused though it is only {}", foreign, rate, step, want + ); + } } } } @@ -451,6 +532,40 @@ fn the_k_u1_edge_books_the_cent_the_exact_product_gives() { ); } +/// A step of 27 or 28 places leaves no place below it for the digit and +/// the sticky digit the one rounding needs (`Decimal` ends at 28), so a +/// product that is not exact is refused there in every mode, though its +/// rounded figure (zero, here) is a `Decimal`. A refusal, never a guess; +/// no currency's step is near it. At 26 places the same product rounds. +#[test] +fn a_step_of_27_places_refuses_a_product_that_is_not_exact() { + let tiny = Decimal::from_i128_with_scale(1, 28); + for mode in [ + Rounding::TowardZero, + Rounding::TowardNegativeInfinity, + Rounding::HalfAwayFromZero, + Rounding::HalfToEven, + ] { + for places in [27, 28] { + let step = Decimal::from_i128_with_scale(1, places); + assert_eq!( + Amount::checked_mul_round_to_step(tiny, tiny, step, mode), + None + ); + // A product that is exact is rounded there as at any step. + assert_eq!( + Amount::checked_mul_round_to_step(Decimal::ONE, step, step, mode), + Some(step) + ); + } + let step = Decimal::from_i128_with_scale(1, 26); + assert_eq!( + Amount::checked_mul_round_to_step(tiny, tiny, step, mode), + Some(Decimal::ZERO) + ); + } +} + // ------------------------------------------------------ exact division proptest! { @@ -458,13 +573,32 @@ proptest! { /// `checked_div_exact` is the exact quotient or `None`: never a /// quotient `rust_decimal` rounded (10 / 3), whose product with the - /// divisor rounds back to the dividend. + /// divisor rounds back to the dividend; and `Some` whenever the exact + /// quotient is a `Decimal`, so an exact division is never refused. #[test] fn div_exact_is_exact_or_none(a in arb_line_amount(), m in 1i128..100_000, s in 0u32..=4) { let b = Decimal::from_i128_with_scale(m, s); - if let Some(q) = Amount::checked_div_exact(a, b) { + let got = Amount::checked_div_exact(a, b); + if let Some(q) = got { prop_assert_eq!(rat(q) * rat(b), rat(a), "{} / {} gave {}", a, b, q); } + prop_assert_eq!(got.is_some(), representable(&(rat(a) / rat(b))), "{} / {}", a, b); + } + + /// The same over the whole range of `Decimal`, divisors that divide + /// evenly included (a quotient times a divisor, divided back). + #[test] + fn div_exact_over_the_whole_range((a, b) in arb_pair(), back in any::()) { + let b = if b.is_zero() { Decimal::ONE } else { b }; + // Half the cases: a dividend built as a product, so the exact + // quotient exists and is a `Decimal`. + let a = if back { Amount::checked_mul(a, b).unwrap_or(a) } else { a }; + let exact = rat(a) / rat(b); + let got = Amount::checked_div_exact(a, b); + if let Some(q) = got { + prop_assert_eq!(rat(q), exact.clone(), "{} / {} gave {}", a, b, q); + } + prop_assert_eq!(got.is_some(), representable(&exact), "{} / {}", a, b); } } diff --git a/docs/proofs/k-u10.md b/docs/proofs/k-u10.md index 1ee0e68b..a51b398f 100644 --- a/docs/proofs/k-u10.md +++ b/docs/proofs/k-u10.md @@ -65,7 +65,9 @@ full-scale mantissa passes 96 bits but whose last digits are zeros, like `100 x 0.3333333333333333333333333333` = 33.33…3300, which `percent_of` computes for every ratio, or `10^20 x 10^-20` squared) and `periods.rs`'s hand-written scale check does exactly that. Comparing values is the -complete test, so nothing exact is refused (`an_exact_product_that_only_looks_wide_is_kept`). +complete test, so nothing exact is refused (`an_exact_product_that_only_looks_wide_is_kept`, +and law 5 of the bridge properties: `Some` exactly when the exact result +is a `Decimal`, decided from the rational alone). `Amount::checked_sub` for `Decimal` is `rust_decimal`'s subtraction under the same check. The trait default (`self + (-rhs)`) gave `-0` for `0 - 0`; @@ -122,15 +124,18 @@ independent `num_rational::BigRational` reference, over every mantissa to | Property | Law | |---|---| -| `add_is_exact_or_none` | `Some(r)` equals the rational sum; equals the old result to the character where that was exact; `None` where it was rounded or `None` | +| `add_is_exact_or_none` | `Some(r)` equals the rational sum; equals the old result to the character where that was exact; `None` where it was rounded or `None`; and `Some` exactly when the rational sum is a `Decimal` (a mantissa under 2^96 at a scale of 0 to 28), decided with none of `rust_decimal`'s arithmetic, so nothing representable is refused | | `sub_is_exact_or_none` | the same, against `rust_decimal`'s subtraction (zero included) | | `mul_is_exact_or_none` | the same, for products | | `a_refusal_is_an_overflow_or_a_rounding` | the kernel refuses only where `rust_decimal` overflowed or rounded | | `posted_range_sums_are_unchanged` | every line-range figure (≤ 10^15, ≤ 10 places, any raw scale holding it): add and subtract equal the old to the character and are never `None` | | `posted_range_running_totals_are_unchanged` | a running total of up to 100 line-range figures is unchanged at every step | +| `posted_range_running_totals_of_thousands_of_lines_are_unchanged` | the same for 4,000 to 5,000 lines, all of one sign in half the cases, where the total's mantissa comes within a factor of two of 2^96 | +| `a_running_total_is_refused_where_it_would_first_round` | 7,922 lines of 999999999999999.9999999999 sum exactly; the 7,923rd passes 2^96 at ten places, where `rust_decimal` drops a place and rounds and the kernel refuses | | `posted_range_fx_products_are_unchanged_or_refused` | foreign (≤ 10^25 mantissa, ≤ 10 places) x rate (≤ 10 places): identical to the old whenever the mantissa product fits 96 bits; otherwise the old figure only if it was exact, else `None` | -| `the_fx_product_is_rounded_once_from_the_exact_one` | `checked_mul_round_to_step` equals the exact rational product rounded once, in each of four modes, at steps of 1, 5 and 25 units of 1, 0.1, 0.01 and 0.001 (a step that is not a power of ten has its half steps one place below it), signs and ties included; `None` only past about 10^23 | -| `div_exact_is_exact_or_none` | a quotient `checked_div_exact` returns, times the divisor, is the dividend as a rational (`a_rounded_quotient_is_not_an_exact_one` names the thirds, sevenths and ninths) | +| `the_fx_product_is_rounded_once_from_the_exact_one` | `checked_mul_round_to_step` equals the exact rational product rounded once, in each of four modes, at steps of 1, 5 and 25 units of 1, 0.1, 0.01 and 0.001 (a step that is not a power of ten has its half steps one place below it), signs and ties included, and at steps of any number of places up to 28; `None` only where the exact product times 10^(the step's places + 2) does not fit 96 bits, or the step has 27 or 28 places (`a_step_of_27_places_refuses_a_product_that_is_not_exact` pins that one) | +| `div_exact_is_exact_or_none` | a quotient `checked_div_exact` returns, times the divisor, is the dividend as a rational (`a_rounded_quotient_is_not_an_exact_one` names the thirds, sevenths and ninths), and it returns one whenever the exact quotient is a `Decimal` | +| `div_exact_over_the_whole_range` | the same over every `Decimal`, half the dividends built as a product so the exact quotient exists | Also: the three flipped canaries (below), `an_exact_product_that_only_looks_wide_is_kept`, `zero_is_exact`, `the_k_u1_edge_books_the_cent_the_exact_products_cent` @@ -171,3 +176,37 @@ each a rounded figure that is now refused or correctly rounded): because `periods.rs` shares by a many-place percent, for one, relies on a rounded product, and each is unreachable below about 7.9e26. A follow-up can convert them one by one against its own refusal. + +## What the independent review found + +A second model read the unit before it merged (2026-11-09) and sampled +400,000 random pairs against the 256-bit arithmetic: no wrong `Some`. Its +findings, each reproduced before it was acted on: + +- **One refusal the docs did not state.** `checked_mul_round_to_step` + returns `None` for a product that is not exact at a step of 27 or 28 + places, though the rounded figure can be a `Decimal` (1e-28 squared to + a step of 1e-27 is zero). The one rounding needs a real digit and a + sticky digit below the step, and `Decimal` has no place for them past + 28. Kept, stated in the trait and in `mul_for_rounding`, and pinned by a + test: it is a refusal, no step in any books is near it, and removing it + means dividing in 256 bits for a case nothing reaches. +- **The properties proved soundness, not completeness.** They compared + the kernel with an expectation built from `rust_decimal`'s own result, + so a refusal of something exact could not fail them. Now each of add, + subtract, multiply and exact division is also `Some` exactly when the + rational result is a `Decimal`, decided from the rational alone. All + hold; nothing was refused that should not be. +- **The FX property reached steps of 0 to 3 places only** and accepted any + `None` past 10^23. It now covers steps of every scale and accepts a + `None` only at the two bounds the code documents. +- **Running totals reached 100 lines.** Now thousands, to within a factor + of two of the mantissa's end, and the first refusal is pinned (line + 7,923 of the largest ten-place amount). +- **Three stale sentences**: `percent_of`'s product (exact or refused + since this unit, only the division rounds), the header of + `allocate.rs`, and this page's table. + +The sampling is a test, not a proof: the 256-bit helpers have no Kani +harness of their own (see "Kani" above), and rest on the bridge +properties and the unit tests against `num_bigint`.