merge: main into k-u11a (K-U10's exact operations)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude committed 2026-11-09 22:41:45 -07:00
commit 3918151794
94 files changed
+19771 -635

No files matched your search

+46 -5
View File
@@ -189,7 +189,7 @@ pub const CODES: &[CodeRow] = &[
CodeRow {
code: "close_split_drifts",
severity: Severity::Failure,
predicate: "a member's running share of the closes is more than a minor unit from its exact share",
predicate: "a member's running share of the closes drifts past the bound its regime allows from its exact share",
},
CodeRow {
code: "schedule_behind",
@@ -474,7 +474,12 @@ pub fn check_control(checks: &[crate::arap::ControlCheck]) -> Vec<Finding> {
}
fn closes(ledger: &Ledger, through: NaiveDate) -> Vec<Finding> {
let unit = Decimal::new(1, ledger.base_currency().minor_units().unwrap_or(2));
// The unit the allocation itself splits to, from the one helper both
// sides use (`Currency::allocation_unit`, on `allocation_places`):
// for a currency with no minor unit the split is far finer than a
// cent, and the audit must not check it at a cent (BS-partner-1
// statement 4).
let unit = ledger.base_currency().allocation_unit();
let mut out = Vec::new();
for p in ledger.list_periods() {
if p.status != PeriodStatus::Closed || p.end > through {
@@ -496,8 +501,33 @@ fn closes(ledger: &Ledger, through: NaiveDate) -> Vec<Finding> {
/// that posted an entry ([`crate::Ledger::member_close_trued_up`]). Until
/// then the count may still carry the rounding of closes made under the
/// older rules, which the first such close trues up (BS-partner-1
/// statement 6; WB-partner-1), so only a drift beyond a unit is raised.
/// Once trued up, a drift of a unit or more is raised: the bound is strict.
/// statement 6; WB-partner-1).
///
/// ```text
/// SOURCE: BS-partner-1 statement 5 (after a close that posts, a member's
/// total MUST be under one smallest unit from their exact share);
/// BS-partner-1 statement 6 (the rounding left by an earlier rule
/// is trued up by the first close that posts: a last-absorbs close
/// rounded each member but the last to within half a unit, and
/// the last absorbed up to half a unit for each of the others --
/// a unit with three members, more with four or more); WB-ledger-16
/// invariant 8.
/// DERIVED: the rule states those per-member facts; it does not state an
/// audit bound. The pre-true-up bound below is derived from them:
/// with n members and unit u under last-absorbs, member i (not last)
/// carries rounding e_i with |e_i| <= u/2, and the last member's part
/// is the remainder, so e_last = -(e_1 + ... + e_{n-1}) and
/// |e_last| <= (n-1) * u/2. The largest drift any member of one such
/// close may legitimately carry is therefore (n-1)*u/2: u with three
/// members, 3u/2 with four, 2u with five. Statement 6 also allows
/// under u per member for each break in an earlier run and for each
/// per-close close, so the allowance is floored at u:
/// B(n) = max(u, (n-1)*u/2). A drift past B(n) is raised; a drift of
/// exactly B(n) is legitimate (every non-last tie rounding the same
/// way reaches it), so the pre-true-up test is strict (> B(n)).
/// Once trued up, statement 5's bound is strict the other way: a
/// drift of a unit or more is raised (>= u).
/// ```
pub fn check_split(
period: u64,
name: &str,
@@ -505,11 +535,22 @@ pub fn check_split(
unit: Decimal,
trued_up: bool,
) -> Vec<Finding> {
// B(n) as derived above: (n-1)*u/2, floored at u. `unit` is a power
// of ten and n is small, so the product and the halving are exact.
let legacy_bound = {
let others = Decimal::new(split.len().saturating_sub(1) as i64, 0);
let last = others * unit / Decimal::new(2, 0);
if last > unit { last } else { unit }
};
split
.iter()
.filter(|m| {
let drift = (m.running - m.exact).abs();
if trued_up { drift >= unit } else { drift > unit }
if trued_up {
drift >= unit
} else {
drift > legacy_bound
}
})
.map(|m| {
Finding::new(
+2 -3
View File
@@ -34,9 +34,8 @@
//! it) is shared among the members credited in proportion to their
//! credits, to the base currency's minor unit (cents, whole yen),
//! leftover units by largest remainder
//! (kernel::apportion, a tie in the rounded remainders to the
//! earlier member; an exact tie follows the quotient's 28th digit,
//! K-U10): each takes at
//! (kernel::apportion over the exact remainders, a tie to the
//! earlier member, K-U10): each takes at
//! most its own credit, and the split depends on the order the
//! members are given only for a tied leftover cent (never on line
//! order). Joint property is joint (BS-partner-1's
+54 -23
View File
@@ -9,7 +9,10 @@
//! division, so a `Decimal` quotient is rounded at 28 significant digits
//! (and a machine integer's is truncated), never an exact rational.
//! Multiplication is not exact either at `Decimal`'s 96-bit mantissa:
//! `checked_mul` rounds the product there. Every invariant below is
//! `checked_mul_rounded` rounds the product there, and this module uses
//! it by name wherever a rounded product is the figure meant (the
//! kernel's `checked_mul` is exact or refused, K-U10, and would refuse a
//! share by a percent of 27 places). Every invariant below is
//! stated of that computation, and of the parts after the named leftover
//! policy, which do sum to the whole exactly. See `docs/proofs/k-u3.md`
//! for the edges where a product's or a quotient's rounding can change a
@@ -21,11 +24,10 @@ use super::{Amount, apportion, plug_last};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Leftover {
/// Each part is rounded down; the units left over go one each to the
/// largest remainders. The remainders are the rounded quotients'
/// differences, not exact rationals, so ranking follows the quotient:
/// an exact tie can go where the quotient's 28th digit sends it, and
/// only a tie in the rounded remainders goes to the earlier part. K-U10
/// decides the exact ranking. [`apportion`].
/// largest remainders. The remainders are exact: `whole x weight -
/// part x total`, an integer comparison, never the rounded quotient's
/// difference, so an exact tie goes to the earlier part (the Lean
/// model's rank, bookspec's `Apportion`). [`apportion`].
LargestRemainder,
/// The last part becomes the whole less the others. [`plug_last`].
LastAbsorbs,
@@ -47,10 +49,13 @@ pub enum Leftover {
/// government's part of a payment), BS-arap-3 (a document line's
/// exact amount).
/// INVARIANTS:
/// 1. Some(s) is the amount type's `checked_mul` of whole and weight,
/// then its checked division by total. For Decimal the product and
/// quotient are exact while they fit 96 bits and scale 28, and are
/// rounded at that edge (rust_decimal's checked operations, K-U10);
/// 1. Some(s) is the amount type's `checked_mul_rounded` of whole and
/// weight, then its checked division by total. For Decimal the
/// product and quotient are exact while they fit 96 bits and scale
/// 28, and are rounded at that edge (rust_decimal's checked
/// operations: a share by a percent of 27 places is a rounded figure
/// by construction, and is computed so, to the digit; K-U10 left
/// this one product rounding, because the quotient rounds anyway);
/// for a machine integer the division truncates toward zero. This is
/// the computation the six call sites made before U3, to the digit.
/// 2. None when total is zero, or when the product or quotient is not
@@ -68,7 +73,7 @@ pub enum Leftover {
/// be None.
/// ```
pub fn share_of<T: Amount>(whole: T, weight: T, total: T) -> Option<T> {
whole.checked_mul(weight)?.checked_div(total)
whole.checked_mul_rounded(weight)?.checked_div(total)
}
/// The largest whole multiple of `step` not above `whole × weight ÷ total`,
@@ -120,7 +125,7 @@ pub fn share_floor_with<T: Amount>(
if total <= T::ZERO || step <= T::ZERO {
return None;
}
let num = whole.checked_mul(weight)?;
let num = whole.checked_mul_rounded(weight)?;
let quotient = num.checked_div(total)?;
let mut part = round(quotient)?;
// The quotient may have rounded across the exact floor: take whole
@@ -130,7 +135,7 @@ pub fn share_floor_with<T: Amount>(
// K-U10, pinned in the bridge). Both directions are bounded so a
// quotient rounded far across the floor refuses instead of hanging.
let mut steps = 0;
while part.checked_mul(total)? > num {
while part.checked_mul_rounded(total)? > num {
if steps == MAX_CORRECTION_STEPS {
return None;
}
@@ -143,13 +148,13 @@ pub fn share_floor_with<T: Amount>(
return None;
}
let next = part.checked_add(step)?;
if next.checked_mul(total)? > num {
if next.checked_mul_rounded(total)? > num {
break;
}
part = next;
steps += 1;
}
let remainder = num.checked_sub(part.checked_mul(total)?)?;
let remainder = num.checked_sub(part.checked_mul_rounded(total)?)?;
Some((part, remainder))
}
@@ -195,11 +200,13 @@ const MAX_CORRECTION_STEPS: usize = 4096;
/// a part more than one step from the exact rational (K-U10, pinned
/// in the bridge). Under the first/last-absorbs policies only the
/// absorbing part may be further, by the rounding of all the others.
/// The largest-remainder ranking compares the rounded quotients'
/// remainders, not exact rationals: an exact tie can go where
/// `Decimal`'s 28th digit sends it, and only a tie in the rounded
/// remainders goes to the earlier part (K-U10 decides the exact
/// rule; the bridge pins today's answer).
/// The largest-remainder ranking compares the exact remainders
/// `whole x weight - part x total` (the quantity `share_floor_with`
/// returns, scaled by total; the sign flipped for a negative total),
/// never the rounded quotients' differences. An exact tie goes to the
/// earlier part, whatever `Decimal`'s 28th digit would have said
/// (K-U10, the owner's decision; exact while the products are, as
/// above).
/// 3. With total not zero, no part exceeds the whole when every weight
/// is in [0, total] and the whole is not negative; no part is
/// negative when the weights and the whole are not.
@@ -213,13 +220,19 @@ const MAX_CORRECTION_STEPS: usize = 4096;
/// promised.
/// SCENARIOS:
/// 1. IF 100 by 1/1/1 to the cent by largest remainder: SHOULD be
/// 33.34, 33.33, 33.33 (the rounded remainders tie, so the cent goes
/// 33.34, 33.33, 33.33 (the exact remainders tie, so the cent goes
/// to the earlier part).
/// 2. IF 0.01 by 1/1 to the cent by largest remainder: SHOULD be
/// 0.01, 0.00.
/// 3. IF 10 by weights 2/3/5 by first-absorbs: SHOULD be the rounded
/// shares with the first taking the whole less the others.
/// 4. IF the total is zero, or every weight is zero: SHOULD be zeros (a
/// 4. IF 20.00 by 4/1/1 over 6 to the cent by largest remainder: SHOULD
/// be 13.34, 3.33, 3.33. The exact remainders (0.02, 0.02, 0.02 over
/// 6, as 80 - 79.98, 20 - 19.98) tie, so the cent goes to the first.
/// The rounded quotients (13.33...3 keeps one fewer fractional digit
/// than 3.33...3 at 28 significant digits) would have put the
/// second's remainder above the first's.
/// 5. IF the total is zero, or every weight is zero: SHOULD be zeros (a
/// zero total) or the largest-remainder handout of the whole (a
/// positive total with zero weights, as the conventions' template
/// split has always done).
@@ -257,8 +270,26 @@ pub fn split_by_weights_into<T: Amount>(
if unit <= T::ZERO {
return None;
}
// Rank by the exact remainder, never the rounded quotient's
// difference: `whole x weight - part x total`, the exact
// rational's fraction scaled by `total`, the same quantity
// `share_floor_with` returns. A negative total flips the
// scale's sign, so the order is the share's own. The two
// products are the rounding ones: each is exact while it fits
// Decimal's mantissa (every split of posted amounts by whole
// weights or basis points), and where a weight of 27 places
// makes a product round, the split is still made, ranked by
// the nearest figures Decimal holds, not refused. Their
// difference is exact: the subtraction refuses otherwise.
for i in 0..weights.len() {
remainders[i] = remainders[i].checked_sub(parts[i])?;
let exact = whole
.checked_mul_rounded(weights[i])?
.checked_sub(parts[i].checked_mul_rounded(total)?)?;
remainders[i] = if total < T::ZERO {
T::ZERO.checked_sub(exact)?
} else {
exact
};
}
apportion(whole, parts, remainders, unit)
}
@@ -0,0 +1,309 @@
//! The exactness check behind `impl Amount for Decimal` (K-U10): a sum or
//! a product `rust_decimal` returns is the exact one, or the kernel
//! refuses it.
//!
//! `rust_decimal`'s `checked_add` and `checked_mul` return `None` only
//! when the integer part overflows. When the exact result merely needs
//! more than 96 bits of mantissa, or a scale past 28, they *round* it and
//! return `Some` (found by K-U1, K-U4, K-U8: `MAX + 0.4` is `Some(MAX)`;
//! `0.01 + 792281625142643375935439503.35` is `…503.4`;
//! `1050000010.0000000001 x 9.9999999999` is `10500000099.895`). The
//! kernel's contract is "exact or `None`" (BS-ledger-1: a product the
//! arithmetic cannot hold MUST be refused), so each operation here runs
//! `rust_decimal`'s and then checks, in integers wide enough that nothing
//! can overflow, that the figure it returned equals the exact result as a
//! rational. It never builds a rounded figure of its own, and a result
//! that is exact is returned as `rust_decimal` gave it, scale and all, so
//! nothing exact changes.
//!
//! A `Decimal` is `m x 10^-s` with `|m| < 2^96` and `s <= 28`. Every
//! quantity compared below is at most `2^96 x 10^28 < 2^190`, or a
//! product `2^96 x 2^96 = 2^192`, so 256 bits hold all of them.
use rust_decimal::Decimal;
/// An unsigned 256-bit integer: `hi x 2^128 + lo`. The field order makes
/// the derived `Ord` the numeric order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Wide {
hi: u128,
lo: u128,
}
impl Wide {
const ZERO: Wide = Wide { hi: 0, lo: 0 };
fn from_u128(lo: u128) -> Wide {
Wide { hi: 0, lo }
}
/// `a x b`, in full.
fn mul_wide(a: u128, b: u128) -> Wide {
const HALF: u128 = (1 << 64) - 1;
let (a1, a0) = (a >> 64, a & HALF);
let (b1, b0) = (b >> 64, b & HALF);
let p00 = a0 * b0;
let p01 = a0 * b1;
let p10 = a1 * b0;
let p11 = a1 * b1;
// The middle column: three 64-bit terms, under 3 x 2^64.
let mid = (p00 >> 64) + (p01 & HALF) + (p10 & HALF);
Wide {
lo: (mid << 64) | (p00 & HALF),
hi: p11 + (p01 >> 64) + (p10 >> 64) + (mid >> 64),
}
}
fn checked_add(self, other: Wide) -> Option<Wide> {
let (lo, carry) = self.lo.overflowing_add(other.lo);
let hi = self
.hi
.checked_add(other.hi)?
.checked_add(u128::from(carry))?;
Some(Wide { hi, lo })
}
/// `self x k`, `None` past 256 bits.
fn checked_mul_small(self, k: u128) -> Option<Wide> {
let low = Wide::mul_wide(self.lo, k);
let hi = self.hi.checked_mul(k)?.checked_add(low.hi)?;
Some(Wide { hi, lo: low.lo })
}
/// `(self / 10, self % 10)`.
fn div_rem_10(self) -> (Wide, u128) {
const HALF: u128 = (1 << 64) - 1;
let hi = self.hi / 10;
let carry = self.hi % 10;
let upper = (carry << 64) | (self.lo >> 64);
let lower = ((upper % 10) << 64) | (self.lo & HALF);
(
Wide {
hi,
lo: ((upper / 10) << 64) | (lower / 10),
},
lower % 10,
)
}
/// The value as a `u128`, when it fits.
fn to_u128(self) -> Option<u128> {
(self.hi == 0).then_some(self.lo)
}
/// `self x 10^k`, `None` past 256 bits.
fn checked_scale_up(self, mut k: u32) -> Option<Wide> {
let mut value = self;
while k > 0 {
let step = k.min(38);
value = value.checked_mul_small(10u128.pow(step))?;
k -= step;
}
Some(value)
}
}
/// `mantissa x 10^k`, as a 256-bit magnitude.
fn scaled(magnitude: u128, k: u32) -> Option<Wide> {
Wide::from_u128(magnitude).checked_scale_up(k)
}
/// `a + b`: `rust_decimal`'s sum when it is the exact sum, else `None`.
pub(super) fn exact_add(a: Decimal, b: Decimal) -> Option<Decimal> {
let sum = Decimal::checked_add(a, b)?;
sum_is_exact(a, b, sum).then_some(sum)
}
/// `a - b`: `rust_decimal`'s difference when it is the exact difference,
/// else `None`.
pub(super) fn exact_sub(a: Decimal, b: Decimal) -> Option<Decimal> {
let difference = Decimal::checked_sub(a, b)?;
sum_is_exact(a, -b, difference).then_some(difference)
}
/// `a x b`: `rust_decimal`'s product when it is the exact product, else
/// `None`.
pub(super) fn exact_mul(a: Decimal, b: Decimal) -> Option<Decimal> {
let product = Decimal::checked_mul(a, b)?;
product_is_exact(a, b, product).then_some(product)
}
/// Is `a + b == sum` as rationals? At the common scale `s` this is
/// `ma 10^(s-sa) + mb 10^(s-sb) - ms 10^(s-ss) == 0`; the terms are moved
/// by sign so each side is a sum of magnitudes (no signed arithmetic, no
/// overflow: every term is under 2^190). Any failure to compute is "not
/// exact", the safe answer.
fn sum_is_exact(a: Decimal, b: Decimal, sum: Decimal) -> bool {
let (ma, mb, ms) = (a.mantissa(), b.mantissa(), sum.mantissa());
let (sa, sb, ss) = (a.scale(), b.scale(), sum.scale());
if sa == sb && sb == ss {
// The common case (cents plus cents): no rescaling. Mantissas are
// under 2^96, so the i128 sum cannot overflow.
return ma + mb == ms;
}
let s = sa.max(sb).max(ss);
// The terms of a + b + (-sum), by sign.
let mut positive = Wide::ZERO;
let mut negative = Wide::ZERO;
for (mantissa, scale, flip) in [(ma, sa, false), (mb, sb, false), (ms, ss, true)] {
let Some(term) = scaled(mantissa.unsigned_abs(), s - scale) else {
return false;
};
let counts_negative = (mantissa < 0) != flip;
let side = if counts_negative {
&mut negative
} else {
&mut positive
};
let Some(next) = side.checked_add(term) else {
return false;
};
*side = next;
}
positive == negative
}
/// Is `a x b == product` as rationals? The exact product is
/// `ma x mb` at scale `sa + sb` (up to 2^192, at scale up to 56), compared
/// with `mp` at scale `sp` by scaling the side with fewer places up; an
/// overflow past 256 bits means that side is larger than the other, so
/// unequal.
fn product_is_exact(a: Decimal, b: Decimal, product: Decimal) -> bool {
let (ma, mb, mp) = (a.mantissa(), b.mantissa(), product.mantissa());
let exact = Wide::mul_wide(ma.unsigned_abs(), mb.unsigned_abs());
if exact == Wide::ZERO {
return mp == 0;
}
if mp == 0 || ((ma < 0) != (mb < 0)) != (mp < 0) {
return false;
}
let exact_scale = a.scale() + b.scale();
let held = Wide::from_u128(mp.unsigned_abs());
if exact_scale >= product.scale() {
held.checked_scale_up(exact_scale - product.scale()) == Some(exact)
} else {
exact.checked_scale_up(product.scale() - exact_scale) == Some(held)
}
}
/// The exact product `a x b` as a `Decimal` that rounds to a multiple of
/// any step of `step_scale` places (or fewer) the way the exact product
/// would, for a product `Decimal` cannot hold: the case
/// [`exact_mul`] refused.
///
/// The product is held in 256 bits and cut down a digit at a time until it
/// fits `Decimal`, remembering whether any cut digit was not zero (a
/// sticky digit, appended as a final `1`). At least one real digit is
/// kept below the step's own places, so the first digit past the step is
/// real and every later one is only "zero or not": that decides a tie
/// (a half followed by zeros) and the directed modes exactly as the full
/// product would, so the one rounding that follows is the correctly
/// rounded one. `None` when the product is too large to hold with those
/// digits: the figure times 10^(step places + 2) must fit 96 bits, so a
/// figure past about 7.9e26 at a whole-unit step, 7.9e24 at a cent (10^9
/// times a journal line's cap). For the same reason a step of 27 or 28
/// places is always `None` here: `Decimal` ends at 28 places, so there is
/// no place below such a step for the real digit and the sticky one. That
/// refuses some figures whose rounded result `Decimal` could hold (1e-28
/// squared to a step of 1e-27 is zero); a refusal, never a guess, and no
/// currency's step is within twenty places of it (pinned in the bridge:
/// `a_step_of_27_places_refuses_a_product_that_is_not_exact`). A zero
/// product is exact and never gets here.
pub(super) fn mul_for_rounding(a: Decimal, b: Decimal, step_scale: u32) -> Option<Decimal> {
let negative = (a.mantissa() < 0) != (b.mantissa() < 0);
let mut digits = Wide::mul_wide(a.mantissa().unsigned_abs(), b.mantissa().unsigned_abs());
let mut scale = a.scale() + b.scale();
let mut sticky = false;
loop {
// The candidate: the digits kept, then the sticky digit if any.
let (mantissa, candidate_scale) = if sticky {
(
digits
.checked_mul_small(10)
.and_then(|d| d.checked_add(Wide::from_u128(1)))
.and_then(Wide::to_u128),
scale + 1,
)
} else {
(digits.to_u128(), scale)
};
if let Some(m) = mantissa
&& candidate_scale <= Decimal::MAX_SCALE
&& let Ok(m) = i128::try_from(m)
&& let Ok(d) =
Decimal::try_from_i128_with_scale(if negative { -m } else { m }, candidate_scale)
{
return Some(d);
}
if scale <= step_scale + 1 {
return None;
}
let (rest, digit) = digits.div_rem_10();
digits = rest;
sticky |= digit != 0;
scale -= 1;
}
}
#[cfg(test)]
mod tests {
//! The 256-bit helpers against `num_bigint`, which shares no code with
//! them: they are private, so the bridge reaches them only through the
//! operations; these check them directly, edges included.
use super::*;
use num_bigint::BigUint;
use proptest::prelude::*;
fn big(w: Wide) -> BigUint {
(BigUint::from(w.hi) << 128u32) + BigUint::from(w.lo)
}
fn edge_u128() -> impl Strategy<Value = u128> {
prop_oneof![
any::<u128>(),
Just(0u128),
Just(1),
Just(u128::MAX),
Just(u128::from(u64::MAX)),
Just(u128::from(u64::MAX) + 1),
Just((1u128 << 96) - 1),
]
}
fn arb_wide() -> impl Strategy<Value = Wide> {
(edge_u128(), edge_u128()).prop_map(|(hi, lo)| Wide { hi, lo })
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(5000))]
#[test]
fn mul_wide_is_the_full_product(a in edge_u128(), b in edge_u128()) {
prop_assert_eq!(big(Wide::mul_wide(a, b)), BigUint::from(a) * BigUint::from(b));
}
#[test]
fn add_and_mul_small_are_exact_or_refuse(w in arb_wide(), o in arb_wide(), k in edge_u128()) {
let limit = BigUint::from(1u8) << 256u32;
let sum = big(w) + big(o);
prop_assert_eq!(w.checked_add(o).map(big), (sum < limit).then_some(sum));
let product = big(w) * BigUint::from(k);
prop_assert_eq!(w.checked_mul_small(k).map(big), (product < limit).then_some(product));
}
#[test]
fn div_rem_10_divides(w in arb_wide()) {
let (q, r) = w.div_rem_10();
prop_assert_eq!(big(q) * 10u8 + BigUint::from(r), big(w));
prop_assert!(r < 10);
}
#[test]
fn scale_up_is_a_power_of_ten(m in edge_u128(), k in 0u32..=60) {
let want = BigUint::from(m) * BigUint::from(10u8).pow(k);
let limit = BigUint::from(1u8) << 256u32;
prop_assert_eq!(scaled(m, k).map(big), (want < limit).then_some(want));
}
}
}
+69 -5
View File
@@ -12,7 +12,8 @@ use rust_decimal::Decimal;
pub trait Amount: Copy + Ord {
/// Zero.
const ZERO: Self;
/// `self + rhs`, or `None` when it cannot be represented exactly.
/// `self + rhs`, or `None` when it cannot be represented exactly (for
/// [`Decimal`], never a sum `rust_decimal` had to round: K-U10).
fn checked_add(self, rhs: Self) -> Option<Self>;
/// `-self`, or `None` when it cannot be represented.
fn checked_neg(self) -> Option<Self>;
@@ -27,9 +28,45 @@ pub trait Amount: Copy + Ord {
fn from_u32(n: u32) -> Option<Self>;
/// `self * rhs`, or `None` when it cannot be represented exactly.
///
/// A quantity times a unit price (a document line, BS-arap-3) is the one
/// use: it never rounds.
/// A quantity times a unit price (a document line, BS-arap-3), a
/// category's book amount times its percent, and the other products
/// that are the amount itself: it never rounds. For [`Decimal`] that
/// is a check, not a given (K-U10): `rust_decimal` rounds a product
/// whose mantissa passes 96 bits or whose scale passes 28, and this
/// refuses it instead.
fn checked_mul(self, rhs: Self) -> Option<Self>;
/// `self * rhs` as the amount type multiplies, which for [`Decimal`] is
/// `rust_decimal`'s: exact where the product fits 96 bits and scale
/// 28, otherwise rounded to what it holds. `None` only on overflow.
///
/// This is the engine's rounding product, as [`Amount::checked_div`]
/// is its rounding division, and for the same use: a proportional
/// share (`whole x weight / total`, [`crate::kernel::share_of`]) whose
/// weight is a percent or a ratio of many places (33.333...3, twenty
/// seven places) is a rounded figure by construction, and has always
/// been computed this way, to the digit. Nothing else calls it; a
/// product that is the amount is [`Amount::checked_mul`]. A machine
/// integer never rounds, so there it is `checked_mul`.
fn checked_mul_rounded(self, rhs: Self) -> Option<Self> {
self.checked_mul(rhs)
}
/// `self * rhs`, computed exactly and rounded once to a whole multiple
/// of `step` in `mode`; `None` when `step` is not positive or the
/// result cannot be represented.
///
/// The one use is a foreign amount at a rate ([`crate::kernel::fx_booked`]).
/// For [`Decimal`] the exact product may need more than 96 bits (ten
/// places each, D-75, is twenty places, and past 7.9e8 the mantissa
/// passes `Decimal`'s): it is held wider than `Decimal` for the one
/// rounding, never rounded early and then again. Two refusals come
/// with that, both far from any books: a product that is not exact
/// and is past about 7.9e26 divided by 10^(the step's places), and a
/// product that is not exact at a step of 27 or 28 places (the
/// rounding needs two places below the step, and `Decimal` ends at
/// 28). An exact product is rounded at any step.
fn checked_mul_round_to_step(self, rhs: Self, step: Self, mode: Rounding) -> Option<Self> {
super::round::round_step(self.checked_mul(rhs)?, step, mode)
}
/// `self / rhs` exactly, or `None` when `rhs` is zero or the quotient
/// is not a whole amount of `Self` (never a rounded share).
fn checked_div_exact(self, rhs: Self) -> Option<Self>;
@@ -79,8 +116,16 @@ pub const MAX_LINE_SCALE: u32 = 10;
impl Amount for Decimal {
const ZERO: Self = Decimal::ZERO;
// Exact or `None` (K-U10): `rust_decimal`'s own add and multiply round a
// result that needs more than 96 bits (or a scale past 28) instead of
// refusing it; `decimal_exact` checks the figure is the exact one.
fn checked_add(self, rhs: Self) -> Option<Self> {
Decimal::checked_add(self, rhs)
super::decimal_exact::exact_add(self, rhs)
}
// `rust_decimal`'s own subtraction, checked the same way (it is not
// `self + (-rhs)` for a zero: that gives a negative zero).
fn checked_sub(self, rhs: Self) -> Option<Self> {
super::decimal_exact::exact_sub(self, rhs)
}
fn checked_neg(self) -> Option<Self> {
Some(-self)
@@ -92,11 +137,30 @@ impl Amount for Decimal {
Some(Decimal::from(n))
}
fn checked_mul(self, rhs: Self) -> Option<Self> {
super::decimal_exact::exact_mul(self, rhs)
}
fn checked_mul_rounded(self, rhs: Self) -> Option<Self> {
Decimal::checked_mul(self, rhs)
}
fn checked_mul_round_to_step(self, rhs: Self, step: Self, mode: Rounding) -> Option<Self> {
if let Some(product) = super::decimal_exact::exact_mul(self, rhs) {
return super::round::round_step(product, step, mode);
}
// The exact product does not fit `Decimal`: round it once, from a
// wider integer, not twice.
if step <= Decimal::ZERO {
return None;
}
let proxy = super::decimal_exact::mul_for_rounding(self, rhs, step.normalize().scale())?;
super::round::round_step(proxy, step, mode)
}
fn checked_div_exact(self, rhs: Self) -> Option<Self> {
let q = self.checked_div(rhs)?;
(q.checked_mul(rhs) == Some(self)).then_some(q)
// The exact product, not `rust_decimal`'s: a rounded quotient
// times the divisor rounds back to the dividend there (10 / 3 is
// 3.333...3, and 3.333...3 x 3 is held as 10), which would pass a
// rounded share as an exact one.
(super::decimal_exact::exact_mul(q, rhs) == Some(self)).then_some(q)
}
fn checked_div(self, rhs: Self) -> Option<Self> {
Decimal::checked_div(self, rhs)
+44 -53
View File
@@ -1,11 +1,11 @@
//! 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
//! product is computed exactly and rounded once, by [`round_step`](super::round_step), to
//! the base currency's smallest unit. No call site multiplies by a rate
//! itself.
use super::round::{Rounding, round_step};
use super::round::Rounding;
use crate::Currency;
use crate::kernel::Amount;
use rust_decimal::Decimal;
@@ -16,34 +16,27 @@ 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
/// `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.
/// exact one 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.
/// **The exact product on `Decimal` (D-75, K-U10).** A foreign amount and
/// a rate of at most [`MAX_LINE_SCALE`](super::MAX_LINE_SCALE) (10) places
/// each, trailing zeros not counted, have an exact product of at most 20
/// places, and `Ledger::add_line_fx` enforces that bound on every new
/// line (never on replay). The product's mantissa can still pass
/// `Decimal`'s 96 bits (a product of twenty places past about 7.9e8), and
/// `Decimal::checked_mul` then drops places. `Amount::checked_mul_round_to_step`
/// does not use it for that case: it holds the exact product in 256 bits,
/// cuts it down only as far as `Decimal` needs (remembering whether any
/// cut digit was not zero), and rounds once, so 1050000010.0000000001 x
/// 9.9999999999 (10500000099.89499999999999999999 exactly) books
/// 10500000099.89, where it booked 10500000099.90 through a rounded
/// 10500000099.895. The same holds past ten places: a product below 1e-28
/// (1e-28 x 1e-28) rounds to zero because its exact value does, and
/// 0.99999999999999999999999999 x 0.005 books 0.00 (the engine refuses
/// such an input all the same, D-75). `None` only for a figure too large
/// to hold with its rounding digits (about 7.9e24 at a cent).
///
/// ```text
/// GOAL: book a foreign amount in the ledger's one money: the exact
@@ -60,43 +53,41 @@ 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 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
/// integer n. None when step <= 0, when rate <= 0, or when 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. 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.
/// going to the multiple farther from zero: the product is rounded
/// once, from the exact one, however many bits it needs (K-U10).
/// 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;
/// (checked_mul, then round_minor half away from zero) exactly
/// wherever that product was exact; where Decimal had rounded the
/// product first, the figure is now the once-rounded one;
/// 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.
/// 4. IF foreign x rate is too large to hold: 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.
/// the rate 0.005 to the cent: SHOULD book 0.00, the exact product
/// being under half a cent (it booked 0.01 when Decimal rounded the
/// product first); the engine refuses such an input (D-75).
/// 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.
/// (ten places each, a product past 96 bits): SHOULD book
/// 10500000099.89, the exact product's cent (it booked
/// 10500000099.90 when Decimal rounded the product first).
/// ```
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)
foreign.checked_mul_round_to_step(rate, step, mode)
}
/// [`fx_booked`] at a currency's minor unit, on `Decimal`: the spelling
@@ -126,7 +117,7 @@ pub fn fx_booked_minor(
if rate <= Decimal::ZERO {
return None;
}
return foreign.checked_mul(rate);
return Amount::checked_mul(foreign, rate);
};
let step = Decimal::try_from_i128_with_scale(1, places).ok()?;
let rounded = fx_booked(foreign, rate, step, mode)?;
+1
View File
@@ -69,6 +69,7 @@
mod allocate;
mod control;
mod decimal_exact;
mod entries;
mod fx;
mod payroll;
+2 -2
View File
@@ -31,8 +31,8 @@ use super::{Amount, Rounding, round_step, share_of};
/// 1. Some(r) is round_step(part / whole × 100, step, mode), computed
/// division first and then the multiplication, the order every call
/// site used before U6. For Decimal the quotient is exact while it
/// fits 28 significant digits and the product while it fits the
/// 96-bit mantissa; either operation rounds at that edge (K-U10).
/// fits 28 significant digits and rounds past them; the product by
/// 100 is exact or refused, never rounded (K-U10).
/// For a machine integer the division truncates toward zero.
/// 2. None when whole <= 0, step <= 0, or a quotient, product or
/// rounded result is not representable. Never a panic.
+2 -1
View File
@@ -1908,7 +1908,8 @@ impl Ledger {
// 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.)
// bits; since K-U10 the kernel holds that product in 256 bits for
// the one rounding, so it too is booked from the exact product.)
// 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() {
+13 -6
View File
@@ -69,6 +69,17 @@ impl Currency {
self.minor_units().unwrap_or(crate::kernel::MAX_LINE_SCALE)
}
/// One allocation unit as an amount: `1` at [`Self::allocation_places`]
/// (a cent, a whole yen, a thousandth of a dinar, the finest a line
/// carries for a code with no minor unit). This is the one place that
/// turns the places into an amount, so a split and a check of that
/// split take their unit from the same rule and cannot drift apart
/// (BS-partner-1 statement 4: the allocation is the split of the
/// amount to the base currency's smallest unit).
pub fn allocation_unit(&self) -> Decimal {
Decimal::new(1, self.allocation_places())
}
/// The three-letter code, e.g. `"USD"`.
pub fn code(&self) -> &str {
std::str::from_utf8(&self.0).expect("currency codes are ASCII by construction")
@@ -134,9 +145,7 @@ impl Money {
/// panic, never rounded).
pub fn checked_add(self, rhs: Money) -> Result<Money, LedgerError> {
self.check_currency(&rhs)?;
let amount = self
.amount
.checked_add(rhs.amount)
let amount = crate::kernel::Amount::checked_add(self.amount, rhs.amount)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{} plus {}", self, rhs)))?;
Ok(Money::new(amount, self.currency))
}
@@ -145,9 +154,7 @@ impl Money {
/// `TooLargeToCompute` when the difference is past exact arithmetic.
pub fn checked_sub(self, rhs: Money) -> Result<Money, LedgerError> {
self.check_currency(&rhs)?;
let amount = self
.amount
.checked_sub(rhs.amount)
let amount = crate::kernel::Amount::checked_sub(self.amount, rhs.amount)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{} minus {}", self, rhs)))?;
Ok(Money::new(amount, self.currency))
}
+25 -22
View File
@@ -22,10 +22,11 @@
//! INVARIANTS:
//! 1. The parts sum to the whole, for every policy.
//! 2. Under largest remainder each part is within one unit (the step)
//! of its exact share: `-total < part x total - whole x weight <=
//! total` at step one. The upper bound is inclusive on `i64` (its
//! division truncates); the bridge checks the strict `Decimal`
//! bound.
//! of its exact share: `-total < part x total - whole x weight <
//! total` at step one, and a part whose share is exact takes no
//! unit. Both rest on the ranking by the exact remainder (K-U10,
//! D-76): `i64`'s division truncates, and the ranking no longer
//! reads the quotient.
//! 3. No part is negative or above the whole for non-negative weights
//! that do not exceed the total.
//! 4. A zero total gives zeros; all-zero weights hand the whole out by
@@ -33,7 +34,7 @@
//! units as there are parts.
//! 5. Overflow is `None`, never a panic.
//! SCENARIOS:
//! 1. IF 101 by 1/1/1 to the unit: SHOULD be 34/34/33 (the rounded
//! 1. IF 101 by 1/1/1 to the unit: SHOULD be 34/34/33 (the exact
//! remainders tie, so the units go to the earlier parts), never
//! 33/34/34.
//! 2. IF a quotient rounds up across the step: `share_floor_with`
@@ -44,8 +45,8 @@
//! Bounds: amounts up to 1,000, weights up to 100, totals fixed (10 and
//! 0), steps 1 and 10. The laws are about the shape of the split, not the
//! magnitude; Lean proves them of the exact-share model at any size, and
//! the bridge checks the `Decimal` engine, whose ranking uses the rounded
//! quotient.
//! the bridge checks the `Decimal` engine, which ranks the same exact
//! remainders.
use crate::kernel::{self, Leftover, Rounding, share_floor_with, share_of, split_by_weights_into};
@@ -93,23 +94,28 @@ fn split_by_weights_sums() {
}
/// Each part is within one step of its share: scaled by the total,
/// `part x total - whole x weight` is above `-total` and at most `total`.
/// `part x total - whole x weight` is above `-total` and below `total`,
/// and a part whose share is exact takes no unit.
///
/// The upper bound is inclusive on the `i64` model: its division
/// truncates, so a part that divides exactly can still take a unit when
/// another part's truncation left one over (`whole = 5`, weights 2/3/5:
/// the first's 1 becomes 2, exactly one step above its truncated share).
/// The `Decimal` quotient keeps the fraction, a part with no remainder
/// never takes a unit, and the bridge checks the strict bound there
/// (`decimal_split_satisfies_the_kani_laws`); Lean's `shares_of_near`
/// proves it for the exact-share model at any size.
/// The upper bound was inclusive on the `i64` model while the ranking
/// read the quotient: `i64`'s division truncates, every remainder read
/// as zero, and a part that divided exactly could take the unit another
/// part's truncation left over (`whole = 5`, weights 2/3/5: the first's 1
/// became 2). The ranking is the exact remainder `whole x weight - part x
/// total` since K-U10 (D-76), which no division touches, so the unit goes
/// to a part that is short (1, 2, 2) and the bound is strict here as on
/// `Decimal` (`decimal_split_satisfies_the_kani_laws`); Lean's
/// `shares_of_near` proves it for the exact-share model at any size.
#[kani::proof]
fn split_by_weights_within_one_step() {
let whole = any_whole();
let (parts, _) = split(whole, 1, Leftover::LargestRemainder).expect("in range");
for i in 0..N {
let drift = parts[i] * TOTAL - whole * WEIGHTS[i];
assert!(-TOTAL < drift && drift <= TOTAL);
assert!(-TOTAL < drift && drift < TOTAL);
if (whole * WEIGHTS[i]) % TOTAL == 0 {
assert_eq!(drift, 0);
}
}
kani::cover!(
parts
@@ -119,11 +125,8 @@ fn split_by_weights_within_one_step() {
"a part off its exact share by the rounding"
);
kani::cover!(
parts
.iter()
.enumerate()
.any(|(i, &p)| p * TOTAL - whole * WEIGHTS[i] == TOTAL),
"a part exactly one step above its truncated share"
(whole * WEIGHTS[0]) % TOTAL == 0 && whole % TOTAL != 0,
"a unit is handed out while the first part's share is exact"
);
}