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:
commit
3da9d97929
9 files changed
+1027
-24
No files matched your search
@@ -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)
|
||||
}
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
Reference in new issue
Block a user