merge: main into k-u11a (K-U10's exact operations)
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
commit
3918151794
94 files changed
+19771
-635
No files matched your search
@@ -4,6 +4,7 @@ version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
description = "Canonical double-entry bookkeeping semantics: the engine everything else is built on."
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -69,6 +69,7 @@
|
||||
|
||||
mod allocate;
|
||||
mod control;
|
||||
mod decimal_exact;
|
||||
mod entries;
|
||||
mod fx;
|
||||
mod payroll;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -311,6 +311,155 @@ fn a_close_split_drifts_by_the_regime_it_was_made_under() {
|
||||
);
|
||||
}
|
||||
|
||||
/// BS-partner-1 statement 4 (the allocation is the split to the base
|
||||
/// currency's smallest unit) and WB-ledger-16 invariant 8: a JPY close is
|
||||
/// checked at the allocation's unit -- a whole yen, JPY having no minor
|
||||
/// unit below it -- not at a cent. A drift of half a yen is under that
|
||||
/// unit; a drift of a whole yen after the true-up is not.
|
||||
#[test]
|
||||
fn a_jpy_close_is_checked_at_the_allocations_unit() {
|
||||
// The one helper both the split and its audit use.
|
||||
assert_eq!(Currency::JPY.allocation_unit(), dec("1"));
|
||||
assert_eq!(Currency::USD.allocation_unit(), dec("0.01"));
|
||||
// A code ISO 4217 gives no minor unit splits at the finest a line
|
||||
// carries, so its audit unit is that, not a cent.
|
||||
assert_eq!(
|
||||
Currency::new("XAU").unwrap().allocation_unit(),
|
||||
dec("0.0000000001")
|
||||
);
|
||||
let yen = Currency::JPY.allocation_unit();
|
||||
let m = |running: &str, exact: &str| MemberSplit {
|
||||
capital: 3001,
|
||||
share: dec("0.5"),
|
||||
part: dec(running),
|
||||
running: dec(running),
|
||||
exact: dec(exact),
|
||||
};
|
||||
// Half a yen of drift is under one yen (it would be fifty cents'
|
||||
// worth of drift at a cent unit, and flagged there).
|
||||
assert!(audit::check_split(1, "Jan", &[m("100.5", "100")], yen, true).is_empty());
|
||||
// A whole yen after the true-up is a finding (statement 5's >= unit).
|
||||
let f = audit::check_split(1, "Jan", &[m("101", "100")], yen, true);
|
||||
assert_eq!(codes(&f), ["close_split_drifts"]);
|
||||
|
||||
// End to end: a yen members close splits in whole yen and the audit
|
||||
// of the closed period raises no close finding.
|
||||
let mut l = Ledger::new(Currency::JPY);
|
||||
let cash = l
|
||||
.add_account("1000", "Bank", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let revenue = l
|
||||
.add_account("4000", "Sales", AccountType::Revenue, None, false)
|
||||
.unwrap();
|
||||
let caps: Vec<u64> = ["3001", "3002"]
|
||||
.iter()
|
||||
.map(|c| {
|
||||
l.add_account(c, c, AccountType::Equity, None, false)
|
||||
.unwrap()
|
||||
})
|
||||
.collect();
|
||||
let e = l.create_entry(d(1, 5), "sale");
|
||||
l.add_line(e, cash, Side::Debit, Money::new(dec("101"), Currency::JPY))
|
||||
.unwrap();
|
||||
l.add_line(
|
||||
e,
|
||||
revenue,
|
||||
Side::Credit,
|
||||
Money::new(dec("101"), Currency::JPY),
|
||||
)
|
||||
.unwrap();
|
||||
l.post_entry(e).unwrap();
|
||||
let jan = l.create_period("2026-01", d(1, 1), d(1, 31)).unwrap();
|
||||
let members = caps
|
||||
.iter()
|
||||
.map(|&capital| MemberClose {
|
||||
capital,
|
||||
share: dec("0.5"),
|
||||
distributions: None,
|
||||
})
|
||||
.collect();
|
||||
l.close_period_to(jan, &CloseTo::Members(members)).unwrap();
|
||||
// 101 yen at 50/50 splits 51 / 50 whole yen (exact 50.5 each).
|
||||
let balances: Vec<Decimal> = caps
|
||||
.iter()
|
||||
.map(|&a| l.account_balance(a).unwrap())
|
||||
.collect();
|
||||
assert_eq!(balances, [dec("51"), dec("50")]);
|
||||
let f = run(&l, &Settings::default(), &all_receipts(&l), d(12, 31));
|
||||
assert!(
|
||||
!codes(&f).contains(&"close_split_drifts"),
|
||||
"{:?}",
|
||||
codes(&f)
|
||||
);
|
||||
}
|
||||
|
||||
/// BS-partner-1 statement 6 and WB-ledger-16 invariant 8: before the
|
||||
/// true-up, a legacy last-absorbs close's largest legitimate drift is
|
||||
/// derived (the rule states the per-member facts, not the bound): with
|
||||
/// n members and unit u, each member but the last was rounded to within
|
||||
/// u/2, and the last absorbed the sum of those roundings, up to
|
||||
/// (n-1)*u/2 -- so 3u/2 with four members and 2u with five (floored at
|
||||
/// u, which statement 6's per-close and run allowances give). At that
|
||||
/// drift a close is not flagged; one unit past it, it is. After the
|
||||
/// true-up, BS-partner-1 statement 5's strict bound holds instead: a
|
||||
/// drift of a unit or more is flagged.
|
||||
#[test]
|
||||
fn a_legacy_last_absorbs_close_drifts_by_member_count_before_its_true_up() {
|
||||
let unit = dec("0.01");
|
||||
// A split of `n` members whose last-listed member carries `drift`
|
||||
// (running against an exact 1.00) and whose others are exact.
|
||||
let split = |n: usize, drift: &str| -> Vec<MemberSplit> {
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let running = if i + 1 == n {
|
||||
dec("1.00") + dec(drift)
|
||||
} else {
|
||||
dec("1.00")
|
||||
};
|
||||
MemberSplit {
|
||||
capital: 3001 + i as u64,
|
||||
share: dec("0.25"),
|
||||
part: running,
|
||||
running,
|
||||
exact: dec("1.00"),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
// Four members: largest legitimate drift 3 * 0.005 = 0.015, either way.
|
||||
assert!(audit::check_split(1, "Jan", &split(4, "0.015"), unit, false).is_empty());
|
||||
assert!(audit::check_split(1, "Jan", &split(4, "-0.015"), unit, false).is_empty());
|
||||
// Anything past it is flagged, exactly one member: a tenth of a
|
||||
// unit past (a bound of two units would let this through), and a
|
||||
// whole unit past.
|
||||
for drift in ["0.016", "-0.016", "0.025"] {
|
||||
let f = audit::check_split(1, "Jan", &split(4, drift), unit, false);
|
||||
assert_eq!(codes(&f), ["close_split_drifts"], "{drift}");
|
||||
}
|
||||
// Three members and two: the bound is the unit itself, as it was.
|
||||
assert!(audit::check_split(1, "Jan", &split(3, "0.01"), unit, false).is_empty());
|
||||
assert!(audit::check_split(1, "Jan", &split(2, "0.01"), unit, false).is_empty());
|
||||
for n in [2, 3] {
|
||||
let f = audit::check_split(1, "Jan", &split(n, "0.011"), unit, false);
|
||||
assert_eq!(codes(&f), ["close_split_drifts"], "{n} members");
|
||||
}
|
||||
// Five members: largest legitimate drift 4 * 0.005 = 0.02.
|
||||
assert!(audit::check_split(1, "Jan", &split(5, "0.02"), unit, false).is_empty());
|
||||
assert!(audit::check_split(1, "Jan", &split(5, "-0.02"), unit, false).is_empty());
|
||||
for drift in ["0.021", "0.03"] {
|
||||
let f = audit::check_split(1, "Jan", &split(5, drift), unit, false);
|
||||
assert_eq!(codes(&f), ["close_split_drifts"], "{drift}");
|
||||
}
|
||||
// After the true-up the same splits answer to statement 5: the
|
||||
// four-member split at its legacy bound is past one unit, so it is
|
||||
// flagged, and one just under a unit is not.
|
||||
let f = audit::check_split(1, "Jan", &split(4, "0.015"), unit, true);
|
||||
assert_eq!(codes(&f), ["close_split_drifts"]);
|
||||
assert!(audit::check_split(1, "Jan", &split(4, "0.009"), unit, true).is_empty());
|
||||
let f = audit::check_split(1, "Jan", &split(4, "0.01"), unit, true);
|
||||
assert_eq!(codes(&f), ["close_split_drifts"]);
|
||||
}
|
||||
|
||||
/// BS-partner-1 statement 6 and 8 (WB-partner-1): a count is trued up by
|
||||
/// the first close under the cumulative rule that posts an entry, not by
|
||||
/// a close of an older rule or one that posts nothing; the books say so
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! `docs/command-steps.md` lists every command on `Ledger`, with the step
|
||||
//! of bookspec's Lean model it is.
|
||||
//!
|
||||
//! bookspec proves its laws for every state a `Step` reaches. A command
|
||||
//! that changes the books and is no step is outside those proofs, so the
|
||||
//! page has to name every command, and a new one has to be placed (or
|
||||
//! written down as not covered) before it ships. This test reads the
|
||||
//! source and the page and fails when they differ.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
const SOURCE: &str = include_str!("../src/ledger.rs");
|
||||
const PAGE: &str = include_str!("../../../docs/command-steps.md");
|
||||
|
||||
/// The steps of the two models (`Bookspec.Step`, `Bookspec.Documents.Step`),
|
||||
/// and `none` for a command that is no step.
|
||||
const STEPS: &[&str] = &[
|
||||
"addAccount",
|
||||
"draft",
|
||||
"post",
|
||||
"reverse",
|
||||
"openPeriod",
|
||||
"close",
|
||||
"closeToRetained",
|
||||
"discard",
|
||||
"record",
|
||||
"document",
|
||||
"doc.reverse",
|
||||
"writeOff",
|
||||
"assign",
|
||||
"release",
|
||||
"markSent",
|
||||
"none",
|
||||
];
|
||||
|
||||
/// The commands that are no step of the model. Adding one here is
|
||||
/// admitting a hole in what the proofs cover: the page says what closes it.
|
||||
const NO_STEP: &[&str] = &["renumber_account"];
|
||||
|
||||
/// Every `pub fn` of `impl Ledger` that takes `&mut self`, by name.
|
||||
fn commands() -> BTreeSet<String> {
|
||||
let start = SOURCE
|
||||
.find("\nimpl Ledger {")
|
||||
.expect("ledger.rs has one `impl Ledger {`");
|
||||
// The block ends at the first line that is a lone closing brace.
|
||||
let body = &SOURCE[start + 1..];
|
||||
let end = body.find("\n}\n").expect("the impl block closes");
|
||||
let lines: Vec<&str> = body[..end].lines().collect();
|
||||
let mut found = BTreeSet::new();
|
||||
for (i, line) in lines.iter().enumerate() {
|
||||
let Some(rest) = line.strip_prefix(" pub fn ") else {
|
||||
continue;
|
||||
};
|
||||
let name: String = rest
|
||||
.chars()
|
||||
.take_while(|c| c.is_alphanumeric() || *c == '_')
|
||||
.collect();
|
||||
// The signature runs to the line that opens the body.
|
||||
let signature: String = lines[i..]
|
||||
.iter()
|
||||
.take_while(|l| !l.trim_end().ends_with('{'))
|
||||
.chain(lines[i..].iter().find(|l| l.trim_end().ends_with('{')))
|
||||
.copied()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
if signature.contains("&mut self") {
|
||||
found.insert(name);
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The page's table: command to its steps.
|
||||
fn rows() -> BTreeMap<String, Vec<String>> {
|
||||
let table = PAGE
|
||||
.split("## Every command")
|
||||
.nth(1)
|
||||
.expect("the page has the section `## Every command`");
|
||||
let mut rows = BTreeMap::new();
|
||||
for line in table.lines() {
|
||||
let cells: Vec<&str> = line.split('|').map(str::trim).collect();
|
||||
// `| `name` | steps | note |` splits into ["", name, steps, note, ""].
|
||||
if cells.len() < 4 || !cells[1].starts_with('`') {
|
||||
continue;
|
||||
}
|
||||
let name = cells[1].trim_matches('`').to_string();
|
||||
let steps = cells[2].split(',').map(|s| s.trim().to_string()).collect();
|
||||
assert!(
|
||||
rows.insert(name.clone(), steps).is_none(),
|
||||
"docs/command-steps.md lists `{name}` twice"
|
||||
);
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Every command has a row, and every row a command.
|
||||
#[test]
|
||||
fn every_command_is_on_the_page() {
|
||||
let commands = commands();
|
||||
assert!(
|
||||
commands.len() > 100,
|
||||
"found only {} commands: the reader of ledger.rs is broken",
|
||||
commands.len()
|
||||
);
|
||||
let listed: BTreeSet<String> = rows().into_keys().collect();
|
||||
let missing: Vec<_> = commands.difference(&listed).collect();
|
||||
let stale: Vec<_> = listed.difference(&commands).collect();
|
||||
assert!(
|
||||
missing.is_empty() && stale.is_empty(),
|
||||
"docs/command-steps.md and `impl Ledger` differ.\n\
|
||||
Commands with no row (add one, with the model's step it is, or a \
|
||||
new `Step` in bookspec): {missing:?}\n\
|
||||
Rows with no command (remove them): {stale:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Every row names steps the model has.
|
||||
#[test]
|
||||
fn every_row_names_a_step_of_the_model() {
|
||||
for (command, steps) in rows() {
|
||||
assert!(!steps.is_empty(), "`{command}` names no step");
|
||||
for step in &steps {
|
||||
assert!(
|
||||
STEPS.contains(&step.as_str()),
|
||||
"`{command}` names `{step}`, which is no step of the model"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands that are no step are the ones written down, and no others.
|
||||
#[test]
|
||||
fn the_commands_outside_the_model_are_the_ones_named() {
|
||||
let outside: BTreeSet<String> = rows()
|
||||
.into_iter()
|
||||
.filter(|(_, steps)| steps.iter().any(|s| s == "none"))
|
||||
.map(|(command, _)| command)
|
||||
.collect();
|
||||
let named: BTreeSet<String> = NO_STEP.iter().map(|s| s.to_string()).collect();
|
||||
assert_eq!(
|
||||
outside, named,
|
||||
"a command marked `none` on the page must be in NO_STEP, and the \
|
||||
page's \"No step\" section must say what closes it"
|
||||
);
|
||||
for (command, steps) in rows() {
|
||||
assert!(
|
||||
steps.len() == 1 || !steps.iter().any(|s| s == "none"),
|
||||
"`{command}` is `none` and a step at once"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,11 @@
|
||||
//!
|
||||
//! Exact only up to the sums the books reach. Near `Decimal::MAX` the add
|
||||
//! rounds dust away (`MAX + 0.4` gives `Some(MAX)`, found by unit K-U4 and
|
||||
//! pinned below; plan unit K-U10 makes the kernel refuse it), and a product
|
||||
//! whose scale can't fit 28 places is rounded (the reason for decision
|
||||
//! D-75's ten-place bound on foreign amounts and rates).
|
||||
//! pinned below), and a product whose scale can't fit 28 places is rounded
|
||||
//! (the reason for decision D-75's ten-place bound on foreign amounts and
|
||||
//! rates). These are `rust_decimal`'s own behaviours, pinned here as
|
||||
//! such; the kernel's `Amount for Decimal` refuses both (K-U10, checked
|
||||
//! in `tests/kernel_bridge/decimal_exact.rs`).
|
||||
//!
|
||||
//! This is a test of the dependency, not of the engine. When a property
|
||||
//! fails, the finding is `rust_decimal`'s, and the failing case stays here
|
||||
@@ -436,8 +438,8 @@ fn checked_add_and_sub_return_none_past_the_maximum() {
|
||||
|
||||
/// Inexact at the edge: within one unit of `Decimal::MAX`, `checked_add`
|
||||
/// rounds the fraction away instead of refusing (K-U4's finding). Pinned
|
||||
/// so the day `rust_decimal` or the kernel (unit K-U10) makes it exact,
|
||||
/// this test says so.
|
||||
/// so the day `rust_decimal` makes it exact, this test says so; the
|
||||
/// kernel's `Amount::checked_add` refuses it (K-U10).
|
||||
#[test]
|
||||
fn checked_add_rounds_dust_away_next_to_the_maximum() {
|
||||
let dust = Decimal::new(4, 1);
|
||||
|
||||
@@ -291,58 +291,31 @@ proptest! {
|
||||
prop_assert_eq!(cents(&got), want);
|
||||
}
|
||||
|
||||
/// The exact reference ranks the exact remainders; the kernel ranks
|
||||
/// the rounded quotients' remainders. With a small non-terminating
|
||||
/// total the two orders agree except at an exact tie, which this
|
||||
/// property excludes and `finding_ties_follow_the_rounded_quotient`
|
||||
/// pins.
|
||||
/// The exact reference ranks the exact remainders, and so does the
|
||||
/// kernel (K-U10): with any weights, ties included (equal weights,
|
||||
/// the 4/1/1 shape, a whole that leaves equal remainders), the split
|
||||
/// is the reference's, at whole units and at the cent.
|
||||
#[test]
|
||||
fn largest_remainder_ranks_like_the_exact_reference(
|
||||
whole_start in 0i64..=2_000,
|
||||
weights in prop::collection::vec(1i64..=9, 2..=4),
|
||||
whole in 0i64..=100_000,
|
||||
weights in prop::collection::vec(1i64..=9, 2..=5),
|
||||
) {
|
||||
// Distinct weights, and a total with a factor of 3 or 7 (a
|
||||
// non-terminating division), by construction: no case is
|
||||
// rejected, and no exact tie is left to the property.
|
||||
let mut weights = weights;
|
||||
weights.sort_unstable();
|
||||
for (i, w) in weights.iter_mut().enumerate() {
|
||||
*w += i as i64;
|
||||
}
|
||||
let plain: i64 = weights.iter().sum();
|
||||
if plain % 3 != 0 && plain % 7 != 0 {
|
||||
*weights.last_mut().unwrap() += 3 - plain % 3;
|
||||
}
|
||||
let total: i64 = weights.iter().sum();
|
||||
let whole = (whole_start..whole_start + total)
|
||||
.find(|&w| {
|
||||
let mut rems: Vec<i128> = weights
|
||||
.iter()
|
||||
.map(|&x| (i128::from(w) * i128::from(x)) % i128::from(total))
|
||||
.collect();
|
||||
rems.sort_unstable();
|
||||
rems.dedup();
|
||||
rems.len() == weights.len()
|
||||
})
|
||||
.expect("whole ≡ 1 mod total leaves distinct remainders");
|
||||
let decimal_weights: Vec<Decimal> = weights.iter().copied().map(Decimal::from).collect();
|
||||
let got = split_by_weights_with(
|
||||
Decimal::from(whole),
|
||||
&decimal_weights,
|
||||
Decimal::from(total),
|
||||
Decimal::ONE,
|
||||
|x| round_step(x, Decimal::ONE, Rounding::TowardZero),
|
||||
Leftover::LargestRemainder,
|
||||
)
|
||||
.unwrap();
|
||||
let want = reference(
|
||||
i128::from(whole),
|
||||
&weights.iter().map(|&w| i128::from(w)).collect::<Vec<_>>(),
|
||||
i128::from(total),
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
prop_assert_eq!(got.iter().map(|&p| integer(p)).collect::<Vec<_>>(), want);
|
||||
let wide: Vec<i128> = weights.iter().map(|&w| i128::from(w)).collect();
|
||||
for places in [0u32, 2] {
|
||||
let got = decimal_split(
|
||||
Decimal::new(whole, places),
|
||||
&decimal_weights,
|
||||
Decimal::from(total),
|
||||
places,
|
||||
Leftover::LargestRemainder,
|
||||
)
|
||||
.unwrap();
|
||||
let want = reference(i128::from(whole), &wide, i128::from(total), 1).unwrap();
|
||||
let got = if places == 0 { got.iter().map(|&p| integer(p)).collect() } else { cents(&got) };
|
||||
prop_assert_eq!(got, want);
|
||||
}
|
||||
}
|
||||
|
||||
/// `share_floor_with` is the exact floor of the rational, even when
|
||||
@@ -571,14 +544,13 @@ fn split_into_matches_the_allocating_split() {
|
||||
);
|
||||
}
|
||||
|
||||
/// The EM's finding, pinned rather than fixed: a split ranks the rounded
|
||||
/// quotients' remainders, so an exact tie goes where the 28th digit sends
|
||||
/// it, not to the earlier part. 20.00 split 4/1/1 over 6 gives
|
||||
/// 13.33/3.34/3.33 (exact ranking would give 13.34/3.33/3.33), and 20 at
|
||||
/// whole units gives 13/4/3 (exact would give 14/3/3). The pre-U3 sites
|
||||
/// did the same. The owner decides the exact ranking in K-U10.
|
||||
/// K-U10 (the owner's decision): a split ranks the exact remainders, so an
|
||||
/// exact tie goes to the earlier part, as the docs and the Lean model say.
|
||||
/// 20.00 split 4/1/1 over 6 is 13.34/3.33/3.33 (the rounded quotients'
|
||||
/// ranking gave 13.33/3.34/3.33), and 20 at whole units is 14/3/3 (it gave
|
||||
/// 13/4/3). Equal weights tie on every odd cent and give it to the first.
|
||||
#[test]
|
||||
fn finding_ties_follow_the_rounded_quotient() {
|
||||
fn ties_go_to_the_earlier_part() {
|
||||
let weights = [Decimal::from(4), Decimal::ONE, Decimal::ONE];
|
||||
let got = decimal_split(
|
||||
parse("20.00"),
|
||||
@@ -590,7 +562,7 @@ fn finding_ties_follow_the_rounded_quotient() {
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
got.iter().map(Decimal::to_string).collect::<Vec<_>>(),
|
||||
["13.33", "3.34", "3.33"]
|
||||
["13.34", "3.33", "3.33"]
|
||||
);
|
||||
let got = decimal_split(
|
||||
Decimal::from(20),
|
||||
@@ -602,7 +574,21 @@ fn finding_ties_follow_the_rounded_quotient() {
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
got.iter().map(Decimal::to_string).collect::<Vec<_>>(),
|
||||
["13", "4", "3"]
|
||||
["14", "3", "3"]
|
||||
);
|
||||
// A negative total keeps the share's own order: ties still go first.
|
||||
let neg = [Decimal::from(-4), Decimal::from(-1), Decimal::from(-1)];
|
||||
let got = decimal_split(
|
||||
parse("20.00"),
|
||||
&neg,
|
||||
Decimal::from(-6),
|
||||
2,
|
||||
Leftover::LargestRemainder,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
got.iter().map(Decimal::to_string).collect::<Vec<_>>(),
|
||||
["13.34", "3.33", "3.33"]
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -77,16 +77,17 @@ fn dec_wide(cents: i128) -> Decimal {
|
||||
Decimal::from_i128_with_scale(cents, 2)
|
||||
}
|
||||
|
||||
/// `Decimal`'s answer against the exact reference: the same figure, or
|
||||
/// `None` or a rounded figure when the reference is `None`. FINDING (K-U8, the K-U4 finding
|
||||
/// again): where a step's exact result does not fit the 96-bit mantissa at
|
||||
/// scale 2, `rust_decimal` does not refuse but rounds the result to a
|
||||
/// coarser scale (so `Amount::checked_add` is not "exact or `None`" near
|
||||
/// the top of the range, not only at `Decimal::MAX`). The reference is
|
||||
/// `None` there and `Decimal` is `Some` at a scale below 2; the
|
||||
/// assertion pins that shape, and the canary test below flips when the
|
||||
/// fix lands in `impl Amount for Decimal`.
|
||||
fn same_or_rounded(
|
||||
/// `Decimal`'s answer against the exact reference: the same figure at
|
||||
/// scale 2, or `None` where the reference is `None`. K-U8's finding
|
||||
/// (the K-U4 finding again) was that where a step's exact result did not
|
||||
/// fit the 96-bit mantissa at scale 2, `rust_decimal` did not refuse but
|
||||
/// rounded the result to a coarser scale; K-U10 closed it, so a figure
|
||||
/// that is not the exact one is a failure. One shape is not a rounding:
|
||||
/// an exact sum whose last digit is a zero fits a coarser scale (so the
|
||||
/// reference's cents overflow at that step and `Decimal`'s figure does
|
||||
/// not, and a later step may bring it back to scale 2); it must equal
|
||||
/// the exact value.
|
||||
fn exact_or_refused(
|
||||
got: Option<Decimal>,
|
||||
want: Option<i128>,
|
||||
exact: i128,
|
||||
@@ -94,18 +95,13 @@ fn same_or_rounded(
|
||||
match (got, want) {
|
||||
(Some(g), Some(w)) => prop_assert_eq!((g.mantissa(), g.scale()), (w, 2)),
|
||||
(None, None) => {}
|
||||
// Rounded at a coarser scale at some step (a later step may bring
|
||||
// it back to scale 2): not exact, and no panic; the finding.
|
||||
// The figure is still close to the exact value (`exact`, in
|
||||
// cents): each coarser step loses at most one unit of its scale
|
||||
// (at worst the whole units, 100 cents), over at most four steps.
|
||||
// (A later step can bring the scale back to 2, so the bound is
|
||||
// not tied to the final scale.)
|
||||
(Some(g), None) => {
|
||||
let shown = g.mantissa() * 10i128.pow(2u32.saturating_sub(g.scale()));
|
||||
let cents = g
|
||||
.mantissa()
|
||||
.checked_mul(10i128.pow(2u32.saturating_sub(g.scale())));
|
||||
prop_assert!(
|
||||
g.scale() <= 2 && (shown - exact).abs() <= 400,
|
||||
"{g} is not within four whole units of {exact} cents"
|
||||
g.scale() <= 2 && cents == Some(exact),
|
||||
"{g} is not the exact {exact} cents"
|
||||
);
|
||||
}
|
||||
(None, Some(w)) => prop_assert!(false, "refused an exact {w}"),
|
||||
@@ -160,15 +156,15 @@ proptest! {
|
||||
let (a, b, c, d, e) = (f[0], f[1], f[2], f[3], f[4]);
|
||||
let got = kernel::aging_total(dec_wide(a), dec_wide(b), dec_wide(c), dec_wide(d), dec_wide(e));
|
||||
let want = ref_chain(&[(a, true), (b, true), (c, true), (d, true), (e, true)]);
|
||||
same_or_rounded(got, want, a + b + c + d + e)?;
|
||||
exact_or_refused(got, want, a + b + c + d + e)?;
|
||||
|
||||
let got = kernel::control_difference(dec_wide(a), dec_wide(b), dec_wide(c));
|
||||
let want = ref_chain(&[(a, true), (b, false), (c, false)]);
|
||||
same_or_rounded(got, want, a - b - c)?;
|
||||
exact_or_refused(got, want, a - b - c)?;
|
||||
|
||||
let got = kernel::reconciliation_total(dec_wide(a), dec_wide(b), dec_wide(c), dec_wide(d));
|
||||
let want = ref_chain(&[(a, true), (b, true), (c, true), (d, false)]);
|
||||
same_or_rounded(got, want, a + b + c - d)?;
|
||||
exact_or_refused(got, want, a + b + c - d)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,16 +227,14 @@ fn reconciliation_laptop() {
|
||||
);
|
||||
}
|
||||
|
||||
/// FINDING (K-U8, K-U10 candidate), pinned as a canary: the dust the K-U4
|
||||
/// finding saw at `Decimal::MAX` is wider than that. Two cents-scale
|
||||
/// figures whose exact sum needs more than 96 bits at scale 2 sum to a
|
||||
/// rounded figure at scale 1, not to `None`. Here 0.01 plus the largest
|
||||
/// scale-2 figure is 792281625142643375935439503.36, which `rust_decimal`
|
||||
/// returns as 792281625142643375935439503.4. Reachable only with figures
|
||||
/// near 7.9 x 10^26, a hundred billion times a journal line's cap, so the
|
||||
/// engine's line cap keeps it out of every ordinary path.
|
||||
/// K-U8's finding, closed by K-U10: the dust the K-U4 finding saw at
|
||||
/// `Decimal::MAX` was wider than that. Two cents-scale figures whose exact
|
||||
/// sum needs more than 96 bits at scale 2 summed to a rounded figure at
|
||||
/// scale 1, not to `None`: 0.01 plus the largest scale-2 figure is
|
||||
/// 792281625142643375935439503.36, which `rust_decimal` returns as
|
||||
/// 792281625142643375935439503.4. The kernel now refuses it.
|
||||
#[test]
|
||||
fn finding_decimal_add_rounds_scale_near_the_top() {
|
||||
fn a_sum_past_exact_arithmetic_is_refused() {
|
||||
let top = Decimal::from_i128_with_scale((1i128 << 96) - 1, 2);
|
||||
let got = kernel::aging_total(
|
||||
Decimal::new(1, 2),
|
||||
@@ -249,8 +243,12 @@ fn finding_decimal_add_rounds_scale_near_the_top() {
|
||||
Decimal::ZERO,
|
||||
top,
|
||||
);
|
||||
assert_eq!(got, None);
|
||||
// The old chain's figure, for the record: rounded.
|
||||
assert_eq!(
|
||||
got.map(|g| (g.mantissa(), g.scale())),
|
||||
Decimal::new(1, 2)
|
||||
.checked_add(top)
|
||||
.map(|g| (g.mantissa(), g.scale())),
|
||||
Some((7922816251426433759354395034, 1))
|
||||
);
|
||||
}
|
||||
@@ -270,6 +268,24 @@ fn arb_decimal() -> impl Strategy<Value = Decimal> {
|
||||
.prop_map(|(m, s)| Decimal::from_i128_with_scale(m, s))
|
||||
}
|
||||
|
||||
fn rat(d: Decimal) -> num_rational::BigRational {
|
||||
num_rational::BigRational::new(
|
||||
num_bigint::BigInt::from(d.mantissa()),
|
||||
num_bigint::BigInt::from(10u8).pow(d.scale()),
|
||||
)
|
||||
}
|
||||
|
||||
/// `rust_decimal`'s `a + b` (or `a - b`) as it returned it, only when it
|
||||
/// is the exact result: the reference the kernel's checked sum must equal.
|
||||
fn exact_only(got: Option<Decimal>, a: Decimal, b: Decimal, add: bool) -> Option<Decimal> {
|
||||
let exact = if add {
|
||||
rat(a) + rat(b)
|
||||
} else {
|
||||
rat(a) - rat(b)
|
||||
};
|
||||
got.filter(|g| rat(*g) == exact)
|
||||
}
|
||||
|
||||
fn shown(d: Option<Decimal>) -> String {
|
||||
d.map_or("None".into(), |d| format!("{d} (scale {})", d.scale()))
|
||||
}
|
||||
@@ -279,26 +295,28 @@ proptest! {
|
||||
|
||||
/// The routed sites give the figures, scales and refusals the
|
||||
/// hand-written chains they replaced did (K-U8's compatibility check),
|
||||
/// compared as strings: the old `AgingRow::total`, the old
|
||||
/// `control_check` difference, the old `Reconciliation::total`.
|
||||
/// compared as strings, except that a step whose result `rust_decimal`
|
||||
/// had to round is now refused (K-U10): the old `AgingRow::total`, the
|
||||
/// old `control_check` difference, the old `Reconciliation::total`,
|
||||
/// each step filtered through an exact rational reference.
|
||||
#[test]
|
||||
fn kernel_matches_the_replaced_chains(f in prop::array::uniform5(arb_decimal())) {
|
||||
let old_aging = [f[1], f[2], f[3], f[4]]
|
||||
.into_iter()
|
||||
.try_fold(f[0], Decimal::checked_add);
|
||||
.try_fold(f[0], |a, b| exact_only(Decimal::checked_add(a, b), a, b, true));
|
||||
prop_assert_eq!(
|
||||
shown(kernel::aging_total(f[0], f[1], f[2], f[3], f[4])),
|
||||
shown(old_aging)
|
||||
);
|
||||
let old_diff = f[0].checked_sub(f[1]).and_then(|d| d.checked_sub(f[2]));
|
||||
let old_diff = exact_only(Decimal::checked_sub(f[0], f[1]), f[0], f[1], false)
|
||||
.and_then(|d| exact_only(Decimal::checked_sub(d, f[2]), d, f[2], false));
|
||||
prop_assert_eq!(
|
||||
shown(kernel::control_difference(f[0], f[1], f[2])),
|
||||
shown(old_diff)
|
||||
);
|
||||
let old_recon = f[0]
|
||||
.checked_add(f[1])
|
||||
.and_then(|x| x.checked_add(f[2]))
|
||||
.and_then(|x| x.checked_sub(f[3]));
|
||||
let old_recon = exact_only(Decimal::checked_add(f[0], f[1]), f[0], f[1], true)
|
||||
.and_then(|x| exact_only(Decimal::checked_add(x, f[2]), x, f[2], true))
|
||||
.and_then(|x| exact_only(Decimal::checked_sub(x, f[3]), x, f[3], false));
|
||||
prop_assert_eq!(
|
||||
shown(kernel::reconciliation_total(f[0], f[1], f[2], f[3])),
|
||||
shown(old_recon)
|
||||
|
||||
@@ -0,0 +1,631 @@
|
||||
//! K-U10 bridge properties: `impl Amount for Decimal`'s add, subtract and
|
||||
//! multiply are exact or `None`, never rounded (BS-ledger-1: a product the
|
||||
//! arithmetic cannot hold MUST be refused; BS-entry-4).
|
||||
//!
|
||||
//! Kani works on `i64`, which never rounds, so the claim rests here: the
|
||||
//! kernel's `Decimal` result is compared with `rust_decimal`'s own
|
||||
//! (the "old" behaviour) and with an independent exact reference
|
||||
//! (`num_rational::BigRational`, sharing no code with the kernel) over
|
||||
//! the whole mantissa (to 2^96 - 1) and scale (0 to 28) range, edges
|
||||
//! included. The law, per operation:
|
||||
//!
|
||||
//! 1. `Some(r)` is the exact result: `r` equals the rational one.
|
||||
//! 2. Where the old result was exact, the kernel returns it unchanged,
|
||||
//! compared as strings (value and scale): nothing exact moves.
|
||||
//! 3. Where the old result was rounded, the kernel returns `None`.
|
||||
//! 4. Where the old result was `None`, so is the kernel's.
|
||||
//! 5. `Some` exactly when the exact result is a `Decimal` at all (a
|
||||
//! mantissa under 2^96 at some scale of 0 to 28), decided from the
|
||||
//! rational alone, with none of `rust_decimal`'s arithmetic: nothing
|
||||
//! representable is refused. Laws 2 to 4 compare with `rust_decimal`;
|
||||
//! this one does not, so it would catch `rust_decimal` rounding a
|
||||
//! result it could have held.
|
||||
//!
|
||||
//! And over the posted range (BS-entry-4's line cap and ten places) the
|
||||
//! kernel equals the old for every input.
|
||||
|
||||
use ledger_core::kernel::{Amount, MAX_LINE_AMOUNT, MAX_LINE_SCALE};
|
||||
use num_bigint::BigInt;
|
||||
use num_rational::BigRational;
|
||||
use proptest::prelude::*;
|
||||
use rust_decimal::Decimal;
|
||||
|
||||
fn rat(d: Decimal) -> BigRational {
|
||||
BigRational::new(
|
||||
BigInt::from(d.mantissa()),
|
||||
BigInt::from(10u8).pow(d.scale()),
|
||||
)
|
||||
}
|
||||
|
||||
fn shown(d: Option<Decimal>) -> String {
|
||||
d.map_or("None".into(), |d| format!("{d} (scale {})", d.scale()))
|
||||
}
|
||||
|
||||
/// What the kernel must return, given what `rust_decimal` returned and
|
||||
/// the exact result: the old figure if it is exact, else `None`.
|
||||
fn expected(old: Option<Decimal>, exact: &BigRational) -> Option<Decimal> {
|
||||
old.filter(|o| rat(*o) == *exact)
|
||||
}
|
||||
|
||||
/// Whether an exact rational is a `Decimal`: `m x 10^-s` with `|m| < 2^96`
|
||||
/// and `s <= 28`. The fewest places that make it whole are tried in turn;
|
||||
/// more places only make the mantissa longer.
|
||||
fn representable(q: &BigRational) -> bool {
|
||||
let ten = BigRational::from_integer(BigInt::from(10u8));
|
||||
let mut scaled = q.clone();
|
||||
for _ in 0..=28 {
|
||||
if scaled.is_integer() {
|
||||
return scaled.numer().magnitude().bits() <= 96;
|
||||
}
|
||||
scaled *= &ten;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Any `Decimal`: mantissas across the whole 96 bits (small, near the
|
||||
/// top, trailing zeros) at every scale.
|
||||
fn arb_decimal() -> impl Strategy<Value = Decimal> {
|
||||
let top = (1i128 << 96) - 1;
|
||||
(
|
||||
prop_oneof![
|
||||
-1_000i128..=1_000,
|
||||
-1_000_000_000_000i128..=1_000_000_000_000,
|
||||
-top..=top,
|
||||
(top - 1_000)..=top,
|
||||
-top..=-(top - 1_000),
|
||||
(-top / 1_000_000..=top / 1_000_000).prop_map(|m| m * 1_000_000),
|
||||
Just(top),
|
||||
Just(-top),
|
||||
Just(0),
|
||||
],
|
||||
0u32..=28,
|
||||
)
|
||||
.prop_map(|(m, s)| Decimal::from_i128_with_scale(m, s))
|
||||
}
|
||||
|
||||
/// A decimal and a second one at a nearby scale or the same: the
|
||||
/// rescaling edge of an add is where the rounding lives.
|
||||
fn arb_pair() -> impl Strategy<Value = (Decimal, Decimal)> {
|
||||
prop_oneof![
|
||||
(arb_decimal(), arb_decimal()),
|
||||
(arb_decimal(), 0u32..=28, -1_000i128..=1_000)
|
||||
.prop_map(|(a, s, m)| (a, Decimal::from_i128_with_scale(m, s))),
|
||||
(arb_decimal(), -1_000i128..=1_000)
|
||||
.prop_map(|(a, m)| (a, Decimal::from_i128_with_scale(m, a.scale()))),
|
||||
]
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(30000))]
|
||||
|
||||
/// Add: laws 1 to 4, over the whole range.
|
||||
#[test]
|
||||
fn add_is_exact_or_none((a, b) in arb_pair()) {
|
||||
let got = Amount::checked_add(a, b);
|
||||
let old = Decimal::checked_add(a, b);
|
||||
let exact = rat(a) + rat(b);
|
||||
if let Some(r) = got {
|
||||
prop_assert_eq!(rat(r), exact.clone(), "{} + {} is rounded", a, b);
|
||||
}
|
||||
prop_assert_eq!(shown(got), shown(expected(old, &exact)));
|
||||
prop_assert_eq!(got.is_some(), representable(&exact), "{} + {}", a, b);
|
||||
}
|
||||
|
||||
/// Subtract: the same laws, against `rust_decimal`'s own subtraction
|
||||
/// (so a zero stays a plain zero).
|
||||
#[test]
|
||||
fn sub_is_exact_or_none((a, b) in arb_pair()) {
|
||||
let got = Amount::checked_sub(a, b);
|
||||
let old = Decimal::checked_sub(a, b);
|
||||
let exact = rat(a) - rat(b);
|
||||
if let Some(r) = got {
|
||||
prop_assert_eq!(rat(r), exact.clone(), "{} - {} is rounded", a, b);
|
||||
}
|
||||
prop_assert_eq!(shown(got), shown(expected(old, &exact)));
|
||||
prop_assert_eq!(got.is_some(), representable(&exact), "{} - {}", a, b);
|
||||
}
|
||||
|
||||
/// Multiply: the same laws.
|
||||
#[test]
|
||||
fn mul_is_exact_or_none((a, b) in arb_pair()) {
|
||||
let got = Amount::checked_mul(a, b);
|
||||
let old = Decimal::checked_mul(a, b);
|
||||
let exact = rat(a) * rat(b);
|
||||
if let Some(r) = got {
|
||||
prop_assert_eq!(rat(r), exact.clone(), "{} x {} is rounded", a, b);
|
||||
}
|
||||
prop_assert_eq!(shown(got), shown(expected(old, &exact)));
|
||||
prop_assert_eq!(got.is_some(), representable(&exact), "{} x {}", a, b);
|
||||
}
|
||||
|
||||
/// Whatever the kernel refuses, `rust_decimal` either refused or
|
||||
/// rounded: the kernel never refuses an exact figure `rust_decimal`
|
||||
/// held (restating laws 2 and 3 as the refusal's only two causes).
|
||||
#[test]
|
||||
fn a_refusal_is_an_overflow_or_a_rounding((a, b) in arb_pair()) {
|
||||
for (got, old, exact) in [
|
||||
(Amount::checked_add(a, b), Decimal::checked_add(a, b), rat(a) + rat(b)),
|
||||
(Amount::checked_mul(a, b), Decimal::checked_mul(a, b), rat(a) * rat(b)),
|
||||
] {
|
||||
if got.is_none() {
|
||||
prop_assert!(old.is_none_or(|o| rat(o) != exact));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A figure a posted line can carry (BS-entry-4): at most
|
||||
/// `MAX_LINE_AMOUNT`, at most `MAX_LINE_SCALE` places once trailing zeros
|
||||
/// are dropped; stored at any raw scale that still holds it.
|
||||
fn arb_line_amount() -> impl Strategy<Value = Decimal> {
|
||||
(0u32..=MAX_LINE_SCALE, any::<bool>()).prop_flat_map(|(scale, negative)| {
|
||||
let cap = 10i128.pow(15 + scale);
|
||||
(0i128..=cap, 0u32..=28).prop_map(move |(m, want)| {
|
||||
let m = if negative { -m } else { m };
|
||||
// Up to `want` extra trailing zeros: the same value at a raw
|
||||
// scale of up to 28, as far as 96 bits hold it.
|
||||
let mut pad = 0;
|
||||
while pad < want
|
||||
&& scale + pad < 28
|
||||
&& m.checked_mul(10i128.pow(pad + 1))
|
||||
.is_some_and(|p| p.unsigned_abs() < 1u128 << 96)
|
||||
{
|
||||
pad += 1;
|
||||
}
|
||||
Decimal::from_i128_with_scale(m * 10i128.pow(pad), scale + pad)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(20000))]
|
||||
|
||||
/// Over the posted range, add and subtract equal `rust_decimal`'s, to
|
||||
/// the character, and are never `None`.
|
||||
#[test]
|
||||
fn posted_range_sums_are_unchanged(a in arb_line_amount(), b in arb_line_amount()) {
|
||||
prop_assert!(a.abs() <= MAX_LINE_AMOUNT && b.abs() <= MAX_LINE_AMOUNT);
|
||||
prop_assert!(a.normalize().scale() <= MAX_LINE_SCALE);
|
||||
let add = Amount::checked_add(a, b);
|
||||
let sub = Amount::checked_sub(a, b);
|
||||
prop_assert!(add.is_some() && sub.is_some());
|
||||
prop_assert_eq!(shown(add), shown(Decimal::checked_add(a, b)));
|
||||
prop_assert_eq!(shown(sub), shown(Decimal::checked_sub(a, b)));
|
||||
}
|
||||
|
||||
/// Over the posted range, an FX product (a foreign amount and a
|
||||
/// rate of at most ten places each, D-75) is the old product to the
|
||||
/// character whenever its mantissa product fits 96 bits (the exact
|
||||
/// product is then representable), and `None` where it does not and
|
||||
/// the old one rounded.
|
||||
#[test]
|
||||
fn posted_range_fx_products_are_unchanged_or_refused(
|
||||
fm in 0i128..=10i128.pow(25),
|
||||
fs in 0u32..=MAX_LINE_SCALE,
|
||||
rm in 0i128..=10i128.pow(13),
|
||||
rs in 0u32..=MAX_LINE_SCALE,
|
||||
) {
|
||||
let foreign = Decimal::from_i128_with_scale(fm, fs);
|
||||
let rate = Decimal::from_i128_with_scale(rm, rs);
|
||||
let got = Amount::checked_mul(foreign, rate);
|
||||
let old = Decimal::checked_mul(foreign, rate);
|
||||
let fits = fm.checked_mul(rm).is_some_and(|p| p < (1i128 << 96));
|
||||
if fits {
|
||||
prop_assert!(got.is_some());
|
||||
prop_assert_eq!(shown(got), shown(old));
|
||||
} else {
|
||||
// Past 96 bits at the full scale: the old product was rounded
|
||||
// unless the product's own trailing zeros made it fit.
|
||||
prop_assert_eq!(shown(got), shown(expected(old, &(rat(foreign) * rat(rate)))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(1500))]
|
||||
|
||||
/// A running total of posted lines (1e18 at the worst, ten places: a
|
||||
/// 29-digit mantissa) is unchanged at every step.
|
||||
#[test]
|
||||
fn posted_range_running_totals_are_unchanged(
|
||||
lines in proptest::collection::vec(arb_line_amount(), 0..=100)
|
||||
) {
|
||||
let mut old = Decimal::ZERO;
|
||||
let mut new = Decimal::ZERO;
|
||||
for l in lines {
|
||||
old = Decimal::checked_add(old, l).expect("posted sums fit");
|
||||
new = Amount::checked_add(new, l).expect("posted sums stay exact");
|
||||
prop_assert_eq!(shown(Some(new)), shown(Some(old)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(24))]
|
||||
|
||||
/// The same over thousands of lines, where the total's mantissa comes
|
||||
/// near 2^96 (5,000 lines of 10^15 at ten places is 5e28 of 7.9e28):
|
||||
/// every step is `rust_decimal`'s, and none is refused.
|
||||
#[test]
|
||||
fn posted_range_running_totals_of_thousands_of_lines_are_unchanged(
|
||||
lines in proptest::collection::vec(arb_line_amount(), 4000..=5000),
|
||||
same_sign in any::<bool>(),
|
||||
) {
|
||||
let mut old = Decimal::ZERO;
|
||||
let mut new = Decimal::ZERO;
|
||||
for l in lines {
|
||||
let l = if same_sign { l.abs() } else { l };
|
||||
old = Decimal::checked_add(old, l).expect("posted sums fit");
|
||||
new = Amount::checked_add(new, l).expect("posted sums stay exact");
|
||||
prop_assert_eq!(shown(Some(new)), shown(Some(old)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a running total stops being exact: 7,922 lines of the largest
|
||||
/// ten-place amount under the cap (999999999999999.9999999999, a mantissa
|
||||
/// of 10^25 - 1) sum exactly; the next one passes 2^96 at ten places.
|
||||
/// `rust_decimal` drops a place and rounds; the kernel refuses.
|
||||
#[test]
|
||||
fn a_running_total_is_refused_where_it_would_first_round() {
|
||||
let line = Decimal::from_i128_with_scale(10i128.pow(25) - 1, 10);
|
||||
assert!(line.in_line_range());
|
||||
let mut old = Decimal::ZERO;
|
||||
let mut new = Decimal::ZERO;
|
||||
for n in 1..=7_922 {
|
||||
old = Decimal::checked_add(old, line).unwrap();
|
||||
new = Amount::checked_add(new, line).unwrap_or_else(|| panic!("line {n} is exact"));
|
||||
assert_eq!(shown(Some(new)), shown(Some(old)), "line {n}");
|
||||
}
|
||||
assert_eq!(
|
||||
rat(new),
|
||||
rat(line) * BigRational::from_integer(BigInt::from(7_922))
|
||||
);
|
||||
let rounded = Decimal::checked_add(old, line).unwrap();
|
||||
assert_ne!(rat(rounded), rat(old) + rat(line), "rust_decimal rounds");
|
||||
assert_eq!(Amount::checked_add(new, line), None);
|
||||
}
|
||||
|
||||
/// The K-U4 canary, flipped: a sum within one unit of `Decimal::MAX`
|
||||
/// that `rust_decimal` rounds is refused, and the exact ones stand.
|
||||
#[test]
|
||||
fn a_sum_past_exact_arithmetic_is_refused_at_the_maximum() {
|
||||
let max = Decimal::MAX;
|
||||
assert_eq!(Decimal::checked_add(max, Decimal::new(4, 1)), Some(max));
|
||||
assert_eq!(Amount::checked_add(max, Decimal::new(4, 1)), None);
|
||||
assert_eq!(Amount::checked_add(max, Decimal::new(5, 1)), None);
|
||||
assert_eq!(Amount::checked_add(max, Decimal::ONE), None);
|
||||
assert_eq!(Amount::checked_add(max, Decimal::ZERO), Some(max));
|
||||
assert_eq!(
|
||||
Amount::checked_add(max, -Decimal::ONE),
|
||||
Some(max - Decimal::ONE)
|
||||
);
|
||||
assert_eq!(Amount::checked_sub(Decimal::MIN, Decimal::new(4, 1)), None);
|
||||
}
|
||||
|
||||
/// The K-U8 canary, flipped: `0.01 + 792281625142643375935439503.35`.
|
||||
#[test]
|
||||
fn a_sum_past_exact_arithmetic_is_refused_near_the_top() {
|
||||
let top = Decimal::from_i128_with_scale((1i128 << 96) - 1, 2);
|
||||
let cent = Decimal::new(1, 2);
|
||||
assert_eq!(
|
||||
shown(Decimal::checked_add(cent, top)),
|
||||
"792281625142643375935439503.4 (scale 1)",
|
||||
"rust_decimal rounds the exact ...503.36"
|
||||
);
|
||||
assert_eq!(Amount::checked_add(cent, top), None);
|
||||
assert_eq!(Amount::checked_add(top, cent), None);
|
||||
// The sums that are exact stay.
|
||||
assert_eq!(
|
||||
Amount::checked_add(-cent, top),
|
||||
Decimal::checked_add(-cent, top)
|
||||
);
|
||||
}
|
||||
|
||||
/// The K-U1 canary, flipped: `1050000010.0000000001 x 9.9999999999` is
|
||||
/// 10500000099.89499999999999999999 exactly, 20 places, 96 bits short;
|
||||
/// `rust_decimal` held 10500000099.895 and the engine booked ...99.90.
|
||||
/// The product is refused.
|
||||
#[test]
|
||||
fn a_product_past_exact_arithmetic_is_refused() {
|
||||
let foreign: Decimal = "1050000010.0000000001".parse().unwrap();
|
||||
let rate: Decimal = "9.9999999999".parse().unwrap();
|
||||
let held = Decimal::checked_mul(foreign, rate).unwrap();
|
||||
assert_ne!(rat(held), rat(foreign) * rat(rate), "rust_decimal rounded");
|
||||
assert_eq!(held.to_string(), "10500000099.895000000000000000");
|
||||
assert_eq!(Amount::checked_mul(foreign, rate), None);
|
||||
// K-U3's square, reachable below the line cap at ten places.
|
||||
let n: Decimal = "123456789.0123456789".parse().unwrap();
|
||||
assert_eq!(
|
||||
shown(Decimal::checked_mul(n, n)),
|
||||
"15241578753238836.750190519988 (scale 12)"
|
||||
);
|
||||
assert_eq!(Amount::checked_mul(n, n), None);
|
||||
// Past scale 28 the old product rounds (or underflows to zero).
|
||||
let tiny = Decimal::from_i128_with_scale(1, 28);
|
||||
assert_eq!(Decimal::checked_mul(tiny, tiny), Some(Decimal::ZERO));
|
||||
assert_eq!(Amount::checked_mul(tiny, tiny), None);
|
||||
}
|
||||
|
||||
/// Exact products with trailing zeros stay, even where the full-scale
|
||||
/// mantissa would pass 96 bits (a scale test would refuse these): 100 x
|
||||
/// 0.3333333333333333333333333333 is 33.333...3300 exactly.
|
||||
#[test]
|
||||
fn an_exact_product_that_only_looks_wide_is_kept() {
|
||||
let third = Decimal::from_i128_with_scale(3_333_333_333_333_333_333_333_333_333, 28);
|
||||
let hundred = Decimal::ONE_HUNDRED;
|
||||
let got = Amount::checked_mul(third, hundred);
|
||||
assert_eq!(shown(got), shown(Decimal::checked_mul(third, hundred)));
|
||||
assert!(got.is_some());
|
||||
// 10^20 at scale 20 (one) squared: 10^40 mantissa, value 1.
|
||||
let one = Decimal::from_i128_with_scale(10i128.pow(20), 20);
|
||||
assert_eq!(
|
||||
shown(Amount::checked_mul(one, one)),
|
||||
shown(Decimal::checked_mul(one, one))
|
||||
);
|
||||
assert_eq!(
|
||||
Amount::checked_mul(one, one).map(rat),
|
||||
Some(rat(Decimal::ONE))
|
||||
);
|
||||
}
|
||||
|
||||
/// Zero is exact in every shape, and a zero factor never refuses.
|
||||
#[test]
|
||||
fn zero_is_exact() {
|
||||
let z28 = Decimal::from_i128_with_scale(0, 28);
|
||||
let big = Decimal::MAX;
|
||||
assert_eq!(
|
||||
shown(Amount::checked_mul(z28, big)),
|
||||
shown(Decimal::checked_mul(z28, big))
|
||||
);
|
||||
assert!(Amount::checked_mul(z28, z28).is_some());
|
||||
assert_eq!(Amount::checked_add(z28, big), Some(big));
|
||||
assert_eq!(
|
||||
Amount::checked_add(Decimal::ZERO, z28).map(|d| d.is_zero()),
|
||||
Some(true)
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- FX
|
||||
|
||||
use ledger_core::kernel::Rounding;
|
||||
|
||||
/// `q` rounded to an integer in `mode`, exactly (no kernel code).
|
||||
fn round_rational(q: &BigRational, mode: Rounding) -> BigInt {
|
||||
let n = q.numer();
|
||||
let d = q.denom();
|
||||
let truncated = n / d;
|
||||
let rem = n - &truncated * d;
|
||||
let zero = BigInt::from(0);
|
||||
let negative = rem < zero;
|
||||
let twice = if negative { -&rem } else { rem.clone() } * 2;
|
||||
let away = if negative { -1 } else { 1 };
|
||||
match mode {
|
||||
Rounding::TowardZero => truncated,
|
||||
Rounding::TowardNegativeInfinity => {
|
||||
if negative {
|
||||
truncated - 1
|
||||
} else {
|
||||
truncated
|
||||
}
|
||||
}
|
||||
Rounding::HalfAwayFromZero => {
|
||||
if twice >= *d {
|
||||
truncated + away
|
||||
} else {
|
||||
truncated
|
||||
}
|
||||
}
|
||||
Rounding::HalfToEven => {
|
||||
if twice > *d || (twice == *d && truncated.bit(0)) {
|
||||
truncated + away
|
||||
} else {
|
||||
truncated
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn arb_mode() -> impl Strategy<Value = Rounding> {
|
||||
prop_oneof![
|
||||
Just(Rounding::TowardZero),
|
||||
Just(Rounding::TowardNegativeInfinity),
|
||||
Just(Rounding::HalfAwayFromZero),
|
||||
Just(Rounding::HalfToEven),
|
||||
]
|
||||
}
|
||||
|
||||
/// A foreign amount or rate of at most ten places (D-75) and up to
|
||||
/// `digits` digits of mantissa, so products reach 2^96 and past it.
|
||||
fn arb_ten_place(digits: u32) -> impl Strategy<Value = Decimal> {
|
||||
(0i128..10i128.pow(digits), 0u32..=MAX_LINE_SCALE)
|
||||
.prop_map(|(m, s)| Decimal::from_i128_with_scale(m, s))
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(30000))]
|
||||
|
||||
/// `checked_mul_round_to_step` is the exact product rounded once, in
|
||||
/// every mode, at the steps the books use (one, a cent, a mill), at
|
||||
/// steps of 5 and 25 of them, and at steps of any number of places,
|
||||
/// whether or not the exact product fits 96 bits, ties and signs
|
||||
/// included. `None` only where the kernel says so: the figure times
|
||||
/// 10^(the step's places + 2) does not fit 96 bits (one real digit
|
||||
/// below the step and the sticky digit have no room), or the step has
|
||||
/// 27 or 28 places (no room below it at all).
|
||||
#[test]
|
||||
fn the_fx_product_is_rounded_once_from_the_exact_one(
|
||||
foreign in arb_ten_place(26),
|
||||
rate in arb_ten_place(14),
|
||||
places in prop_oneof![4 => 0u32..=3, 1 => 0u32..=28],
|
||||
unit in prop_oneof![Just(1i128), Just(5i128), Just(25i128)],
|
||||
mode in arb_mode(),
|
||||
negative in any::<bool>(),
|
||||
) {
|
||||
let foreign = if negative { -foreign } else { foreign };
|
||||
// A step that is not a power of ten too (a nickel, 0.025): its
|
||||
// half steps sit one place below it, where the kept digit is real.
|
||||
let step = Decimal::from_i128_with_scale(unit, places);
|
||||
let got = Amount::checked_mul_round_to_step(foreign, rate, step, mode);
|
||||
let exact = rat(foreign) * rat(rate);
|
||||
let count = round_rational(&(exact.clone() / rat(step)), mode);
|
||||
let want = BigRational::from_integer(count) * rat(step);
|
||||
match got {
|
||||
Some(g) => prop_assert_eq!(rat(g), want, "{} x {} to {} places, {:?}", foreign, rate, places, mode),
|
||||
None => {
|
||||
// The digits the rounding needs: the figure to one place
|
||||
// below the step, then the sticky digit.
|
||||
let step_places = step.normalize().scale();
|
||||
let needed = (exact.clone()
|
||||
* BigRational::from_integer(BigInt::from(10u8).pow(step_places + 2)))
|
||||
.to_integer();
|
||||
let room = (BigInt::from(1u8) << 96u32) - BigInt::from(10u8);
|
||||
prop_assert!(
|
||||
step_places >= 27 || *needed.magnitude() >= *room.magnitude(),
|
||||
"{} x {} to a step of {} refused though it is only {}", foreign, rate, step, want
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The K-U1 edge, now rounded once: the exact product is
|
||||
/// 10500000099.89499999999999999999, so the cent is 10500000099.89 (the
|
||||
/// engine used to book ...99.90, off by a cent, by rounding twice).
|
||||
#[test]
|
||||
fn the_k_u1_edge_books_the_cent_the_exact_product_gives() {
|
||||
let foreign: Decimal = "1050000010.0000000001".parse().unwrap();
|
||||
let rate: Decimal = "9.9999999999".parse().unwrap();
|
||||
let cent = Decimal::new(1, 2);
|
||||
assert_eq!(
|
||||
Amount::checked_mul_round_to_step(foreign, rate, cent, Rounding::HalfAwayFromZero),
|
||||
Some("10500000099.89".parse().unwrap())
|
||||
);
|
||||
// Products straddling a half cent by digits far below the cent, with
|
||||
// a 97-bit mantissa (so they cannot take the plain path): the sticky
|
||||
// digit puts each on its side of the tie.
|
||||
let rate: Decimal = "1.0000000001".parse().unwrap();
|
||||
let book = |foreign: &str, mode| {
|
||||
Amount::checked_mul_round_to_step(foreign.parse().unwrap(), rate, cent, mode)
|
||||
};
|
||||
let above = "1000000000.0050000001"; // 1000000000.10500000010050000001
|
||||
let below = "1000000000.0049999999"; // 1000000000.10499999990049999999
|
||||
assert!(
|
||||
Decimal::checked_mul(above.parse().unwrap(), rate)
|
||||
.is_some_and(|p| { rat(p) != rat(above.parse().unwrap()) * rat(rate) })
|
||||
);
|
||||
assert_eq!(
|
||||
book(above, Rounding::HalfAwayFromZero),
|
||||
Some("1000000000.11".parse().unwrap())
|
||||
);
|
||||
assert_eq!(
|
||||
book(above, Rounding::HalfToEven),
|
||||
Some("1000000000.11".parse().unwrap())
|
||||
);
|
||||
assert_eq!(
|
||||
book(above, Rounding::TowardZero),
|
||||
Some("1000000000.10".parse().unwrap())
|
||||
);
|
||||
assert_eq!(
|
||||
book(below, Rounding::HalfAwayFromZero),
|
||||
Some("1000000000.10".parse().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
/// A step of 27 or 28 places leaves no place below it for the digit and
|
||||
/// the sticky digit the one rounding needs (`Decimal` ends at 28), so a
|
||||
/// product that is not exact is refused there in every mode, though its
|
||||
/// rounded figure (zero, here) is a `Decimal`. A refusal, never a guess;
|
||||
/// no currency's step is near it. At 26 places the same product rounds.
|
||||
#[test]
|
||||
fn a_step_of_27_places_refuses_a_product_that_is_not_exact() {
|
||||
let tiny = Decimal::from_i128_with_scale(1, 28);
|
||||
for mode in [
|
||||
Rounding::TowardZero,
|
||||
Rounding::TowardNegativeInfinity,
|
||||
Rounding::HalfAwayFromZero,
|
||||
Rounding::HalfToEven,
|
||||
] {
|
||||
for places in [27, 28] {
|
||||
let step = Decimal::from_i128_with_scale(1, places);
|
||||
assert_eq!(
|
||||
Amount::checked_mul_round_to_step(tiny, tiny, step, mode),
|
||||
None
|
||||
);
|
||||
// A product that is exact is rounded there as at any step.
|
||||
assert_eq!(
|
||||
Amount::checked_mul_round_to_step(Decimal::ONE, step, step, mode),
|
||||
Some(step)
|
||||
);
|
||||
}
|
||||
let step = Decimal::from_i128_with_scale(1, 26);
|
||||
assert_eq!(
|
||||
Amount::checked_mul_round_to_step(tiny, tiny, step, mode),
|
||||
Some(Decimal::ZERO)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------ exact division
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(30000))]
|
||||
|
||||
/// `checked_div_exact` is the exact quotient or `None`: never a
|
||||
/// quotient `rust_decimal` rounded (10 / 3), whose product with the
|
||||
/// divisor rounds back to the dividend; and `Some` whenever the exact
|
||||
/// quotient is a `Decimal`, so an exact division is never refused.
|
||||
#[test]
|
||||
fn div_exact_is_exact_or_none(a in arb_line_amount(), m in 1i128..100_000, s in 0u32..=4) {
|
||||
let b = Decimal::from_i128_with_scale(m, s);
|
||||
let got = Amount::checked_div_exact(a, b);
|
||||
if let Some(q) = got {
|
||||
prop_assert_eq!(rat(q) * rat(b), rat(a), "{} / {} gave {}", a, b, q);
|
||||
}
|
||||
prop_assert_eq!(got.is_some(), representable(&(rat(a) / rat(b))), "{} / {}", a, b);
|
||||
}
|
||||
|
||||
/// The same over the whole range of `Decimal`, divisors that divide
|
||||
/// evenly included (a quotient times a divisor, divided back).
|
||||
#[test]
|
||||
fn div_exact_over_the_whole_range((a, b) in arb_pair(), back in any::<bool>()) {
|
||||
let b = if b.is_zero() { Decimal::ONE } else { b };
|
||||
// Half the cases: a dividend built as a product, so the exact
|
||||
// quotient exists and is a `Decimal`.
|
||||
let a = if back { Amount::checked_mul(a, b).unwrap_or(a) } else { a };
|
||||
let exact = rat(a) / rat(b);
|
||||
let got = Amount::checked_div_exact(a, b);
|
||||
if let Some(q) = got {
|
||||
prop_assert_eq!(rat(q), exact.clone(), "{} / {} gave {}", a, b, q);
|
||||
}
|
||||
prop_assert_eq!(got.is_some(), representable(&exact), "{} / {}", a, b);
|
||||
}
|
||||
}
|
||||
|
||||
/// A third, a seventh, a ninth: no exact quotient, so `None`, where the
|
||||
/// check through `rust_decimal`'s rounding product let each through. A
|
||||
/// quarter and a basis-point division are exact and are kept.
|
||||
#[test]
|
||||
fn a_rounded_quotient_is_not_an_exact_one() {
|
||||
let d = |s: &str| s.parse::<Decimal>().unwrap();
|
||||
for (a, b) in [
|
||||
("10", "3"),
|
||||
("20", "3"),
|
||||
("10", "7"),
|
||||
("80", "9"),
|
||||
("10", "6"),
|
||||
("1000000.00", "3"),
|
||||
] {
|
||||
assert_eq!(
|
||||
Amount::checked_div_exact(d(a), d(b)),
|
||||
None,
|
||||
"{a} / {b} has no exact quotient"
|
||||
);
|
||||
}
|
||||
assert_eq!(Amount::checked_div_exact(d("10"), d("4")), Some(d("2.5")));
|
||||
assert_eq!(
|
||||
Amount::checked_div_exact(d("123456.78") * d("250"), d("10000")),
|
||||
Some(d("3086.4195"))
|
||||
);
|
||||
assert_eq!(Amount::checked_div_exact(d("1"), d("0")), None);
|
||||
}
|
||||
@@ -335,8 +335,8 @@ fn ten_places_each_is_exact_through_the_engine() {
|
||||
/// 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
|
||||
/// 0.00); `Decimal` rounded the product to 28 places first and the
|
||||
/// kernel booked 0.01 (K-U10: it now books 0.00 too). 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() {
|
||||
@@ -355,8 +355,8 @@ fn past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses() {
|
||||
);
|
||||
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"
|
||||
Some(parse("0.00")),
|
||||
"outside D-75 too, the product is rounded once, from the exact one (K-U10)"
|
||||
);
|
||||
let (mut ledger, cash, entry) = usd_books();
|
||||
for (foreign, rate) in [
|
||||
@@ -376,17 +376,18 @@ fn past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses() {
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// D-75, closed by K-U10): 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` used to drop
|
||||
/// places from the product and the kernel rounded the already rounded
|
||||
/// value: 1050000010.0000000001 x 9.9999999999 is
|
||||
/// 10500000099.89499999999999999999 exactly, and 10500000099.89 to the
|
||||
/// cent, but `Decimal` held 10500000099.895 and the kernel booked
|
||||
/// 10500000099.90. The kernel now holds the exact product wide for its
|
||||
/// one rounding, so it books what the reference does, and `Amount`'s own
|
||||
/// product refuses what `Decimal` cannot hold (decimal_exact.rs).
|
||||
#[test]
|
||||
fn the_mantissa_edge_is_outside_the_precondition_and_pinned() {
|
||||
fn the_mantissa_edge_books_the_exact_products_cent() {
|
||||
let foreign = parse("1050000010.0000000001");
|
||||
let rate = parse("9.9999999999");
|
||||
assert_eq!(foreign.scale(), 10);
|
||||
@@ -403,6 +404,6 @@ fn the_mantissa_edge_is_outside_the_precondition_and_pinned() {
|
||||
);
|
||||
assert_eq!(
|
||||
fx_booked_minor(foreign, rate, Currency::USD, Rounding::HalfAwayFromZero),
|
||||
Some(parse("10500000099.90"))
|
||||
Some(parse("10500000099.89"))
|
||||
);
|
||||
}
|
||||
@@ -9,12 +9,14 @@
|
||||
// One file per kernel-sweep unit; the properties above stay here.
|
||||
mod allocate;
|
||||
mod control;
|
||||
mod decimal_exact;
|
||||
mod entries;
|
||||
mod fx;
|
||||
mod payroll;
|
||||
mod ratio;
|
||||
mod round;
|
||||
mod schedule;
|
||||
mod ties;
|
||||
mod total;
|
||||
|
||||
use ledger_core::kernel::{self, Amount, LineError};
|
||||
|
||||
@@ -242,16 +242,25 @@ fn the_edges() {
|
||||
// answer is not None, because the plug is exact; but the quotient
|
||||
// MAX / 2 = ...167.5 has 29 digits, so Decimal's division rounds it to
|
||||
// ...168 first, and the part is half a unit from the exact quotient,
|
||||
// a hundred steps at the cent: the K-U10 item, which is why the
|
||||
// callers refuse totals of 10^26 or more (EXACT_LIMIT).
|
||||
// a hundred steps at the cent: the K-U10 item (the division's, left
|
||||
// as it is), which is why the callers refuse totals of 10^26 or more
|
||||
// (EXACT_LIMIT). The sum of the parts is exact or refused (K-U10):
|
||||
// 599 parts of 1.3e26 at the cent need more than 96 bits at scale 2,
|
||||
// and `rust_decimal` used to round that sum.
|
||||
for months in [1usize, 2, 3, 7, 600] {
|
||||
for step in ["1", "0.01", "0.001"] {
|
||||
let parts = decimal_parts(widest, parse(step), months)
|
||||
.expect("MAX fits: the quotient is smaller, the last is the remainder");
|
||||
let parts = decimal_parts(widest, parse(step), months);
|
||||
if months == 600 && step != "1" {
|
||||
assert_eq!(
|
||||
parts, None,
|
||||
"{months} months at {step}: the sum is not exact"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let parts =
|
||||
parts.expect("MAX fits: the quotient is smaller, the last is the remainder");
|
||||
assert_eq!(
|
||||
parts
|
||||
.iter()
|
||||
.try_fold(Decimal::ZERO, |a, &b| a.checked_add(b)),
|
||||
kernel::total(parts.iter().copied()),
|
||||
Some(widest),
|
||||
"{months} months at {step}"
|
||||
);
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
//! K-U10: what ranking the leftover cents by the exact remainder moves.
|
||||
//!
|
||||
//! `split_by_weights_into` used to rank its largest remainders by
|
||||
//! `Decimal`'s rounded quotient (28 significant digits), so an exact tie
|
||||
//! was decided by the quotient's last digit; it now ranks the exact
|
||||
//! integer remainder `whole x weight - part x total`, ties to the earlier
|
||||
//! part. This file keeps the old ranking as a reference (`old_split`,
|
||||
//! built from the kernel's own public `share_of`, `round_places` and
|
||||
//! `apportion`, exactly as the kernel built it) and measures, over
|
||||
//! realistic inputs, how often the two differ and by how much. Run it
|
||||
//! with `--nocapture` to see the table the owner's decision rests on:
|
||||
//!
|
||||
//! ```text
|
||||
//! cargo test -p ledger-core --test kernel_bridge ties -- --nocapture
|
||||
//! ```
|
||||
//!
|
||||
//! Realistic inputs: whole-cent amounts up to 1,000,000.00, two to five
|
||||
//! parties, weights that are whole percentages or small integers.
|
||||
|
||||
use ledger_core::kernel::{
|
||||
Leftover, Rounding, apportion, round_places, share_of, split_by_weights_with,
|
||||
};
|
||||
use rust_decimal::Decimal;
|
||||
|
||||
fn cents(c: i64) -> Decimal {
|
||||
Decimal::new(c, 2)
|
||||
}
|
||||
|
||||
/// The ranking the kernel had before K-U10: each remainder is the rounded
|
||||
/// quotient less its rounded-down part.
|
||||
fn old_split(whole: Decimal, weights: &[Decimal], total: Decimal) -> Vec<Decimal> {
|
||||
let shares: Vec<Decimal> = weights
|
||||
.iter()
|
||||
.map(|&w| share_of(whole, w, total).unwrap())
|
||||
.collect();
|
||||
let mut parts: Vec<Decimal> = shares
|
||||
.iter()
|
||||
.map(|&s| round_places(s, 2, Rounding::TowardZero).unwrap())
|
||||
.collect();
|
||||
let rems: Vec<Decimal> = shares.iter().zip(&parts).map(|(s, p)| s - p).collect();
|
||||
apportion(whole, &mut parts, &rems, cents(1)).unwrap();
|
||||
parts
|
||||
}
|
||||
|
||||
fn new_split(whole: Decimal, weights: &[Decimal], total: Decimal) -> Vec<Decimal> {
|
||||
split_by_weights_with(
|
||||
whole,
|
||||
weights,
|
||||
total,
|
||||
cents(1),
|
||||
|x| round_places(x, 2, Rounding::TowardZero),
|
||||
Leftover::LargestRemainder,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// True when two parts have an equal exact remainder `whole x w - part x
|
||||
/// total` (before the leftover is handed out): the only place the two
|
||||
/// rankings can part.
|
||||
fn has_exact_tie(whole: Decimal, weights: &[Decimal], total: Decimal) -> bool {
|
||||
let rems: Vec<Decimal> = weights
|
||||
.iter()
|
||||
.map(|&w| {
|
||||
let share =
|
||||
round_places(share_of(whole, w, total).unwrap(), 2, Rounding::TowardZero).unwrap();
|
||||
// The exact floor: a quotient that rounded up across a cent is
|
||||
// taken back, as `share_floor_with` does.
|
||||
let mut part = share;
|
||||
while part * total > whole * w {
|
||||
part -= cents(1);
|
||||
}
|
||||
whole * w - part * total
|
||||
})
|
||||
.collect();
|
||||
(0..rems.len()).any(|i| (i + 1..rems.len()).any(|j| rems[i] == rems[j]))
|
||||
}
|
||||
|
||||
/// A small deterministic generator (xorshift64*): the sweep is the same on
|
||||
/// every machine and every run.
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Tally {
|
||||
runs: u64,
|
||||
differ: u64,
|
||||
max_moved_cents: i64,
|
||||
examples: Vec<String>,
|
||||
}
|
||||
|
||||
impl Tally {
|
||||
fn run(&mut self, whole: Decimal, weights: &[Decimal]) {
|
||||
let total: Decimal = weights.iter().copied().sum();
|
||||
let old = old_split(whole, weights, total);
|
||||
let new = new_split(whole, weights, total);
|
||||
self.runs += 1;
|
||||
// Both sum to the whole, exactly, whatever the ranking.
|
||||
assert_eq!(old.iter().copied().sum::<Decimal>(), whole);
|
||||
assert_eq!(new.iter().copied().sum::<Decimal>(), whole);
|
||||
if old == new {
|
||||
return;
|
||||
}
|
||||
self.differ += 1;
|
||||
// They differ only where an exact tie gave the ranking a choice,
|
||||
// and by at most one cent a part.
|
||||
assert!(
|
||||
has_exact_tie(whole, weights, total),
|
||||
"{whole} by {weights:?}: differ without an exact tie"
|
||||
);
|
||||
for (o, n) in old.iter().zip(&new) {
|
||||
let moved = ((o - n).abs() * Decimal::from(100)).trunc();
|
||||
let moved = i64::try_from(moved.mantissa()).unwrap();
|
||||
assert!(moved <= 1, "{whole} by {weights:?}: moved {moved} cents");
|
||||
self.max_moved_cents = self.max_moved_cents.max(moved);
|
||||
}
|
||||
if self.examples.len() < 3 {
|
||||
let show = |v: &[Decimal]| {
|
||||
v.iter()
|
||||
.map(|d| d.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" / ")
|
||||
};
|
||||
self.examples.push(format!(
|
||||
"{whole} by {} -> was {}, now {}",
|
||||
weights
|
||||
.iter()
|
||||
.map(|d| d.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("/"),
|
||||
show(&old),
|
||||
show(&new)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn report(&self, name: &str) {
|
||||
println!(
|
||||
"{name:<44} {:>8} runs {:>8} differ {:>7.3}% max {} cent/part",
|
||||
self.runs,
|
||||
self.differ,
|
||||
100.0 * self.differ as f64 / self.runs as f64,
|
||||
self.max_moved_cents
|
||||
);
|
||||
for e in &self.examples {
|
||||
println!(" e.g. {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const RUNS: u64 = 60_000;
|
||||
|
||||
/// A random whole of 0.01 to 1,000,000.00; `dollars` rounds it to whole
|
||||
/// dollars (round amounts are the realistic ones, and tie more).
|
||||
fn random_whole(rng: &mut Rng, dollars: bool) -> Decimal {
|
||||
let c = 1 + rng.below(100_000_000) as i64;
|
||||
if dollars {
|
||||
cents(((c + 99) / 100) * 100)
|
||||
} else {
|
||||
cents(c)
|
||||
}
|
||||
}
|
||||
|
||||
fn random_percentages(rng: &mut Rng) -> Vec<Decimal> {
|
||||
let n = 2 + rng.below(4) as usize;
|
||||
// A random composition of 100 into n positive whole percentages.
|
||||
let mut cuts: Vec<u64> = Vec::new();
|
||||
while cuts.len() < n - 1 {
|
||||
let c = 1 + rng.below(99);
|
||||
if !cuts.contains(&c) {
|
||||
cuts.push(c);
|
||||
}
|
||||
}
|
||||
cuts.sort_unstable();
|
||||
let mut prev = 0;
|
||||
let mut out = Vec::new();
|
||||
for c in cuts.iter().copied().chain(std::iter::once(100)) {
|
||||
out.push(Decimal::from(c - prev));
|
||||
prev = c;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn random_small_integers(rng: &mut Rng) -> Vec<Decimal> {
|
||||
let n = 2 + rng.below(4) as usize;
|
||||
(0..n).map(|_| Decimal::from(1 + rng.below(5))).collect()
|
||||
}
|
||||
|
||||
/// The splits an agreement is likely to name.
|
||||
const COMMON: &[&[i64]] = &[
|
||||
&[50, 50],
|
||||
&[60, 40],
|
||||
&[70, 30],
|
||||
&[75, 25],
|
||||
&[80, 20],
|
||||
&[90, 10],
|
||||
&[34, 33, 33],
|
||||
&[40, 30, 30],
|
||||
&[50, 25, 25],
|
||||
&[60, 20, 20],
|
||||
&[25, 25, 25, 25],
|
||||
&[40, 20, 20, 20],
|
||||
&[20, 20, 20, 20, 20],
|
||||
];
|
||||
|
||||
/// Equal weights: every remainder is `w x (whole - n x part)`, equal for
|
||||
/// every part, so both rankings give the leftover cents to the earliest
|
||||
/// parts and never differ. Two 50/50 members, thirds, quarters: no cent
|
||||
/// moves, ever.
|
||||
#[test]
|
||||
fn equal_weights_never_differ() {
|
||||
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
|
||||
let mut t = Tally::default();
|
||||
for i in 0..RUNS {
|
||||
let n = 2 + rng.below(4) as usize;
|
||||
let w = Decimal::from(1 + rng.below(100));
|
||||
let weights = vec![w; n];
|
||||
t.run(random_whole(&mut rng, i % 2 == 0), &weights);
|
||||
}
|
||||
t.report("equal weights (2-5 parties)");
|
||||
assert_eq!(t.differ, 0);
|
||||
}
|
||||
|
||||
/// Two parties never differ, whatever the weights. With two parts the
|
||||
/// leftover is at most one cent, and the two remainders sum to `total` times
|
||||
/// that cent, so they tie only at exactly half a cent over `total` each:
|
||||
/// both shares then end in exactly half a cent, the quotient terminates,
|
||||
/// and the rounded quotient ranks them as the exact one does. A two-member
|
||||
/// company (the live books' shape) is therefore unmoved by K-U10.
|
||||
#[test]
|
||||
fn two_parties_never_differ() {
|
||||
let mut rng = Rng(0x2545_F491_4F6C_DD1D);
|
||||
let mut t = Tally::default();
|
||||
for i in 0..RUNS {
|
||||
let weights = [
|
||||
Decimal::from(1 + rng.below(10_000)),
|
||||
Decimal::from(1 + rng.below(10_000)),
|
||||
];
|
||||
t.run(random_whole(&mut rng, i % 2 == 0), &weights);
|
||||
}
|
||||
// And the smallest weights, where ties are the most frequent.
|
||||
for a in 1..=12u64 {
|
||||
for b in 1..=12u64 {
|
||||
for c in 1..=300 {
|
||||
t.run(cents(c), &[Decimal::from(a), Decimal::from(b)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
t.report("two parties, any weights");
|
||||
assert_eq!(t.differ, 0);
|
||||
}
|
||||
|
||||
/// The measurement: how often the old and new rankings differ, by class
|
||||
/// of weights and of amount. Asserts only the structure (both sum to the
|
||||
/// whole; a difference needs an exact tie and is at most a cent a part);
|
||||
/// the rates are printed for the owner.
|
||||
#[test]
|
||||
fn what_exact_tie_ranking_moves() {
|
||||
println!();
|
||||
for dollars in [false, true] {
|
||||
let kind = if dollars {
|
||||
"whole dollars"
|
||||
} else {
|
||||
"any cents"
|
||||
};
|
||||
let mut rng = Rng(0xD1B5_4A32_D192_ED03);
|
||||
|
||||
let mut t = Tally::default();
|
||||
for _ in 0..RUNS {
|
||||
let w = random_percentages(&mut rng);
|
||||
t.run(random_whole(&mut rng, dollars), &w);
|
||||
}
|
||||
t.report(&format!("whole percentages, {kind}"));
|
||||
|
||||
let mut t = Tally::default();
|
||||
for _ in 0..RUNS {
|
||||
let w: Vec<Decimal> = COMMON[rng.below(COMMON.len() as u64) as usize]
|
||||
.iter()
|
||||
.map(|&p| Decimal::from(p))
|
||||
.collect();
|
||||
t.run(random_whole(&mut rng, dollars), &w);
|
||||
}
|
||||
t.report(&format!("common agreements, {kind}"));
|
||||
|
||||
let mut t = Tally::default();
|
||||
for _ in 0..RUNS {
|
||||
let w = random_small_integers(&mut rng);
|
||||
t.run(random_whole(&mut rng, dollars), &w);
|
||||
}
|
||||
t.report(&format!("small integers 1-5, {kind}"));
|
||||
}
|
||||
// The K-1 property split's real shape: weights are the members'
|
||||
// credits in one entry (whole dollars to 10,000), the whole at most
|
||||
// their sum.
|
||||
let mut rng = Rng(0xA076_1D64_78BD_642F);
|
||||
let mut t = Tally::default();
|
||||
for _ in 0..RUNS {
|
||||
let n = 2 + rng.below(4) as usize;
|
||||
let w: Vec<Decimal> = (0..n)
|
||||
.map(|_| Decimal::from(1 + rng.below(10_000)))
|
||||
.collect();
|
||||
let total: Decimal = w.iter().copied().sum();
|
||||
let pool = cents(1 + rng.below(total.mantissa() as u64 * 100) as i64);
|
||||
t.run(pool, &w);
|
||||
}
|
||||
t.report("K-1 credits, whole dollars to 10,000");
|
||||
// The 4/1/1 shape, every whole-dollar amount to 100.
|
||||
let mut t = Tally::default();
|
||||
for d in 1..=100 {
|
||||
t.run(
|
||||
Decimal::from(d),
|
||||
&[Decimal::from(4), Decimal::ONE, Decimal::ONE],
|
||||
);
|
||||
}
|
||||
t.report("4/1/1, $1 to $100 whole dollars");
|
||||
}
|
||||
|
||||
/// The pinned examples, in dollars and cents, with both answers.
|
||||
#[test]
|
||||
fn the_pinned_examples_move_as_the_owner_was_told() {
|
||||
let w = [Decimal::from(4), Decimal::ONE, Decimal::ONE];
|
||||
let six = Decimal::from(6);
|
||||
let show = |v: Vec<Decimal>| v.iter().map(Decimal::to_string).collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
show(old_split(cents(2000), &w, six)),
|
||||
["13.33", "3.34", "3.33"]
|
||||
);
|
||||
assert_eq!(
|
||||
show(new_split(cents(2000), &w, six)),
|
||||
["13.34", "3.33", "3.33"]
|
||||
);
|
||||
}
|
||||
|
||||
/// Weights of `places` places that sum to `total` exactly: `n - 1` of
|
||||
/// `total / n` rounded down, and a last one taking what is left. Built on
|
||||
/// the mantissas: `Decimal` cannot hold the running sum of percents of 27
|
||||
/// places (88.888...8 has 29 digits and passes its 96 bits), and would
|
||||
/// round it without a word, which is the fault K-U10 closed in the kernel.
|
||||
fn even_weights(total: i128, n: u32, places: u32) -> Vec<Decimal> {
|
||||
let whole = total * 10i128.pow(places);
|
||||
let w = whole / i128::from(n);
|
||||
let last = whole - w * i128::from(n - 1);
|
||||
let mut weights = vec![Decimal::from_i128_with_scale(w, places); n as usize];
|
||||
*weights.last_mut().unwrap() = Decimal::from_i128_with_scale(last, places);
|
||||
assert_eq!(weights.iter().map(Decimal::mantissa).sum::<i128>(), whole);
|
||||
weights
|
||||
}
|
||||
|
||||
/// K-U10 made the kernel's product exact or refused. A split by shares
|
||||
/// of 28 places that sum to one (as a convention's shares do) or by
|
||||
/// percents of 27 places that sum to 100 (thirds, sevenths, ninths) has
|
||||
/// products past `Decimal`'s 28 digits, so the ranking uses the rounding
|
||||
/// product there: the split is made, not refused, the parts sum to the
|
||||
/// whole, and each is within a cent of its share. A negative whole is
|
||||
/// rounded down, as apportioning requires (the parts rounded toward zero
|
||||
/// would pass the whole, which `apportion` refuses).
|
||||
#[test]
|
||||
fn a_split_by_weights_of_27_places_is_made_not_refused() {
|
||||
let cent = cents(1);
|
||||
for (total, places) in [(1i128, 28u32), (100, 27)] {
|
||||
for n in [3u32, 6, 7, 9, 11] {
|
||||
let weights = even_weights(total, n, places);
|
||||
let total = Decimal::from_i128_with_scale(total, 0);
|
||||
let amounts = (1..=400_000i64)
|
||||
.step_by(37)
|
||||
.chain([23_769, 99_999_999_999_999_999, 100_000_000_000_000_000])
|
||||
.flat_map(|c| [c, -c]);
|
||||
for c in amounts {
|
||||
let whole = cents(c);
|
||||
let mode = if c < 0 {
|
||||
Rounding::TowardNegativeInfinity
|
||||
} else {
|
||||
Rounding::TowardZero
|
||||
};
|
||||
let parts = split_by_weights_with(
|
||||
whole,
|
||||
&weights,
|
||||
total,
|
||||
cent,
|
||||
|x| round_places(x, 2, mode),
|
||||
Leftover::LargestRemainder,
|
||||
)
|
||||
.unwrap_or_else(|| panic!("{whole} by {n} parts of {places} places was refused"));
|
||||
assert_eq!(
|
||||
parts.iter().copied().sum::<Decimal>(),
|
||||
whole,
|
||||
"{whole} by {n}"
|
||||
);
|
||||
for (p, &wt) in parts.iter().zip(&weights) {
|
||||
let share = share_of(whole, wt, total).unwrap();
|
||||
assert!(
|
||||
(*p - share).abs() < cent,
|
||||
"{whole} by {n}: {p} for a share of {share}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,23 +121,22 @@ fn decimal_edge_table() {
|
||||
);
|
||||
}
|
||||
|
||||
/// FINDING (K-U4), pinned as a canary: `rust_decimal` rounds sub-unit dust
|
||||
/// away when a sum lands on `Decimal::MAX`, so `Amount::checked_add` for
|
||||
/// `Decimal` is not exact at the very edge (`MAX + 0.4 = MAX`, but `MAX +
|
||||
/// 0.5` is `None`). The kernel's "exact or `None`" contract (and `total`'s
|
||||
/// invariant 2) therefore holds for `Decimal` everywhere except figures
|
||||
/// within one unit of `Decimal::MAX` (~7.9 x 10^28, 10^13 times a journal
|
||||
/// line's cap). The fix belongs in `impl Amount for Decimal`
|
||||
/// (`kernel/entries.rs`), not in `total`; when it lands this test fails
|
||||
/// and is flipped to expect `None`. See docs/proofs/k-u4.md.
|
||||
/// K-U4's finding, closed by K-U10: `rust_decimal` rounds sub-unit dust
|
||||
/// away when a sum lands on `Decimal::MAX` (`MAX + 0.4 = MAX`, but `MAX +
|
||||
/// 0.5` is `None`), so `Amount::checked_add` for `Decimal` was not "exact
|
||||
/// or `None`" within one unit of `Decimal::MAX`. `impl Amount for Decimal`
|
||||
/// now checks the sum is the exact one, so `total`'s invariant 2 holds
|
||||
/// there too: the rounded sum is refused. See docs/proofs/k-u4.md and
|
||||
/// k-u10.md.
|
||||
#[test]
|
||||
fn finding_decimal_add_rounds_dust_at_the_edge() {
|
||||
fn a_sum_past_exact_arithmetic_is_refused() {
|
||||
let max = Decimal::MAX;
|
||||
let dust = Decimal::new(4, 1);
|
||||
assert_eq!(
|
||||
kernel::total([max, dust]),
|
||||
rust_decimal::Decimal::checked_add(max, dust),
|
||||
Some(max),
|
||||
"rust_decimal rounds the 0.4 away"
|
||||
"rust_decimal rounds the 0.4 away; the kernel does not"
|
||||
);
|
||||
assert_eq!(kernel::total([max, dust]), None);
|
||||
assert_eq!(kernel::total([max, Decimal::new(5, 1)]), None);
|
||||
}
|
||||
Reference in new issue
Block a user