diff --git a/crates/ledger-core/src/k1.rs b/crates/ledger-core/src/k1.rs index 7df03c34..6abaa601 100644 --- a/crates/ledger-core/src/k1.rs +++ b/crates/ledger-core/src/k1.rs @@ -34,7 +34,9 @@ //! 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, ties to the earlier member): each takes at +//! (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 //! 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 diff --git a/crates/ledger-core/src/kernel/allocate.rs b/crates/ledger-core/src/kernel/allocate.rs index 36e82d58..ece8d6ba 100644 --- a/crates/ledger-core/src/kernel/allocate.rs +++ b/crates/ledger-core/src/kernel/allocate.rs @@ -7,24 +7,31 @@ //! //! Division is not exact: [`share_of`] is the amount type's checked //! division, so a `Decimal` quotient is rounded at 28 significant digits -//! (and a machine integer's is truncated), never an exact rational. 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 one place the quotient's rounding can -//! change a rounded part (Decimal's edge, K-U10). +//! (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 +//! 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 +//! rounded part (Decimal's edge, K-U10). -use super::round::Rounding; -use super::{Amount, apportion, plug_last, round_step}; +use super::{Amount, apportion, plug_last}; /// What a split does with the units its rounded parts leave over. #[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 (ties to the earlier part). [`apportion`]. + /// 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`]. LargestRemainder, /// The last part becomes the whole less the others. [`plug_last`]. LastAbsorbs, - /// The first part becomes the whole less the others. + /// The first part becomes its rounded share plus the shortfall (the + /// whole less every rounded part), so its scale is the shortfall + /// addition's; the value is the whole less the others. FirstAbsorbs, } @@ -49,8 +56,9 @@ pub enum Leftover { /// 2. None when total is zero, or when the product or quotient is not /// representable. Never a panic, never a wrapped amount. /// 3. When total is not zero and whole x weight is representable, the -/// division is the only step that can round; a `Some` is always the -/// amount type's quotient, never a guessed one. +/// product and the division are the two steps that can round: either +/// `Decimal` operation rounds at its own edge. A `Some` is always the +/// amount type's quotient of its product, never a guessed one. /// SCENARIOS: /// 1. IF 100 by 40 of 100: SHOULD be 40. /// 2. IF 1 by 1 of 3: SHOULD be 0.333... (28 significant digits), not an @@ -70,9 +78,10 @@ pub fn share_of(whole: T, weight: T, total: T) -> Option { /// GOAL: the exact floor of a proportional share to a step, without /// trusting a rounded quotient, and the exact remainder that ranks /// the parts of a largest-remainder split. -/// SOURCE: BS-1099-1 (a payment split into its buckets to the cent), +/// SOURCE: BS-partner-1, BS-1099-1 (a payment split into its buckets to +/// the cent; partners share by the agreement), /// BS-entry-3 (amounts are exact; round only where a rule says -/// to), BS-partner-1 (largest remainder). +/// to). /// INVARIANTS: /// 1. whole and weight are non-negative (the callers pass magnitudes). /// Provided `part x total` and `(part + step) x total` are exact @@ -90,6 +99,10 @@ pub fn share_of(whole: T, weight: T, total: T) -> Option { /// the product's rounding). /// 3. None when step or total is not positive, a product is not /// representable, or the correction leaves the range; never a panic. +/// The correction takes at most [`MAX_CORRECTION_STEPS`] steps in +/// each direction and returns None past the cap: a malformed input +/// (one whose product's rounding put the estimate many steps away) +/// refuses rather than runs without end. /// SCENARIOS: /// 1. IF 60 x 33.33 / 100 to the cent: SHOULD be (19.99, 80), since /// 60 x 33.33 = 1999.80 and 19.99 x 100 = 1999. @@ -114,34 +127,39 @@ pub fn share_floor_with( // steps back until part x total <= num, then forward while one more // step still fits. The comparisons multiply, never divide; they are // exact while the product fits Decimal's mantissa (the edge is - // K-U10, pinned in the bridge). + // 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 { + if steps == MAX_CORRECTION_STEPS { + return None; + } + steps += 1; part = part.checked_sub(step)?; } + steps = 0; loop { + if steps == MAX_CORRECTION_STEPS { + return None; + } let next = part.checked_add(step)?; if next.checked_mul(total)? > num { break; } part = next; + steps += 1; } let remainder = num.checked_sub(part.checked_mul(total)?)?; Some((part, remainder)) } -/// [`share_floor_with`] with [`round_step`] as the first estimate: the -/// exact floor of `whole × weight ÷ total` to `step`, in `mode`'s -/// direction (only `TowardZero` is the floor; the correction makes the -/// result exact either way). -pub fn share_floor( - whole: T, - weight: T, - total: T, - step: T, - mode: Rounding, -) -> Option<(T, T)> { - share_floor_with(whole, weight, total, step, |x| round_step(x, step, mode)) -} +/// The most correction steps [`share_floor_with`] takes in each direction. +/// The first estimate is at most one step off in practice (half-away's +/// rounding of a quotient whose product is exact); a few thousand leaves +/// room for any quotient rounding that still describes the same figure. +/// A share further away is a malformed input, and the function refuses it +/// rather than loop without end. +const MAX_CORRECTION_STEPS: usize = 4096; /// Split `whole` by `weights` over `total`, each part the exact share /// rounded by `round`, the leftover by `policy`, written into `parts` (and @@ -177,6 +195,11 @@ pub fn share_floor( /// 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). /// 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. @@ -190,7 +213,8 @@ pub fn share_floor( /// promised. /// SCENARIOS: /// 1. IF 100 by 1/1/1 to the cent by largest remainder: SHOULD be -/// 33.34, 33.33, 33.33 (the tied cent to the first). +/// 33.34, 33.33, 33.33 (the rounded 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 @@ -240,14 +264,19 @@ pub fn split_by_weights_into( } Leftover::LastAbsorbs => plug_last(whole, parts), Leftover::FirstAbsorbs => { - let Some((first, rest)) = parts.split_first_mut() else { + // The old `split_first`: the first part takes its rounded share + // plus the shortfall (the whole less every rounded part). The + // value is the whole less the others, but its scale is the sum + // and the addition's, as the call site has always produced. + let mut sum = T::ZERO; + for &p in parts.iter() { + sum = sum.checked_add(p)?; + } + let Some(first) = parts.first_mut() else { return Some(()); }; - let mut others = T::ZERO; - for &p in rest.iter() { - others = others.checked_add(p)?; - } - *first = whole.checked_sub(others)?; + let left = whole.checked_sub(sum)?; + *first = first.checked_add(left)?; Some(()) } } @@ -277,24 +306,3 @@ pub fn split_by_weights_with( )?; Some(parts) } - -/// [`split_by_weights_with`] with [`round_step`] as the rounding: the -/// generic spelling for a caller whose parts carry a whole number of -/// `step`s. -pub fn split_by_weights( - whole: T, - weights: &[T], - total: T, - step: T, - mode: Rounding, - policy: Leftover, -) -> Option> { - split_by_weights_with( - whole, - weights, - total, - step, - |x| round_step(x, step, mode), - policy, - ) -} diff --git a/crates/ledger-core/src/proofs/allocate.rs b/crates/ledger-core/src/proofs/allocate.rs index da3f7a69..25fea242 100644 --- a/crates/ledger-core/src/proofs/allocate.rs +++ b/crates/ledger-core/src/proofs/allocate.rs @@ -4,10 +4,11 @@ //! The divisor is fixed in every harness: CBMC's bit-blasted division by //! a symbolic `i64` did not finish in 30 minutes in K-U2 //! (`docs/proofs/k-u2.md`), and every split here divides by a total or a -//! step. The fixed weights and totals cover a tied split (2/3/5), a zero -//! weight, a total of one, and a step that is not a power of ten; the -//! bridge carries the same laws to every `Decimal` weight and step, and -//! bookspec's Lean proves them for any number of parts. +//! step. The fixed weights and totals cover three different weights +//! (2/3/5), a zero weight and a total of one; the steps used are 1 and +//! 10. The bridge carries the same laws to every `Decimal` weight and +//! step, and bookspec's Lean proves them of the exact-share model for any +//! number of parts. //! //! ```text //! GOAL: the parts of a weighted split sum to the whole exactly, each @@ -21,8 +22,10 @@ //! 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. +//! 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. //! 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 @@ -30,17 +33,19 @@ //! 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 tied unit -//! to the first), never 33/34/34. +//! 1. IF 101 by 1/1/1 to the unit: SHOULD be 34/34/33 (the rounded +//! 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` //! SHOULD still give the exact floor, by multiplication. //! 3. IF the product `whole x weight` is past `i64`: SHOULD be None. //! ``` //! -//! Bounds: amounts up to 1,000, weights up to 100, totals and steps fixed -//! (`10`, `1`, `7`). The laws are about the shape of the split, not the -//! magnitude; Lean proves them at any size and the bridge checks the -//! `Decimal` engine. +//! 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. use crate::kernel::{self, Leftover, Rounding, share_floor_with, share_of, split_by_weights_into}; diff --git a/crates/ledger-core/src/shares.rs b/crates/ledger-core/src/shares.rs index 092910ce..269d1ed7 100644 --- a/crates/ledger-core/src/shares.rs +++ b/crates/ledger-core/src/shares.rs @@ -451,8 +451,9 @@ fn original_target( /// Split `whole` (at most the sum of `sizes`) over `sizes` in proportion, /// to the cent, leftover cents by largest remainder (k1's -/// share_property), ties to the earlier in `order` (each part's rank). -/// None past exact arithmetic. +/// `share_property`), a tie in the rounded remainders to the earlier in +/// `order` (each part's rank); an exact tie follows the quotient's 28th +/// digit, and K-U10 decides the exact ranking. None past exact arithmetic. fn share_by(whole: Decimal, sizes: &[Decimal], order: &[usize]) -> Option> { let ranked: Vec = order.iter().map(|&i| sizes[i]).collect(); let shared = crate::k1::share_property(whole, &ranked, 2).ok()?; diff --git a/crates/ledger-core/src/tax_capital.rs b/crates/ledger-core/src/tax_capital.rs index 12b68b15..ab417ab8 100644 --- a/crates/ledger-core/src/tax_capital.rs +++ b/crates/ledger-core/src/tax_capital.rs @@ -365,7 +365,8 @@ fn too_large() -> LedgerError { /// 2. A member's exact running total is Σ whole × weight / Σ weights /// over every split so far; their running total (Σ of their parts) /// is the largest-remainder rounding to the cent of the exact running -/// totals (ties to the earlier member), so it is within a cent of +/// totals (a tie in the rounded remainders to the earlier member; an +/// exact tie follows the quotient's 28th digit, K-U10), so it is within a cent of /// exact, strictly. A negative running whole is rounded as its /// magnitude and negated; a running whole of zero is rounded by the /// sign of the whole just split. So a run of losses mirrors the run @@ -655,7 +656,8 @@ fn entry_wholes( /// their part: the pair leaves every later entry's cents as they /// would be without it. Its own parts (it reads as the contrary /// kind, a distribution for a contribution) are split on its own, -/// largest remainder, ties to the earlier member. +/// largest remainder, a tie in the rounded remainders to the earlier +/// member (an exact tie follows the quotient's 28th digit, K-U10). /// ``` fn entry_parts( ledger: &Ledger, diff --git a/crates/ledger-core/tests/kernel_bridge/allocate.rs b/crates/ledger-core/tests/kernel_bridge/allocate.rs index 328c02b9..c32e4ee8 100644 --- a/crates/ledger-core/tests/kernel_bridge/allocate.rs +++ b/crates/ledger-core/tests/kernel_bridge/allocate.rs @@ -11,8 +11,8 @@ //! `Decimal::MAX` and scale 28, each `None` or exact, never a panic. use ledger_core::kernel::{ - Leftover, Rounding, round_places, round_step, share_floor_with, share_of, split_by_weights, - split_by_weights_with, + Leftover, Rounding, round_places, round_step, share_floor_with, share_of, + split_by_weights_into, split_by_weights_with, }; use proptest::prelude::*; use rust_decimal::Decimal; @@ -157,12 +157,12 @@ proptest! { fn i64_and_decimal_agree(k in 0i64..=100_000) { let whole = k * 10; let weights = [2i64, 3, 5]; - let narrow = split_by_weights( + let narrow = split_by_weights_with( whole, &weights, 10, 1, - Rounding::TowardZero, + |x| round_step(x, 1, Rounding::TowardZero), Leftover::LargestRemainder, ) .unwrap(); @@ -238,21 +238,21 @@ proptest! { #[test] fn leftovers_at_each_policy(whole in 0i64..=1_000_000) { let weights = [2i64, 3, 5]; - let first = split_by_weights( + let first = split_by_weights_with( whole, &weights, 10, 1, - Rounding::TowardZero, + |x| round_step(x, 1, Rounding::TowardZero), Leftover::FirstAbsorbs, ) .unwrap(); - let last = split_by_weights( + let last = split_by_weights_with( whole, &weights, 10, 1, - Rounding::TowardZero, + |x| round_step(x, 1, Rounding::TowardZero), Leftover::LastAbsorbs, ) .unwrap(); @@ -291,6 +291,60 @@ 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. + #[test] + fn largest_remainder_ranks_like_the_exact_reference( + whole_start in 0i64..=2_000, + weights in prop::collection::vec(1i64..=9, 2..=4), + ) { + // 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 = 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 = 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::>(), + i128::from(total), + 1, + ) + .unwrap(); + prop_assert_eq!(got.iter().map(|&p| integer(p)).collect::>(), want); + } + /// `share_floor_with` is the exact floor of the rational, even when /// the division does not terminate (total 3, 7, 11): the quotient's /// 28-digit rounding is corrected by multiplication. @@ -414,18 +468,177 @@ fn decimal_edges_are_none_or_exact() { // A zero total is zeros, whatever the weights. assert_eq!( - split_by_weights( + split_by_weights_with( dec(5), &[dec(1), dec(2)], Decimal::ZERO, Decimal::ONE, - Rounding::TowardZero, + |x| round_step(x, Decimal::ONE, Rounding::TowardZero), Leftover::LargestRemainder ), Some(vec![Decimal::ZERO, Decimal::ZERO]) ); } +/// The absorbing parts keep the scale the pre-U3 code produced. Decimal's +/// equality ignores scale, so these compare the strings: the old +/// `shares::split_first` added the shortfall to the first rounded share +/// (4860 by 6/0.7/0.5 gave `4050`, not `4050.00`), and 902 by +/// 1/0.000001/0.000001 gave `902.00` there; the kernel now computes the +/// same expression, not the algebraically equal `whole − Σ rest`. +#[test] +fn the_absorbing_parts_keep_the_old_scale() { + let text = |parts: &[Decimal]| parts.iter().map(Decimal::to_string).collect::>(); + let weights = [parse("6"), parse("0.7"), parse("0.5")]; + let got = split_by_weights_with( + parse("4860"), + &weights, + parse("7.2"), + parse("0.01"), + |x| round_places(x, 2, Rounding::TowardZero), + Leftover::FirstAbsorbs, + ) + .unwrap(); + assert_eq!(text(&got), ["4050", "472.50", "337.50"]); + + let weights = [Decimal::ONE, parse("0.000001"), parse("0.000001")]; + let got = split_by_weights_with( + parse("902"), + &weights, + parse("1.000002"), + parse("0.01"), + |x| round_places(x, 2, Rounding::TowardZero), + Leftover::FirstAbsorbs, + ) + .unwrap(); + assert_eq!(text(&got), ["902.00", "0.00", "0.00"]); + + // LastAbsorbs is the old `plug_last` (and the no-places conventions + // split): the last part is the whole less the others, same scale. + let got = split_by_weights_with( + parse("4860"), + &weights[..1], + Decimal::ONE, + Decimal::ONE, + Some, + Leftover::LastAbsorbs, + ) + .unwrap(); + assert_eq!(text(&got), ["4860"]); + let got = split_by_weights_with( + parse("7"), + &[parse("0.5"), parse("0.5")], + Decimal::ONE, + Decimal::ONE, + Some, + Leftover::LastAbsorbs, + ) + .unwrap(); + assert_eq!(text(&got), ["3.5", "3.5"]); +} + +/// The buffer API and the allocating one agree, including scale: the +/// bridge calls `split_by_weights_into` itself (fixed arrays), as the +/// traceability gate requires. +#[test] +fn split_into_matches_the_allocating_split() { + let weights = [parse("6"), parse("0.7"), parse("0.5")]; + let mut parts = [Decimal::ZERO; 3]; + let mut remainders = [Decimal::ZERO; 3]; + split_by_weights_into( + parse("4860"), + &weights, + parse("7.2"), + parse("0.01"), + |x| round_places(x, 2, Rounding::TowardZero), + Leftover::FirstAbsorbs, + &mut parts, + &mut remainders, + ) + .unwrap(); + let with = split_by_weights_with( + parse("4860"), + &weights, + parse("7.2"), + parse("0.01"), + |x| round_places(x, 2, Rounding::TowardZero), + Leftover::FirstAbsorbs, + ) + .unwrap(); + assert_eq!( + parts.iter().map(Decimal::to_string).collect::>(), + with.iter().map(Decimal::to_string).collect::>() + ); +} + +/// 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. +#[test] +fn finding_ties_follow_the_rounded_quotient() { + let weights = [Decimal::from(4), Decimal::ONE, Decimal::ONE]; + let got = decimal_split( + parse("20.00"), + &weights, + Decimal::from(6), + 2, + Leftover::LargestRemainder, + ) + .unwrap(); + assert_eq!( + got.iter().map(Decimal::to_string).collect::>(), + ["13.33", "3.34", "3.33"] + ); + let got = decimal_split( + Decimal::from(20), + &weights, + Decimal::from(6), + 0, + Leftover::LargestRemainder, + ) + .unwrap(); + assert_eq!( + got.iter().map(Decimal::to_string).collect::>(), + ["13", "4", "3"] + ); +} + +/// The review's hang: `0.1113 × 5909471247797156928749568911.8 ÷ +/// 0.11134381908633486049673` to the cent put the rounded product far +/// past the exact floor, and the correction walked without end. It now +/// refuses past the cap, quickly; the other two buckets keep exact floors. +#[test] +fn share_floor_refuses_past_the_correction_cap() { + let b = [ + parse("0.1113"), + parse("0.00004381908373486049673"), + parse("0.0000000000026"), + ]; + let v = parse("-5909471247797156928749568911.8"); + let total = b + .iter() + .copied() + .try_fold(Decimal::ZERO, |s, x| s.checked_add(x)) + .unwrap(); + let started = std::time::Instant::now(); + let got = share_floor_with(b[0].abs(), v.abs(), total, parse("0.01"), |x| { + round_places(x, 2, Rounding::TowardZero) + }); + assert_eq!(got, None); + assert!(started.elapsed() < std::time::Duration::from_secs(5)); + for bucket in &b[1..] { + assert!( + share_floor_with(bucket.abs(), v.abs(), total, parse("0.01"), |x| { + round_places(x, 2, Rounding::TowardZero) + },) + .is_some() + ); + } +} + /// The K-U10 finding: at `Decimal`'s mantissa edge, `checked_div`'s /// rounding can move a share across a step, and `checked_mul`'s rounding /// hides it from the exact-floor correction. The exact share is