diff --git a/crates/ledger-core/tests/decimal_exact.rs b/crates/ledger-core/tests/decimal_exact.rs index 6490fc27..0370866f 100644 --- a/crates/ledger-core/tests/decimal_exact.rs +++ b/crates/ledger-core/tests/decimal_exact.rs @@ -17,9 +17,11 @@ //! //! Exact only up to the sums the books reach. Near `Decimal::MAX` the add //! rounds dust away (`MAX + 0.4` gives `Some(MAX)`, found by unit K-U4 and -//! pinned below; plan unit K-U10 makes the kernel refuse it), and a product -//! whose scale can't fit 28 places is rounded (the reason for decision -//! D-75's ten-place bound on foreign amounts and rates). +//! pinned below), and a product whose scale can't fit 28 places is rounded +//! (the reason for decision D-75's ten-place bound on foreign amounts and +//! rates). These are `rust_decimal`'s own behaviours, pinned here as +//! such; the kernel's `Amount for Decimal` refuses both (K-U10, checked +//! in `tests/kernel_bridge/decimal_exact.rs`). //! //! This is a test of the dependency, not of the engine. When a property //! fails, the finding is `rust_decimal`'s, and the failing case stays here @@ -436,8 +438,8 @@ fn checked_add_and_sub_return_none_past_the_maximum() { /// Inexact at the edge: within one unit of `Decimal::MAX`, `checked_add` /// rounds the fraction away instead of refusing (K-U4's finding). Pinned -/// so the day `rust_decimal` or the kernel (unit K-U10) makes it exact, -/// this test says so. +/// so the day `rust_decimal` makes it exact, this test says so; the +/// kernel's `Amount::checked_add` refuses it (K-U10). #[test] fn checked_add_rounds_dust_away_next_to_the_maximum() { let dust = Decimal::new(4, 1); diff --git a/crates/ledger-core/tests/kernel_bridge/control.rs b/crates/ledger-core/tests/kernel_bridge/control.rs index 974e40ac..c62db781 100644 --- a/crates/ledger-core/tests/kernel_bridge/control.rs +++ b/crates/ledger-core/tests/kernel_bridge/control.rs @@ -77,16 +77,17 @@ fn dec_wide(cents: i128) -> Decimal { Decimal::from_i128_with_scale(cents, 2) } -/// `Decimal`'s answer against the exact reference: the same figure, or -/// `None` or a rounded figure when the reference is `None`. FINDING (K-U8, the K-U4 finding -/// again): where a step's exact result does not fit the 96-bit mantissa at -/// scale 2, `rust_decimal` does not refuse but rounds the result to a -/// coarser scale (so `Amount::checked_add` is not "exact or `None`" near -/// the top of the range, not only at `Decimal::MAX`). The reference is -/// `None` there and `Decimal` is `Some` at a scale below 2; the -/// assertion pins that shape, and the canary test below flips when the -/// fix lands in `impl Amount for Decimal`. -fn same_or_rounded( +/// `Decimal`'s answer against the exact reference: the same figure at +/// scale 2, or `None` where the reference is `None`. K-U8's finding +/// (the K-U4 finding again) was that where a step's exact result did not +/// fit the 96-bit mantissa at scale 2, `rust_decimal` did not refuse but +/// rounded the result to a coarser scale; K-U10 closed it, so a figure +/// that is not the exact one is a failure. One shape is not a rounding: +/// an exact sum whose last digit is a zero fits a coarser scale (so the +/// reference's cents overflow at that step and `Decimal`'s figure does +/// not, and a later step may bring it back to scale 2); it must equal +/// the exact value. +fn exact_or_refused( got: Option, want: Option, exact: i128, @@ -94,18 +95,13 @@ fn same_or_rounded( match (got, want) { (Some(g), Some(w)) => prop_assert_eq!((g.mantissa(), g.scale()), (w, 2)), (None, None) => {} - // Rounded at a coarser scale at some step (a later step may bring - // it back to scale 2): not exact, and no panic; the finding. - // The figure is still close to the exact value (`exact`, in - // cents): each coarser step loses at most one unit of its scale - // (at worst the whole units, 100 cents), over at most four steps. - // (A later step can bring the scale back to 2, so the bound is - // not tied to the final scale.) (Some(g), None) => { - let shown = g.mantissa() * 10i128.pow(2u32.saturating_sub(g.scale())); + let cents = g + .mantissa() + .checked_mul(10i128.pow(2u32.saturating_sub(g.scale()))); prop_assert!( - g.scale() <= 2 && (shown - exact).abs() <= 400, - "{g} is not within four whole units of {exact} cents" + g.scale() <= 2 && cents == Some(exact), + "{g} is not the exact {exact} cents" ); } (None, Some(w)) => prop_assert!(false, "refused an exact {w}"), @@ -160,15 +156,15 @@ proptest! { let (a, b, c, d, e) = (f[0], f[1], f[2], f[3], f[4]); let got = kernel::aging_total(dec_wide(a), dec_wide(b), dec_wide(c), dec_wide(d), dec_wide(e)); let want = ref_chain(&[(a, true), (b, true), (c, true), (d, true), (e, true)]); - same_or_rounded(got, want, a + b + c + d + e)?; + exact_or_refused(got, want, a + b + c + d + e)?; let got = kernel::control_difference(dec_wide(a), dec_wide(b), dec_wide(c)); let want = ref_chain(&[(a, true), (b, false), (c, false)]); - same_or_rounded(got, want, a - b - c)?; + exact_or_refused(got, want, a - b - c)?; let got = kernel::reconciliation_total(dec_wide(a), dec_wide(b), dec_wide(c), dec_wide(d)); let want = ref_chain(&[(a, true), (b, true), (c, true), (d, false)]); - same_or_rounded(got, want, a + b + c - d)?; + exact_or_refused(got, want, a + b + c - d)?; } } @@ -231,16 +227,14 @@ fn reconciliation_laptop() { ); } -/// FINDING (K-U8, K-U10 candidate), pinned as a canary: the dust the K-U4 -/// finding saw at `Decimal::MAX` is wider than that. Two cents-scale -/// figures whose exact sum needs more than 96 bits at scale 2 sum to a -/// rounded figure at scale 1, not to `None`. Here 0.01 plus the largest -/// scale-2 figure is 792281625142643375935439503.36, which `rust_decimal` -/// returns as 792281625142643375935439503.4. Reachable only with figures -/// near 7.9 x 10^26, a hundred billion times a journal line's cap, so the -/// engine's line cap keeps it out of every ordinary path. +/// K-U8's finding, closed by K-U10: the dust the K-U4 finding saw at +/// `Decimal::MAX` was wider than that. Two cents-scale figures whose exact +/// sum needs more than 96 bits at scale 2 summed to a rounded figure at +/// scale 1, not to `None`: 0.01 plus the largest scale-2 figure is +/// 792281625142643375935439503.36, which `rust_decimal` returns as +/// 792281625142643375935439503.4. The kernel now refuses it. #[test] -fn finding_decimal_add_rounds_scale_near_the_top() { +fn a_sum_past_exact_arithmetic_is_refused() { let top = Decimal::from_i128_with_scale((1i128 << 96) - 1, 2); let got = kernel::aging_total( Decimal::new(1, 2), @@ -249,8 +243,12 @@ fn finding_decimal_add_rounds_scale_near_the_top() { Decimal::ZERO, top, ); + assert_eq!(got, None); + // The old chain's figure, for the record: rounded. assert_eq!( - got.map(|g| (g.mantissa(), g.scale())), + Decimal::new(1, 2) + .checked_add(top) + .map(|g| (g.mantissa(), g.scale())), Some((7922816251426433759354395034, 1)) ); } @@ -270,6 +268,24 @@ fn arb_decimal() -> impl Strategy { .prop_map(|(m, s)| Decimal::from_i128_with_scale(m, s)) } +fn rat(d: Decimal) -> num_rational::BigRational { + num_rational::BigRational::new( + num_bigint::BigInt::from(d.mantissa()), + num_bigint::BigInt::from(10u8).pow(d.scale()), + ) +} + +/// `rust_decimal`'s `a + b` (or `a - b`) as it returned it, only when it +/// is the exact result: the reference the kernel's checked sum must equal. +fn exact_only(got: Option, a: Decimal, b: Decimal, add: bool) -> Option { + let exact = if add { + rat(a) + rat(b) + } else { + rat(a) - rat(b) + }; + got.filter(|g| rat(*g) == exact) +} + fn shown(d: Option) -> String { d.map_or("None".into(), |d| format!("{d} (scale {})", d.scale())) } @@ -279,26 +295,28 @@ proptest! { /// The routed sites give the figures, scales and refusals the /// hand-written chains they replaced did (K-U8's compatibility check), - /// compared as strings: the old `AgingRow::total`, the old - /// `control_check` difference, the old `Reconciliation::total`. + /// compared as strings, except that a step whose result `rust_decimal` + /// had to round is now refused (K-U10): the old `AgingRow::total`, the + /// old `control_check` difference, the old `Reconciliation::total`, + /// each step filtered through an exact rational reference. #[test] fn kernel_matches_the_replaced_chains(f in prop::array::uniform5(arb_decimal())) { let old_aging = [f[1], f[2], f[3], f[4]] .into_iter() - .try_fold(f[0], Decimal::checked_add); + .try_fold(f[0], |a, b| exact_only(Decimal::checked_add(a, b), a, b, true)); prop_assert_eq!( shown(kernel::aging_total(f[0], f[1], f[2], f[3], f[4])), shown(old_aging) ); - let old_diff = f[0].checked_sub(f[1]).and_then(|d| d.checked_sub(f[2])); + let old_diff = exact_only(Decimal::checked_sub(f[0], f[1]), f[0], f[1], false) + .and_then(|d| exact_only(Decimal::checked_sub(d, f[2]), d, f[2], false)); prop_assert_eq!( shown(kernel::control_difference(f[0], f[1], f[2])), shown(old_diff) ); - let old_recon = f[0] - .checked_add(f[1]) - .and_then(|x| x.checked_add(f[2])) - .and_then(|x| x.checked_sub(f[3])); + let old_recon = exact_only(Decimal::checked_add(f[0], f[1]), f[0], f[1], true) + .and_then(|x| exact_only(Decimal::checked_add(x, f[2]), x, f[2], true)) + .and_then(|x| exact_only(Decimal::checked_sub(x, f[3]), x, f[3], false)); prop_assert_eq!( shown(kernel::reconciliation_total(f[0], f[1], f[2], f[3])), shown(old_recon) diff --git a/crates/ledger-core/tests/kernel_bridge/decimal_exact.rs b/crates/ledger-core/tests/kernel_bridge/decimal_exact.rs new file mode 100644 index 00000000..43748ee0 --- /dev/null +++ b/crates/ledger-core/tests/kernel_bridge/decimal_exact.rs @@ -0,0 +1,449 @@ +//! K-U10 bridge properties: `impl Amount for Decimal`'s add, subtract and +//! multiply are exact or `None`, never rounded (BS-ledger-1: a product the +//! arithmetic cannot hold MUST be refused; BS-entry-4). +//! +//! Kani works on `i64`, which never rounds, so the claim rests here: the +//! kernel's `Decimal` result is compared with `rust_decimal`'s own +//! (the "old" behaviour) and with an independent exact reference +//! (`num_rational::BigRational`, sharing no code with the kernel) over +//! the whole mantissa (to 2^96 - 1) and scale (0 to 28) range, edges +//! included. The law, per operation: +//! +//! 1. `Some(r)` is the exact result: `r` equals the rational one. +//! 2. Where the old result was exact, the kernel returns it unchanged, +//! 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. +//! +//! And over the posted range (BS-entry-4's line cap and ten places) the +//! kernel equals the old for every input. + +use ledger_core::kernel::{Amount, MAX_LINE_AMOUNT, MAX_LINE_SCALE}; +use num_bigint::BigInt; +use num_rational::BigRational; +use proptest::prelude::*; +use rust_decimal::Decimal; + +fn rat(d: Decimal) -> BigRational { + BigRational::new( + BigInt::from(d.mantissa()), + BigInt::from(10u8).pow(d.scale()), + ) +} + +fn shown(d: Option) -> String { + d.map_or("None".into(), |d| format!("{d} (scale {})", d.scale())) +} + +/// What the kernel must return, given what `rust_decimal` returned and +/// the exact result: the old figure if it is exact, else `None`. +fn expected(old: Option, exact: &BigRational) -> Option { + old.filter(|o| rat(*o) == *exact) +} + +/// Any `Decimal`: mantissas across the whole 96 bits (small, near the +/// top, trailing zeros) at every scale. +fn arb_decimal() -> impl Strategy { + let top = (1i128 << 96) - 1; + ( + prop_oneof![ + -1_000i128..=1_000, + -1_000_000_000_000i128..=1_000_000_000_000, + -top..=top, + (top - 1_000)..=top, + -top..=-(top - 1_000), + (-top / 1_000_000..=top / 1_000_000).prop_map(|m| m * 1_000_000), + Just(top), + Just(-top), + Just(0), + ], + 0u32..=28, + ) + .prop_map(|(m, s)| Decimal::from_i128_with_scale(m, s)) +} + +/// A decimal and a second one at a nearby scale or the same: the +/// rescaling edge of an add is where the rounding lives. +fn arb_pair() -> impl Strategy { + prop_oneof![ + (arb_decimal(), arb_decimal()), + (arb_decimal(), 0u32..=28, -1_000i128..=1_000) + .prop_map(|(a, s, m)| (a, Decimal::from_i128_with_scale(m, s))), + (arb_decimal(), -1_000i128..=1_000) + .prop_map(|(a, m)| (a, Decimal::from_i128_with_scale(m, a.scale()))), + ] +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(30000))] + + /// Add: laws 1 to 4, over the whole range. + #[test] + fn add_is_exact_or_none((a, b) in arb_pair()) { + let got = Amount::checked_add(a, b); + let old = Decimal::checked_add(a, b); + let exact = rat(a) + rat(b); + if let Some(r) = got { + prop_assert_eq!(rat(r), exact.clone(), "{} + {} is rounded", a, b); + } + prop_assert_eq!(shown(got), shown(expected(old, &exact))); + } + + /// Subtract: the same laws, against `rust_decimal`'s own subtraction + /// (so a zero stays a plain zero). + #[test] + fn sub_is_exact_or_none((a, b) in arb_pair()) { + let got = Amount::checked_sub(a, b); + let old = Decimal::checked_sub(a, b); + let exact = rat(a) - rat(b); + if let Some(r) = got { + prop_assert_eq!(rat(r), exact.clone(), "{} - {} is rounded", a, b); + } + prop_assert_eq!(shown(got), shown(expected(old, &exact))); + } + + /// Multiply: the same laws. + #[test] + fn mul_is_exact_or_none((a, b) in arb_pair()) { + let got = Amount::checked_mul(a, b); + let old = Decimal::checked_mul(a, b); + let exact = rat(a) * rat(b); + if let Some(r) = got { + prop_assert_eq!(rat(r), exact.clone(), "{} x {} is rounded", a, b); + } + prop_assert_eq!(shown(got), shown(expected(old, &exact))); + } + + /// Whatever the kernel refuses, `rust_decimal` either refused or + /// rounded: the kernel never refuses an exact figure `rust_decimal` + /// held (restating laws 2 and 3 as the refusal's only two causes). + #[test] + fn a_refusal_is_an_overflow_or_a_rounding((a, b) in arb_pair()) { + for (got, old, exact) in [ + (Amount::checked_add(a, b), Decimal::checked_add(a, b), rat(a) + rat(b)), + (Amount::checked_mul(a, b), Decimal::checked_mul(a, b), rat(a) * rat(b)), + ] { + if got.is_none() { + prop_assert!(old.is_none_or(|o| rat(o) != exact)); + } + } + } +} + +/// A figure a posted line can carry (BS-entry-4): at most +/// `MAX_LINE_AMOUNT`, at most `MAX_LINE_SCALE` places once trailing zeros +/// are dropped; stored at any raw scale that still holds it. +fn arb_line_amount() -> impl Strategy { + (0u32..=MAX_LINE_SCALE, any::()).prop_flat_map(|(scale, negative)| { + let cap = 10i128.pow(15 + scale); + (0i128..=cap, 0u32..=28).prop_map(move |(m, want)| { + let m = if negative { -m } else { m }; + // Up to `want` extra trailing zeros: the same value at a raw + // scale of up to 28, as far as 96 bits hold it. + let mut pad = 0; + while pad < want + && scale + pad < 28 + && m.checked_mul(10i128.pow(pad + 1)) + .is_some_and(|p| p.unsigned_abs() < 1u128 << 96) + { + pad += 1; + } + Decimal::from_i128_with_scale(m * 10i128.pow(pad), scale + pad) + }) + }) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(20000))] + + /// Over the posted range, add and subtract equal `rust_decimal`'s, to + /// the character, and are never `None`. + #[test] + fn posted_range_sums_are_unchanged(a in arb_line_amount(), b in arb_line_amount()) { + prop_assert!(a.abs() <= MAX_LINE_AMOUNT && b.abs() <= MAX_LINE_AMOUNT); + prop_assert!(a.normalize().scale() <= MAX_LINE_SCALE); + let add = Amount::checked_add(a, b); + let sub = Amount::checked_sub(a, b); + prop_assert!(add.is_some() && sub.is_some()); + prop_assert_eq!(shown(add), shown(Decimal::checked_add(a, b))); + prop_assert_eq!(shown(sub), shown(Decimal::checked_sub(a, b))); + } + + /// Over the posted range, an FX product (a foreign amount and a + /// rate of at most ten places each, D-75) is the old product to the + /// character whenever its mantissa product fits 96 bits (the exact + /// product is then representable), and `None` where it does not and + /// the old one rounded. + #[test] + fn posted_range_fx_products_are_unchanged_or_refused( + fm in 0i128..=10i128.pow(25), + fs in 0u32..=MAX_LINE_SCALE, + rm in 0i128..=10i128.pow(13), + rs in 0u32..=MAX_LINE_SCALE, + ) { + let foreign = Decimal::from_i128_with_scale(fm, fs); + let rate = Decimal::from_i128_with_scale(rm, rs); + let got = Amount::checked_mul(foreign, rate); + let old = Decimal::checked_mul(foreign, rate); + let fits = fm.checked_mul(rm).is_some_and(|p| p < (1i128 << 96)); + if fits { + prop_assert!(got.is_some()); + prop_assert_eq!(shown(got), shown(old)); + } else { + // Past 96 bits at the full scale: the old product was rounded + // unless the product's own trailing zeros made it fit. + prop_assert_eq!(shown(got), shown(expected(old, &(rat(foreign) * rat(rate))))); + } + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(1500))] + + /// A running total of posted lines (1e18 at the worst, ten places: a + /// 29-digit mantissa) is unchanged at every step. + #[test] + fn posted_range_running_totals_are_unchanged( + lines in proptest::collection::vec(arb_line_amount(), 0..=100) + ) { + let mut old = Decimal::ZERO; + let mut new = Decimal::ZERO; + for l in lines { + 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))); + } + } +} + +/// 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] +fn a_sum_past_exact_arithmetic_is_refused_at_the_maximum() { + let max = Decimal::MAX; + assert_eq!(Decimal::checked_add(max, Decimal::new(4, 1)), Some(max)); + assert_eq!(Amount::checked_add(max, Decimal::new(4, 1)), None); + assert_eq!(Amount::checked_add(max, Decimal::new(5, 1)), None); + assert_eq!(Amount::checked_add(max, Decimal::ONE), None); + assert_eq!(Amount::checked_add(max, Decimal::ZERO), Some(max)); + assert_eq!( + Amount::checked_add(max, -Decimal::ONE), + Some(max - Decimal::ONE) + ); + assert_eq!(Amount::checked_sub(Decimal::MIN, Decimal::new(4, 1)), None); +} + +/// The K-U8 canary, flipped: `0.01 + 792281625142643375935439503.35`. +#[test] +fn a_sum_past_exact_arithmetic_is_refused_near_the_top() { + let top = Decimal::from_i128_with_scale((1i128 << 96) - 1, 2); + let cent = Decimal::new(1, 2); + assert_eq!( + shown(Decimal::checked_add(cent, top)), + "792281625142643375935439503.4 (scale 1)", + "rust_decimal rounds the exact ...503.36" + ); + assert_eq!(Amount::checked_add(cent, top), None); + assert_eq!(Amount::checked_add(top, cent), None); + // The sums that are exact stay. + assert_eq!( + Amount::checked_add(-cent, top), + Decimal::checked_add(-cent, top) + ); +} + +/// The K-U1 canary, flipped: `1050000010.0000000001 x 9.9999999999` is +/// 10500000099.89499999999999999999 exactly, 20 places, 96 bits short; +/// `rust_decimal` held 10500000099.895 and the engine booked ...99.90. +/// The product is refused. +#[test] +fn a_product_past_exact_arithmetic_is_refused() { + let foreign: Decimal = "1050000010.0000000001".parse().unwrap(); + let rate: Decimal = "9.9999999999".parse().unwrap(); + let held = Decimal::checked_mul(foreign, rate).unwrap(); + assert_ne!(rat(held), rat(foreign) * rat(rate), "rust_decimal rounded"); + assert_eq!(held.to_string(), "10500000099.895000000000000000"); + assert_eq!(Amount::checked_mul(foreign, rate), None); + // K-U3's square, reachable below the line cap at ten places. + let n: Decimal = "123456789.0123456789".parse().unwrap(); + assert_eq!( + shown(Decimal::checked_mul(n, n)), + "15241578753238836.750190519988 (scale 12)" + ); + assert_eq!(Amount::checked_mul(n, n), None); + // Past scale 28 the old product rounds (or underflows to zero). + let tiny = Decimal::from_i128_with_scale(1, 28); + assert_eq!(Decimal::checked_mul(tiny, tiny), Some(Decimal::ZERO)); + assert_eq!(Amount::checked_mul(tiny, tiny), None); +} + +/// Exact products with trailing zeros stay, even where the full-scale +/// mantissa would pass 96 bits (a scale test would refuse these): 100 x +/// 0.3333333333333333333333333333 is 33.333...3300 exactly. +#[test] +fn an_exact_product_that_only_looks_wide_is_kept() { + let third = Decimal::from_i128_with_scale(3_333_333_333_333_333_333_333_333_333, 28); + let hundred = Decimal::ONE_HUNDRED; + let got = Amount::checked_mul(third, hundred); + assert_eq!(shown(got), shown(Decimal::checked_mul(third, hundred))); + assert!(got.is_some()); + // 10^20 at scale 20 (one) squared: 10^40 mantissa, value 1. + let one = Decimal::from_i128_with_scale(10i128.pow(20), 20); + assert_eq!( + shown(Amount::checked_mul(one, one)), + shown(Decimal::checked_mul(one, one)) + ); + assert_eq!( + Amount::checked_mul(one, one).map(rat), + Some(rat(Decimal::ONE)) + ); +} + +/// Zero is exact in every shape, and a zero factor never refuses. +#[test] +fn zero_is_exact() { + let z28 = Decimal::from_i128_with_scale(0, 28); + let big = Decimal::MAX; + assert_eq!( + shown(Amount::checked_mul(z28, big)), + shown(Decimal::checked_mul(z28, big)) + ); + assert!(Amount::checked_mul(z28, z28).is_some()); + assert_eq!(Amount::checked_add(z28, big), Some(big)); + assert_eq!( + Amount::checked_add(Decimal::ZERO, z28).map(|d| d.is_zero()), + Some(true) + ); +} + +// ---------------------------------------------------------------- FX + +use ledger_core::kernel::Rounding; + +/// `q` rounded to an integer in `mode`, exactly (no kernel code). +fn round_rational(q: &BigRational, mode: Rounding) -> BigInt { + let n = q.numer(); + let d = q.denom(); + let truncated = n / d; + let rem = n - &truncated * d; + let zero = BigInt::from(0); + let negative = rem < zero; + let twice = if negative { -&rem } else { rem.clone() } * 2; + let away = if negative { -1 } else { 1 }; + match mode { + Rounding::TowardZero => truncated, + Rounding::TowardNegativeInfinity => { + if negative { + truncated - 1 + } else { + truncated + } + } + Rounding::HalfAwayFromZero => { + if twice >= *d { + truncated + away + } else { + truncated + } + } + Rounding::HalfToEven => { + if twice > *d || (twice == *d && truncated.bit(0)) { + truncated + away + } else { + truncated + } + } + } +} + +fn arb_mode() -> impl Strategy { + prop_oneof![ + Just(Rounding::TowardZero), + Just(Rounding::TowardNegativeInfinity), + Just(Rounding::HalfAwayFromZero), + Just(Rounding::HalfToEven), + ] +} + +/// A foreign amount or rate of at most ten places (D-75) and up to +/// `digits` digits of mantissa, so products reach 2^96 and past it. +fn arb_ten_place(digits: u32) -> impl Strategy { + (0i128..10i128.pow(digits), 0u32..=MAX_LINE_SCALE) + .prop_map(|(m, s)| Decimal::from_i128_with_scale(m, s)) +} + +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), + /// 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). + #[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, + mode in arb_mode(), + negative in any::(), + ) { + let foreign = if negative { -foreign } else { foreign }; + let step = Decimal::from_i128_with_scale(1, places); + let got = Amount::checked_mul_round_to_step(foreign, rate, step, mode); + let scale = BigRational::from_integer(BigInt::from(10u8).pow(places)); + let count = round_rational(&(rat(foreign) * rat(rate) * scale.clone()), mode); + let want = BigRational::from_integer(count) / scale; + 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 + ), + } + } +} + +/// The K-U1 edge, now rounded once: the exact product is +/// 10500000099.89499999999999999999, so the cent is 10500000099.89 (the +/// engine used to book ...99.90, off by a cent, by rounding twice). +#[test] +fn the_k_u1_edge_books_the_cent_the_exact_product_gives() { + let foreign: Decimal = "1050000010.0000000001".parse().unwrap(); + let rate: Decimal = "9.9999999999".parse().unwrap(); + let cent = Decimal::new(1, 2); + assert_eq!( + Amount::checked_mul_round_to_step(foreign, rate, cent, Rounding::HalfAwayFromZero), + Some("10500000099.89".parse().unwrap()) + ); + // Products straddling a half cent by digits far below the cent, with + // a 97-bit mantissa (so they cannot take the plain path): the sticky + // digit puts each on its side of the tie. + let rate: Decimal = "1.0000000001".parse().unwrap(); + let book = |foreign: &str, mode| { + Amount::checked_mul_round_to_step(foreign.parse().unwrap(), rate, cent, mode) + }; + let above = "1000000000.0050000001"; // 1000000000.10500000010050000001 + let below = "1000000000.0049999999"; // 1000000000.10499999990049999999 + assert!( + Decimal::checked_mul(above.parse().unwrap(), rate) + .is_some_and(|p| { rat(p) != rat(above.parse().unwrap()) * rat(rate) }) + ); + assert_eq!( + book(above, Rounding::HalfAwayFromZero), + Some("1000000000.11".parse().unwrap()) + ); + assert_eq!( + book(above, Rounding::HalfToEven), + Some("1000000000.11".parse().unwrap()) + ); + assert_eq!( + book(above, Rounding::TowardZero), + Some("1000000000.10".parse().unwrap()) + ); + assert_eq!( + book(below, Rounding::HalfAwayFromZero), + Some("1000000000.10".parse().unwrap()) + ); +} diff --git a/crates/ledger-core/tests/kernel_bridge/fx.rs b/crates/ledger-core/tests/kernel_bridge/fx.rs index 80eb609e..95899086 100644 --- a/crates/ledger-core/tests/kernel_bridge/fx.rs +++ b/crates/ledger-core/tests/kernel_bridge/fx.rs @@ -335,8 +335,8 @@ fn ten_places_each_is_exact_through_the_engine() { /// D-75's bound is what keeps the reference and the engine equal: the /// K-U1 review's input, 0.99999999999999999999999999 (26 places) x 0.005, /// is 0.00499999999999999999999999995 exactly (under half a cent, so -/// 0.00), but `Decimal` rounds the product to 28 places first and the -/// kernel books 0.01. The engine refuses any foreign amount or rate of +/// 0.00); `Decimal` rounded the product to 28 places first and the +/// kernel booked 0.01 (K-U10: it now books 0.00 too). The engine refuses any foreign amount or rate of /// eleven or more places before it computes. #[test] fn past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses() { @@ -355,8 +355,8 @@ fn past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses() { ); assert_eq!( fx_booked_minor(foreign, rate, Currency::USD, Rounding::HalfAwayFromZero), - Some(parse("0.01")), - "outside D-75 the kernel inherits Decimal's early rounding" + Some(parse("0.00")), + "outside D-75 too, the product is rounded once, from the exact one (K-U10)" ); let (mut ledger, cash, entry) = usd_books(); for (foreign, rate) in [ @@ -376,17 +376,18 @@ fn past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses() { } /// The other half of exactness (found by this bridge, reported with -/// D-75): ten places each keep the product's scale within 28, but -/// `Decimal`'s mantissa is 96 bits (7.9e28), and a product of twenty -/// places past about 7.9e8 does not fit. `Decimal` then drops places -/// from the product, and the kernel rounds the already rounded value. -/// 1050000010.0000000001 x 9.9999999999 is 10500000099.89499999999999999999 -/// exactly, and 10500000099.89 to the cent, but `Decimal` holds -/// 10500000099.895 and the kernel books 10500000099.90. Pinned as it is -/// today, outside the precondition of `fx_booked` (which says the -/// mantissas' product must fit); a unit to refuse it is the owner's call. +/// D-75, closed by K-U10): ten places each keep the product's scale +/// within 28, but `Decimal`'s mantissa is 96 bits (7.9e28), and a product +/// of twenty places past about 7.9e8 does not fit. `Decimal` used to drop +/// places from the product and the kernel rounded the already rounded +/// value: 1050000010.0000000001 x 9.9999999999 is +/// 10500000099.89499999999999999999 exactly, and 10500000099.89 to the +/// cent, but `Decimal` held 10500000099.895 and the kernel booked +/// 10500000099.90. The kernel now holds the exact product wide for its +/// one rounding, so it books what the reference does, and `Amount`'s own +/// product refuses what `Decimal` cannot hold (decimal_exact.rs). #[test] -fn the_mantissa_edge_is_outside_the_precondition_and_pinned() { +fn the_mantissa_edge_books_the_exact_products_cent() { let foreign = parse("1050000010.0000000001"); let rate = parse("9.9999999999"); assert_eq!(foreign.scale(), 10); @@ -403,6 +404,6 @@ fn the_mantissa_edge_is_outside_the_precondition_and_pinned() { ); assert_eq!( fx_booked_minor(foreign, rate, Currency::USD, Rounding::HalfAwayFromZero), - Some(parse("10500000099.90")) + Some(parse("10500000099.89")) ); } diff --git a/crates/ledger-core/tests/kernel_bridge/main.rs b/crates/ledger-core/tests/kernel_bridge/main.rs index 31e1090e..7d482238 100644 --- a/crates/ledger-core/tests/kernel_bridge/main.rs +++ b/crates/ledger-core/tests/kernel_bridge/main.rs @@ -9,6 +9,7 @@ // One file per kernel-sweep unit; the properties above stay here. mod allocate; mod control; +mod decimal_exact; mod entries; mod fx; mod payroll; diff --git a/crates/ledger-core/tests/kernel_bridge/schedule.rs b/crates/ledger-core/tests/kernel_bridge/schedule.rs index c8ecc08d..0d8119ef 100644 --- a/crates/ledger-core/tests/kernel_bridge/schedule.rs +++ b/crates/ledger-core/tests/kernel_bridge/schedule.rs @@ -242,16 +242,25 @@ fn the_edges() { // answer is not None, because the plug is exact; but the quotient // MAX / 2 = ...167.5 has 29 digits, so Decimal's division rounds it to // ...168 first, and the part is half a unit from the exact quotient, - // a hundred steps at the cent: the K-U10 item, which is why the - // callers refuse totals of 10^26 or more (EXACT_LIMIT). + // a hundred steps at the cent: the K-U10 item (the division's, left + // as it is), which is why the callers refuse totals of 10^26 or more + // (EXACT_LIMIT). The sum of the parts is exact or refused (K-U10): + // 599 parts of 1.3e26 at the cent need more than 96 bits at scale 2, + // and `rust_decimal` used to round that sum. for months in [1usize, 2, 3, 7, 600] { for step in ["1", "0.01", "0.001"] { - let parts = decimal_parts(widest, parse(step), months) - .expect("MAX fits: the quotient is smaller, the last is the remainder"); + let parts = decimal_parts(widest, parse(step), months); + if months == 600 && step != "1" { + assert_eq!( + parts, None, + "{months} months at {step}: the sum is not exact" + ); + continue; + } + let parts = + parts.expect("MAX fits: the quotient is smaller, the last is the remainder"); assert_eq!( - parts - .iter() - .try_fold(Decimal::ZERO, |a, &b| a.checked_add(b)), + kernel::total(parts.iter().copied()), Some(widest), "{months} months at {step}" ); diff --git a/crates/ledger-core/tests/kernel_bridge/total.rs b/crates/ledger-core/tests/kernel_bridge/total.rs index e8a35880..13f2e0a8 100644 --- a/crates/ledger-core/tests/kernel_bridge/total.rs +++ b/crates/ledger-core/tests/kernel_bridge/total.rs @@ -121,23 +121,22 @@ fn decimal_edge_table() { ); } -/// FINDING (K-U4), pinned as a canary: `rust_decimal` rounds sub-unit dust -/// away when a sum lands on `Decimal::MAX`, so `Amount::checked_add` for -/// `Decimal` is not exact at the very edge (`MAX + 0.4 = MAX`, but `MAX + -/// 0.5` is `None`). The kernel's "exact or `None`" contract (and `total`'s -/// invariant 2) therefore holds for `Decimal` everywhere except figures -/// within one unit of `Decimal::MAX` (~7.9 x 10^28, 10^13 times a journal -/// line's cap). The fix belongs in `impl Amount for Decimal` -/// (`kernel/entries.rs`), not in `total`; when it lands this test fails -/// and is flipped to expect `None`. See docs/proofs/k-u4.md. +/// K-U4's finding, closed by K-U10: `rust_decimal` rounds sub-unit dust +/// away when a sum lands on `Decimal::MAX` (`MAX + 0.4 = MAX`, but `MAX + +/// 0.5` is `None`), so `Amount::checked_add` for `Decimal` was not "exact +/// or `None`" within one unit of `Decimal::MAX`. `impl Amount for Decimal` +/// now checks the sum is the exact one, so `total`'s invariant 2 holds +/// there too: the rounded sum is refused. See docs/proofs/k-u4.md and +/// k-u10.md. #[test] -fn finding_decimal_add_rounds_dust_at_the_edge() { +fn a_sum_past_exact_arithmetic_is_refused() { let max = Decimal::MAX; let dust = Decimal::new(4, 1); assert_eq!( - kernel::total([max, dust]), + rust_decimal::Decimal::checked_add(max, dust), Some(max), - "rust_decimal rounds the 0.4 away" + "rust_decimal rounds the 0.4 away; the kernel does not" ); + assert_eq!(kernel::total([max, dust]), None); assert_eq!(kernel::total([max, Decimal::new(5, 1)]), None); }