merge: foreign-currency conversion in the kernel, fx_booked, and D-75's ten-place bound (K-U1; branch t3/kernel-fx-booked-conversion; reviewed, fixes applied)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-11-08 18:51:53 -07:00
commit 3da9d97929
9 files changed
+1027 -24

No files matched your search

+140 -5
View File
@@ -1,5 +1,140 @@
//! 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
/// `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
/// 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 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.
/// 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.
/// 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<T: Amount>(foreign: T, rate: T, step: T, mode: Rounding) -> Option<T> {
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<Decimal> {
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)
}
+35 -7
View File
@@ -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,15 +1875,32 @@ impl Ledger {
found: foreign_currency.code().to_string(),
});
}
let exact = foreign_amount
.checked_mul(fx_rate)
.ok_or(LedgerError::AmountOutOfRange)?;
// 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
// 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,
)
+118 -3
View File
@@ -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");
}
+406 -2
View File
@@ -1,4 +1,408 @@
//! 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 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::kernel::{Rounding, fx_booked, fx_booked_minor};
use ledger_core::{AccountType, Currency, Ledger, LedgerError, Side};
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<Decimal> {
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 mut count = i128::try_from(count).ok()?;
if negative {
count = -count;
}
// The kernel returns an exact multiple already in range as it is, so a
// count `places` places would push past 96 bits is compared at a
// coarser scale (the same value, trailing zeros dropped).
let mut scale = places;
loop {
if let Ok(value) = Decimal::try_from_i128_with_scale(count, scale) {
return Some(value);
}
if scale == 0 || count % 10 != 0 {
return None;
}
count /= 10;
scale -= 1;
}
}
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 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 << 47)..=(1i128 << 47),
fsc in 0u32..=10,
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);
// 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),
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"))
);
}
/// 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"))
);
}
+90
View File
@@ -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::<Decimal>().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.
+38
View File
@@ -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::<Decimal>().unwrap());
assert_eq!(
lines[0].foreign_amount,
Some("0.99999999999999999999999999".parse::<Decimal>().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,