From f9affd0e1f60fe3ebbada1873690e73ff6c0b232 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 15:11:36 -0700 Subject: [PATCH 1/5] refactor(core): foreign currency conversion, fx_booked, in the kernel The one FX conversion that books money (add_line_fx: foreign x rate, rounded once to the base currency's minor unit, half away from zero, B-3 / BS-ledger-1 and its CHOICE BS-ledger-14) was inline in ledger.rs. It now lives in kernel/fx.rs as fx_booked (exact checked product, one round_step; None on a non-positive rate or overflow) with fx_booked_minor as its Decimal/currency spelling, which also keeps the pre-kernel scale and books the exact product for a currency with no minor unit. add_line_fx keeps its own error variants and refusals, so behaviour is identical for every input; every test and golden passes unchanged. Grep found no other FX conversion site: set/get_fx_rate only record a rate, the store delegates to the core, and replay books a recorded amount verbatim. Co-Authored-By: Muse Wonder 1.0 --- crates/ledger-core/src/kernel/fx.rs | 108 ++++++++++++++++++++++++++-- crates/ledger-core/src/ledger.rs | 13 ++-- 2 files changed, 110 insertions(+), 11 deletions(-) diff --git a/crates/ledger-core/src/kernel/fx.rs b/crates/ledger-core/src/kernel/fx.rs index 11680873..6681c51f 100644 --- a/crates/ledger-core/src/kernel/fx.rs +++ b/crates/ledger-core/src/kernel/fx.rs @@ -1,5 +1,103 @@ -//! U1: foreign-currency conversion, the booking of a foreign amount at the transaction-date rate (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`. +//! U1: foreign-currency conversion, the booking of a foreign amount at +//! the transaction-date rate (kernel sweep, `plan/kernel-sweep-audit.md` +//! section 3). The one place foreign x rate becomes booked money: the +//! product is computed exactly and rounded once, by [`round_step`], to +//! the base currency's smallest unit. No call site multiplies by a rate +//! itself. + +use super::round::{Rounding, round_step}; +use crate::Currency; +use crate::kernel::Amount; +use rust_decimal::Decimal; + +/// The booked base amount for a foreign amount at a rate: `foreign x +/// rate` computed exactly, rounded once to a whole multiple of `step` +/// (the base currency's minor unit) in `mode`. +/// +/// The rate's precision is carried by the value itself: a `Decimal` +/// rate keeps its own scale (1.0834567 is exact), and the product is the +/// exact `Decimal` product before the single rounding, exactly as +/// `Ledger::add_line_fx` computed it before this kernel existed. At +/// `i64` (the Kani model) amounts and the rate are plain integers in +/// the smallest unit, and the same law is proved of the product. +/// +/// ```text +/// GOAL: book a foreign amount in the ledger's one money: the exact +/// product foreign x rate, rounded once to the base currency's +/// smallest unit, half away from zero. +/// SOURCE: bookspec BS-ledger-1 (one money; a foreign amount at the +/// transaction-date rate, ASC 830-20-30-1; the smallest unit +/// from ISO 4217), and its CHOICE BS-ledger-14 +/// "book-in-the-smallest-unit" (the owner, 2026-10-13: book in +/// the smallest unit, half away from zero); wanderbooks +/// docs/spec/claims/ledger.md B-3 states the same pick. The +/// rounding itself is kernel::round_step (BS-ledger-1, +/// BS-entry-3); 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. None when step <= 0, when rate <= 0, or when the +/// exact product or the rounded result cannot be held. +/// 2. In HalfAwayFromZero (the mode add_line_fx books in) r is +/// within half a step of the exact product foreign x rate, an +/// exact half going to the multiple farther from zero. +/// 3. Positive foreign and rate give a non-negative r, and a +/// positive r whenever the exact product reaches half a step +/// (a smaller product rounds to zero, which the caller refuses +/// as it does today). The sign never crosses zero. +/// 4. On Decimal the value equals the pre-kernel computation +/// (checked_mul, then round_minor half away from zero) exactly; +/// fx_booked_minor also keeps its scale. +/// SCENARIOS: +/// 1. IF 100.00 at 1.0834567 to the cent: SHOULD book 108.35. +/// 2. IF 10.00 at 151.237 to the yen (step 1): SHOULD book 1512. +/// 3. IF the rate is zero or negative: SHOULD be None, never a guess. +/// 4. IF foreign x rate overflows: SHOULD be None, never a panic. +/// ``` +pub fn fx_booked(foreign: T, rate: T, step: T, mode: Rounding) -> Option { + if rate <= T::ZERO { + return None; + } + let exact = foreign.checked_mul(rate)?; + round_step(exact, step, mode) +} + +/// [`fx_booked`] at a currency's minor unit, on `Decimal`: the spelling +/// `Ledger::add_line_fx` books through. A currency ISO 4217 gives no +/// minor unit (gold, SDRs) books the exact product, as `round_minor` +/// has always done (B-3). The result's scale is the pre-kernel +/// computation's: `round_places` keeps an amount already at or under +/// the minor places unchanged, and otherwise carries exactly the minor +/// places (a booked 1.50 prints "1.50", never "1.5000"). +pub fn fx_booked_minor( + foreign: Decimal, + rate: Decimal, + currency: Currency, + mode: Rounding, +) -> Option { + let Some(places) = currency.minor_units() else { + if rate <= Decimal::ZERO { + return None; + } + return foreign.checked_mul(rate); + }; + let step = Decimal::try_from_i128_with_scale(1, places).ok()?; + let rounded = fx_booked(foreign, rate, step, mode)?; + if rounded.is_zero() { + // The old round_places scale for a zero (the caller refuses it). + return Decimal::try_from_i128_with_scale(0, places).ok(); + } + if rounded.scale() != places { + // fx_booked returns an exact multiple unchanged, trailing zeros + // and all; the old computation carried exactly the minor places + // whenever the product was finer than them. The multiple is + // exact at `places`, so this rescale rounds nothing. + let exact = foreign.checked_mul(rate)?; + if exact.scale() > places { + let mut rounded = rounded; + rounded.rescale(places); + return Some(rounded); + } + } + Some(rounded) +} diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index 6358a1c1..8fc03d64 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -1864,15 +1864,16 @@ impl Ledger { found: foreign_currency.code().to_string(), }); } - let exact = foreign_amount - .checked_mul(fx_rate) - .ok_or(LedgerError::AmountOutOfRange)?; // Booked in the base currency's smallest unit (cents for USD), half // 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 = crate::kernel::round_minor( - exact, + // the GnuCash cross-check found the difference). The kernel's + // fx_booked_minor is that computation (foreign x rate exactly, + // rounded once); the rate and zero-result refusals above and + // below keep their error variants. + let base_amount = crate::kernel::fx_booked_minor( + foreign_amount, + fx_rate, self.base_currency, crate::kernel::Rounding::HalfAwayFromZero, ) From abad8d892b81a0b90a0585091785400cef4e797a Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 15:11:41 -0700 Subject: [PATCH 2/5] 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. From bf2fe200c2666ae4b20fa26e26b866ef4c60c076 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 18:08:12 -0700 Subject: [PATCH 3/5] style: rustfmt engine.rs (main's S-C7 merge left it unformatted) No accounting change; `cargo fmt --check` was red on main. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/tests/bookspec/engine.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ledger-core/tests/bookspec/engine.rs b/crates/ledger-core/tests/bookspec/engine.rs index 03e22ff3..636266a2 100644 --- a/crates/ledger-core/tests/bookspec/engine.rs +++ b/crates/ledger-core/tests/bookspec/engine.rs @@ -79,7 +79,11 @@ pub(crate) const PICKS: &[(Area, u32, &str)] = &[ (Area::Partner, 12, "labelled-cash-default-or-all"), (Area::Partner, 13, "tax-basis-beside-book"), (Area::Partner, 14, "running-cumulative"), - (Area::Partner, 15, "contract-is-property-vendor-paid-is-cash"), + ( + Area::Partner, + 15, + "contract-is-property-vendor-paid-is-cash", + ), (Area::Partner, 16, "close-at-the-change"), (Area::Partner, 17, "book-amount-with-note"), (Area::Asset, 3, "tag-and-never-reuse"), From c5a4894985381f1830edacc0ff305c727e621ec3 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 18:08:12 -0700 Subject: [PATCH 4/5] fix(core): foreign amounts and rates take at most 10 places (D-75) The K-U1 review: foreign 0.99999999999999999999999999 (26 places) x rate 0.005 into USD booked 0.01, though the exact product 0.00499999999999999999999999995 is under half a cent. Decimal::checked_mul rounds a product finer than 28 places to 28 before fx_booked rounds it to the cent: two roundings, one cent off. A ledger in one money books the exact product rounded once (BS-ledger-1, BS-ledger-14). Owner decision D-75 (2026-11-08): a new line's foreign amount and its rate take at most MAX_LINE_SCALE (10) decimal places each, as a base amount does (B-28), so their product has at most 20 places, under Decimal's 28. Ledger::add_line_fx refuses past it with ValueOutOfRange ("foreign amount ..." / "FX rate ..."; the variant for an amount that is not a journal line's), trailing zeros not counted, before computing, and never on replay (is_replaying; replay_add_line_fx books a journal's older line verbatim). Tests: 11-place foreign amount and rate refused; ten and ten accepted with hand-checked books; the review's input refused, not mis-booked; trailing zeros are not places; replay keeps a 26-place foreign line in core, and a store journal holding one opens with its figures. fx_booked's spec block states the precondition (scales within 10 each, and the mantissas' product within Decimal's 96 bits) and that the result is exact under it, and documents Decimal::checked_mul's behaviours outside it (rounding past scale 28 and past 96 bits; 1e-28 x 1e-28 underflowing to zero); invariant 1 now says None when T's checked_mul cannot hold the product. The bridge covers every D-75 scale (0..=10 each, products to 20 places) against an independent exact reference, shows 26 places is where the reference and Decimal part (and the engine refuses), and pins an open edge this bridge found: ten places each still allow a 20-place product past ~7.9e8 that outgrows 96 bits (1050000010.0000000001 x 9.9999999999 books 10500000099.90, exact 10500000099.89). B-28 and B-3 claims record the enforcement and checks. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-core/src/kernel/fx.rs | 63 +++++-- crates/ledger-core/src/ledger.rs | 29 ++- crates/ledger-core/tests/kernel_bridge/fx.rs | 179 +++++++++++++++++-- crates/ledger-core/tests/spec_bounds.rs | 90 ++++++++++ crates/ledger-store/tests/store.rs | 38 ++++ docs/spec/claims/entry.md | 18 +- docs/spec/claims/ledger.md | 10 +- 7 files changed, 394 insertions(+), 33 deletions(-) diff --git a/crates/ledger-core/src/kernel/fx.rs b/crates/ledger-core/src/kernel/fx.rs index 6681c51f..078238fc 100644 --- a/crates/ledger-core/src/kernel/fx.rs +++ b/crates/ledger-core/src/kernel/fx.rs @@ -16,10 +16,34 @@ use rust_decimal::Decimal; /// /// The rate's precision is carried by the value itself: a `Decimal` /// rate keeps its own scale (1.0834567 is exact), and the product is the -/// exact `Decimal` product before the single rounding, exactly as -/// `Ledger::add_line_fx` computed it before this kernel existed. At -/// `i64` (the Kani model) amounts and the rate are plain integers in -/// the smallest unit, and the same law is proved of the product. +/// `T::checked_mul` product before the single rounding. At `i64` (the +/// Kani model) amounts and the rate are plain integers in the smallest +/// unit, and the same law is proved of the product. +/// +/// **The precondition that makes the product exact (D-75).** On +/// `Decimal`, `checked_mul` is exact only while the product keeps its +/// full scale: that scale (the two scales added) must be within 28, and +/// the product's mantissa (the two mantissas multiplied) must fit +/// `Decimal`'s 96 bits, under 7.9e28. A foreign amount and a rate of at +/// most [`MAX_LINE_SCALE`](super::MAX_LINE_SCALE) (10) places each, +/// trailing zeros not counted, meet the first half: a product of at most +/// 20 places, under 28. `Ledger::add_line_fx` enforces that bound on +/// every new line (never on replay). The second half is not enforced: +/// a product of 20 places past about 7.9e8 needs more than 96 bits, and +/// `Decimal` then drops places (see below). Under both halves the +/// product is the exact one and the result is rounded exactly once. +/// Outside them `Decimal::checked_mul` keeps the behaviours it has +/// always had, which this function inherits and does not hide: a +/// product that does not fit is rounded by `Decimal` (to 28 places, or +/// to the places 96 bits hold) before this function rounds it (a second +/// rounding, so a result can sit a unit off the exact product's: +/// 0.99999999999999999999999999 x 0.005 is 0.00499999999999999999999999995 +/// exactly but 0.005 as held, and books 0.01; 1050000010.0000000001 x +/// 9.9999999999 is 10500000099.89 to the cent but 10500000099.895 as +/// held, and books 10500000099.90), and a product below 1e-28 (1e-28 x +/// 1e-28) underflows to zero. Invariants 2 and 3 are stated for +/// products that are exact; invariant 1 (a whole multiple of the step) +/// holds regardless. The bridge pins both behaviours. /// /// ```text /// GOAL: book a foreign amount in the ledger's one money: the exact @@ -36,15 +60,18 @@ use rust_decimal::Decimal; /// bookspec's Lean). /// INVARIANTS: /// 1. Some(r) is a whole multiple of step: r = n x step for an -/// integer n. None when step <= 0, when rate <= 0, or when the -/// exact product or the rounded result cannot be held. -/// 2. In HalfAwayFromZero (the mode add_line_fx books in) r is -/// within half a step of the exact product foreign x rate, an -/// exact half going to the multiple farther from zero. -/// 3. Positive foreign and rate give a non-negative r, and a -/// positive r whenever the exact product reaches half a step -/// (a smaller product rounds to zero, which the caller refuses -/// as it does today). The sign never crosses zero. +/// integer n. None when step <= 0, when rate <= 0, or when T's +/// checked_mul cannot hold the product (the exact product, under +/// the precondition above) or the rounded result cannot be held. +/// 2. Under the precondition (both halves: the product is exact), in +/// HalfAwayFromZero (the mode add_line_fx books in) r is within +/// half a step of the exact product foreign x rate, an exact half +/// going to the multiple farther from zero. +/// 3. Under the precondition, positive foreign and rate give a +/// non-negative r, and a positive r whenever the exact product +/// reaches half a step (a smaller product rounds to zero, which +/// the caller refuses as it does today). The sign never crosses +/// zero. /// 4. On Decimal the value equals the pre-kernel computation /// (checked_mul, then round_minor half away from zero) exactly; /// fx_booked_minor also keeps its scale. @@ -53,6 +80,16 @@ use rust_decimal::Decimal; /// 2. IF 10.00 at 151.237 to the yen (step 1): SHOULD book 1512. /// 3. IF the rate is zero or negative: SHOULD be None, never a guess. /// 4. IF foreign x rate overflows: SHOULD be None, never a panic. +/// 5. IF foreign is 0.99999999999999999999999999 (26 places) and +/// the rate 0.005 to the cent: outside the precondition, books +/// 0.01 where the exact product is under half a cent BECAUSE +/// Decimal rounded the product first; the engine refuses such an +/// input (D-75), and the bridge pins this behaviour. +/// 6. IF foreign 1050000010.0000000001 at 9.9999999999 to the cent +/// (ten places each, a product past 96 bits): outside the +/// precondition's second half, books 10500000099.90 where the +/// exact product rounds to 10500000099.89; the bridge pins this +/// open edge. /// ``` pub fn fx_booked(foreign: T, rate: T, step: T, mode: Rounding) -> Option { if rate <= T::ZERO { diff --git a/crates/ledger-core/src/ledger.rs b/crates/ledger-core/src/ledger.rs index 8fc03d64..58aae056 100644 --- a/crates/ledger-core/src/ledger.rs +++ b/crates/ledger-core/src/ledger.rs @@ -1831,15 +1831,26 @@ impl Ledger { /// GOAL: book a foreign-currency amount in the ledger's one money. /// SOURCE: docs/spec/rules.md B-3 (Pacioli ch. 36: one money; ASC /// 830-20-30-1: at the transaction-date rate); minor units: ISO - /// 4217; rounding: DECISION (owner, 2026-10-13). + /// 4217; rounding: DECISION (owner, 2026-10-13); the ten-place + /// bound (invariant 3): DECISION D-75 (owner, 2026-11-08), + /// B-28's bound, stated in bookspec BS-entry-4. /// INVARIANTS: /// 1. The base amount MUST be a whole number of the base currency's /// smallest unit, within half a unit of foreign * rate. /// 2. NEVER convert into the base currency itself. + /// 3. MUST refuse a foreign amount or a rate of more than ten + /// decimal places (ValueOutOfRange), so the product keeps its + /// scale (within Decimal's 28) and is rounded once; NEVER on + /// replay. /// SCENARIOS: /// 1. IF 100.00 EUR at 1.0834567 into USD: SHOULD book 108.35. /// 2. IF 10.00 USD at 151.237 into JPY: SHOULD book 1512. /// 3. IF the rounded amount is zero: SHOULD refuse. + /// 4. IF the foreign amount is 0.99999999999999999999999999 at + /// 0.005 into USD: SHOULD refuse (more than ten places) + /// BECAUSE Decimal rounds that product to 28 places before the + /// cent rounding, booking a cent the exact product does not + /// reach (found by the K-U1 review). /// ``` pub fn add_line_fx( &mut self, @@ -1864,6 +1875,22 @@ impl Ledger { found: foreign_currency.code().to_string(), }); } + // D-75 (owner, 2026-11-08): a new line's foreign amount and its + // rate take at most MAX_LINE_SCALE places each, as a base amount + // does (B-28), so their product has at most twice that many (20, + // under Decimal's 28) and keeps its scale: the booked amount is + // rounded once, not after Decimal's own rounding of the product. + // (A 20-place product past about 7.9e8 still outgrows Decimal's 96 + // bits; kernel::fx_booked's spec block names that open edge.) + // The command's bound, never replay's: a journal's older line with + // a finer foreign amount opens as it was booked (replay_add_line_fx). + if !crate::parties::is_replaying() { + for (what, value) in [("foreign amount", foreign_amount), ("FX rate", fx_rate)] { + if value.normalize().scale() > kernel::MAX_LINE_SCALE { + return Err(LedgerError::ValueOutOfRange(format!("{what} {value}"))); + } + } + } // Booked in the base currency's smallest unit (cents for USD), half // 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 diff --git a/crates/ledger-core/tests/kernel_bridge/fx.rs b/crates/ledger-core/tests/kernel_bridge/fx.rs index 819bbcb0..80eb609e 100644 --- a/crates/ledger-core/tests/kernel_bridge/fx.rs +++ b/crates/ledger-core/tests/kernel_bridge/fx.rs @@ -5,13 +5,21 @@ //! 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, +//! rates of every scale D-75 allows, 0 to 10 places each (so products of +//! up to 20 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). +//! +//! D-75 is what keeps the reference and the engine equal: past ten +//! places, `Decimal` rounds the product to 28 places before the kernel +//! rounds it to the minor unit, and the two disagree +//! (`past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses`). +//! The scale is half of the exactness condition; the other half is that +//! the mantissas' product fits `Decimal`'s 96 bits (`the_mantissa_edge_*`). -use ledger_core::Currency; use ledger_core::kernel::{Rounding, fx_booked, fx_booked_minor}; +use ledger_core::{AccountType, Currency, Ledger, LedgerError, Side}; use proptest::prelude::*; use rust_decimal::Decimal; @@ -39,8 +47,24 @@ fn reference(fm: i128, fsc: u32, rm: i128, rsc: u32, places: u32) -> Option Currency { @@ -75,22 +99,26 @@ proptest! { ); } - /// 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. + /// The exact reference above, on foreign amounts and rates of every + /// scale D-75 allows (0 to 10 places each, so products to 20 + /// 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. The mantissas stay under + /// 2^47 so their product fits `Decimal`'s 96 bits (the other half of + /// exactness, pinned below). #[test] fn decimal_matches_the_exact_reference( - fm in -(1i128 << 40)..=(1i128 << 40), + fm in -(1i128 << 47)..=(1i128 << 47), fsc in 0u32..=10, - rm in 1i128..=(1i128 << 40), + rm in 1i128..=(1i128 << 47), 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"); + // A result `Decimal` cannot hold (a count past 96 bits) is None in + // both: never a panic, never a wrapped amount. let step = Decimal::try_from_i128_with_scale(1, places).unwrap(); prop_assert_eq!( fx_booked(foreign, rate, step, Rounding::HalfAwayFromZero), @@ -251,3 +279,130 @@ fn fx_booked_at_the_edges() { Some(parse("1.851851835")) ); } + +/// A fresh USD ledger with an entry to add lines to. +fn usd_books() -> (Ledger, ledger_core::AccountId, ledger_core::EntryId) { + let mut ledger = Ledger::new(Currency::USD); + let cash = ledger + .add_account("1000", "Cash", AccountType::Asset, None, false) + .unwrap(); + let entry = ledger.create_entry(chrono::NaiveDate::from_ymd_opt(2026, 1, 1).unwrap(), "fx"); + (ledger, cash, entry) +} + +/// The top of D-75's range: ten places each, a product of twenty places, +/// every digit of it kept: the exact product, rounded once. +#[test] +fn ten_places_each_is_exact_through_the_engine() { + let (mut ledger, cash, entry) = usd_books(); + // 0.9999999999 x 0.0050000001 = 0.00499999999500000001...: let the + // exact product be 0.00500000009...; a hand-checked row each side of + // half a cent. 0.0000000001 x 0.0000000001 = 1e-20 books nothing. + for (foreign, rate, want) in [ + // 0.4999999999 x 0.01 = 0.004999999999: under half a cent. + ("0.4999999999", "0.0100000000", None), + // 0.5000000001 x 0.01 = 0.005000000001: over half a cent. + ("0.5000000001", "0.0100000000", Some("0.01")), + // 0.9999999999 x 0.5000000001 = 0.50000000004999999999: 0.50. + ("0.9999999999", "0.5000000001", Some("0.50")), + // 99999.9999999999 x 99999.9999999999 = 9999999999.99998...: 10000000000.00. + ( + "99999.9999999999", + "99999.9999999999", + Some("10000000000.00"), + ), + ] { + let (f, r) = (parse(foreign), parse(rate)); + let booked = ledger.add_line_fx(entry, cash, Side::Debit, Currency::EUR, f, r); + match want { + None => assert!(booked.is_err(), "{foreign} x {rate} books nothing"), + Some(want) => { + booked.unwrap_or_else(|e| panic!("{foreign} x {rate}: {e}")); + let lines = ledger.get_entry(entry).unwrap().lines(); + assert_eq!(lines.last().unwrap().amount.amount, parse(want)); + } + } + let (fm, fsc) = (f.mantissa(), f.scale()); + let (rm, rsc) = (r.mantissa(), r.scale()); + assert_eq!( + fx_booked_minor(f, r, Currency::USD, Rounding::HalfAwayFromZero), + reference(fm, fsc, rm, rsc, 2), + "{foreign} x {rate}: kernel equals the exact reference" + ); + } +} + +/// 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 +/// eleven or more places before it computes. +#[test] +fn past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses() { + let foreign = parse("0.99999999999999999999999999"); + let rate = parse("0.005"); + assert_eq!( + reference( + foreign.mantissa(), + foreign.scale(), + rate.mantissa(), + rate.scale(), + 2 + ), + Some(parse("0.00")), + "the exact product is under half a cent" + ); + 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" + ); + let (mut ledger, cash, entry) = usd_books(); + for (foreign, rate) in [ + (foreign, rate), + (parse("1.00000000001"), Decimal::ONE), + (Decimal::ONE, parse("1.00000000001")), + ] { + assert!( + matches!( + ledger.add_line_fx(entry, cash, Side::Debit, Currency::EUR, foreign, rate), + Err(LedgerError::ValueOutOfRange(_)) + ), + "{foreign} x {rate} is refused" + ); + } + assert!(ledger.get_entry(entry).unwrap().lines().is_empty()); +} + +/// 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. +#[test] +fn the_mantissa_edge_is_outside_the_precondition_and_pinned() { + let foreign = parse("1050000010.0000000001"); + let rate = parse("9.9999999999"); + assert_eq!(foreign.scale(), 10); + assert_eq!(rate.scale(), 10); + assert_eq!( + reference( + foreign.mantissa(), + foreign.scale(), + rate.mantissa(), + rate.scale(), + 2 + ), + Some(parse("10500000099.89")) + ); + assert_eq!( + fx_booked_minor(foreign, rate, Currency::USD, Rounding::HalfAwayFromZero), + Some(parse("10500000099.90")) + ); +} diff --git a/crates/ledger-core/tests/spec_bounds.rs b/crates/ledger-core/tests/spec_bounds.rs index 88ae63db..f16a5a99 100644 --- a/crates/ledger-core/tests/spec_bounds.rs +++ b/crates/ledger-core/tests/spec_bounds.rs @@ -743,6 +743,96 @@ fn disposal_proceeds_and_dates_are_bounded() { .unwrap(); } +/// D-75 (owner, 2026-11-08): a new line's foreign amount and its rate take +/// at most ten decimal places each, as a base amount does (B-28), so the +/// product is exact (at most twenty places, under Decimal's 28) and the +/// booked amount is rounded once. Found by the K-U1 review: a 26-place +/// foreign amount times 0.005 books 0.01 though the exact product is under +/// half a cent, because Decimal rounded the product to 28 places first. +/// Replay is exempt (B-28): an older line keeps its figures. +#[test] +fn a_foreign_amount_and_a_rate_take_at_most_ten_places() { + let dec = |s: &str| s.parse::().unwrap(); + let mut b = books(); + let e = b.ledger.try_create_entry(d(2026, 1, 1), "fx").unwrap(); + let mut fx = |amount: &str, rate: &str| { + b.ledger.add_line_fx( + e, + b.cash, + Side::Debit, + Currency::EUR, + dec(amount), + dec(rate), + ) + }; + // Eleven places in the foreign amount, or in the rate: refused, naming + // which; ten and ten accepted. + assert_eq!( + fx("1.00000000001", "1"), + Err(LedgerError::ValueOutOfRange( + "foreign amount 1.00000000001".into() + )) + ); + assert_eq!( + fx("1", "1.00000000001"), + Err(LedgerError::ValueOutOfRange("FX rate 1.00000000001".into())) + ); + // The review's input: refused, not mis-booked as 0.01. + assert_eq!( + fx("0.99999999999999999999999999", "0.005"), + Err(LedgerError::ValueOutOfRange( + "foreign amount 0.99999999999999999999999999".into() + )) + ); + // Ten places each: the product (twenty places) is exact and booked + // once. 0.0000000001 x 5000000000.0000000001 = 0.50000000000000000001 + // books 0.50; 0.9999999999 x 0.5000000001 = 0.50000000004999999999 + // books 0.50. + assert_eq!(fx("0.0000000001", "5000000000.0000000001"), Ok(())); + assert_eq!(fx("0.9999999999", "0.5000000001"), Ok(())); + // Trailing zeros are not places: 1.50000000000 is 1.5. + assert_eq!(fx("1.50000000000", "2.0000000000000"), Ok(())); + let lines = b.ledger.get_entry(e).unwrap().lines(); + assert_eq!(lines.len(), 3, "the refused lines were not added"); + assert_eq!(lines[0].amount.amount, dec("0.50")); + assert_eq!(lines[0].foreign_amount, Some(dec("0.0000000001"))); + assert_eq!(lines[1].amount.amount, dec("0.50")); + assert_eq!(lines[2].amount.amount, dec("3.00")); + // The exact tie just under half a cent is not rounded up: with ten + // places each the product is held, so 0.4999999999 x 0.01 = 0.004999999999 + // books to zero and is refused as before. + assert_eq!( + b.ledger.add_line_fx( + e, + b.cash, + Side::Debit, + Currency::EUR, + dec("0.4999999999"), + dec("0.01") + ), + Err(LedgerError::InvalidFxRate(dec("0.01"))) + ); + // Replay keeps an older line with a finer foreign amount, exactly as + // booked. + b.ledger + .replay_add_line_fx( + e, + b.cash, + Side::Debit, + usd(dec("0.01")), + Currency::EUR, + dec("0.99999999999999999999999999"), + ) + .unwrap(); + let lines = b.ledger.get_entry(e).unwrap().lines(); + assert_eq!(lines.len(), 4); + assert_eq!( + lines[3].foreign_amount, + Some(dec("0.99999999999999999999999999")) + ); + assert_eq!(lines[3].amount.amount, dec("0.01")); +} + /// The bounds are the line limit exactly: a new draft line (base or /// foreign) and a recurring template's line may be as large as a line, and /// no larger; a replayed one past it is accepted as journaled. diff --git a/crates/ledger-store/tests/store.rs b/crates/ledger-store/tests/store.rs index 196a71a3..2563ee9d 100644 --- a/crates/ledger-store/tests/store.rs +++ b/crates/ledger-store/tests/store.rs @@ -1792,6 +1792,44 @@ mod refusals { } } +/// D-75: the ten-place bound on a foreign amount is the command's, never +/// replay's (B-28). A journal an earlier version wrote, holding a line with +/// a 26-place foreign amount, opens with its figures exactly as journaled. +#[test] +fn a_journaled_foreign_line_finer_than_ten_places_still_opens() { + use serde_json::json; + let dir = test_dir("fx-fine-foreign"); + let mut store = Store::create(&dir, Currency::USD).unwrap(); + let cash = store + .add_account("1000", "Cash", AccountType::Asset, None, false) + .unwrap(); + drop(store); + let mut w = JournalWriter::open(&dir.join(ledger_store::JOURNAL_FILE)).unwrap(); + w.append( + "entry.created", + json!({"id": 1, "date": "2026-03-01", "description": "old fx"}), + ) + .unwrap(); + w.append( + "entry.line_added", + json!({"id": 1, "account": cash, "side": "debit", "amount": "0.01", "currency": "USD", + "foreign_currency": "EUR", "foreign_amount": "0.99999999999999999999999999", + "fx_rate": "0.005"}), + ) + .unwrap(); + drop(w); + let _ = std::fs::remove_file(dir.join(ledger_store::db_file())); + let store = Store::open(&dir).expect("the older foreign line still opens"); + store.verify().unwrap(); + let lines = store.ledger().get_entry(1).unwrap().lines(); + assert_eq!(lines.len(), 1); + assert_eq!(lines[0].amount.amount, "0.01".parse::().unwrap()); + assert_eq!( + lines[0].foreign_amount, + Some("0.99999999999999999999999999".parse::().unwrap()) + ); +} + /// Contract (2026-10-13): rules added to the engine never lock anyone out /// of books written before them. A journal holding what the new rules /// refuse (a child account of another type, partially overlapping periods, diff --git a/docs/spec/claims/entry.md b/docs/spec/claims/entry.md index c5aa77df..1a065f0e 100644 --- a/docs/spec/claims/entry.md +++ b/docs/spec/claims/entry.md @@ -68,16 +68,23 @@ None. **Claims:** yes -**Pick:** the bounds are bookspec's (dates 0001-01-01 through 9999-12-31, an amount at most `kernel::MAX_LINE_AMOUNT` = 1,000,000,000,000,000, scale at most `MAX_LINE_SCALE` = 10), and one run of the recurring entries creates at most 1,000 drafts (`MAX_RECURRING_RUN`). Provenance: CHOICE (P0 review round 3, 2026-10-16, finding S1: the +**Pick:** the bounds are bookspec's (dates 0001-01-01 through 9999-12-31, an amount at most `kernel::MAX_LINE_AMOUNT` = 1,000,000,000,000,000, scale at most `MAX_LINE_SCALE` = 10; a new foreign line's foreign amount and its FX rate take at most `MAX_LINE_SCALE` places each, so their product keeps its scale), and one run of the recurring entries creates at most 1,000 drafts (`MAX_RECURRING_RUN`). Provenance: CHOICE (P0 review round 3, 2026-10-16, finding S1: the server stops for every session when a request panics, so no input may reach one); CHOICE (P0 review round 4, 2026-10-17: posted is forever, so the bounds are the commands', never replay's). A new asset's life past 9999 is refused at registration, the bound the life's last day held (P3 settled the plan's defect 22 question this way); ones an earlier version took open, and their months after 9999-12 show as scheduled and never post. +The ten-place bound on a foreign amount and a rate is D-75 (the owner, +2026-11-08, "Cap them at 10 places"): the K-U1 review found that with a +26-place foreign amount `Decimal` rounded the product to 28 places before +the engine rounded it to the cent, booking a cent the exact product does +not reach (0.99999999999999999999999999 x 0.005 into USD). A journal's +older, finer foreign line replays as booked (`replay_add_line_fx`). **Enforced:** `ledger_core::calendar`; `Ledger::try_create_entry`, -`add_line`, `add_line_fx`, `validate_new_asset`, `dispose_asset`, +`add_line`, `add_line_fx` (the foreign amount and the rate, `ValueOutOfRange`, +never on replay), `validate_new_asset`, `dispose_asset`, `schedules::validate_schedule`, `validate_recurring`, `periods::validate_period_range`, `arap::validate_lines`, `validate_due_date`, `payroll::check_payroll_ranges`, `payout_plan`, @@ -87,9 +94,12 @@ took open, and their months after 9999-12 show as scheduled and never post. `run_recurring`; `ledger-mcp` `parse_date`, `parse_period_mcp`, `last_day_of_month`. **Checked:** `ledger-core` `tests/spec_bounds.rs` (each bound and its -replay pair), `calendar.rs`, `assets.rs` +replay pair; `a_foreign_amount_and_a_rate_take_at_most_ten_places`), +`kernel_bridge/fx.rs` (`past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses`, +`ten_places_each_is_exact_through_the_engine`), `calendar.rs`, `assets.rs` `registration_rejects_date_overflow`, `invariants.rs` -`out_of_range_amount_is_rejected`; `ledger-store` `tests/bounds.rs`; +`out_of_range_amount_is_rejected`; `ledger-store` `tests/bounds.rs`, +`tests/store.rs` `a_journaled_foreign_line_finer_than_ten_places_still_opens`; `ledger-cli` `server.rs` `periods_are_a_year_and_a_month`, `dates_are_four_digit_years_and_real_days`. diff --git a/docs/spec/claims/ledger.md b/docs/spec/claims/ledger.md index e5dc5053..0d9e9f78 100644 --- a/docs/spec/claims/ledger.md +++ b/docs/spec/claims/ledger.md @@ -18,7 +18,9 @@ Rules: B-3, B-4, B-5, B-8, B-9, B-10, B-20, B-23, B-29, B-31, B-32, B-44, B-45. **Enforced:** `Ledger::add_line` (base currency only, no fraction of the minor unit), `Ledger::add_line_fx` (base amount = foreign amount × rate, -rounded to the minor unit; original kept), `Ledger::post_entry` (every +rounded once to the minor unit by `kernel::fx_booked_minor`; original kept; +a foreign amount or a rate past ten places is refused, D-75, B-28), +`Ledger::post_entry` (every line, whatever made it: payroll, closes, disposals; `FinerThanMinorUnit`, since 2026-10-13 after a payroll run posted $65.27794). Journals from before replay as booked (`replay_post_entry`). A new asset's cost and @@ -29,8 +31,10 @@ replay as journaled. **Checked:** `an_asset_cost_finer_than_a_cent_is_refused`, `a_foreign_line_is_booked_in_whole_base_units`, `no_entry_posts_a_fraction_of_the_minor_unit`, -`foreign_currency_line_is_rejected`, `fx_overflow_is_an_error`; the -GnuCash oracle. +`foreign_currency_line_is_rejected`, `fx_overflow_is_an_error`; +`kernel_bridge/fx.rs` (the exact reference, ten places each); Kani +`proofs::fx::*`; Lean `Fx.booked_near`, `Fx.booked_whole`, `Fx.booked_pos`; +the GnuCash oracle. ### Product rules From c4006243102311b41221946dd275839c1a36ba7f Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 8 Nov 2026 18:08:12 -0700 Subject: [PATCH 5/5] docs(proofs): K-U1 notes after review and D-75 The overflow harness proves two concrete cases (and non-positive rate for every symbolic rate), not every overflow; step <= 0 -> None rests on K-U2's round_step_refuses_nonpositive_step and the bridge; the D-75 precondition, the open 96-bit edge, the bridge's new properties, Fx.booked_pos now proved at the tie, and the BS-ledger-14 link landed. Co-Authored-By: Claude Sonnet 5.5 --- docs/proofs/k-u1.md | 109 +++++++++++++++++++++++++++++++++----------- 1 file changed, 82 insertions(+), 27 deletions(-) diff --git a/docs/proofs/k-u1.md b/docs/proofs/k-u1.md index e0e0846a..1a121079 100644 --- a/docs/proofs/k-u1.md +++ b/docs/proofs/k-u1.md @@ -1,6 +1,6 @@ # K-U1: FX conversion, `fx_booked` -Status: landed 2026-11-08. The kernel sweep's U1 +Status: landed 2026-11-08; review fixes and D-75 the same day. 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 @@ -25,7 +25,39 @@ 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 +**The precondition (D-75, owner, 2026-11-08).** `Decimal::checked_mul` +is the exact product only while the product keeps its full scale: the +two scales added within 28, and the two mantissas multiplied within +`Decimal`'s 96 bits (7.9e28). Outside that it rounds the product itself +(to 28 places, or to the places 96 bits hold), and `fx_booked` then +rounds the rounded value: a second rounding. The K-U1 review found it +with foreign `0.99999999999999999999999999` (26 places) x rate `0.005` +into USD: the exact product is 0.00499999999999999999999999995, under +half a cent, but `Decimal` holds 0.005 and the booking is 0.01. +`Ledger::add_line_fx` now refuses a foreign amount or a rate of more +than `MAX_LINE_SCALE` (10) decimal places (trailing zeros not counted), +with `LedgerError::ValueOutOfRange` ("foreign amount ..." / "FX rate +..."; the variant for an amount that is not a journal line's), before +computing and never on replay (`is_replaying()`; `replay_add_line_fx` +books a journal's older line verbatim, and a store whose journal holds +a 26-place foreign amount opens with its figures). Ten places each give +a product of at most twenty, under 28. `fx_booked`'s spec block states +the precondition, and states that `Decimal::checked_mul`'s two +behaviours outside it are inherited, not hidden: rounding past scale 28 +(and past 96 bits), and `1e-28 x 1e-28` underflowing to zero. + +**An open edge, not closed by D-75.** The 96-bit half of the +precondition is not enforced: ten places each still allow a product of +twenty places past about 7.9e8, which needs more than 96 bits. +`1050000010.0000000001 x 9.9999999999` is 10500000099.89499999999999999999 +exactly (10500000099.89 to the cent) but `Decimal` holds +10500000099.895, and the engine books 10500000099.90. The bridge pins +this (`the_mantissa_edge_is_outside_the_precondition_and_pinned`) and +the spec block names it; refusing it is a decision for the owner (see +the report that came with this change). + +Behaviour is unchanged for every input within the precondition (inputs +outside it are the ones above): `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), @@ -56,6 +88,26 @@ carries the same laws to every `Decimal` step, and Lean to any step. | `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) | +What the harnesses do and do not prove, stated plainly: + +- `fx_booked_refuses_overflow` proves **two concrete overflow cases** + (`i64::MAX x 2` and `100 x i64::MAX`, step 1) are `None`, plus that a + non-positive rate is `None` for every symbolic rate <= 0. It is not a + proof that every overflowing product is refused. +- That every overflow is `None` rests on `i64::checked_mul` (and + `Decimal::checked_mul`) returning `None` when the product cannot be + held, which the bridge exercises (`Decimal::MAX x 2`, the proptest's + products), not on a Kani proof. +- **step <= 0 -> `None`** is not a harness of this unit: it is `round_step`'s + refusal, proved by K-U2's `round_step_refuses_nonpositive_step` + (`docs/proofs/k-u2.md`), and checked here by the bridge (`fx_booked(100, 1, 0)` is `None`). +- Every Kani law above is on the integer model, where the product is exact + by construction (`foreign * rate` is a bounded `i64` product, no + scale, no rounding before `round_step`). The D-75 precondition is + what carries those laws to `Decimal`: with it, `Decimal::checked_mul` is + the same exact integer product of mantissas, and the bridge compares + the engine to an independent exact reference (below). + 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` @@ -68,9 +120,21 @@ standard axioms only. 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`. + code, no `Decimal` division) over foreign amounts and rates of every + scale D-75 allows, 0 to 10 places each (products to scale 20), with + mantissas to 2^47 (so the product fits 96 bits), booked into 0, 2, + and 3 minor units (JPY, USD, KWD), through both `fx_booked` and + `fx_booked_minor`. A result `Decimal` cannot hold is `None` in both. +- `ten_places_each_is_exact_through_the_engine`: the top of D-75's + range through `Ledger::add_line_fx` and the reference, a hand-checked + row each side of half a cent. +- `past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses`: + the D-75 bound is what keeps the reference and the engine equal. The + review's 26-place input has reference 0.00 and kernel 0.01 (the + kernel inherits `Decimal`'s early rounding); `add_line_fx` refuses it + and any 11-place foreign amount or rate (`ValueOutOfRange`). +- `the_mantissa_edge_is_outside_the_precondition_and_pinned`: the open + edge above, pinned as it is. - `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 @@ -91,7 +155,10 @@ standard axioms only; `cargo test --workspace` and - `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. + once the product reaches half a unit, the tie included + (`step <= 2 * product`; first landed as `step < 2 * product`, short of + the stated law and of the Kani assertion `2 * exact >= step`; the tie + follows from `Round.tie_halfAway_pos` with `k = 0`). `Fx.booked` is `Round.roundStep .halfAway` of the product, so the three theorems restate `Round.roundStep_multiple`, @@ -101,24 +168,12 @@ 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. +BS-ledger-14 (the CHOICE split out of BS-ledger-1, S-C7) is on bookspec +`main`; its two FX invariants now cite `Fx.booked_near` (the exact-product +rounding) and `Fx.booked_whole` (every booked amount in `Z * u`). The +D-75 bound is stated in BS-entry-4 as an engine-neutral MUST (a foreign +amount and an exchange rate each take at most ten decimal places, trailing +zeros not counted; replay exempt, BS-entry-8), with D-75 as its +provenance. wanderbooks' claim for B-28 (`docs/spec/claims/entry.md`) +lists the enforcement (`add_line_fx`, `ValueOutOfRange`, never on replay) +and the checks.