From abad8d892b81a0b90a0585091785400cef4e797a Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 15:11:41 -0700 Subject: [PATCH] test(core): Kani and bridge for fx_booked Four Kani harnesses on i64 with fixed steps (a symbolic step is intractable for CBMC's division, as K-U2 found; written down in docs/proofs/k-u1.md): whole unit, within half a unit with tie covers, positive for positive, and overflow/non-positive rate refused. The bridge checks i64 against Decimal and Decimal against an independent i128 exact-product reference at 0, 2 and 3 minor units (JPY, USD, KWD), with Decimal::MAX, scale 28, and both-sign tie edges. The law itself is proved in bookspec's Lean (Fx.booked_whole/near/pos, law 41) on the k-u1 branch there. Co-Authored-By: Muse Wonder 1.0 --- crates/ledger-core/src/proofs/fx.rs | 121 ++++++++- crates/ledger-core/tests/kernel_bridge/fx.rs | 253 ++++++++++++++++++- docs/proofs/k-u1.md | 124 +++++++++ 3 files changed, 493 insertions(+), 5 deletions(-) create mode 100644 docs/proofs/k-u1.md diff --git a/crates/ledger-core/src/proofs/fx.rs b/crates/ledger-core/src/proofs/fx.rs index 366c235f..e1899a85 100644 --- a/crates/ledger-core/src/proofs/fx.rs +++ b/crates/ledger-core/src/proofs/fx.rs @@ -1,5 +1,120 @@ //! U1 proof harnesses: foreign-currency conversion (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::fx_booked` on `i64`: amounts and the rate are plain +//! integers (the rate's precision is the value's own, as a `Decimal` +//! rate's is its scale), the step a fixed constant. A symbolic step was +//! not used: `round_step`'s harnesses found CBMC's bit-blasted division +//! by a symbolic `i64` intractable (K-U2), and `fx_booked` rounds through +//! `round_step`, so the steps are the fixed set below — an even step (a +//! tie exists), odd steps, 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. + +use crate::kernel::{Rounding, fx_booked}; +use kani::cover; + +/// The fixed steps: one, evens (a tie exists), an odd step, a decimal +/// step, and a step well above the amounts' products. +const STEPS: [i64; 5] = [1, 2, 5, 10, 100]; + +fn any_foreign() -> i64 { + let value: i64 = kani::any(); + kani::assume(value >= -256 && value <= 256); + value +} + +fn any_rate() -> i64 { + let value: i64 = kani::any(); + kani::assume(value >= 1 && value <= 16); + value +} + +/// The result is a whole multiple of the minor unit. +#[kani::proof] +#[kani::unwind(8)] +fn fx_booked_is_whole_unit() { + let foreign = any_foreign(); + let rate = any_rate(); + for step in STEPS { + let booked = fx_booked(foreign, rate, step, Rounding::HalfAwayFromZero) + .expect("no overflow under these bounds"); + assert_eq!(booked % step, 0, "a whole multiple of the step"); + } + cover!( + (foreign * rate).rem_euclid(10) != 0, + "a non-zero remainder rounded to the step" + ); + cover!(foreign < 0, "a negative foreign amount"); +} + +/// The result is within half a unit of the exact product, a tie at +/// exactly half included. +#[kani::proof] +#[kani::unwind(8)] +fn fx_booked_within_half_unit() { + let foreign = any_foreign(); + let rate = any_rate(); + let exact = foreign * rate; + for step in STEPS { + let booked = fx_booked(foreign, rate, step, Rounding::HalfAwayFromZero) + .expect("no overflow under these bounds"); + let distance = (booked - exact).abs(); + assert!(2 * distance <= step, "within half a unit of the product"); + } + cover!(exact.rem_euclid(10) != 0, "a non-zero remainder"); + cover!(exact.rem_euclid(10) == 5, "an exact tie at step 10"); + cover!( + exact.rem_euclid(2) == 1, + "an exact tie at step 2 (half of an even step)" + ); +} + +/// Positive foreign and rate book a non-negative amount, and a +/// positive one once the product reaches half a unit (a smaller +/// product rounds to zero, which `add_line_fx` refuses). +#[kani::proof] +#[kani::unwind(8)] +fn fx_booked_positive_for_positive() { + let foreign: i64 = kani::any(); + kani::assume(foreign >= 1 && foreign <= 256); + let rate = any_rate(); + let exact = foreign * rate; + for step in STEPS { + let booked = fx_booked(foreign, rate, step, Rounding::HalfAwayFromZero) + .expect("no overflow under these bounds"); + assert!(booked >= 0, "never negative for positive inputs"); + if 2 * exact >= step { + assert!(booked > 0, "positive once the product reaches half a unit"); + } + } + cover!(exact >= 100, "a product past the largest step"); + cover!(2 * exact < 100, "a product under half the largest step"); +} + +/// Overflow and a non-positive rate are refused, never a panic or a +/// wrapped product. +#[kani::proof] +fn fx_booked_refuses_overflow() { + assert_eq!( + fx_booked(i64::MAX, 2, 1, Rounding::HalfAwayFromZero), + None, + "a product past i64 is refused" + ); + assert_eq!( + fx_booked(100, i64::MAX, 1, Rounding::HalfAwayFromZero), + None, + "a huge rate is refused the same way" + ); + let foreign = any_foreign(); + let rate: i64 = kani::any(); + kani::assume(rate <= 0); + for step in STEPS { + assert_eq!( + fx_booked(foreign, rate, step, Rounding::HalfAwayFromZero), + None, + "a non-positive rate is refused" + ); + } + cover!(rate < 0, "a negative rate"); + cover!(rate == 0, "a zero rate"); +} diff --git a/crates/ledger-core/tests/kernel_bridge/fx.rs b/crates/ledger-core/tests/kernel_bridge/fx.rs index 5c426108..819bbcb0 100644 --- a/crates/ledger-core/tests/kernel_bridge/fx.rs +++ b/crates/ledger-core/tests/kernel_bridge/fx.rs @@ -1,4 +1,253 @@ //! U1 bridge properties: foreign-currency conversion (kernel sweep). //! -//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, -//! beside `main.rs` and the other units. +//! `proofs/fx.rs` proves `fx_booked` on `i64` (plain integers, fixed +//! steps); the engine runs the same code on `Decimal`. These properties +//! check that both instantiations agree, that `Decimal` agrees with an +//! independent exact rational reference (integer mantissas over powers +//! of ten, sharing no code with the kernel) for foreign amounts and +//! rates of up to ten places into base currencies of 0, 2 and 3 minor +//! units (JPY, USD, KWD), and the edge table: `Decimal::MAX`, scale 28, +//! half-unit ties of both signs, and a product that overflows (None, +//! never a panic). + +use ledger_core::Currency; +use ledger_core::kernel::{Rounding, fx_booked, fx_booked_minor}; +use proptest::prelude::*; +use rust_decimal::Decimal; + +fn parse(text: &str) -> Decimal { + text.parse().expect("a decimal literal") +} + +/// An independent exact reference: the product of `fm x 10^-fsc` and +/// `rm x 10^-rsc` (both exact `i128` integers), rounded once half away +/// from zero to `places` places. No kernel code, no `Decimal` division. +fn reference(fm: i128, fsc: u32, rm: i128, rsc: u32, places: u32) -> Option { + let product = fm.checked_mul(rm)?; + let scale = fsc + rsc; + let negative = product < 0; + let magnitude = product.unsigned_abs(); + let count = if scale >= places { + let divisor = 10u128.checked_pow(scale - places)?; + let floor = magnitude / divisor; + let remainder = magnitude % divisor; + if remainder.checked_mul(2)? >= divisor { + floor.checked_add(1)? + } else { + floor + } + } else { + magnitude.checked_mul(10u128.checked_pow(places - scale)?)? + }; + let count = i128::try_from(count).ok()?; + Decimal::try_from_i128_with_scale(if negative { -count } else { count }, places).ok() +} + +fn currency_for(places: u32) -> Currency { + match places { + 0 => Currency::JPY, + 2 => Currency::USD, + _ => Currency::new("KWD").unwrap(), + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(2000))] + + /// The `i64` kernel (the Kani model) and the `Decimal` kernel (the + /// engine) agree on the same plain-integer conversion. + #[test] + fn i64_and_decimal_agree( + foreign in -(1i64 << 20)..=(1i64 << 20), + rate in 1i64..=(1i64 << 12), + step in 1i64..=(1i64 << 12), + ) { + let ours = fx_booked(foreign, rate, step, Rounding::HalfAwayFromZero) + .map(Decimal::from); + prop_assert_eq!( + ours, + fx_booked( + Decimal::from(foreign), + Decimal::from(rate), + Decimal::from(step), + Rounding::HalfAwayFromZero, + ) + ); + } + + /// The exact reference above, on foreign amounts and rates of up + /// to ten places, booked into 0, 2 and 3 minor units: the + /// `Decimal` kernel is the exact product rounded once, both + /// through a bare step and through the currency wrapper. + #[test] + fn decimal_matches_the_exact_reference( + fm in -(1i128 << 40)..=(1i128 << 40), + fsc in 0u32..=10, + rm in 1i128..=(1i128 << 40), + rsc in 0u32..=10, + places in prop_oneof![Just(0u32), Just(2u32), Just(3u32)], + ) { + let foreign = Decimal::try_from_i128_with_scale(fm, fsc).expect("in range"); + let rate = Decimal::try_from_i128_with_scale(rm, rsc).expect("in range"); + let want = reference(fm, fsc, rm, rsc, places); + prop_assert!(want.is_some(), "the reference fits for these ranges"); + let step = Decimal::try_from_i128_with_scale(1, places).unwrap(); + prop_assert_eq!( + fx_booked(foreign, rate, step, Rounding::HalfAwayFromZero), + want + ); + prop_assert_eq!( + fx_booked_minor(foreign, rate, currency_for(places), Rounding::HalfAwayFromZero), + want + ); + } +} + +/// The edge table, each row checked by hand. +#[test] +fn fx_booked_at_the_edges() { + let cent = parse("0.01"); + // The ledger's own examples (BS-ledger-1): to the cent, to the yen. + assert_eq!( + fx_booked( + parse("100.00"), + parse("1.0834567"), + cent, + Rounding::HalfAwayFromZero + ), + Some(parse("108.35")) + ); + assert_eq!( + fx_booked_minor( + parse("10.00"), + parse("151.237"), + Currency::JPY, + Rounding::HalfAwayFromZero + ), + Some(parse("1512")) + ); + // A thousandths currency (KWD), an exact half thousandth away. + assert_eq!( + fx_booked_minor( + parse("1"), + parse("1.2345"), + Currency::new("KWD").unwrap(), + Rounding::HalfAwayFromZero + ), + Some(parse("1.235")) + ); + // Half-unit ties, both signs (the kernel books the magnitude). + assert_eq!( + fx_booked(parse("1"), parse("0.125"), cent, Rounding::HalfAwayFromZero), + Some(parse("0.13")) + ); + assert_eq!( + fx_booked( + parse("-1"), + parse("0.125"), + cent, + Rounding::HalfAwayFromZero + ), + Some(parse("-0.13")) + ); + // Scale 28: the finest amount, and a product that rounds to zero. + let finest = parse("0.0000000000000000000000000001"); + assert_eq!( + fx_booked(finest, Decimal::ONE, cent, Rounding::HalfAwayFromZero), + Some(Decimal::ZERO) + ); + // Decimal's own multiplication underflows the finest product to + // zero (checked_mul holds it as 0); the kernel keeps that exactly, + // as the pre-kernel computation did. + assert_eq!( + fx_booked(finest, finest, Decimal::ONE, Rounding::HalfAwayFromZero), + Some(Decimal::ZERO) + ); + // Decimal's largest value converts at rate one; at rate two the + // product cannot be held: None, never a panic. + assert_eq!( + fx_booked( + Decimal::MAX, + Decimal::ONE, + Decimal::ONE, + Rounding::HalfAwayFromZero + ), + Some(Decimal::MAX) + ); + assert_eq!( + fx_booked( + Decimal::MAX, + Decimal::from(2), + cent, + Rounding::HalfAwayFromZero + ), + None + ); + assert_eq!( + fx_booked_minor( + Decimal::MAX, + Decimal::from(2), + Currency::USD, + Rounding::HalfAwayFromZero + ), + None + ); + // A non-positive rate and a non-positive step are refused. + assert_eq!( + fx_booked( + parse("100"), + Decimal::ZERO, + cent, + Rounding::HalfAwayFromZero + ), + None + ); + assert_eq!( + fx_booked( + parse("100"), + parse("-1.5"), + cent, + Rounding::HalfAwayFromZero + ), + None + ); + assert_eq!( + fx_booked( + parse("100"), + Decimal::ONE, + Decimal::ZERO, + Rounding::HalfAwayFromZero + ), + None + ); + // The booked scale is the old computation's: an exact product with + // trailing zeros past the cents books at exactly the minor places, + // and one already at the cents keeps its scale. + let booked = fx_booked_minor( + parse("1.50"), + parse("1.00"), + Currency::USD, + Rounding::HalfAwayFromZero, + ) + .unwrap(); + assert_eq!(booked.to_string(), "1.50"); + let booked = fx_booked_minor( + parse("108.3"), + Decimal::ONE, + Currency::USD, + Rounding::HalfAwayFromZero, + ) + .unwrap(); + assert_eq!(booked.to_string(), "108.3"); + // A currency with no minor unit books the exact product. + let gold = Currency::new("XAU").unwrap(); + assert_eq!( + fx_booked_minor( + parse("1.5"), + parse("1.23456789"), + gold, + Rounding::HalfAwayFromZero + ), + Some(parse("1.851851835")) + ); +} diff --git a/docs/proofs/k-u1.md b/docs/proofs/k-u1.md new file mode 100644 index 00000000..e0e0846a --- /dev/null +++ b/docs/proofs/k-u1.md @@ -0,0 +1,124 @@ +# K-U1: FX conversion, `fx_booked` + +Status: landed 2026-11-08. The kernel sweep's U1 +(`plan/kernel-sweep-audit.md` section 3): the one foreign-currency +conversion that books money (`Ledger::add_line_fx`) moves into the +kernel, proved once in bookspec's Lean, checked on `i64` by Kani and +on `Decimal` by the bridge. + +## The API + +```rust +pub fn fx_booked(foreign: T, rate: T, step: T, mode: Rounding) -> Option +pub fn fx_booked_minor(foreign: Decimal, rate: Decimal, currency: Currency, mode: Rounding) -> Option +``` + +`fx_booked` is `foreign x rate` computed exactly (`checked_mul`), +rounded once to a whole multiple of `step` by `round_step` (never a +second rounding); `None` for a non-positive rate, a non-positive step, +or an unrepresentable product or result. The rate's precision is the +value's own: a `Decimal` rate keeps its scale (1.0834567 is exact), so +the product is the pre-kernel `checked_mul` product to the digit. +`fx_booked_minor` is the `Decimal`/currency spelling `add_line_fx` +books through: it picks `10^-currency.minor_units()` as the step, and +keeps the pre-kernel scale (an exact product at or under the minor +places unchanged, otherwise exactly the minor places; a currency with +no minor unit books the exact product, as `round_minor` always did). + +Behaviour is identical for every input: `add_line_fx` keeps its own +refusals (`InvalidDocumentLineAmount` for a non-positive foreign +amount, `InvalidFxRate` for a non-positive rate or a result that +rounds to zero, `CurrencyMismatch`, `AmountOutOfRange` on overflow), +and every existing test and golden passed unchanged. + +Other FX sites, by grep over `crates/ledger-core/src` and +`crates/ledger-store/src` for `fx_rate`/`rate`/`foreign`: the only +conversion is `add_line_fx`. `set_fx_rate`/`get_fx_rate` (core and +store) only record and return a rate for reference; the store's +`add_line_fx` already delegates to the core's; journal replay +(`replay_add_line_fx`) books a recorded amount verbatim and converts +nothing. None needed routing. + +## Kani harnesses (`crates/ledger-core/src/proofs/fx.rs`) + +All at `i64`, foreign symbolic in `[-256, 256]`, rate in `[1, 16]`, +over the fixed steps `1, 2, 5, 10, 100`. A symbolic step was not used: +K-U2 found CBMC's bit-blasted division by a symbolic `i64` +intractable (30 minutes unfinished), and `fx_booked` rounds through +`round_step`; the fixed steps include an even step (a tie exists), +odd steps, a decimal step, and steps above the products. The bridge +carries the same laws to every `Decimal` step, and Lean to any step. + +| Harness | Law | Verification | +|---|---|---| +| `fx_booked_is_whole_unit` | the result is a whole multiple of the minor unit | 9.1 s (2 covers) | +| `fx_booked_within_half_unit` | within half a unit of the exact product | 16.4 s (3 covers: non-zero remainder, ties at steps 10 and 2) | +| `fx_booked_positive_for_positive` | positive inputs book non-negative, positive once the product reaches half a unit | 3.2 s (2 covers) | +| `fx_booked_refuses_overflow` | an overflowing product and a non-positive rate are `None`, never a panic | 2.6 s (2 covers) | + +Measured alone on this machine, 2026-11-08, with +`cargo kani -p ledger-core --exact --harness proofs::fx::` +(verification time; wall time includes the build). `just prove` +(fast set) passes with these four included, Lean at 151 theorems, +standard axioms only. + +## Bridge (`crates/ledger-core/tests/kernel_bridge/fx.rs`) + +- `i64_and_decimal_agree`: the Kani model and the engine agree on + plain-integer conversions, value for value. +- `decimal_matches_the_exact_reference`: an independent `i128` + reference (exact integer product, one integer rounding; no kernel + code, no `Decimal` division) over foreign amounts and rates of up + to 10 places, booked into 0, 2, and 3 minor units (JPY, USD, KWD), + through both `fx_booked` and `fx_booked_minor`. +- `fx_booked_at_the_edges`: 100.00 x 1.0834567 to the cent, 10.00 x + 151.237 to the yen, a KWD half-thousandth tie, half-unit ties of + both signs, scale 28 (including `Decimal`'s multiplication + underflowing the finest product to zero, kept exactly as before), + `Decimal::MAX` at rates one (books) and two (`None`, never a + panic), a non-positive rate and step, the booked scale ("1.50", + "108.3"), and gold's exact product. + +All pass with the rest of `kernel_bridge`. + +## Lean (bookspec, branch `k-u1`) + +`lean/Bookspec/Fx.lean`, law 41 in `spec/laws.md`, headline theorems +in `lean/Audit.lean`. Build: `lake build && lake env lean Audit.lean`, +standard axioms only; `cargo test --workspace` and +`render -- --check` pass (checker law count 40 to 41). + +- `Fx.booked_whole` — the booked amount is a multiple of the unit. +- `Fx.booked_near` — within half a unit of the exact product, any size. +- `Fx.booked_pos` — positive inputs book non-negative, and positive + once the product reaches half a unit. + +`Fx.booked` is `Round.roundStep .halfAway` of the product, so the +three theorems restate `Round.roundStep_multiple`, +`Round.near_halfAway`, and `Round.sign_preserved` for the product +(the half-away mode is `Deductible.roundHA`; nothing reproved). +BS-ledger-1's FX invariants now name `Fx.booked_near`, +`Fx.booked_whole`, and `Fx.booked_pos` where the theorem matches; +its tie invariants keep `Deductible.roundHA_tie_*`. + +BS-ledger-14 (the CHOICE split out of BS-ledger-1) is absent from +bookspec `main` (`c467093`, the commit `k-u1` branches from). Its +record is located at `rules/ledger/BS-ledger-14.toml` in commit +`233a569` on the unmerged branch `s-c7a` (worktree +`~/Code/bookspec-wt/s-c7a`, clean at inspection). Linking it from +`k-u1` therefore needs an owner/integrator decision: + +1. **(Recommended)** Land S-C7a (or the merged `s-c7`) on `main` + first, rebase `k-u1`, then set BS-ledger-14's two FX invariants + to `lean = "Fx.booked_near"` (the exact-product invariant) and + `lean = "Fx.booked_whole"` (every booked amount in `Z * u`), + regenerating the pages. No other record changes. +2. Cherry-pick `233a569` into `k-u1` now and link there. This was + not done: that commit also creates BS-entry-6..8, + BS-ledger-15..21, BS-period-4/5, BS-statement-6..9 and + BS-prepaid-2..4, well outside this unit, and would collide with + S-C7 at merge. + +Outcome recorded here: option 1; the BS-ledger-14 link is the one +item left for the integrator, and everything it needs (theorem +names, which invariant each matches) is stated above.