diff --git a/crates/ledger-core/src/cashflow.rs b/crates/ledger-core/src/cashflow.rs index da271eb3..01ba2ba1 100644 --- a/crates/ledger-core/src/cashflow.rs +++ b/crates/ledger-core/src/cashflow.rs @@ -1716,15 +1716,20 @@ fn split_part( (ours, theirs): (Decimal, Decimal), places: u32, ) -> Result<(Decimal, Decimal), LedgerError> { - let whole = add(ours, theirs, "an entry's party shares")?; - let part = crate::kernel::share_of(amount, ours, whole) - .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"))?; - Ok((part, rest)) + // The shares' own sum fails with the party-shares message, as it did + // before the split moved into the kernel; the rest of the split's + // arithmetic keeps the government-part message. + add(ours, theirs, "an entry's party shares")?; + let step = Decimal::try_from_i128_with_scale(1, places) + .map_err(|_| too_large("a payment's government part"))?; + crate::kernel::split_ratio( + amount, + ours, + theirs, + step, + crate::kernel::Rounding::HalfToEven, + ) + .ok_or_else(|| too_large("a payment's government part")) } /// The codes of the accounts in some parts, sorted, once each. diff --git a/crates/ledger-core/src/kernel/ratio.rs b/crates/ledger-core/src/kernel/ratio.rs index 67943669..a4ad2719 100644 --- a/crates/ledger-core/src/kernel/ratio.rs +++ b/crates/ledger-core/src/kernel/ratio.rs @@ -1,5 +1,126 @@ -//! U6: ratios, percentages and averages that reports show (kernel sweep). +//! Percentages and ratio splits: `part ÷ whole × 100` rounded to a step, +//! and an amount split `a : b` with one side rounded and the other exact. +//! The kernel sweep's U6 (`plan/kernel-sweep-audit.md` section 3): the +//! contribution margin the projects page and the tools print, and the +//! government's part of an operating payment (BS-statement-3 statement 8). //! -//! 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`. +//! U3 already took the cash-flow government split's share through +//! [`super::share_of`]; [`split_ratio`] names the whole shape it has -- +//! the rounded part and the exact rest -- so the sum is proved, not +//! assumed. Division and multiplication are not exact at `Decimal`'s +//! edges (the 28-digit quotient and the 96-bit product): see +//! [`percent_of`]'s spec and `docs/proofs/k-u6.md` for what rounds +//! (K-U10). + +use super::{Amount, Rounding, round_step, share_of}; + +/// `part / whole × 100`, rounded to a whole multiple of `step` in `mode`; +/// `None` when `whole` is zero or negative (a percent of nothing, or of a +/// negative base, means nothing), when `step` is not positive, or when a +/// quotient or the product is not representable. +/// +/// ```text +/// GOAL: one definition of a percentage: the exact ratio times 100, +/// rounded once, at the step and mode the caller names. +/// SOURCE: docs/spec/claims/statement.md BS-statement-5 statement 2 (a +/// project's net is its revenue less its expenses) and +/// WB-statement-7 (that net as a percent of revenue: one place, +/// half to even, none without revenue), with BS-entry-3 (amounts +/// are exact; round only where a rule says to). +/// INVARIANTS: +/// 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). +/// 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. +/// 3. When the division and the product are exact (every posted +/// amount: the line cap is 10^15), r is the exact ratio times 100 +/// rounded once, so |r − exact| <= step/2 for the two half modes. +/// At Decimal's mantissa edge the quotient's own rounding can move +/// r by one more step (K-U10, pinned in the bridge). +/// 4. The percent carries the part's sign: a zero part is zero, a +/// positive part with a positive whole is not negative, a negative +/// part not positive. +/// SCENARIOS: +/// 1. IF 32,000 of 50,000: SHOULD be 64 at one place (the ratio 64%). +/// 2. IF 125 of 10,000 to one place, half to even: SHOULD be 1.2, not +/// 1.3. +/// 3. IF the whole is zero or negative: SHOULD be None, not a division +/// by zero and not a percent of a negative base. +/// 4. IF the part is past the amount's range: SHOULD be None, never a +/// panic. +/// ``` +pub fn percent_of(part: T, whole: T, step: T, mode: Rounding) -> Option { + if whole <= T::ZERO { + return None; + } + let hundred = T::from_u32(100)?; + let ratio = part.checked_div(whole)?.checked_mul(hundred)?; + round_step(ratio, step, mode) +} + +/// `amount` split as `a` to `b`: the `a` side is `amount × a ÷ (a + b)` +/// rounded to a whole multiple of `step` in `mode`, the `b` side the +/// exact rest, so the two always sum to `amount`; `None` for a negative +/// share, a non-positive `a + b`, a non-positive step, or an amount the +/// type cannot hold. +/// +/// ```text +/// GOAL: one definition of a ratio split: the named side rounded once, +/// the other side exact, and the two summing to the whole. +/// SOURCE: docs/spec/claims/statement.md BS-statement-3 statement 8 (of a +/// payment to a government, the government's part is rounded +/// half to even to the base currency's places and the rest is +/// exact, so the two always sum to the payment), BS-partner-1 +/// (a share of a whole by the parties' ratio), and BS-entry-3 +/// (round only where a rule says to). +/// INVARIANTS: +/// 1. Some((part, rest)): part = round_step(amount × a ÷ (a + b), step, +/// mode), the same share U3's `share_of` computes, rounded once; +/// rest = amount − part exactly, so part + rest = amount to the +/// last digit and no unit is lost or invented. +/// 2. part is a whole multiple of step. With 0 <= a <= a + b and +/// amount >= 0, 0 <= part <= amount; with a = 0 the part is zero +/// and the rest is the whole. +/// 3. None when a or b is negative, a + b <= 0, step <= 0, or a share, +/// part or rest is not representable. Never a panic: a zero ratio is +/// a refusal, not a division by zero. +/// 4. The split is odd in the amount for the symmetric modes: the parts +/// of −amount are the parts of amount negated. The rest keeps the +/// amount's sign whenever the part does. +/// 5. What rounds is the share's own arithmetic: for Decimal the +/// product and quotient round at 96 bits and 28 digits (K-U10), and +/// for a machine integer the division truncates; the rest is an +/// exact checked subtraction either way. +/// 6. The part's scale is the share's when it is already a whole +/// multiple of the step, and the step's otherwise; a caller that +/// needs a fixed scale rescales, as `contribution_margin_pct` does +/// for its one-place display. +/// SCENARIOS: +/// 1. IF −10.00 split 1 : 2 to the cent, half to even: SHOULD be +/// (−3.33, −6.67), and the two sum to −10.00. +/// 2. IF 0.05 split 1 : 1 to the cent, half to even: SHOULD be (0.02, +/// 0.03), never 0.03 and 0.02. +/// 3. IF 0.07 split 1 : 1 to the cent, half to even: SHOULD be (0.04, +/// 0.03). +/// 4. IF a and b are both zero: SHOULD be None, never a division by +/// zero. +/// ``` +pub fn split_ratio(amount: T, a: T, b: T, step: T, mode: Rounding) -> Option<(T, T)> { + if a < T::ZERO || b < T::ZERO { + return None; + } + let whole = a.checked_add(b)?; + if whole <= T::ZERO { + return None; + } + let part = round_step(share_of(amount, a, whole)?, step, mode)?; + let rest = amount.checked_sub(part)?; + // A checked subtraction can hand back a negative zero (the negated + // subtrahend keeps the sign bit); money's zero is always +0. + let rest = if rest == T::ZERO { T::ZERO } else { rest }; + Some((part, rest)) +} diff --git a/crates/ledger-core/src/proofs/ratio.rs b/crates/ledger-core/src/proofs/ratio.rs index 0708f480..84d15bff 100644 --- a/crates/ledger-core/src/proofs/ratio.rs +++ b/crates/ledger-core/src/proofs/ratio.rs @@ -1,5 +1,143 @@ -//! U6 proof harnesses: ratios (kernel sweep). +//! U6 proof harnesses: percentages and ratio splits (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::percent_of` and `kernel::split_ratio` on `i64`: a percent is +//! within half a step of the exact ratio, a percent of no whole is `None`, +//! and a ratio split's two parts sum to the whole exactly. +//! +//! The divisor is fixed in every harness. CBMC's bit-blasted division by +//! a symbolic `i64` did not finish in K-U2 (`docs/proofs/k-u2.md`), and +//! both functions divide by a whole. The percent harness fixes the whole +//! at eight and takes the part as a whole multiple of it, so the model's +//! division is exact: `part / 8 = k` and the exact percent is `100 × k`. +//! The model divides before it multiplies (the order the engine's call +//! site always used), and a machine integer's division truncates, so an +//! arbitrary part would lose its fraction before the percent was formed +//! and could be a hundred points from the exact ratio; `Decimal` keeps +//! that fraction, and the bridge checks every fractional ratio there +//! against an exact reference. The step is three, so the harness reaches +//! a percent that is not already a whole multiple (the truncating model +//! cannot represent a fraction of a percent, but it can round one). +//! +//! ```text +//! GOAL: a percent is the exact ratio times 100, rounded to the step; a +//! percent of a whole that is not positive is refused; a ratio +//! split's parts sum to the whole exactly. +//! SOURCE: BS-statement-5 statement 2 and WB-statement-7 (the project +//! margin: net over revenue, one place, half to even, none +//! without revenue), BS-statement-3 statement 8 (the +//! government's part rounded and the rest exact, the two summing +//! to the payment), BS-partner-1 (a share of a whole), and +//! BS-entry-3 (exact amounts; round only where a rule says to). +//! INVARIANTS: +//! 1. |r − 100 × part / whole| <= step/2 for the two half modes, where +//! the model's division is exact (the part a whole multiple of the +//! whole). +//! 2. A zero or negative whole is None for every part and mode; a +//! non-positive step is None too. +//! 3. split_ratio(amount, 1, 2, 3): the rounded part plus the exact rest +//! is the amount, and the part is a whole multiple of the step (three, +//! so the claim is not vacuous). +//! 4. Never a panic; an unrepresentable result is None. +//! SCENARIOS: +//! 1. IF the exact percent is not a whole multiple of the step: the +//! half modes take the nearest multiple, a tie to their own rule. +//! 2. IF the whole is zero: SHOULD be None. +//! 3. IF two parts of 1 : 2 are added: SHOULD be the amount, exactly. +//! ``` +//! +//! Bounds: parts -512 to 512 by whole multiples of eight, amounts -1,000 +//! to 1,000, every step 3 (the percent's and the split's). The laws are about the shape of the +//! arithmetic, not its magnitude; Lean proves the same laws of the exact +//! ratio at any size, and the bridge checks the `Decimal` engine against +//! an independent exact reference. + +use crate::kernel::{Rounding, percent_of, split_ratio}; + +/// The fixed whole the percent harness divides by. +const WHOLE: i64 = 8; +/// The fixed step: three percent points, so a rounded percent moves. +const STEP: i64 = 3; +/// The percent harness's quotient bound: `part = WHOLE × k`. +const QUOTIENT: i64 = 64; +/// The split harness's step: three units, so the part is a multiple of a +/// step that is not one and the divisibility claim has content. +const SPLIT_STEP: i64 = 3; + +fn any_half_mode() -> Rounding { + if kani::any() { + Rounding::HalfAwayFromZero + } else { + Rounding::HalfToEven + } +} + +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_part() -> i64 { + let part: i64 = kani::any(); + kani::assume((-QUOTIENT * WHOLE..=QUOTIENT * WHOLE).contains(&part)); + part +} + +/// The percent is within half a step of the exact ratio: with the part a +/// whole multiple of the whole, `100 × part / whole = 100 × k`, and the +/// two half modes put the percent within half a step of it. +#[kani::proof] +fn percent_of_within_half_step() { + let k: i64 = kani::any(); + kani::assume((-QUOTIENT..=QUOTIENT).contains(&k)); + let part = WHOLE * k; + let mode = any_half_mode(); + let r = percent_of(part, WHOLE, STEP, mode).expect("in range"); + let exact = 100 * k; + assert!( + 2 * (r - exact).abs() <= STEP, + "within half a step of 100 x part / whole" + ); + kani::cover!(exact % STEP != 0, "a percent that is not a whole multiple"); + kani::cover!(k < 0, "a negative part keeps its sign"); +} + +/// A percent of no whole is `None`: zero and negative wholes, and a step +/// that is not positive, refuse for every part and mode. +#[kani::proof] +fn percent_of_zero_whole_is_none() { + let part = any_part(); + let mode = any_mode(); + assert!(percent_of(part, 0, STEP, mode).is_none(), "zero whole"); + assert!( + percent_of(part, -WHOLE, STEP, mode).is_none(), + "negative whole" + ); + assert!(percent_of(part, WHOLE, 0, mode).is_none(), "zero step"); + kani::cover!(part != 0, "a nonzero part still has no percent of no whole"); +} + +/// A ratio split's parts sum to the whole exactly, and the rounded side is +/// a whole multiple of the step. +#[kani::proof] +fn split_ratio_sums() { + let amount: i64 = kani::any(); + kani::assume((-1_000..=1_000).contains(&amount)); + let mode = any_mode(); + let (part, rest) = split_ratio(amount, 1, 2, SPLIT_STEP, mode).expect("in range"); + assert_eq!(part + rest, amount, "the two parts sum to the whole"); + assert!( + part % SPLIT_STEP == 0, + "the rounded side is a whole multiple of the step" + ); + kani::cover!( + part * 3 != amount, + "the rounded side is not the exact share" + ); + kani::cover!(amount < 0, "a negative amount keeps its sign"); +} diff --git a/crates/ledger-core/src/reports.rs b/crates/ledger-core/src/reports.rs index b3769f90..1a2f88da 100644 --- a/crates/ledger-core/src/reports.rs +++ b/crates/ledger-core/src/reports.rs @@ -627,14 +627,10 @@ impl ProjectToDate { /// 3. NEVER panics: None when the quotient can't be represented. /// ``` pub fn contribution_margin_pct(contribution: Decimal, revenue: Decimal) -> Option { - if revenue <= Decimal::ZERO { - return None; - } - let mut x = crate::kernel::round_places( - contribution - .checked_div(revenue)? - .checked_mul(Decimal::ONE_HUNDRED)?, - 1, + let mut x = crate::kernel::percent_of( + contribution, + revenue, + Decimal::new(1, 1), crate::kernel::Rounding::HalfToEven, )?; // Display padding only: the margin always prints its one place. diff --git a/crates/ledger-core/tests/kernel_bridge/ratio.rs b/crates/ledger-core/tests/kernel_bridge/ratio.rs index 852b5784..bfb7b0ca 100644 --- a/crates/ledger-core/tests/kernel_bridge/ratio.rs +++ b/crates/ledger-core/tests/kernel_bridge/ratio.rs @@ -1,4 +1,391 @@ -//! U6 bridge properties: ratios (kernel sweep). +//! U6 bridge properties: percentages and ratio splits (kernel sweep). //! -//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, -//! beside `main.rs` and the other units. +//! `proofs/ratio.rs` proves `percent_of` and `split_ratio` on `i64` +//! (whole eight, unit step; a 1 : 2 split); the engine runs the same code +//! on `Decimal`. These properties check that the two instantiations agree +//! where the integer quotient is exact, that `Decimal` agrees with an +//! independent exact `i128` reference (integer numerator and denominator, +//! rounded by mode, sharing no code with the kernel and doing no `Decimal` +//! division at the reference), that a split's parts sum on every input, +//! and the edge table: a zero whole, a negative whole, `Decimal::MAX`, +//! scale 28, and a zero ratio, which must be `None` or exact, never a +//! panic. +//! +//! What rounds, stated plainly (the K-U10 item): `percent_of` divides +//! first (`Decimal`'s own division, exact where it terminates and +//! otherwise rounded at 28 significant digits), then multiplies by 100 +//! (a 96-bit product that can round), then rounds once to the step in +//! exact integer arithmetic. `split_ratio` multiplies before dividing +//! (`share_of`), so `Decimal`'s product can round first. For every figure +//! the call sites produce (lines are capped at 10^15), both operations are +//! exact and the reference agrees; at `Decimal`'s mantissa edge the +//! reference and the engine can differ, which is K-U10's to settle. + +use ledger_core::kernel::{self, Rounding}; +use proptest::prelude::*; +use rust_decimal::Decimal; + +fn mode(value: u8) -> Rounding { + match value { + 0 => Rounding::HalfAwayFromZero, + 1 => Rounding::HalfToEven, + 2 => Rounding::TowardZero, + _ => Rounding::TowardNegativeInfinity, + } +} + +fn step(places: u32) -> Decimal { + Decimal::try_from_i128_with_scale(1, places).expect("a step") +} + +fn power(exp: u32) -> Option { + 10i128.checked_pow(exp) +} + +/// The nearest integer to `num / den` in `mode`, as plain integer +/// arithmetic: no `Decimal` division and no kernel code. +fn rounded_quotient(num: i128, den: i128, mode: Rounding) -> Option { + if den <= 0 { + return None; + } + let negative = num < 0; + let magnitude = num.unsigned_abs(); + let divisor = den.unsigned_abs(); + let floor = magnitude / divisor; + let remainder = magnitude % divisor; + let twice = remainder.checked_mul(2)?; + let 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 up { floor.checked_add(1)? } else { floor }; + let count = i128::try_from(count).ok()?; + Some(if negative { -count } else { count }) +} + +/// The exact percent reference: `100 × part ÷ whole`, rounded to a whole +/// multiple of `step` in `mode`, from the four mantissas and scales. +fn percent_reference( + part_mantissa: i128, + part_scale: u32, + whole_mantissa: i128, + whole_scale: u32, + step_mantissa: i128, + step_scale: u32, + mode: Rounding, +) -> Option { + if whole_mantissa <= 0 || step_mantissa <= 0 { + return None; + } + // 100 x (pm 10^-ps) / (wm 10^-ws) / (sm 10^-ss) + // = (100 pm 10^(ws + ss)) / (wm 10^ps sm). + let exponent = whole_scale.checked_add(step_scale)?; + let numerator = 100i128 + .checked_mul(part_mantissa)? + .checked_mul(power(exponent)?)?; + let denominator = whole_mantissa + .checked_mul(power(part_scale)?)? + .checked_mul(step_mantissa)?; + let count = rounded_quotient(numerator, denominator, mode)?; + let mantissa = count.checked_mul(step_mantissa)?; + Decimal::try_from_i128_with_scale(mantissa, step_scale).ok() +} + +/// The exact first-part reference: `amount × a ÷ (a + b)`, rounded to a +/// whole multiple of `step` in `mode`. +fn split_first_reference( + amount_mantissa: i128, + amount_scale: u32, + a: i128, + b: i128, + step_mantissa: i128, + step_scale: u32, + mode: Rounding, +) -> Option { + let whole = a.checked_add(b)?; + if a < 0 || b < 0 || whole <= 0 || step_mantissa <= 0 { + return None; + } + // (am 10^-as) x a / whole / (sm 10^-ss) + // = (am a 10^ss) / (10^as whole sm). + let numerator = amount_mantissa + .checked_mul(a)? + .checked_mul(power(step_scale)?)?; + let denominator = power(amount_scale)? + .checked_mul(whole)? + .checked_mul(step_mantissa)?; + let count = rounded_quotient(numerator, denominator, mode)?; + let mantissa = count.checked_mul(step_mantissa)?; + Decimal::try_from_i128_with_scale(mantissa, step_scale).ok() +} + +fn arb_mode() -> impl Strategy { + (0u8..4).prop_map(mode) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(3000))] + + /// `Decimal`'s percent is the exact ratio times 100 rounded once, for + /// parts and wholes of every sign and scale, every mode and step. + #[test] + fn decimal_percent_matches_the_exact_reference( + part_mantissa in -(1_000_000_000i128)..=1_000_000_000i128, + part_scale in 0u32..=4, + whole_mantissa in 1i128..=1_000_000_000i128, + whole_scale in 0u32..=4, + step_mantissa in 1i128..=10_000i128, + step_scale in 0u32..=2, + mode in arb_mode(), + ) { + let part = Decimal::try_from_i128_with_scale(part_mantissa, part_scale).unwrap(); + let whole = Decimal::try_from_i128_with_scale(whole_mantissa, whole_scale).unwrap(); + let step = Decimal::try_from_i128_with_scale(step_mantissa, step_scale).unwrap(); + let want = percent_reference( + part_mantissa, part_scale, whole_mantissa, whole_scale, + step_mantissa, step_scale, mode, + ); + prop_assert_eq!(kernel::percent_of(part, whole, step, mode), want); + } + + /// The Kani model (whole percent points) and the engine (a `Decimal` + /// percent) agree wherever the integer quotient is exact, so + /// truncation moves nothing: `part = whole x factor` is `100 x + /// factor` percent exactly. + #[test] + fn i64_and_decimal_percent_agree_where_the_quotient_is_exact( + whole in 1i64..=1_000, + factor in -1_000i64..=1_000, + mode in arb_mode(), + ) { + let part = whole * factor; + let ours = kernel::percent_of(part, whole, 1, mode).unwrap(); + let theirs = kernel::percent_of( + Decimal::from(part), + Decimal::from(whole), + Decimal::ONE, + mode, + ) + .unwrap(); + prop_assert_eq!(Decimal::from(ours), theirs); + } + + /// A split's parts sum to the whole on every input, the rounded side + /// is a whole multiple of the step, and the rest is exact. + #[test] + fn decimal_split_sums( + amount_mantissa in -(1_000_000_000_000i128)..=1_000_000_000_000i128, + amount_scale in 0u32..=6, + a in 0i128..=1_000, + b in 0i128..=1_000, + step_mantissa in 1i128..=10_000i128, + step_scale in 0u32..=3, + mode in arb_mode(), + ) { + prop_assume!(a + b > 0); + let amount = Decimal::try_from_i128_with_scale(amount_mantissa, amount_scale).unwrap(); + let step = Decimal::try_from_i128_with_scale(step_mantissa, step_scale).unwrap(); + let (part, rest) = + kernel::split_ratio(amount, Decimal::from(a), Decimal::from(b), step, mode).unwrap(); + prop_assert_eq!(part + rest, amount); + prop_assert!((part % step).is_zero(), "the rounded side is a whole multiple"); + if rest.is_zero() { + prop_assert!(!rest.is_sign_negative(), "a zero rest is +0"); + } + if a == 0 { + prop_assert!(part.is_zero()); + prop_assert_eq!(rest, amount); + } + } + + /// `Decimal`'s first part is the exact ratio rounded once, for every + /// amount, ratio and step. + #[test] + fn decimal_split_matches_the_exact_reference( + amount_mantissa in -(1_000_000_000i128)..=1_000_000_000i128, + amount_scale in 0u32..=4, + a in 0i128..=100, + b in 0i128..=100, + step_mantissa in 1i128..=1_000i128, + step_scale in 0u32..=3, + mode in arb_mode(), + ) { + prop_assume!(a + b > 0); + let amount = Decimal::try_from_i128_with_scale(amount_mantissa, amount_scale).unwrap(); + let step = Decimal::try_from_i128_with_scale(step_mantissa, step_scale).unwrap(); + let want = split_first_reference( + amount_mantissa, amount_scale, a, b, step_mantissa, step_scale, mode, + ); + let (part, rest) = + kernel::split_ratio(amount, Decimal::from(a), Decimal::from(b), step, mode).unwrap(); + prop_assert_eq!(Some(part), want); + prop_assert_eq!(rest, amount - part); + } + + /// The Kani model in cents and the engine in dollars agree on a + /// 1 : 2 split wherever the integer quotient is exact (`amount` a + /// multiple of three). + #[test] + fn i64_and_decimal_split_agree_where_the_quotient_is_exact( + quotient in -100_000i64..=100_000, + mode in arb_mode(), + ) { + let amount_cents = 3 * quotient; + let (part_cents, rest_cents) = kernel::split_ratio(amount_cents, 1, 2, 1, mode).unwrap(); + let (part, rest) = kernel::split_ratio( + Decimal::new(amount_cents, 2), + Decimal::ONE, + Decimal::from(2), + step(2), + mode, + ) + .unwrap(); + prop_assert_eq!(part, Decimal::new(part_cents, 2)); + prop_assert_eq!(rest, Decimal::new(rest_cents, 2)); + } +} + +/// A percent of no whole is `None`, the whole being zero or negative, +/// and no ratio to split is `None` too: no division by zero, never a +/// panic. +#[test] +fn percent_of_refuses_no_whole() { + for mode in [ + Rounding::HalfAwayFromZero, + Rounding::HalfToEven, + Rounding::TowardZero, + Rounding::TowardNegativeInfinity, + ] { + assert_eq!( + kernel::percent_of(Decimal::ONE, Decimal::ZERO, step(1), mode), + None + ); + assert_eq!( + kernel::percent_of(Decimal::ONE, -Decimal::ONE, step(1), mode), + None + ); + assert_eq!( + kernel::percent_of(Decimal::ONE, Decimal::ONE, Decimal::ZERO, mode), + None + ); + assert_eq!( + kernel::percent_of(Decimal::ONE, Decimal::ONE, -step(1), mode), + None + ); + assert_eq!( + kernel::split_ratio(Decimal::ONE, Decimal::ZERO, Decimal::ZERO, step(2), mode), + None + ); + assert_eq!( + kernel::split_ratio(Decimal::ONE, Decimal::ONE, Decimal::from(2), -step(2), mode), + None + ); + assert_eq!( + kernel::split_ratio(Decimal::ONE, -Decimal::ONE, Decimal::from(2), step(2), mode), + None + ); + assert_eq!( + kernel::split_ratio( + Decimal::ONE, + Decimal::ONE, + Decimal::from(2), + Decimal::ZERO, + mode + ), + None + ); + } +} + +/// The edges: `Decimal::MAX`, scale 28, and a tiny whole. Each answer is +/// `None` or exact, never a panic. +#[test] +fn decimal_ratio_at_the_edges() { + // A part past the type's range: the product by 100 is not + // representable, so the percent refuses. + assert_eq!( + kernel::percent_of(Decimal::MAX, Decimal::ONE, step(1), Rounding::HalfToEven), + None + ); + // A tiny part at scale 28 is under a tenth of a percent: zero, never + // a negative zero. + let tiny = Decimal::try_from_i128_with_scale(1, 28).unwrap(); + let got = kernel::percent_of(tiny, Decimal::ONE, step(1), Rounding::HalfToEven).unwrap(); + assert!(got.is_zero() && !got.is_sign_negative()); + // A whole at scale 28 whose ratio is exactly one. + let hundred = kernel::percent_of(tiny, tiny, step(1), Rounding::HalfToEven).unwrap(); + assert_eq!(hundred, Decimal::ONE_HUNDRED); + // A whole past the type's range leaves a percent under a unit. + let under = kernel::percent_of(Decimal::ONE, Decimal::MAX, step(1), Rounding::HalfToEven) + .expect("a tiny percent is zero, not a refusal"); + assert!(under.is_zero()); + + // A split at the amount's edge either refuses or its parts sum; it + // never panics. + for (a, b) in [(1, 1), (1, 2), (2, 1), (0, 1)] { + if let Some((part, rest)) = kernel::split_ratio( + Decimal::MAX, + Decimal::from(a), + Decimal::from(b), + step(2), + Rounding::HalfToEven, + ) { + assert_eq!(part + rest, Decimal::MAX); + } + } + // A zero amount splits into two zero parts, and both are +0: a + // checked subtraction used to hand the rest back as -0, which equality + // hides but a sign test does not. + let (part, rest) = kernel::split_ratio( + Decimal::ZERO, + Decimal::ONE, + Decimal::from(2), + step(2), + Rounding::HalfToEven, + ) + .expect("a zero amount splits"); + assert_eq!((part, rest), (Decimal::ZERO, Decimal::ZERO)); + assert!(part.is_zero() && !part.is_sign_negative()); + assert!( + rest.is_zero() && !rest.is_sign_negative(), + "a zero rest is +0" + ); + + // The same for a negative-zero amount, whose sign bit a subtraction can + // carry: both parts come back +0. + let negative_zero = -Decimal::ZERO; + assert!(negative_zero.is_sign_negative()); + let (part, rest) = kernel::split_ratio( + negative_zero, + Decimal::ONE, + Decimal::from(2), + step(2), + Rounding::HalfToEven, + ) + .expect("a negative-zero amount splits"); + assert!(part.is_zero() && !part.is_sign_negative()); + assert!( + rest.is_zero() && !rest.is_sign_negative(), + "a zero rest is +0" + ); + + // A zero part over a positive whole is a zero percent, never -0. + let zero = kernel::percent_of( + Decimal::ZERO, + Decimal::from(2), + step(1), + Rounding::HalfToEven, + ) + .expect("a zero part has a percent"); + assert!(zero.is_zero() && !zero.is_sign_negative()); + let zero = kernel::percent_of( + negative_zero, + Decimal::from(2), + step(1), + Rounding::HalfToEven, + ) + .expect("a negative-zero part has a percent"); + assert!(zero.is_zero() && !zero.is_sign_negative()); +} diff --git a/docs/proofs/k-u6.md b/docs/proofs/k-u6.md new file mode 100644 index 00000000..fcf3669a --- /dev/null +++ b/docs/proofs/k-u6.md @@ -0,0 +1,196 @@ +# K-U6: percentages and ratios (`kernel/ratio.rs`) + +_Folded into `docs/verification.md` by the integrator; this note is the +unit's own record._ + +Kernel sweep unit U6 (`plan/kernel-sweep-audit.md` section 3). It serves +the contribution margin the projects page and the tools print +(BS-statement-5 statement 2, and wanderbooks' WB-statement-7), the +government's part of an operating payment (BS-statement-3 statement 8), +and the viewer's percentage columns (display only, untouched; see below). + +## What remained after K-U3 + +K-U3 already routed the cash-flow government split's share through +`kernel::share_of` (`cashflow::split_part`). What was still outside the +kernel: + +- `reports::contribution_margin_pct`: `contribution / revenue × 100`, + rounded to one place half to even, `None` without revenue. +- `cashflow::split_part`: the exact shape around `share_of` — the rounded + government part and the exact rest that sums to the payment. U3 had + the share, not the named law that the two parts sum. +- Display-only percentages in `ledger-gui` (`pages::profit::pct`, + `pages::reports`' change and share-of-income columns, `pages::capital`'s + share rendering, `fmt::pct_change`'s chart percentage). These are class + (b)/(c) in the audit: K-U9's display arithmetic, not kernel laws. They + were left, with why, below. +- `shares::Percent` shares are already weights through + `split_by_weights_with` (U3), and `tax::tax_summary`'s deductible + percentages are already `kernel::deductible_amount`; neither is a new + percent or ratio. + +## The API + +```rust +pub fn percent_of(part: T, whole: T, step: T, mode: Rounding) -> Option +pub fn split_ratio( + amount: T, a: T, b: T, step: T, mode: Rounding, +) -> Option<(T, T)> +``` + +`percent_of` is `part ÷ whole × 100`, division first (the order the +contribution-margin call site always used), rounded once with +`round_step`; `None` when the whole is zero or negative, the step is not +positive, or a quotient, product or result is not representable. + +`split_ratio` is `amount × a ÷ (a + b)` (`share_of`) rounded once with +`round_step`, and the exact rest `amount − part`; it refuses a negative +share, a non-positive ratio, a non-positive step, or an unrepresentable +part or rest. The two parts sum to the amount by construction, exactly. + +### What rounds, stated plainly (the K-U10 item) + +`percent_of` divides first (`Decimal`'s own division: exact where it +terminates, otherwise rounded at 28 significant digits), then multiplies +by 100 (a 96-bit product that can round), then rounds once to the step in +exact integer arithmetic. `split_ratio` multiplies before dividing +(`share_of`: product first, then quotient), so `Decimal`'s product can +round first. For every figure the call sites produce (lines are capped at +10^15), both operations are exact and the result is the exact ratio +rounded once; at `Decimal`'s mantissa edge the reference and the engine +can differ. Both roundings are K-U10's to settle, not silent behaviour +changes here. + +The `i64` model's division truncates *before* the percent's multiply, so +an arbitrary part could be a hundred points from the exact ratio. The Kani +percent harness therefore fixes the quotient exact (the part a whole +multiple of the whole); the bridge checks every fractional ratio on +`Decimal`, and Lean proves the exact-ratio law at any size. + +## Kani harnesses (`src/proofs/ratio.rs`) + +On `i64`, each with `kani::cover!`. The whole is fixed at 8 (both +functions divide by a whole or a ratio, and a symbolic divisor did not +finish in K-U2); the percent harness takes the part as `8 × k` so the +model's division is exact, and steps at 3 so a rounded percent moves. The +split is fixed at 1 : 2 with step 3 (so divisibility is not vacuous) and +the amount runs −1,000 to 1,000. + +| Harness | Law | Verification | +|---|---|---| +| `percent_of_within_half_step` | 44 | with the model's division exact (`part = 8 k`), the half modes put the percent within half a step of `100 k`; a percent not already a multiple of the step and a negative part are reached (2 covers). 7.4 s wall, 0.79 s verification | +| `percent_of_zero_whole_is_none` | 44 | a zero whole, a negative whole and a zero step are `None` for every part and mode; a nonzero part is reached (1 cover). 16.8 s wall, 0.13 s verification | +| `split_ratio_sums` | 44 | a 1 : 2 split at step 3: the rounded part plus its exact rest is the amount and the part is a whole multiple of the step, for positive and negative amounts; a part off the exact share and a negative amount are reached (2 covers). 3.1 s wall, 0.66 s verification | + +Times: `cargo kani -p ledger-core --exact --harness proofs::ratio::`, +the verifier's own verification time and the wall time including Kani's +build, the shared dev machine under `nice -n 15`, 2026-11-09. + +The bookspec law each harness proves (machine-readable for the +traceability gate, `crates/ledger-core/tests/bookspec/traceability.rs`): + +| Harness | Law | +|---|---| +| `percent_of_within_half_step` | 44 | +| `percent_of_zero_whole_is_none` | 44 | +| `split_ratio_sums` | 44 | + +## Bridge (`tests/kernel_bridge/ratio.rs`) + +- `i64_and_decimal_percent_agree_where_the_quotient_is_exact`: the Kani + model in whole percent points and the engine in `Decimal`, where + `part = whole × factor` divides exactly. +- `decimal_percent_matches_the_exact_reference`: an independent exact + `i128` reference (integer numerator over denominator, rounded by mode, + no kernel code and no `Decimal` division) for parts of every sign, + wholes greater than zero, four scales and any step. +- `i64_and_decimal_split_agree_where_the_quotient_is_exact`: a 1 : 2 + split in cents against the engine in dollars where the amount is a + multiple of three. +- `decimal_split_matches_the_exact_reference`: the first part is the + exact share rounded once, at any amount, ratio and step. +- `decimal_split_sums`: on every input the parts sum to the amount, the + rounded side is a whole multiple of the step, and a zero `a` share + leaves the whole to the rest. +- `percent_of_refuses_no_whole`: a zero or negative whole, a zero ratio + and a non-positive step are `None`, never a division by zero. A + negative step refuses both functions. +- `decimal_ratio_at_the_edges`: `Decimal::MAX` (a part past the range + refuses; a split either refuses or sums), scale 28 (a tiny part is + zero, no negative zero; a ratio of one is 100), a whole past the range + (a percent under a unit is zero), and a zero amount split whose two + parts are asserted to be `+0` (a checked subtraction once handed the + rest back as `-0`, which equality hides and a sign test does not). A + zero part over a positive whole is likewise a `+0` percent. + +All pass with the rest of `kernel_bridge`. + +## Lean (bookspec `lean/Bookspec/Ratio.lean`, law 44) + +`percent_near` (the percent is within half a step of the exact ratio, +`2 × |whole × percent − 100 × part| ≤ whole × step`, at any size), +`percent_zero`, `percent_sign`, `percent_neg`, `splitFirst_near` and +`splitRatio_sum`, with `whole_mul_percent` and `sum_mul_splitFirst` as +the exact-quotient lemmas. The model rounds `100 × part` to a multiple of +`whole × step` and divides by `whole` (exact, so the quotient is never +rounded twice), reusing `Round.near_halfEven`; it does not model +`Decimal`'s 28-digit division, which the bridge's exact reference carries. +The model is total where the kernel is partial: `splitRatio_sum` holds at +`a + b = 0` (there is no division), while the kernel returns `None` for +that ratio. +No `sorry`; `#print axioms` shows only `propext`, `Quot.sound` and +`Classical.choice`. + +BS-statement-5 links `percent_near`/`percent_zero`/`percent_sign` and +BS-statement-3 statement 8 links `splitRatio_sum`/`splitFirst_near` +(law 44 in `spec/laws.md`). + +## Sites routed and left + +Routed: + +- `reports::contribution_margin_pct` → `kernel::percent_of` with step + `0.1`, half to even; the display `rescale(1)` stays. The figures are + unchanged (the kernel computes the same division-first product). +- `cashflow::split_part` → `kernel::split_ratio` with the currency's + `10^-places` step, half to even; the shares' own sum still reports the + old "party shares" refusal, and the split's errors the government-part + one. The figures, including `−3.33/−6.67`, `0.02/0.03` and the reversal + mirror, are unchanged. + +Left, with why: + +- `ledger-gui::pages::profit::pct`: it computes the same percent for a + positive whole, but it also returns a percent for a *negative* whole + (a refund-heavy P&L month), where `percent_of` is `None` by the margin + rule. Routing it would change what is shown, so it stays display code + (K-U9). +- `ledger-gui::pages::reports`' change/share-of-income columns: same + reason (negative denominators are displayed today), and their rounding + is display `round_dp(1)`, K-U9's. +- `ledger-gui::pages::capital::percent`: `share × 100` with + `normalize()`, a stored ratio printed exactly, not `part / whole × + 100`; no rounding is taken. +- `ledger-gui::fmt::pct_change`: a chart's percentage change in `f64`, + not money and not a report figure (class (c)). +- `arap::percent_text`: basis points formatted as trade terms; integer + text, not a ratio. +- `shares::Percent` and `tax::tax_summary`: already kernel arithmetic + (U3's weights and `deductible_amount`). + +## Gates + +- `cargo test -p ledger-core`: all tests and every golden unchanged. It + passes against the `k-u6` bookspec branch (patched checker/runner); the + traceability gate alone fails against the still-pinned revision, because + law 44 is not in it yet, exactly as every K-U law before the integrator + moves the pin. +- `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`. +- Kani: the three harnesses above. +- The traceability gate against the merged `k-u6` bookspec branch (patched + checker/runner), with `Cargo.lock` restored afterwards: 62 kernel + functions (47 fully backed), 44 law rows, 133 claims sections, 1962 + backticked tokens; 15 exceptions, the pinned skipped set unchanged. +- bookspec: `lake build`, `lake env lean Audit.lean` (standard axioms), + `cargo test --workspace`, `render -- --check`, `scripts/spec-floors.sh main`.