merge: one rounding primitive, round_step, in the kernel, proved for every mode (K-U2; branch t3/kernel-round-step-primitive, f0a5d107; reviewed, fixes applied)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-11-08 14:04:40 -07:00
commit f77eaa515a
15 files changed
+1203 -46

No files matched your search

+3 -2
View File
@@ -1720,8 +1720,9 @@ fn split_part(
let part = amount
.checked_mul(ours)
.and_then(|x| x.checked_div(whole))
.ok_or_else(|| too_large("a payment's government part"))?
.round_dp_with_strategy(places, rust_decimal::RoundingStrategy::MidpointNearestEven);
.ok_or_else(|| too_large("a payment's government part"))?;
let part = crate::kernel::round_places(part, places, crate::kernel::Rounding::HalfToEven)
.ok_or_else(|| too_large("a payment's government part"))?;
let rest = amount
.checked_sub(part)
.ok_or_else(|| too_large("a payment's government part"))?;
+3 -3
View File
@@ -454,7 +454,7 @@ pub fn check_id(id: &str) -> Result<(), String> {
/// ([`crate::kernel::apportion`]): the parts sum to `amount` exactly
/// (INVARIANT 2).
pub fn split(amount: Decimal, shares: &[Decimal], places: Option<u32>) -> Option<Vec<Decimal>> {
use rust_decimal::RoundingStrategy::ToZero;
use crate::kernel::{Rounding, round_places};
let exact: Vec<Decimal> = shares
.iter()
.map(|s| amount.checked_mul(*s))
@@ -466,8 +466,8 @@ pub fn split(amount: Decimal, shares: &[Decimal], places: Option<u32>) -> Option
};
let mut parts: Vec<Decimal> = exact
.iter()
.map(|e| e.round_dp_with_strategy(places, ToZero))
.collect();
.map(|e| round_places(*e, places, Rounding::TowardZero))
.collect::<Option<_>>()?;
let remainders: Vec<Decimal> = exact
.iter()
.zip(&parts)
+7 -2
View File
@@ -728,7 +728,11 @@ fn vendor_part(payment: Decimal, share: Decimal, target: Decimal) -> Result<Deci
"a vendor's share ({share}) of a payment of {payment}"
))
})?;
Ok(scaled.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::MidpointAwayFromZero))
kernel::round_places(scaled, 2, kernel::Rounding::HalfAwayFromZero).ok_or_else(|| {
LedgerError::TooLargeToCompute(format!(
"a vendor's share ({share}) of a payment of {payment}"
))
})
}
}
@@ -761,7 +765,8 @@ fn split_share(b: [Decimal; 3], v: Decimal) -> Result<[Decimal; 3], LedgerError>
// exactly (the division alone rounds past 28 digits).
let num = b[i].abs().checked_mul(av).ok_or_else(too_large)?;
let q = num.checked_div(ap).ok_or_else(too_large)?;
let mut part = q.round_dp_with_strategy(2, rust_decimal::RoundingStrategy::ToZero);
let mut part =
kernel::round_places(q, 2, kernel::Rounding::TowardZero).ok_or_else(too_large)?;
while times(part)? > num {
part -= cent;
}
+4 -3
View File
@@ -314,7 +314,7 @@ pub(crate) fn share_property(
credits: &[Decimal],
places: u32,
) -> Result<Vec<Decimal>, LedgerError> {
use rust_decimal::RoundingStrategy::ToZero;
use crate::kernel::{Rounding, round_places};
let too_large =
|| LedgerError::TooLargeToCompute("a member's share of contributed property".into());
let total = credits
@@ -334,8 +334,9 @@ pub(crate) fn share_property(
.ok_or_else(too_large)?;
let mut parts: Vec<Decimal> = exact
.iter()
.map(|x| x.round_dp_with_strategy(places, ToZero))
.collect();
.map(|x| round_places(*x, places, Rounding::TowardZero))
.collect::<Option<_>>()
.ok_or_else(too_large)?;
let remainders: Vec<Decimal> = exact.iter().zip(&parts).map(|(x, p)| x - p).collect();
crate::kernel::apportion(whole, &mut parts, &remainders, Decimal::new(1, places))
.expect("each part is short by under a unit, so the shortfall is under a unit per member");
+16
View File
@@ -2,6 +2,7 @@
//! grouping the lines of an entry or a book, unchanged in U0. The laws it
//! serves are listed at the module root, [`super`].
use super::round::Rounding;
use crate::assets::BasisRule;
use crate::{AccountType, Side};
use rust_decimal::Decimal;
@@ -41,6 +42,12 @@ pub trait Amount: Copy + Ord {
/// B-21), whose shares are added exactly and rounded once, never
/// share by share.
fn checked_div_round_cent(self, rhs: Self) -> Option<Self>;
/// `self` rounded to a whole multiple of `step`, in `mode`; `None`
/// when `step` is not positive or the result cannot be represented.
///
/// The instantiation of [`crate::kernel::round_step`], which the call
/// sites use; a machine integer is already a whole smallest unit.
fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option<Self>;
/// `self - rhs`, or `None` when it cannot be represented exactly.
fn checked_sub(self, rhs: Self) -> Option<Self> {
@@ -148,6 +155,9 @@ impl Amount for Decimal {
let signed = if negative { -signed_mag } else { signed_mag };
Decimal::try_from_i128_with_scale(signed, scale).ok()
}
fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option<Self> {
super::round::round_decimal_to_step(self, step, mode)
}
}
impl Amount for i32 {
@@ -196,6 +206,9 @@ impl Amount for i32 {
q.checked_sub(1)
}
}
fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option<Self> {
super::round::round_i32_to_step(self, step, mode)
}
}
impl Amount for i64 {
@@ -245,6 +258,9 @@ impl Amount for i64 {
q.checked_sub(1)
}
}
fn checked_round_to_step(self, step: Self, mode: Rounding) -> Option<Self> {
super::round::round_i64_to_step(self, step, mode)
}
}
/// Why the kernel rejected an entry's lines.
+293 -5
View File
@@ -1,5 +1,293 @@
//! U2: one rounding primitive, the single place money is rounded to a step (kernel sweep).
//!
//! Empty in U0: the unit adds its arithmetic here, in this file alone, so
//! no two sweep units ever edit the same file. The module root re-exports
//! it, keeping every path `crate::kernel::foo`.
//! The rounding primitive: money rounded to a whole multiple of a unit,
//! once, in a named mode. The kernel sweep's U2 (plan/kernel-sweep-audit.md
//! section 3) routes every `round_dp*`/`rescale` on money through it, so
//! the engine has one definition of "round" and no call site invents a
//! second.
use crate::Currency;
use crate::kernel::Amount;
use rust_decimal::Decimal;
/// How a value is rounded to a step. Only the modes the engine uses today
/// are here; a new mode is a new match arm in each [`Amount`]
/// instantiation, never a silent default.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Rounding {
/// Nearest multiple; an exact half rounds away from zero
/// (2.5 -> 3, -2.5 -> -3). The FX booking rule (B-3).
HalfAwayFromZero,
/// Nearest multiple; an exact half rounds to the even multiple
/// (2.5 -> 2, 3.5 -> 4). Rust's `Decimal::round_dp`.
HalfToEven,
/// Down in magnitude, toward zero (2.9 -> 2, -2.9 -> -2).
TowardZero,
/// Down, toward negative infinity (2.9 -> 2, -2.9 -> -3).
TowardNegativeInfinity,
}
/// `amount` rounded to a whole multiple of `step`, in `mode`.
///
/// ```text
/// GOAL: one rounding primitive: money is rounded to a whole multiple of a
/// unit, once, with the mode named at the call.
/// SOURCE: docs/spec/claims/ledger.md B-3 (a ledger in one money holds no
/// fractions of its smallest unit; FX books the base currency's
/// minor unit, half away from zero), claims/entry.md B-21 (exact
/// amounts in the books; round only where a rule says to), and
/// claims/ledger.md B-32; the call sites' own rules (B-13, B-14,
/// B-15, B-16, B-19, B-35, B-36, B-37); owner decision D-69 (the
/// laws live once, in bookspec's Lean).
/// INVARIANTS:
/// 1. Some(r) is a whole multiple of step: r = n x step for an integer
/// n, with step > 0. None when step <= 0 or nothing can hold the
/// result.
/// 2. HalfAwayFromZero and HalfToEven are nearest: |r - amount| <=
/// step/2; at exactly half, the mode's tie rule picks the multiple.
/// 3. TowardZero never increases magnitude: |r| <= |amount| and
/// |r - amount| < step.
/// 4. TowardNegativeInfinity is the floor: r <= amount < r + step.
/// 5. Idempotent: round(round(x)) = round(x) for the same step and mode.
/// 6. The symmetric modes (HalfAwayFromZero, HalfToEven, TowardZero) are
/// odd: round(-x) = -round(x). No mode ever flips the sign (a
/// non-zero amount never rounds to the other side of zero).
/// 7. Never a negative zero: a result that is zero is +0. Never a panic;
/// overflow and an impossible step are None.
/// SCENARIOS:
/// 1. IF 1.005 to the cent, HalfAwayFromZero: SHOULD be 1.01.
/// 2. IF 1.005 to the cent, HalfToEven: SHOULD be 1.00 (100 is even).
/// 3. IF -1.005 to the cent, TowardNegativeInfinity: SHOULD be -1.01.
/// 4. IF 0.004 to the cent, either half mode: SHOULD be 0 (not -0).
/// 5. IF the step is zero or negative: SHOULD be None, never a guess.
/// ```
pub fn round_step<T: Amount>(amount: T, step: T, mode: Rounding) -> Option<T> {
amount.checked_round_to_step(step, mode)
}
/// `amount` rounded to `places` decimal places in `mode`, exactly as
/// `Decimal::round_dp_with_strategy` does today: an amount carrying no
/// more places than `places` is returned unchanged, and otherwise the
/// result carries exactly `places` places. This is the behaviour-preserving
/// wrapper the call sites use while U2 proves `round_step` underneath
/// them; it is not a second rounding rule.
pub fn round_places(amount: Decimal, places: u32, mode: Rounding) -> Option<Decimal> {
if amount.is_zero() {
// Keep round_dp's scale, but never its negative zero.
return Decimal::try_from_i128_with_scale(0, amount.scale().min(places)).ok();
}
if amount.scale() <= places {
return Some(amount);
}
let step = Decimal::try_from_i128_with_scale(1, places).ok()?;
let rounded = round_step(amount, step, mode)?;
if rounded.is_zero() {
// Keep the places (a report prints "0.00"), never a negative zero.
return Decimal::try_from_i128_with_scale(0, places).ok();
}
let mut rounded = rounded;
if rounded.scale() != places {
// Round_dp_with_strategy returns the target scale even when the
// value is a whole multiple (1.200 at two places is 1.20), and
// round_step returns an exact multiple unchanged.
rounded.rescale(places);
}
Some(rounded)
}
/// `amount` rounded to whole `currency` minor units in `mode`: cents for
/// USD, whole yen for JPY, thousandths for KWD. A currency ISO 4217 gives
/// no minor unit (gold, SDRs) is returned exactly, as the FX booking rule
/// has always done (B-3).
pub fn round_minor(amount: Decimal, currency: Currency, mode: Rounding) -> Option<Decimal> {
match currency.minor_units() {
Some(places) => round_places(amount, places, mode),
None => Some(amount),
}
}
/// The `Decimal` instantiation of [`Amount::checked_round_to_step`]: exact
/// integer arithmetic on the two mantissas and scales, so no intermediate
/// `amount / step` is ever rounded by `Decimal`'s 28-digit division. The
/// quotient is rounded in integer space and multiplied by the step's
/// mantissa once; reduction by trailing zeros (as in
/// `checked_div_round_cent`) makes the result fit Decimal's 96-bit
/// mantissa when the value allows it.
pub(crate) fn round_decimal_to_step(
amount: Decimal,
step: Decimal,
mode: Rounding,
) -> Option<Decimal> {
if step <= Decimal::ZERO {
return None;
}
if amount.is_zero() {
return Some(Decimal::ZERO);
}
let negative = amount.is_sign_negative();
let a = amount.mantissa().unsigned_abs();
let b = step.mantissa().unsigned_abs();
let exponent = i64::from(step.scale()) - i64::from(amount.scale());
// An exact multiple is already rounded. That case also covers the one
// the integer quotient cannot name: a step far finer than the amount
// (1e28 as 1e-20 steps is a 48-digit count, but the value is 1e28).
if is_exact_multiple(a, b, exponent) {
return Some(amount);
}
let (mut floor, round_up) = if exponent >= 0 {
let exp = u32::try_from(exponent).ok()?;
let power = 10u128.checked_pow(exp)?;
let whole = a / b;
let mut remainder = a % b;
let mut fraction = 0u128;
for _ in 0..exp {
remainder = remainder.checked_mul(10)?;
fraction = fraction.checked_mul(10)?.checked_add(remainder / b)?;
remainder %= b;
}
let floor = whole.checked_mul(power)?.checked_add(fraction)?;
let twice = remainder.checked_mul(2)?;
let round_up = match mode {
Rounding::TowardZero => false,
Rounding::TowardNegativeInfinity => negative && remainder != 0,
Rounding::HalfAwayFromZero => twice >= b,
Rounding::HalfToEven => twice > b || (twice == b && !floor.is_multiple_of(2)),
};
(floor, round_up)
} else {
let places = u32::try_from(-exponent).ok()?;
let power = 10u128.checked_pow(places)?;
let quotient = a / b;
let remainder = a % b;
let digit = quotient % power;
let floor = quotient / power;
let twice = digit.checked_mul(2)?;
let round_up = match mode {
Rounding::TowardZero => false,
Rounding::TowardNegativeInfinity => negative && (digit != 0 || remainder != 0),
Rounding::HalfAwayFromZero => twice >= power,
Rounding::HalfToEven => {
twice > power || (twice == power && (remainder != 0 || !floor.is_multiple_of(2)))
}
};
(floor, round_up)
};
if round_up {
floor = floor.checked_add(1)?;
}
let mut mantissa = floor.checked_mul(b)?;
if mantissa == 0 {
// Never a negative zero: money never prints "-0".
return Some(Decimal::ZERO);
}
let max = Decimal::MAX.mantissa().unsigned_abs();
let mut scale = step.scale();
while mantissa > max {
if scale == 0 || !mantissa.is_multiple_of(10) {
return None;
}
mantissa /= 10;
scale -= 1;
}
let signed = i128::try_from(mantissa).ok()?;
let signed = if negative { -signed } else { signed };
Decimal::try_from_i128_with_scale(signed, scale).ok()
}
/// True when `a x 10^exponent` (or `a / 10^-exponent`) is a whole multiple
/// of `b`, without ever materialising the product: only remainders below
/// `b` (under Decimal's 96-bit mantissa) are multiplied by ten.
fn is_exact_multiple(a: u128, b: u128, exponent: i64) -> bool {
if exponent >= 0 {
let mut remainder = a % b;
for _ in 0..exponent {
if remainder == 0 {
return true;
}
remainder = (remainder * 10) % b;
}
remainder == 0
} else {
let places = u32::try_from(-exponent).unwrap_or(u32::MAX);
let Some(power) = 10u128.checked_pow(places) else {
return false;
};
if !a.is_multiple_of(power) {
return false;
}
(a / power).is_multiple_of(b)
}
}
/// The `i64` instantiation: a machine integer is already a whole smallest
/// unit, so the step is a whole number of them (a Kani model, never money
/// with a fractional unit).
pub(crate) fn round_i64_to_step(value: i64, step: i64, mode: Rounding) -> Option<i64> {
if step <= 0 {
return None;
}
let negative = value < 0;
let magnitude = value.unsigned_abs();
let divisor = step.unsigned_abs();
let floor = magnitude / divisor;
let remainder = magnitude % divisor;
let twice = remainder.checked_mul(2)?;
let round_up = match mode {
Rounding::TowardZero => false,
Rounding::TowardNegativeInfinity => negative && remainder != 0,
Rounding::HalfAwayFromZero => twice >= divisor,
Rounding::HalfToEven => twice > divisor || (twice == divisor && !floor.is_multiple_of(2)),
};
let count = if round_up {
floor.checked_add(1)?
} else {
floor
};
let magnitude = count.checked_mul(divisor)?;
let limit = if negative {
1u64 << 63
} else {
i64::MAX as u64
};
if magnitude > limit {
return None;
}
let signed = magnitude as i64;
Some(if negative { -signed } else { signed })
}
/// The `i32` instantiation, the proof model's smaller type: the same rule
/// in 32 bits.
pub(crate) fn round_i32_to_step(value: i32, step: i32, mode: Rounding) -> Option<i32> {
if step <= 0 {
return None;
}
let negative = value < 0;
let magnitude = value.unsigned_abs();
let divisor = step.unsigned_abs();
let floor = magnitude / divisor;
let remainder = magnitude % divisor;
let twice = remainder.checked_mul(2)?;
let round_up = match mode {
Rounding::TowardZero => false,
Rounding::TowardNegativeInfinity => negative && remainder != 0,
Rounding::HalfAwayFromZero => twice >= divisor,
Rounding::HalfToEven => twice > divisor || (twice == divisor && !floor.is_multiple_of(2)),
};
let count = if round_up {
floor.checked_add(1)?
} else {
floor
};
let magnitude = count.checked_mul(divisor)?;
let limit = if negative {
1u32 << 31
} else {
i32::MAX as u32
};
if magnitude > limit {
return None;
}
let signed = magnitude as i32;
Some(if negative { -signed } else { signed })
}
+6 -5
View File
@@ -1871,11 +1871,12 @@ impl Ledger {
// away from zero: a ledger in one money holds no fractions of its
// smallest unit (rules.md B-3; DECISION, owner 2026-10-13, after
// the GnuCash cross-check found the difference).
let base_amount = match self.base_currency.minor_units() {
Some(dp) => exact
.round_dp_with_strategy(dp, rust_decimal::RoundingStrategy::MidpointAwayFromZero),
None => exact,
};
let base_amount = crate::kernel::round_minor(
exact,
self.base_currency,
crate::kernel::Rounding::HalfAwayFromZero,
)
.ok_or(LedgerError::AmountOutOfRange)?;
if base_amount <= Decimal::ZERO {
return Err(LedgerError::InvalidFxRate(fx_rate));
}
+15 -6
View File
@@ -124,12 +124,15 @@ pub fn allocate(
amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal],
) -> Vec<rust_decimal::Decimal> {
use rust_decimal::{Decimal, RoundingStrategy::ToZero};
use rust_decimal::Decimal;
let magnitude = amount.abs();
let exact: Vec<Decimal> = shares.iter().map(|s| magnitude * s).collect();
let mut parts: Vec<Decimal> = exact
.iter()
.map(|e| e.round_dp_with_strategy(2, ToZero))
.map(|e| {
crate::kernel::round_places(*e, 2, crate::kernel::Rounding::TowardZero)
.expect("a cent place of a representable amount is representable")
})
.collect();
let remainders: Vec<Decimal> = exact.iter().zip(&parts).map(|(e, p)| e - p).collect();
crate::kernel::apportion(magnitude, &mut parts, &remainders, Decimal::new(1, 2))
@@ -149,10 +152,13 @@ pub fn allocate_last_absorbs(
amount: rust_decimal::Decimal,
shares: &[rust_decimal::Decimal],
) -> Vec<rust_decimal::Decimal> {
use rust_decimal::RoundingStrategy::MidpointAwayFromZero;
use crate::kernel::{Rounding, round_places};
let mut parts: Vec<_> = shares
.iter()
.map(|s| (amount * s).round_dp_with_strategy(2, MidpointAwayFromZero))
.map(|s| {
round_places(amount * s, 2, Rounding::HalfAwayFromZero)
.expect("a cent place of a representable amount is representable")
})
.collect();
crate::kernel::plug_last(amount, &mut parts).expect("allocated amounts are in range");
parts
@@ -205,7 +211,8 @@ pub fn allocate_cumulative(
given: &[rust_decimal::Decimal],
places: u32,
) -> Result<Vec<rust_decimal::Decimal>, LedgerError> {
use rust_decimal::{Decimal, RoundingStrategy::ToZero};
use crate::kernel::{Rounding, round_places};
use rust_decimal::Decimal;
if shares.len() != given.len() {
return Err(LedgerError::InvalidMembers(format!(
"{} shares but {} earlier parts",
@@ -236,7 +243,9 @@ pub fn allocate_cumulative(
"a member's share {share} of {magnitude}, to its last digit,"
))
})?;
let floor = exact.round_dp_with_strategy(places, ToZero);
let floor = round_places(exact, places, Rounding::TowardZero).ok_or_else(|| {
LedgerError::TooLargeToCompute(format!("a member's share {share} of {magnitude}"))
})?;
parts.push(floor);
remainders.push(exact - floor);
}
+264 -3
View File
@@ -1,5 +1,266 @@
//! U2 proof harnesses: the rounding primitive (kernel sweep).
//!
//! Empty in U0: the unit adds its Kani harnesses here; `just prove` scans
//! every file in `proofs/`, so a harness needs no change to the module
//! root or the recipe.
//! `kernel::round_step` on `i64` money in the smallest unit: the result is
//! a whole multiple of the step; the half modes are nearest; each mode
//! breaks a tie as it says; rounding twice is rounding once; and the sign
//! never flips (so no zero is ever a negative zero).
//!
//! The steps are the fixed constants below rather than a symbolic `step`:
//! a symbolic divisor makes CBMC's bit-blasted division intractable (one
//! harness did not finish in 30 minutes). They cover one, an even step, an
//! odd step, a non-power-of-ten, a decimal step and a larger step; the
//! bridge's exact-reference property carries the same laws to every
//! `Decimal` step, and bookspec's Lean proves the law for any step. The
//! amount is symbolic up to [`VALUE`].
use crate::kernel::{Rounding, round_step};
use kani::cover;
/// Every amount the harnesses explore is within this magnitude.
const VALUE: i64 = 1 << 12;
/// The fixed steps: one, evens (a tie exists), odds, a non-power of ten,
/// a decimal step, and a step well above one.
const STEPS: [i64; 6] = [1, 2, 3, 7, 10, 101];
/// The even steps, where an exact half exists.
const EVEN_STEPS: [i64; 4] = [2, 4, 10, 100];
fn any_mode() -> Rounding {
let mode: u8 = kani::any();
kani::assume(mode < 4);
match mode {
0 => Rounding::HalfAwayFromZero,
1 => Rounding::HalfToEven,
2 => Rounding::TowardZero,
_ => Rounding::TowardNegativeInfinity,
}
}
fn any_half_mode() -> Rounding {
if kani::any() {
Rounding::HalfAwayFromZero
} else {
Rounding::HalfToEven
}
}
fn any_value() -> i64 {
let value: i64 = kani::any();
kani::assume(value >= -VALUE && value <= VALUE);
value
}
fn check_multiple(value: i64, step: i64, mode: Rounding) {
let rounded = round_step(value, step, mode).expect("no overflow under these bounds");
assert_eq!(rounded % step, 0, "a whole multiple of the step");
if value > 0 {
assert!(rounded >= 0, "a positive amount never rounds below zero");
} else if value < 0 {
assert!(rounded <= 0, "a negative amount never rounds above zero");
} else {
assert_eq!(rounded, 0, "zero rounds to zero");
}
}
/// The result is a whole multiple of the step, and it never crosses zero:
/// a positive amount rounds to a non-negative amount, a negative one to a
/// non-positive amount, and zero to zero.
#[kani::proof]
#[kani::unwind(8)]
fn round_step_is_multiple() {
let value = any_value();
let mode = any_mode();
for step in STEPS {
check_multiple(value, step, mode);
cover!(
step > 1 && value % step != 0,
"a non-multiple rounded to a step above one"
);
}
cover!(value.abs() % 101 > 1, "a non-multiple of a larger step");
}
fn check_nearest(value: i64, step: i64, mode: Rounding) {
let rounded = round_step(value, step, mode).expect("no overflow under these bounds");
let distance = (rounded - value).abs();
assert!(
2 * distance <= step,
"nearest: at most half a step away, a tie at exactly half"
);
}
/// The half modes are nearest: the result is within half a step of the
/// amount, ties included.
#[kani::proof]
#[kani::unwind(8)]
fn round_step_is_nearest() {
let value = any_value();
let mode = any_half_mode();
for step in STEPS {
check_nearest(value, step, mode);
}
cover!(value % 10 != 0, "a value that actually moves");
cover!(value.abs() % 10 == 5, "an exact tie (the mode decides it)");
cover!(value.abs() % 10 != 0 && value.abs() % 10 != 5, "a non-tie");
}
/// At an exact tie every mode picks the multiple its definition names.
/// The tie is built as `whole x step + step/2` (and its negation) with an
/// even fixed step, so it is exact in `i64` and both signs are reached.
#[kani::proof]
#[kani::unwind(8)]
fn round_step_ties() {
let whole: i64 = kani::any();
kani::assume(whole >= 0 && whole <= 64);
let negative: bool = kani::any();
for step in EVEN_STEPS {
let half = step / 2;
let magnitude = whole * step + half;
let value = if negative { -magnitude } else { magnitude };
let up = whole + 1;
let even = if whole % 2 == 0 { whole } else { up };
let cases = [
(Rounding::HalfAwayFromZero, up),
(Rounding::HalfToEven, even),
(Rounding::TowardZero, whole),
(
Rounding::TowardNegativeInfinity,
if negative { up } else { whole },
),
];
for (mode, pick) in cases {
let want = if negative {
-(pick * step)
} else {
pick * step
};
assert_eq!(
round_step(value, step, mode),
Some(want),
"each mode's tie rule"
);
}
}
cover!(!negative, "a positive tie");
cover!(negative, "a negative tie");
cover!(whole % 2 == 1, "HalfToEven rounds an odd floor up");
cover!(whole % 2 == 0, "HalfToEven keeps an even floor");
}
/// Rounding twice is rounding once, in every mode.
#[kani::proof]
#[kani::unwind(8)]
fn round_step_is_idempotent() {
let value = any_value();
let mode = any_mode();
for step in STEPS {
let once = round_step(value, step, mode).expect("no overflow under these bounds");
assert_eq!(round_step(once, step, mode), Some(once));
}
}
/// No negative zero and no sign flip: zero in gives zero out, and a result
/// that reaches zero only does so from an amount that rounds there.
#[kani::proof]
#[kani::unwind(8)]
fn round_step_never_negative_zero() {
let value = any_value();
let mode = any_mode();
for step in STEPS {
let rounded = round_step(value, step, mode).expect("no overflow under these bounds");
if value == 0 {
assert_eq!(rounded, 0);
}
if rounded == 0 {
assert!(
value.abs() < step,
"a zero is a rounding to the zero multiple"
);
}
assert!(
value == 0 || rounded == 0 || (rounded > 0) == (value > 0),
"the sign never flips"
);
}
cover!(
value % 3 != 0 || value % 10 != 0,
"a non-zero amount rounded to another multiple"
);
}
/// Toward zero never grows the magnitude and lands less than a step from
/// the amount: `|r| <= |x|` and `|r - x| < step`, for every amount (ties
/// are not special: both modes pick the same multiple whether or not the
/// amount is exactly between two).
#[kani::proof]
#[kani::unwind(8)]
fn round_step_toward_zero_bounds() {
let value = any_value();
for step in STEPS {
let rounded =
round_step(value, step, Rounding::TowardZero).expect("no overflow under these bounds");
assert!(rounded.abs() <= value.abs(), "magnitude never grows");
assert!((rounded - value).abs() < step, "less than a step away");
}
cover!(value % 10 != 0 && value > 0, "a positive non-multiple");
cover!(value % 10 != 0 && value < 0, "a negative non-multiple");
cover!(
value.abs() % 10 != 0 && value.abs() % 10 != 5,
"a non-tie, a non-multiple of ten"
);
}
/// Toward negative infinity is the floor: `r <= x < r + step`, for every
/// amount of either sign.
#[kani::proof]
#[kani::unwind(8)]
fn round_step_toward_neg_inf_is_floor() {
let value = any_value();
for step in STEPS {
let rounded = round_step(value, step, Rounding::TowardNegativeInfinity)
.expect("no overflow under these bounds");
assert!(rounded <= value, "never above the amount");
assert!(value < rounded + step, "less than a step below it");
}
cover!(value % 10 != 0 && value > 0, "a positive non-multiple");
cover!(
value % 10 != 0 && value < 0,
"a negative non-multiple (the floor moves away from zero)"
);
cover!(
value.abs() % 10 != 0 && value.abs() % 10 != 5,
"a non-tie, a non-multiple of ten"
);
}
/// No mode flips the sign: a non-negative amount rounds to a non-negative
/// one, and a non-positive amount to a non-positive one.
#[kani::proof]
#[kani::unwind(8)]
fn round_step_sign_preserved() {
let value = any_value();
let mode = any_mode();
for step in STEPS {
let rounded = round_step(value, step, mode).expect("no overflow under these bounds");
if value >= 0 {
assert!(rounded >= 0, "a non-negative amount stays non-negative");
}
if value <= 0 {
assert!(rounded <= 0, "a non-positive amount stays non-positive");
}
}
cover!(value > 0, "a positive amount");
cover!(value < 0, "a negative amount");
cover!(value == 0, "zero");
}
/// A step of zero or less is refused, never guessed at.
#[kani::proof]
fn round_step_refuses_nonpositive_step() {
let value = any_value();
let mode = any_mode();
for step in [0i64, -1, -7, i64::MIN] {
assert_eq!(round_step(value, step, mode), None);
}
cover!(value > 0, "a positive amount with a refused step");
}
+8 -4
View File
@@ -626,10 +626,14 @@ pub fn contribution_margin_pct(contribution: Decimal, revenue: Decimal) -> Optio
if revenue <= Decimal::ZERO {
return None;
}
let mut x = contribution
.checked_div(revenue)?
.checked_mul(Decimal::ONE_HUNDRED)?
.round_dp_with_strategy(1, rust_decimal::RoundingStrategy::MidpointNearestEven);
let mut x = crate::kernel::round_places(
contribution
.checked_div(revenue)?
.checked_mul(Decimal::ONE_HUNDRED)?,
1,
crate::kernel::Rounding::HalfToEven,
)?;
// Display padding only: the margin always prints its one place.
x.rescale(1);
Some(x)
}
+11 -4
View File
@@ -193,10 +193,17 @@ pub fn amortization_plan(
if total.abs() >= EXACT_LIMIT {
return Err(too_large());
}
let each = total
.checked_div(Decimal::from(months))
.ok_or_else(too_large)?
.round_dp(2);
// Two places whatever the currency: the monthly-even plan's cent rule is
// replay-frozen, and moving it to the currency's minor unit is K-U5
// (owner decision D-72), not this behaviour-preserving rounding unit.
let each = kernel::round_places(
total
.checked_div(Decimal::from(months))
.ok_or_else(too_large)?,
2,
kernel::Rounding::HalfToEven,
)
.ok_or_else(too_large)?;
let first = start
.with_day(1)
.ok_or(LedgerError::DateOutOfRange(start))?;
+2 -2
View File
@@ -284,7 +284,7 @@ fn checked_sum(values: impl IntoIterator<Item = Decimal>) -> Option<Decimal> {
/// part rounded toward zero to the cent, the cents left over to the first.
/// None when a product or sum is past exact arithmetic.
fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option<Vec<Decimal>> {
use rust_decimal::RoundingStrategy::ToZero;
use crate::kernel::{Rounding, round_places};
let total = checked_sum(weights.iter().copied())?;
if weights.is_empty() || total.is_zero() {
return Some(vec![Decimal::ZERO; weights.len()]);
@@ -295,7 +295,7 @@ fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option<Vec<Decimal>>
magnitude
.checked_mul(*w)
.and_then(|x| x.checked_div(total))
.map(|x| x.round_dp_with_strategy(2, ToZero))
.and_then(|x| round_places(x, 2, Rounding::TowardZero))
})
.collect::<Option<_>>()?;
let left = magnitude.checked_sub(checked_sum(parts.iter().copied())?)?;
+7 -5
View File
@@ -456,7 +456,7 @@ impl RunningSplit {
whole: Decimal,
weights: &[Decimal],
) -> Result<Vec<Decimal>, LedgerError> {
use rust_decimal::RoundingStrategy::ToNegativeInfinity;
use crate::kernel::{Rounding, round_places};
let n = self.given.len();
let Some(sum) = self.weight_sum(weights)? else {
return Ok(vec![Decimal::ZERO; n]);
@@ -482,12 +482,14 @@ impl RunningSplit {
// rounded down to the cent, what rounding took its remainder.
let snapped: Vec<Decimal> = exact
.iter()
.map(|x| (x * sign).round_dp(EXACT_PLACES))
.collect();
.map(|x| round_places(x * sign, EXACT_PLACES, Rounding::HalfToEven))
.collect::<Option<_>>()
.ok_or_else(too_large)?;
let mut parts: Vec<Decimal> = snapped
.iter()
.map(|x| x.round_dp_with_strategy(2, ToNegativeInfinity))
.collect();
.map(|x| round_places(*x, 2, Rounding::TowardNegativeInfinity))
.collect::<Option<_>>()
.ok_or_else(too_large)?;
let remainders: Vec<Decimal> = snapped.iter().zip(&parts).map(|(x, p)| x - p).collect();
let given: Vec<Decimal> = self.given.iter().map(|g| g * sign).collect();
crate::kernel::apportion_cumulative(
+388 -2
View File
@@ -1,4 +1,390 @@
//! U2 bridge properties: the rounding primitive (kernel sweep).
//!
//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here,
//! beside `main.rs` and the other units.
//! `proofs/round.rs` proves `round_step` on `i64` money in the smallest
//! unit; the engine runs the same code on `Decimal`. These properties check
//! that both instantiations agree, that `Decimal` agrees with an
//! independent integer reference on amounts of up to ten decimal places,
//! that the primitive reproduces `round_dp_with_strategy` exactly (the
//! behaviour U2 preserves), and the edge table: halves both ways, a
//! sub-half amount, a binary-looking 1.005, scale 28 and `Decimal::MAX`.
use ledger_core::kernel::{Rounding, round_step};
use proptest::prelude::*;
use rust_decimal::Decimal;
use rust_decimal::RoundingStrategy;
fn parse(text: &str) -> Decimal {
text.parse().expect("a decimal literal")
}
fn any_mode() -> impl Strategy<Value = Rounding> {
prop_oneof![
Just(Rounding::HalfAwayFromZero),
Just(Rounding::HalfToEven),
Just(Rounding::TowardZero),
Just(Rounding::TowardNegativeInfinity),
]
}
fn strategy(mode: Rounding) -> RoundingStrategy {
match mode {
Rounding::HalfAwayFromZero => RoundingStrategy::MidpointAwayFromZero,
Rounding::HalfToEven => RoundingStrategy::MidpointNearestEven,
Rounding::TowardZero => RoundingStrategy::ToZero,
Rounding::TowardNegativeInfinity => RoundingStrategy::ToNegativeInfinity,
}
}
/// An independent integer reference: `value x 10^-scale` rounded to a
/// whole multiple of `10^-places`, in `mode`, using only `i128` division
/// and remainder. Shares no code with the kernel.
fn reference(value: i128, scale: u32, places: u32, mode: Rounding) -> Option<Decimal> {
let common = scale.max(places);
let amount = value.checked_mul(10i128.checked_pow(common - scale)?)?;
let divisor = 10i128.checked_pow(common - places)?;
let negative = amount < 0;
let magnitude = amount.unsigned_abs();
let divisor = u128::try_from(divisor).ok()?;
let floor = magnitude / divisor;
let remainder = magnitude % divisor;
let twice = remainder.checked_mul(2)?;
let round_up = match mode {
Rounding::TowardZero => false,
Rounding::TowardNegativeInfinity => negative && remainder != 0,
Rounding::HalfAwayFromZero => twice >= divisor,
Rounding::HalfToEven => twice > divisor || (twice == divisor && !floor.is_multiple_of(2)),
};
let count = if round_up {
floor.checked_add(1)?
} else {
floor
};
let count = i128::try_from(count).ok()?;
Decimal::try_from_i128_with_scale(if negative { -count } else { count }, places).ok()
}
/// An independent integer reference for any step `mantissa x 10^-step_scale`
/// (not only a power of ten): both operands go to their common scale as
/// `i128`, the quotient and remainder come from `i128` division, and the
/// result `count x step` is reduced by trailing zeros to the smallest scale
/// that holds it. Shares no code with the kernel, and no digit loop.
fn reference_step(
value: i128,
scale: u32,
mantissa: i128,
step_scale: u32,
mode: Rounding,
) -> Option<Decimal> {
let common = scale.max(step_scale);
let amount = value.checked_mul(10i128.checked_pow(common - scale)?)?;
let step = mantissa.checked_mul(10i128.checked_pow(common - step_scale)?)?;
let negative = amount < 0;
let magnitude = amount.unsigned_abs();
let step = u128::try_from(step).ok()?;
let floor = magnitude / step;
let remainder = magnitude % step;
let twice = remainder.checked_mul(2)?;
let round_up = match mode {
Rounding::TowardZero => false,
Rounding::TowardNegativeInfinity => negative && remainder != 0,
Rounding::HalfAwayFromZero => twice >= step,
Rounding::HalfToEven => twice > step || (twice == step && !floor.is_multiple_of(2)),
};
let count = if round_up {
floor.checked_add(1)?
} else {
floor
};
let mut result = i128::try_from(count.checked_mul(step)?).ok()?;
let mut places = common;
while places > 0 && result % 10 == 0 && result != 0 {
result /= 10;
places -= 1;
}
if result == 0 {
places = 0;
}
let result = if negative { -result } else { result };
Decimal::try_from_i128_with_scale(result, places).ok()
}
/// Rounds `value x 10^-scale` to the step `mantissa x 10^-step_scale` with
/// the kernel and with the reference, and asserts they are the same value.
fn assert_matches_reference(
value: i128,
scale: u32,
mantissa: i128,
step_scale: u32,
mode: Rounding,
) -> Result<(), TestCaseError> {
let amount = Decimal::try_from_i128_with_scale(value, scale).expect("in Decimal's range");
let step = Decimal::try_from_i128_with_scale(mantissa, step_scale).expect("in range");
let want = reference_step(value, scale, mantissa, step_scale, mode);
prop_assert!(want.is_some(), "the reference fits for these ranges");
prop_assert_eq!(round_step(amount, step, mode), want);
Ok(())
}
/// The mantissas and scales of the finer-step tests: a step is any
/// `mantissa x 10^-scale`; a tie needs an even mantissa, so a tie row
/// builds its own.
fn step_parts() -> impl Strategy<Value = (i128, u32)> {
(1i128..=1000, 0u32..=10)
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(2000))]
/// The `i64` kernel (the Kani model) and the `Decimal` kernel (the
/// engine) agree on the same money in cents.
#[test]
fn i64_and_decimal_agree(
value in -(1i64 << 40)..=(1i64 << 40),
step in 1i64..=(1i64 << 20),
mode in any_mode(),
) {
let ours = round_step(value, step, mode).map(|r| Decimal::new(r, 2));
prop_assert_eq!(
ours,
round_step(Decimal::new(value, 2), Decimal::new(step, 2), mode)
);
}
/// The exact reference above, on books of up to ten decimal places and
/// steps from one to a ten-thousandth: the `Decimal` primitive is the
/// integer rounding, carried out exactly.
#[test]
fn decimal_matches_the_integer_reference(
value in -(1i128 << 60)..=(1i128 << 60),
scale in 0u32..=10,
places in 0u32..=4,
mode in any_mode(),
) {
let amount = Decimal::try_from_i128_with_scale(value, scale).expect("in Decimal's range");
let step = Decimal::new(1, places);
prop_assert_eq!(
round_step(amount, step, mode),
reference(value, scale, places, mode)
);
}
/// Steps that are not powers of ten: a mantissa 1..1000 at scales
/// 0..10 against amounts at scales 0..28, every mode, checked against
/// the independent reference. When the step carries more places than
/// the amount, the kernel's digit loop runs with a mantissa above one
/// (the finer-step branch); otherwise the coarser-step branch does.
#[test]
fn decimal_matches_the_reference_for_any_step(
value in -(1i128 << 60)..=(1i128 << 60),
scale in 0u32..=28,
(mantissa, step_scale) in step_parts(),
mode in any_mode(),
) {
assert_matches_reference(value, scale, mantissa, step_scale, mode)?;
}
/// Small amounts, so exact multiples are common: the same comparison.
#[test]
fn decimal_matches_the_reference_for_any_step_on_small_amounts(
value in -5000i128..=5000,
scale in 0u32..=12,
(mantissa, step_scale) in step_parts(),
mode in any_mode(),
) {
assert_matches_reference(value, scale, mantissa, step_scale, mode)?;
}
/// Exact ties: the amount is an odd number of half-steps, written with
/// up to three trailing zeros removed (so the step often has more
/// places than the amount). Every mode's tie rule against the reference.
#[test]
fn decimal_matches_the_reference_at_ties(
q in 0i128..=10_000,
half in 1i128..=100,
tens in 0u32..=3,
step_scale in 0u32..=10,
strip in 0u32..=3,
negative in any::<bool>(),
mode in any_mode(),
) {
let half = half * 10i128.pow(tens);
let mantissa = 2 * half;
let mut value = (2 * q + 1) * half;
let mut scale = step_scale;
for _ in 0..strip {
if scale > 0 && value % 10 == 0 {
value /= 10;
scale -= 1;
}
}
let value = if negative { -value } else { value };
assert_matches_reference(value, scale, mantissa, step_scale, mode)?;
}
/// Behaviour preservation: with a power-of-ten step, `round_step` is
/// exactly `round_dp_with_strategy`, the call sites' old primitive.
#[test]
fn round_step_is_round_dp_for_a_power_of_ten(
value in -(1i128 << 60)..=(1i128 << 60),
scale in 0u32..=10,
places in 0u32..=10,
mode in any_mode(),
) {
let amount = Decimal::try_from_i128_with_scale(value, scale).expect("in Decimal's range");
let mut want = amount.round_dp_with_strategy(places, strategy(mode));
// The kernel never returns a negative zero; Decimal's rounding can.
if want.is_zero() && want.is_sign_negative() {
want = Decimal::ZERO;
}
prop_assert_eq!(round_step(amount, Decimal::new(1, places), mode), Some(want));
}
/// And `round_places` matches it to the character: same value, same
/// scale, the call sites' exact output. (A negative zero becomes +0.)
#[test]
fn round_places_matches_round_dp_to_the_character(
value in -(1i128 << 60)..=(1i128 << 60),
scale in 0u32..=10,
places in 0u32..=10,
mode in any_mode(),
) {
let amount = Decimal::try_from_i128_with_scale(value, scale).expect("in Decimal's range");
let got = ledger_core::kernel::round_places(amount, places, mode).unwrap();
let want = amount.round_dp_with_strategy(places, strategy(mode));
if want.is_zero() {
prop_assert!(got.is_zero());
prop_assert!(!got.is_sign_negative());
} else {
prop_assert_eq!(got.to_string(), want.to_string());
}
}
}
/// The edge table, each row checked by hand.
#[test]
fn round_step_at_the_edges() {
let cent = parse("0.01");
// A half, both signs, in every mode.
assert_eq!(
round_step(parse("0.5"), cent, Rounding::HalfAwayFromZero),
Some(parse("0.50"))
);
assert_eq!(
round_step(parse("-0.5"), cent, Rounding::HalfAwayFromZero),
Some(parse("-0.50"))
);
assert_eq!(
round_step(parse("0.5"), cent, Rounding::HalfToEven),
Some(parse("0.50"))
);
assert_eq!(
round_step(parse("-0.5"), cent, Rounding::TowardNegativeInfinity),
Some(parse("-0.50"))
);
// Under half a cent: zero, and never a negative zero.
let tiny = round_step(parse("0.004"), cent, Rounding::HalfAwayFromZero).unwrap();
assert!(tiny.is_zero());
assert!(!tiny.is_sign_negative());
let tiny = round_step(parse("-0.004"), cent, Rounding::HalfToEven).unwrap();
assert!(tiny.is_zero());
assert!(!tiny.is_sign_negative());
// 1.005 is exactly a half at the cent (Decimal carries it exactly).
assert_eq!(
round_step(parse("1.005"), cent, Rounding::HalfAwayFromZero),
Some(parse("1.01"))
);
assert_eq!(
round_step(parse("1.005"), cent, Rounding::HalfToEven),
Some(parse("1.00"))
);
assert_eq!(
round_step(parse("-1.005"), cent, Rounding::HalfAwayFromZero),
Some(parse("-1.01"))
);
assert_eq!(
round_step(parse("-1.005"), cent, Rounding::HalfToEven),
Some(parse("-1.00"))
);
assert_eq!(
round_step(parse("-1.005"), cent, Rounding::TowardNegativeInfinity),
Some(parse("-1.01"))
);
// Scale 28: a whole multiple, and a tie at the last place.
let last = parse("0.0000000000000000000000000001");
let five = parse("0.0000000000000000000000000005");
assert_eq!(round_step(five, last, Rounding::HalfToEven), Some(five));
let two_last = parse("0.0000000000000000000000000002");
assert_eq!(
round_step(five, two_last, Rounding::HalfToEven),
Some(parse("0.0000000000000000000000000004"))
);
assert_eq!(
round_step(five, two_last, Rounding::HalfAwayFromZero),
Some(parse("0.0000000000000000000000000006"))
);
// Decimal's largest value is a whole multiple of a unit and a cent.
assert_eq!(
round_step(Decimal::MAX, Decimal::ONE, Rounding::HalfToEven),
Some(Decimal::MAX)
);
assert_eq!(
round_step(Decimal::MAX, cent, Rounding::HalfAwayFromZero),
Some(Decimal::MAX)
);
// A step that is not positive is refused.
assert_eq!(
round_step(Decimal::ONE, Decimal::ZERO, Rounding::HalfToEven),
None
);
assert_eq!(
round_step(Decimal::ONE, -Decimal::ONE, Rounding::HalfToEven),
None
);
}
/// `round_places` is the behaviour-preserving wrapper the call sites use:
/// it keeps `round_dp_with_strategy`'s scale and its early return.
#[test]
fn round_places_keeps_the_old_scale() {
use ledger_core::kernel::round_places;
assert_eq!(
round_places(parse("1.200"), 2, Rounding::HalfToEven),
Some(parse("1.20"))
);
assert_eq!(
round_places(parse("1.5"), 2, Rounding::HalfToEven),
Some(parse("1.5"))
);
let zero = round_places(parse("0.004"), 2, Rounding::HalfAwayFromZero).unwrap();
assert_eq!(zero.to_string(), "0.00");
assert!(!zero.is_sign_negative());
}
/// `round_minor` picks the currency's own unit; a currency with none is
/// returned exactly (the FX rule, B-3).
#[test]
fn round_minor_follows_the_currency() {
use ledger_core::Currency;
use ledger_core::kernel::round_minor;
assert_eq!(
round_minor(parse("1.2345"), Currency::USD, Rounding::HalfAwayFromZero),
Some(parse("1.23"))
);
assert_eq!(
round_minor(parse("1234.5"), Currency::JPY, Rounding::HalfAwayFromZero),
Some(parse("1235"))
);
assert_eq!(
round_minor(
parse("1.2345"),
Currency::new("KWD").unwrap(),
Rounding::HalfAwayFromZero
),
Some(parse("1.235"))
);
let gold = Currency::new("XAU").unwrap();
assert_eq!(
round_minor(parse("1.23456789"), gold, Rounding::HalfAwayFromZero),
Some(parse("1.23456789"))
);
}