diff --git a/crates/ledger-core/src/k1.rs b/crates/ledger-core/src/k1.rs index 6abaa601..7949bdd9 100644 --- a/crates/ledger-core/src/k1.rs +++ b/crates/ledger-core/src/k1.rs @@ -34,9 +34,8 @@ //! it) is shared among the members credited in proportion to their //! credits, to the base currency's minor unit (cents, whole yen), //! leftover units by largest remainder -//! (kernel::apportion, a tie in the rounded remainders to the -//! earlier member; an exact tie follows the quotient's 28th digit, -//! K-U10): each takes at +//! (kernel::apportion over the exact remainders, a tie to the +//! earlier member, K-U10): each takes at //! most its own credit, and the split depends on the order the //! members are given only for a tied leftover cent (never on line //! order). Joint property is joint (BS-partner-1's diff --git a/crates/ledger-core/src/kernel/allocate.rs b/crates/ledger-core/src/kernel/allocate.rs index eedc3734..402a9bdc 100644 --- a/crates/ledger-core/src/kernel/allocate.rs +++ b/crates/ledger-core/src/kernel/allocate.rs @@ -24,11 +24,10 @@ use super::{Amount, apportion, plug_last}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Leftover { /// Each part is rounded down; the units left over go one each to the - /// largest remainders. The remainders are the rounded quotients' - /// differences, not exact rationals, so ranking follows the quotient: - /// an exact tie can go where the quotient's 28th digit sends it, and - /// only a tie in the rounded remainders goes to the earlier part. K-U10 - /// decides the exact ranking. [`apportion`]. + /// largest remainders. The remainders are exact: `whole x weight - + /// part x total`, an integer comparison, never the rounded quotient's + /// difference, so an exact tie goes to the earlier part (the Lean + /// model's rank, bookspec's `Apportion`). [`apportion`]. LargestRemainder, /// The last part becomes the whole less the others. [`plug_last`]. LastAbsorbs, @@ -201,11 +200,13 @@ const MAX_CORRECTION_STEPS: usize = 4096; /// a part more than one step from the exact rational (K-U10, pinned /// in the bridge). Under the first/last-absorbs policies only the /// absorbing part may be further, by the rounding of all the others. -/// The largest-remainder ranking compares the rounded quotients' -/// remainders, not exact rationals: an exact tie can go where -/// `Decimal`'s 28th digit sends it, and only a tie in the rounded -/// remainders goes to the earlier part (K-U10 decides the exact -/// rule; the bridge pins today's answer). +/// The largest-remainder ranking compares the exact remainders +/// `whole x weight - part x total` (the quantity `share_floor_with` +/// returns, scaled by total; the sign flipped for a negative total), +/// never the rounded quotients' differences. An exact tie goes to the +/// earlier part, whatever `Decimal`'s 28th digit would have said +/// (K-U10, the owner's decision; exact while the products are, as +/// above). /// 3. With total not zero, no part exceeds the whole when every weight /// is in [0, total] and the whole is not negative; no part is /// negative when the weights and the whole are not. @@ -219,13 +220,19 @@ const MAX_CORRECTION_STEPS: usize = 4096; /// promised. /// SCENARIOS: /// 1. IF 100 by 1/1/1 to the cent by largest remainder: SHOULD be -/// 33.34, 33.33, 33.33 (the rounded remainders tie, so the cent goes +/// 33.34, 33.33, 33.33 (the exact remainders tie, so the cent goes /// to the earlier part). /// 2. IF 0.01 by 1/1 to the cent by largest remainder: SHOULD be /// 0.01, 0.00. /// 3. IF 10 by weights 2/3/5 by first-absorbs: SHOULD be the rounded /// shares with the first taking the whole less the others. -/// 4. IF the total is zero, or every weight is zero: SHOULD be zeros (a +/// 4. IF 20.00 by 4/1/1 over 6 to the cent by largest remainder: SHOULD +/// be 13.34, 3.33, 3.33. The exact remainders (0.02, 0.02, 0.02 over +/// 6, as 80 - 79.98, 20 - 19.98) tie, so the cent goes to the first. +/// The rounded quotients (13.33...3 keeps one fewer fractional digit +/// than 3.33...3 at 28 significant digits) would have put the +/// second's remainder above the first's. +/// 5. IF the total is zero, or every weight is zero: SHOULD be zeros (a /// zero total) or the largest-remainder handout of the whole (a /// positive total with zero weights, as the conventions' template /// split has always done). @@ -263,8 +270,26 @@ pub fn split_by_weights_into( if unit <= T::ZERO { return None; } + // Rank by the exact remainder, never the rounded quotient's + // difference: `whole x weight - part x total`, the exact + // rational's fraction scaled by `total`, the same quantity + // `share_floor_with` returns. A negative total flips the + // scale's sign, so the order is the share's own. The two + // products are the rounding ones: each is exact while it fits + // Decimal's mantissa (every split of posted amounts by whole + // weights or basis points), and where a weight of 27 places + // makes a product round, the split is still made, ranked by + // the nearest figures Decimal holds, not refused. Their + // difference is exact: the subtraction refuses otherwise. for i in 0..weights.len() { - remainders[i] = remainders[i].checked_sub(parts[i])?; + let exact = whole + .checked_mul_rounded(weights[i])? + .checked_sub(parts[i].checked_mul_rounded(total)?)?; + remainders[i] = if total < T::ZERO { + T::ZERO.checked_sub(exact)? + } else { + exact + }; } apportion(whole, parts, remainders, unit) } diff --git a/crates/ledger-core/src/proofs/allocate.rs b/crates/ledger-core/src/proofs/allocate.rs index 7785a9c1..b1c71dcf 100644 --- a/crates/ledger-core/src/proofs/allocate.rs +++ b/crates/ledger-core/src/proofs/allocate.rs @@ -22,10 +22,11 @@ //! INVARIANTS: //! 1. The parts sum to the whole, for every policy. //! 2. Under largest remainder each part is within one unit (the step) -//! of its exact share: `-total < part x total - whole x weight <= -//! total` at step one. The upper bound is inclusive on `i64` (its -//! division truncates); the bridge checks the strict `Decimal` -//! bound. +//! of its exact share: `-total < part x total - whole x weight < +//! total` at step one, and a part whose share is exact takes no +//! unit. Both rest on the ranking by the exact remainder (K-U10, +//! D-76): `i64`'s division truncates, and the ranking no longer +//! reads the quotient. //! 3. No part is negative or above the whole for non-negative weights //! that do not exceed the total. //! 4. A zero total gives zeros; all-zero weights hand the whole out by @@ -33,7 +34,7 @@ //! units as there are parts. //! 5. Overflow is `None`, never a panic. //! SCENARIOS: -//! 1. IF 101 by 1/1/1 to the unit: SHOULD be 34/34/33 (the rounded +//! 1. IF 101 by 1/1/1 to the unit: SHOULD be 34/34/33 (the exact //! remainders tie, so the units go to the earlier parts), never //! 33/34/34. //! 2. IF a quotient rounds up across the step: `share_floor_with` @@ -44,8 +45,8 @@ //! Bounds: amounts up to 1,000, weights up to 100, totals fixed (10 and //! 0), steps 1 and 10. The laws are about the shape of the split, not the //! magnitude; Lean proves them of the exact-share model at any size, and -//! the bridge checks the `Decimal` engine, whose ranking uses the rounded -//! quotient. +//! the bridge checks the `Decimal` engine, which ranks the same exact +//! remainders. use crate::kernel::{self, Leftover, Rounding, share_floor_with, share_of, split_by_weights_into}; @@ -93,23 +94,28 @@ fn split_by_weights_sums() { } /// Each part is within one step of its share: scaled by the total, -/// `part x total - whole x weight` is above `-total` and at most `total`. +/// `part x total - whole x weight` is above `-total` and below `total`, +/// and a part whose share is exact takes no unit. /// -/// The upper bound is inclusive on the `i64` model: its division -/// truncates, so a part that divides exactly can still take a unit when -/// another part's truncation left one over (`whole = 5`, weights 2/3/5: -/// the first's 1 becomes 2, exactly one step above its truncated share). -/// The `Decimal` quotient keeps the fraction, a part with no remainder -/// never takes a unit, and the bridge checks the strict bound there -/// (`decimal_split_satisfies_the_kani_laws`); Lean's `shares_of_near` -/// proves it for the exact-share model at any size. +/// The upper bound was inclusive on the `i64` model while the ranking +/// read the quotient: `i64`'s division truncates, every remainder read +/// as zero, and a part that divided exactly could take the unit another +/// part's truncation left over (`whole = 5`, weights 2/3/5: the first's 1 +/// became 2). The ranking is the exact remainder `whole x weight - part x +/// total` since K-U10 (D-76), which no division touches, so the unit goes +/// to a part that is short (1, 2, 2) and the bound is strict here as on +/// `Decimal` (`decimal_split_satisfies_the_kani_laws`); Lean's +/// `shares_of_near` proves it for the exact-share model at any size. #[kani::proof] fn split_by_weights_within_one_step() { let whole = any_whole(); let (parts, _) = split(whole, 1, Leftover::LargestRemainder).expect("in range"); for i in 0..N { let drift = parts[i] * TOTAL - whole * WEIGHTS[i]; - assert!(-TOTAL < drift && drift <= TOTAL); + assert!(-TOTAL < drift && drift < TOTAL); + if (whole * WEIGHTS[i]) % TOTAL == 0 { + assert_eq!(drift, 0); + } } kani::cover!( parts @@ -119,11 +125,8 @@ fn split_by_weights_within_one_step() { "a part off its exact share by the rounding" ); kani::cover!( - parts - .iter() - .enumerate() - .any(|(i, &p)| p * TOTAL - whole * WEIGHTS[i] == TOTAL), - "a part exactly one step above its truncated share" + (whole * WEIGHTS[0]) % TOTAL == 0 && whole % TOTAL != 0, + "a unit is handed out while the first part's share is exact" ); } diff --git a/crates/ledger-core/tests/kernel_bridge/allocate.rs b/crates/ledger-core/tests/kernel_bridge/allocate.rs index c32e4ee8..080caea7 100644 --- a/crates/ledger-core/tests/kernel_bridge/allocate.rs +++ b/crates/ledger-core/tests/kernel_bridge/allocate.rs @@ -291,58 +291,31 @@ proptest! { prop_assert_eq!(cents(&got), want); } - /// The exact reference ranks the exact remainders; the kernel ranks - /// the rounded quotients' remainders. With a small non-terminating - /// total the two orders agree except at an exact tie, which this - /// property excludes and `finding_ties_follow_the_rounded_quotient` - /// pins. + /// The exact reference ranks the exact remainders, and so does the + /// kernel (K-U10): with any weights, ties included (equal weights, + /// the 4/1/1 shape, a whole that leaves equal remainders), the split + /// is the reference's, at whole units and at the cent. #[test] fn largest_remainder_ranks_like_the_exact_reference( - whole_start in 0i64..=2_000, - weights in prop::collection::vec(1i64..=9, 2..=4), + whole in 0i64..=100_000, + weights in prop::collection::vec(1i64..=9, 2..=5), ) { - // Distinct weights, and a total with a factor of 3 or 7 (a - // non-terminating division), by construction: no case is - // rejected, and no exact tie is left to the property. - let mut weights = weights; - weights.sort_unstable(); - for (i, w) in weights.iter_mut().enumerate() { - *w += i as i64; - } - let plain: i64 = weights.iter().sum(); - if plain % 3 != 0 && plain % 7 != 0 { - *weights.last_mut().unwrap() += 3 - plain % 3; - } let total: i64 = weights.iter().sum(); - let whole = (whole_start..whole_start + total) - .find(|&w| { - let mut rems: Vec = 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); + let wide: Vec = weights.iter().map(|&w| i128::from(w)).collect(); + for places in [0u32, 2] { + let got = decimal_split( + Decimal::new(whole, places), + &decimal_weights, + Decimal::from(total), + places, + Leftover::LargestRemainder, + ) + .unwrap(); + let want = reference(i128::from(whole), &wide, i128::from(total), 1).unwrap(); + let got = if places == 0 { got.iter().map(|&p| integer(p)).collect() } else { cents(&got) }; + prop_assert_eq!(got, want); + } } /// `share_floor_with` is the exact floor of the rational, even when @@ -571,14 +544,13 @@ fn split_into_matches_the_allocating_split() { ); } -/// The EM's finding, pinned rather than fixed: a split ranks the rounded -/// quotients' remainders, so an exact tie goes where the 28th digit sends -/// it, not to the earlier part. 20.00 split 4/1/1 over 6 gives -/// 13.33/3.34/3.33 (exact ranking would give 13.34/3.33/3.33), and 20 at -/// whole units gives 13/4/3 (exact would give 14/3/3). The pre-U3 sites -/// did the same. The owner decides the exact ranking in K-U10. +/// K-U10 (the owner's decision): a split ranks the exact remainders, so an +/// exact tie goes to the earlier part, as the docs and the Lean model say. +/// 20.00 split 4/1/1 over 6 is 13.34/3.33/3.33 (the rounded quotients' +/// ranking gave 13.33/3.34/3.33), and 20 at whole units is 14/3/3 (it gave +/// 13/4/3). Equal weights tie on every odd cent and give it to the first. #[test] -fn finding_ties_follow_the_rounded_quotient() { +fn ties_go_to_the_earlier_part() { let weights = [Decimal::from(4), Decimal::ONE, Decimal::ONE]; let got = decimal_split( parse("20.00"), @@ -590,7 +562,7 @@ fn finding_ties_follow_the_rounded_quotient() { .unwrap(); assert_eq!( got.iter().map(Decimal::to_string).collect::>(), - ["13.33", "3.34", "3.33"] + ["13.34", "3.33", "3.33"] ); let got = decimal_split( Decimal::from(20), @@ -602,7 +574,21 @@ fn finding_ties_follow_the_rounded_quotient() { .unwrap(); assert_eq!( got.iter().map(Decimal::to_string).collect::>(), - ["13", "4", "3"] + ["14", "3", "3"] + ); + // A negative total keeps the share's own order: ties still go first. + let neg = [Decimal::from(-4), Decimal::from(-1), Decimal::from(-1)]; + let got = decimal_split( + parse("20.00"), + &neg, + Decimal::from(-6), + 2, + Leftover::LargestRemainder, + ) + .unwrap(); + assert_eq!( + got.iter().map(Decimal::to_string).collect::>(), + ["13.34", "3.33", "3.33"] ); } diff --git a/crates/ledger-core/tests/kernel_bridge/main.rs b/crates/ledger-core/tests/kernel_bridge/main.rs index 7d482238..6da78c5a 100644 --- a/crates/ledger-core/tests/kernel_bridge/main.rs +++ b/crates/ledger-core/tests/kernel_bridge/main.rs @@ -16,6 +16,7 @@ mod payroll; mod ratio; mod round; mod schedule; +mod ties; mod total; use ledger_core::kernel::{self, Amount, LineError}; diff --git a/crates/ledger-core/tests/kernel_bridge/ties.rs b/crates/ledger-core/tests/kernel_bridge/ties.rs new file mode 100644 index 00000000..7f98eaf1 --- /dev/null +++ b/crates/ledger-core/tests/kernel_bridge/ties.rs @@ -0,0 +1,408 @@ +//! K-U10: what ranking the leftover cents by the exact remainder moves. +//! +//! `split_by_weights_into` used to rank its largest remainders by +//! `Decimal`'s rounded quotient (28 significant digits), so an exact tie +//! was decided by the quotient's last digit; it now ranks the exact +//! integer remainder `whole x weight - part x total`, ties to the earlier +//! part. This file keeps the old ranking as a reference (`old_split`, +//! built from the kernel's own public `share_of`, `round_places` and +//! `apportion`, exactly as the kernel built it) and measures, over +//! realistic inputs, how often the two differ and by how much. Run it +//! with `--nocapture` to see the table the owner's decision rests on: +//! +//! ```text +//! cargo test -p ledger-core --test kernel_bridge ties -- --nocapture +//! ``` +//! +//! Realistic inputs: whole-cent amounts up to 1,000,000.00, two to five +//! parties, weights that are whole percentages or small integers. + +use ledger_core::kernel::{ + Leftover, Rounding, apportion, round_places, share_of, split_by_weights_with, +}; +use rust_decimal::Decimal; + +fn cents(c: i64) -> Decimal { + Decimal::new(c, 2) +} + +/// The ranking the kernel had before K-U10: each remainder is the rounded +/// quotient less its rounded-down part. +fn old_split(whole: Decimal, weights: &[Decimal], total: Decimal) -> Vec { + let shares: Vec = weights + .iter() + .map(|&w| share_of(whole, w, total).unwrap()) + .collect(); + let mut parts: Vec = shares + .iter() + .map(|&s| round_places(s, 2, Rounding::TowardZero).unwrap()) + .collect(); + let rems: Vec = shares.iter().zip(&parts).map(|(s, p)| s - p).collect(); + apportion(whole, &mut parts, &rems, cents(1)).unwrap(); + parts +} + +fn new_split(whole: Decimal, weights: &[Decimal], total: Decimal) -> Vec { + split_by_weights_with( + whole, + weights, + total, + cents(1), + |x| round_places(x, 2, Rounding::TowardZero), + Leftover::LargestRemainder, + ) + .unwrap() +} + +/// True when two parts have an equal exact remainder `whole x w - part x +/// total` (before the leftover is handed out): the only place the two +/// rankings can part. +fn has_exact_tie(whole: Decimal, weights: &[Decimal], total: Decimal) -> bool { + let rems: Vec = weights + .iter() + .map(|&w| { + let share = + round_places(share_of(whole, w, total).unwrap(), 2, Rounding::TowardZero).unwrap(); + // The exact floor: a quotient that rounded up across a cent is + // taken back, as `share_floor_with` does. + let mut part = share; + while part * total > whole * w { + part -= cents(1); + } + whole * w - part * total + }) + .collect(); + (0..rems.len()).any(|i| (i + 1..rems.len()).any(|j| rems[i] == rems[j])) +} + +/// A small deterministic generator (xorshift64*): the sweep is the same on +/// every machine and every run. +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } +} + +#[derive(Default)] +struct Tally { + runs: u64, + differ: u64, + max_moved_cents: i64, + examples: Vec, +} + +impl Tally { + fn run(&mut self, whole: Decimal, weights: &[Decimal]) { + let total: Decimal = weights.iter().copied().sum(); + let old = old_split(whole, weights, total); + let new = new_split(whole, weights, total); + self.runs += 1; + // Both sum to the whole, exactly, whatever the ranking. + assert_eq!(old.iter().copied().sum::(), whole); + assert_eq!(new.iter().copied().sum::(), whole); + if old == new { + return; + } + self.differ += 1; + // They differ only where an exact tie gave the ranking a choice, + // and by at most one cent a part. + assert!( + has_exact_tie(whole, weights, total), + "{whole} by {weights:?}: differ without an exact tie" + ); + for (o, n) in old.iter().zip(&new) { + let moved = ((o - n).abs() * Decimal::from(100)).trunc(); + let moved = i64::try_from(moved.mantissa()).unwrap(); + assert!(moved <= 1, "{whole} by {weights:?}: moved {moved} cents"); + self.max_moved_cents = self.max_moved_cents.max(moved); + } + if self.examples.len() < 3 { + let show = |v: &[Decimal]| { + v.iter() + .map(|d| d.to_string()) + .collect::>() + .join(" / ") + }; + self.examples.push(format!( + "{whole} by {} -> was {}, now {}", + weights + .iter() + .map(|d| d.to_string()) + .collect::>() + .join("/"), + show(&old), + show(&new) + )); + } + } + + fn report(&self, name: &str) { + println!( + "{name:<44} {:>8} runs {:>8} differ {:>7.3}% max {} cent/part", + self.runs, + self.differ, + 100.0 * self.differ as f64 / self.runs as f64, + self.max_moved_cents + ); + for e in &self.examples { + println!(" e.g. {e}"); + } + } +} + +const RUNS: u64 = 60_000; + +/// A random whole of 0.01 to 1,000,000.00; `dollars` rounds it to whole +/// dollars (round amounts are the realistic ones, and tie more). +fn random_whole(rng: &mut Rng, dollars: bool) -> Decimal { + let c = 1 + rng.below(100_000_000) as i64; + if dollars { + cents(((c + 99) / 100) * 100) + } else { + cents(c) + } +} + +fn random_percentages(rng: &mut Rng) -> Vec { + let n = 2 + rng.below(4) as usize; + // A random composition of 100 into n positive whole percentages. + let mut cuts: Vec = Vec::new(); + while cuts.len() < n - 1 { + let c = 1 + rng.below(99); + if !cuts.contains(&c) { + cuts.push(c); + } + } + cuts.sort_unstable(); + let mut prev = 0; + let mut out = Vec::new(); + for c in cuts.iter().copied().chain(std::iter::once(100)) { + out.push(Decimal::from(c - prev)); + prev = c; + } + out +} + +fn random_small_integers(rng: &mut Rng) -> Vec { + let n = 2 + rng.below(4) as usize; + (0..n).map(|_| Decimal::from(1 + rng.below(5))).collect() +} + +/// The splits an agreement is likely to name. +const COMMON: &[&[i64]] = &[ + &[50, 50], + &[60, 40], + &[70, 30], + &[75, 25], + &[80, 20], + &[90, 10], + &[34, 33, 33], + &[40, 30, 30], + &[50, 25, 25], + &[60, 20, 20], + &[25, 25, 25, 25], + &[40, 20, 20, 20], + &[20, 20, 20, 20, 20], +]; + +/// Equal weights: every remainder is `w x (whole - n x part)`, equal for +/// every part, so both rankings give the leftover cents to the earliest +/// parts and never differ. Two 50/50 members, thirds, quarters: no cent +/// moves, ever. +#[test] +fn equal_weights_never_differ() { + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + let mut t = Tally::default(); + for i in 0..RUNS { + let n = 2 + rng.below(4) as usize; + let w = Decimal::from(1 + rng.below(100)); + let weights = vec![w; n]; + t.run(random_whole(&mut rng, i % 2 == 0), &weights); + } + t.report("equal weights (2-5 parties)"); + assert_eq!(t.differ, 0); +} + +/// Two parties never differ, whatever the weights. With two parts the +/// leftover is at most one cent, and the two remainders sum to `total` times +/// that cent, so they tie only at exactly half a cent over `total` each: +/// both shares then end in exactly half a cent, the quotient terminates, +/// and the rounded quotient ranks them as the exact one does. A two-member +/// company (the live books' shape) is therefore unmoved by K-U10. +#[test] +fn two_parties_never_differ() { + let mut rng = Rng(0x2545_F491_4F6C_DD1D); + let mut t = Tally::default(); + for i in 0..RUNS { + let weights = [ + Decimal::from(1 + rng.below(10_000)), + Decimal::from(1 + rng.below(10_000)), + ]; + t.run(random_whole(&mut rng, i % 2 == 0), &weights); + } + // And the smallest weights, where ties are the most frequent. + for a in 1..=12u64 { + for b in 1..=12u64 { + for c in 1..=300 { + t.run(cents(c), &[Decimal::from(a), Decimal::from(b)]); + } + } + } + t.report("two parties, any weights"); + assert_eq!(t.differ, 0); +} + +/// The measurement: how often the old and new rankings differ, by class +/// of weights and of amount. Asserts only the structure (both sum to the +/// whole; a difference needs an exact tie and is at most a cent a part); +/// the rates are printed for the owner. +#[test] +fn what_exact_tie_ranking_moves() { + println!(); + for dollars in [false, true] { + let kind = if dollars { + "whole dollars" + } else { + "any cents" + }; + let mut rng = Rng(0xD1B5_4A32_D192_ED03); + + let mut t = Tally::default(); + for _ in 0..RUNS { + let w = random_percentages(&mut rng); + t.run(random_whole(&mut rng, dollars), &w); + } + t.report(&format!("whole percentages, {kind}")); + + let mut t = Tally::default(); + for _ in 0..RUNS { + let w: Vec = COMMON[rng.below(COMMON.len() as u64) as usize] + .iter() + .map(|&p| Decimal::from(p)) + .collect(); + t.run(random_whole(&mut rng, dollars), &w); + } + t.report(&format!("common agreements, {kind}")); + + let mut t = Tally::default(); + for _ in 0..RUNS { + let w = random_small_integers(&mut rng); + t.run(random_whole(&mut rng, dollars), &w); + } + t.report(&format!("small integers 1-5, {kind}")); + } + // The K-1 property split's real shape: weights are the members' + // credits in one entry (whole dollars to 10,000), the whole at most + // their sum. + let mut rng = Rng(0xA076_1D64_78BD_642F); + let mut t = Tally::default(); + for _ in 0..RUNS { + let n = 2 + rng.below(4) as usize; + let w: Vec = (0..n) + .map(|_| Decimal::from(1 + rng.below(10_000))) + .collect(); + let total: Decimal = w.iter().copied().sum(); + let pool = cents(1 + rng.below(total.mantissa() as u64 * 100) as i64); + t.run(pool, &w); + } + t.report("K-1 credits, whole dollars to 10,000"); + // The 4/1/1 shape, every whole-dollar amount to 100. + let mut t = Tally::default(); + for d in 1..=100 { + t.run( + Decimal::from(d), + &[Decimal::from(4), Decimal::ONE, Decimal::ONE], + ); + } + t.report("4/1/1, $1 to $100 whole dollars"); +} + +/// The pinned examples, in dollars and cents, with both answers. +#[test] +fn the_pinned_examples_move_as_the_owner_was_told() { + let w = [Decimal::from(4), Decimal::ONE, Decimal::ONE]; + let six = Decimal::from(6); + let show = |v: Vec| v.iter().map(Decimal::to_string).collect::>(); + assert_eq!( + show(old_split(cents(2000), &w, six)), + ["13.33", "3.34", "3.33"] + ); + assert_eq!( + show(new_split(cents(2000), &w, six)), + ["13.34", "3.33", "3.33"] + ); +} + +/// Weights of `places` places that sum to `total` exactly: `n - 1` of +/// `total / n` rounded down, and a last one taking what is left. Built on +/// the mantissas: `Decimal` cannot hold the running sum of percents of 27 +/// places (88.888...8 has 29 digits and passes its 96 bits), and would +/// round it without a word, which is the fault K-U10 closed in the kernel. +fn even_weights(total: i128, n: u32, places: u32) -> Vec { + let whole = total * 10i128.pow(places); + let w = whole / i128::from(n); + let last = whole - w * i128::from(n - 1); + let mut weights = vec![Decimal::from_i128_with_scale(w, places); n as usize]; + *weights.last_mut().unwrap() = Decimal::from_i128_with_scale(last, places); + assert_eq!(weights.iter().map(Decimal::mantissa).sum::(), whole); + weights +} + +/// K-U10 made the kernel's product exact or refused. A split by shares +/// of 28 places that sum to one (as a convention's shares do) or by +/// percents of 27 places that sum to 100 (thirds, sevenths, ninths) has +/// products past `Decimal`'s 28 digits, so the ranking uses the rounding +/// product there: the split is made, not refused, the parts sum to the +/// whole, and each is within a cent of its share. A negative whole is +/// rounded down, as apportioning requires (the parts rounded toward zero +/// would pass the whole, which `apportion` refuses). +#[test] +fn a_split_by_weights_of_27_places_is_made_not_refused() { + let cent = cents(1); + for (total, places) in [(1i128, 28u32), (100, 27)] { + for n in [3u32, 6, 7, 9, 11] { + let weights = even_weights(total, n, places); + let total = Decimal::from_i128_with_scale(total, 0); + let amounts = (1..=400_000i64) + .step_by(37) + .chain([23_769, 99_999_999_999_999_999, 100_000_000_000_000_000]) + .flat_map(|c| [c, -c]); + for c in amounts { + let whole = cents(c); + let mode = if c < 0 { + Rounding::TowardNegativeInfinity + } else { + Rounding::TowardZero + }; + let parts = split_by_weights_with( + whole, + &weights, + total, + cent, + |x| round_places(x, 2, mode), + Leftover::LargestRemainder, + ) + .unwrap_or_else(|| panic!("{whole} by {n} parts of {places} places was refused")); + assert_eq!( + parts.iter().copied().sum::(), + whole, + "{whole} by {n}" + ); + for (p, &wt) in parts.iter().zip(&weights) { + let share = share_of(whole, wt, total).unwrap(); + assert!( + (*p - share).abs() < cent, + "{whole} by {n}: {p} for a share of {share}" + ); + } + } + } + } +} diff --git a/docs/proofs/k-u3.md b/docs/proofs/k-u3.md index 1239630c..296e1264 100644 --- a/docs/proofs/k-u3.md +++ b/docs/proofs/k-u3.md @@ -73,12 +73,14 @@ split when the whole divides), the step is 1 (or 10 for the floor harness), and the bounds are `whole` 0 to 1,000 (100 for the floor harness). 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. +checks the `Decimal` engine, whose ranking is the exact remainder (K-U10: +`whole × weight − part × total`, ties to the earlier part, the same +quantity `share_floor_with` returns). | Harness | Law | Verification | |---|---|---| | `split_by_weights_sums` | 18 | the parts sum to the whole exactly; a shortfall is handed out; the largest weight takes more. 23.9 s (2 covers) | -| `split_by_weights_within_one_step` | 42 | each part is above `-total` and at most `total` from its share, scaled by the total; a part off its share and a part exactly one step above are reached. 14.4 s (2 covers) | +| `split_by_weights_within_one_step` | 42 | each part is above `-total` and below `total` from its share, scaled by the total, and a part whose share is exact takes no unit; a part off its share, and a unit handed out while the first part's share is exact, are reached. 22 s (2 covers) | | `split_by_weights_no_part_exceeds` | 18 | no part is negative or above the whole. 12.4 s (1 cover) | | `split_by_weights_first_absorbs` | 18 | the first part is its rounded share plus the shortfall; the sum is the whole; no part exceeds it. 2.3 s (1 cover) | | `split_by_weights_last_absorbs` | 18 | the last part is the whole less the others; the sum is the whole; no part exceeds it. 4.3 s (1 cover) | @@ -86,13 +88,16 @@ checks the `Decimal` engine, whose ranking uses the rounded quotient. | `share_of_refuses_overflow` | 42 | `share_of(whole, 2, 1) = whole × 2` exactly when the product fits; a zero total and an overflowing product are `None`, never a panic. 0.47 s (2 covers) | | `share_floor_is_the_exact_floor` | 42 | the part is a multiple of the step, one more step passes the share, and the remainder is exact below `step × total`; the correction down is reached. 5.1 s (2 covers) | -The upper bound of `split_by_weights_within_one_step` is inclusive on -the `i64` model: its division truncates, so a part that divides exactly -can still take a unit when another part's truncation left one over -(`whole = 5`, weights 2/3/5: the first's 1 becomes 2, exactly one step -above its truncated share). The `Decimal` quotient keeps the fraction, a -part with no remainder never takes a unit, and the bridge checks the -strict bound there. +The upper bound of `split_by_weights_within_one_step` was inclusive on +the `i64` model until K-U10: `i64`'s division truncates, the ranking read +the quotient, and a part that divided exactly could take the unit another +part's truncation left over (`whole = 5`, weights 2/3/5: the first's 1 +became 2). The ranking is now the exact remainder, which no division +touches, so the split is 1, 2, 2 and the bound is strict on `i64` as on +`Decimal`. Kani said so itself: with the exact ranking the old cover "a +part exactly one step above its truncated share" could not be reached, +and `just prove` fails on a cover that cannot. The harness now asserts +the strict bound and that an exact share takes no unit. `share_floor_is_the_exact_floor` needed `#[kani::unwind(4)]`: without a bound on the correction loops, CBMC tried to unwind them without end and @@ -143,10 +148,9 @@ harness 500.8 s, the run inside its 3600-second cap). Lean: no-rounding split, at the scales the call sites produce. - `decimal_edges_are_none_or_exact`: `Decimal::MAX`, a product past it, a zero total, and scale 28: each `None` or exact, never a panic. -- `largest_remainder_ranks_like_the_exact_reference`: random distinct - weights over a non-terminating total (a factor of 3 or 7), against the - exact `i128` reference's ranking; exact ties are pinned below, not left - to fail this property. +- `largest_remainder_ranks_like_the_exact_reference`: random weights (ties + included, since K-U10) at whole units and at the cent, against the exact + `i128` reference's ranking. - `the_absorbing_parts_keep_the_old_scale`: the strings, scale included, for 4860 by 6/0.7/0.5 (first `4050`, as the old `split_first` gave) and 902 by 1/0.000001/0.000001 (first `902.00`); last absorbs against the @@ -154,9 +158,10 @@ harness 500.8 s, the run inside its 3600-second cap). Lean: - `split_into_matches_the_allocating_split`: the fixed-array `split_by_weights_into` and `split_by_weights_with` agree, scale included (the gate requires a bridge that calls the fixed-array form). -- `finding_ties_follow_the_rounded_quotient`: 20.00 split 4/1/1 over 6 is - 13.33/3.34/3.33, and 20 whole is 13/4/3, not the exact tie's earlier - part (K-U10 decides). +- `ties_go_to_the_earlier_part`: 20.00 split 4/1/1 over 6 is + 13.34/3.33/3.33, and 20 whole is 14/3/3 (K-U10: the ranking is exact; + the rounded quotient gave 13.33/3.34/3.33 and 13/4/3). A negative total + keeps the share's own order. - `share_floor_refuses_past_the_correction_cap`: the review's 0.1113 × 5909471247797156928749568911.8 ÷ 0.11134381908633486049673 returns `None` promptly instead of hanging. @@ -208,9 +213,9 @@ the `allocW_*` theorems were reused, not restated. `split` at ~684 is not arithmetic (it reads `k1_detail` rows) and needed no routing. 2. **The `i64` model's division truncates.** The Kani within-one-step - bound is therefore inclusive on `i64`; the `Decimal` bridge checks the - strict bound for the engine. This is a model statement, not an engine - change. + bound was therefore inclusive on `i64` while the ranking read the + quotient; since K-U10 ranks the exact remainder it is strict there + too (above). 3. **K-U10, Decimal's edges.** At `Decimal`'s 96-bit mantissa edge, `checked_div`'s rounding can move a share across a step, and `checked_mul`'s rounding hides it from `share_floor_with`'s correction. @@ -249,11 +254,17 @@ the `allocW_*` theorems were reused, not restated. checked arithmetic), and `the_absorbing_parts_keep_the_old_scale` compares strings. `LastAbsorbs` was already the old `plug_last` and the no-places conventions split, and the same property checks it. -7. **Ties follow the rounded quotient.** `split_by_weights_into` ranks the - rounded quotients' remainders, not exact rationals, so an exact tie goes - where the 28th digit sends it, not to the earlier part: - 20.00 split 4/1/1 over 6 is `13.33, 3.34, 3.33` (exact ranking would be - `13.34, 3.33, 3.33`), and 20 whole is `13, 4, 3` (exact would be - `14, 3, 3`). The pre-U3 sites did the same. Pinned by - `finding_ties_follow_the_rounded_quotient`; the owner decides the exact - ranking in K-U10, and the ranking is unchanged here. +7. **Ties go to the earlier part, exactly (K-U10).** The first version of + `split_by_weights_into` (and the pre-U3 call sites) ranked the leftover + units by the rounded quotients' remainders, so an exact tie went where + the quotient's 28th digit sent it: 20.00 split 4/1/1 over 6 was + `13.33, 3.34, 3.33` and 20 whole was `13, 4, 3`. It now ranks the exact + integer remainder `whole × weight − part × total` (the quantity + `share_floor_with` returns; the sign flipped for a negative total), so + a tie goes to the earlier part, as `apportion`'s docs and bookspec's + `Apportion.lean` (`remW`, `allocNat`: ties to the earlier member) say: + `13.34, 3.33, 3.33` and `14, 3, 3`. Pinned by + `ties_go_to_the_earlier_part`; `tests/kernel_bridge/ties.rs` keeps the + old ranking as a reference and measures what the change moves. A + recomputed past report can differ from what it showed before by a cent + between parties (a posted entry never moves). diff --git a/docs/verification.md b/docs/verification.md index a77cc8e7..3c8feb66 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -892,7 +892,7 @@ replay rules. `largest_remainder_ranks_like_the_exact_reference`, `the_absorbing_parts_keep_the_old_scale`, `split_into_matches_the_allocating_split`, - `finding_ties_follow_the_rounded_quotient`, + `ties_go_to_the_earlier_part`, `share_floor_refuses_past_the_correction_cap`, `finding_the_quotients_rounding_can_cross_a_step` - `split_by_weights_with` is an `EXCEPTIONS` wrapper (it allocates two @@ -988,20 +988,22 @@ kernel. What the proofs and their reviews found, beyond the tidying: decimal places, before computing and never on replay (D-75, `ValueOutOfRange`); `past_ten_places_the_reference_and_decimal_part_and_the_engine_refuses` pins it. -- **The 96-bit half of that precondition is not enforced.** Ten places +- **The 96-bit half of that precondition was not enforced.** Ten places each still allow a product of twenty places past about 7.9e8, which needs more than 96 bits: `1050000010.0000000001 × 9.9999999999` is `10500000099.89499999999999999999` exactly (10500000099.89 to the cent) - but `Decimal` holds 10500000099.895 and the engine books - 10500000099.90. `the_mantissa_edge_is_outside_the_precondition_and_pinned` - pins it; refusing it is the owner's decision (K-U10). -- **`Decimal`'s addition is not exact in the top unit of `MAX`.** + but `Decimal` held 10500000099.895 and the engine booked + 10500000099.90. Closed by K-U10: the kernel holds the product in 256 + bits and rounds it once, so the line books 10500000099.89 + (`the_mantissa_edge_books_the_exact_products_cent`). A line already + posted is not recomputed: replay reads the booked amount. +- **`Decimal`'s addition was not exact in the top unit of `MAX`.** `Decimal::MAX.checked_add(0.4)` is `Some(MAX)`: `rust_decimal` rounds sub-unit dust when the sum needs a 97th bit (`MAX + 0.5` is `None`), so - the kernel's "exact or `None`" contract fails there for every function + the kernel's "exact or `None`" contract failed there for every function that adds, not only `total`. No posted line reaches it (the line cap is - 10^15); `finding_decimal_add_rounds_dust_at_the_edge` and - `decimal_edge_table` pin it, and it is K-U10's to settle. + 10^15). Closed by K-U10: the kernel's sum is the exact one or `None` + (`a_sum_past_exact_arithmetic_is_refused`, `decimal_edge_table`). - **A share's quotient can cross a step, and its product's rounding can hide it.** At `Decimal`'s 96-bit mantissa edge, `checked_div`'s rounding can move a share across a step and `checked_mul`'s rounding hides that @@ -1014,7 +1016,12 @@ kernel. What the proofs and their reviews found, beyond the tidying: division carries the same edge: `MAX / 2` rounds before the step, so the part is not within half a step of the exact quotient (`the_edges` pins it); the engine's callers refuse totals of `EXACT_LIMIT` (10^26) or - more, so no schedule reaches it. Both are K-U10 items. + more, so no schedule reaches it. K-U10 settled the products: a product + that is the amount itself (`checked_mul`) is exact or refused, so the + square above is `None`; a share's product keeps rounding, under its own + name (`checked_mul_rounded`), since a share by a percent of 27 places + is a rounded figure by construction and is divided next. The division + (`checked_div`) is the engine's rounding division and is unchanged. - **One panic became a refusal.** `k1::share_property`'s old `apportion(...).expect(...)` would panic at that edge; the kernel returns `None` and the site reports `TooLargeToCompute`. @@ -1031,13 +1038,33 @@ kernel. What the proofs and their reviews found, beyond the tidying: 337.50`, the kernel `4050.00, …`), and that scale reaches `Part.amount`. The kernel computes the old expression, pinned by `the_absorbing_parts_keep_the_old_scale`. -- **Ties follow the rounded quotient.** The split ranks the rounded - quotients' remainders, not exact rationals, so an exact tie goes where - the 28th digit sends it: 20.00 split 4/1/1 over 6 is `13.33, 3.34, - 3.33` (exact ranking `13.34, 3.33, 3.33`), and 20 whole is `13, 4, 3` - (exact `14, 3, 3`). The pre-sweep sites did the same; - `finding_ties_follow_the_rounded_quotient` pins it, and the owner decides - the exact ranking in K-U10, unchanged here. +- **Ties go to the earlier part, exactly (K-U10).** The split ranked the + rounded quotients' remainders, so an exact tie went where the 28th digit + sent it: 20.00 split 4/1/1 over 6 was `13.33, 3.34, 3.33` and 20 whole + was `13, 4, 3`. The pre-sweep sites did the same, and K-U3 kept it and + pinned it. It now ranks the exact remainder `whole x weight - part x + total` (as `share_floor_with` does), so a tie goes to the earlier part: + `13.34, 3.33, 3.33` and `14, 3, 3`, which is what bookspec's + `Apportion.lean` models (`remW`, ties to the earlier member). + `ties_go_to_the_earlier_part` pins it, and `tests/kernel_bridge/ties.rs` + measures what it moves against the old ranking: nothing between two + parts or by equal weights, at most a cent a part elsewhere. The owner + decided for the exact ranking (D-76, 2026-11-09). Kani then found the + same on whole numbers: with the exact ranking a part whose share is + exact can no longer take a leftover unit (5 by 2/3/5 is 1, 2, 2, where + the truncated quotients gave 2, 1, 2), so a cover in + `split_by_weights_within_one_step` could not be reached; the harness + now asserts the strict bound and that an exact share takes no unit. +- **`Decimal`'s sums and products are exact or refused (K-U10).** + `rust_decimal` rounds a sum or product it cannot hold and returns + `Some`; the kernel's `Amount for Decimal` now checks each result in 256 + bits and refuses a rounded one. `checked_div_exact` accepted a rounded + quotient that multiplied back (`10 / 3`), found in review of the unit; + it refuses them. An independent review then found the bridge + properties proved a returned figure exact, not that an exact figure is + never refused; they now prove both, from the rational alone. One + refusal remains by design: a product that is not exact, rounded to a + step of 27 or 28 places. `docs/proofs/k-u10.md` has the account. - **The sweep changed no posted figure.** Every golden and existing test passed unchanged. `round_places` reproduces `round_dp_with_strategy` to the character except a negative-zero input (which no call site can @@ -1092,16 +1119,19 @@ Be precise about the claims: checked; the sweep's bridge properties compare the engine to an independent exact `i128` reference for every step, count and amount the `Decimal` type can hold. -- **The sweep's `Decimal` edges are pinned, not refused.** `checked_mul` - rounds at 96 bits (`fx`'s `the_mantissa_edge_is_outside_the_precondition_and_pinned` - and `123456789.0123456789²`), `checked_div` rounds at 28 significant - digits (K-U3's `finding_the_quotients_rounding_can_cross_a_step`, K-U5's - `the_edges` at `Decimal::MAX / 2`), and `checked_add` rounds sub-unit - dust in the top unit of `MAX` (K-U4's - `finding_decimal_add_rounds_dust_at_the_edge`). None is reachable by a - posted line (the line cap is 10^15, and schedules refuse totals of - `EXACT_LIMIT` or more), so the laws hold at the engine's inputs; whether - the kernel should refuse these shapes outright is K-U10's decision. +- **The sweep's `Decimal` sums and products are refused at their edges; + its divisions are pinned.** Since K-U10 the kernel's `checked_add`, + `checked_sub` and `checked_mul` for `Decimal` are exact or `None` + (`tests/kernel_bridge/decimal_exact.rs`: `Some` exactly when the exact + result is a `Decimal`), and a foreign amount at a rate is rounded once + from the exact product. Two operations round, each by name: + `checked_div` at 28 significant digits (K-U3's + `finding_the_quotients_rounding_can_cross_a_step`, K-U5's `the_edges` + at `Decimal::MAX / 2`) and a share's `checked_mul_rounded`. Neither + edge is reachable by a posted line (the line cap is 10^15, and + schedules refuse totals of `EXACT_LIMIT` or more), so the laws hold at + the engine's inputs. Not proved by Kani: the 256-bit helpers, which + rest on the bridge properties and unit tests against `num_bigint`. - **The FX overflow harness proves two concrete cases, not every overflow.** `fx_booked_refuses_overflow` proves `i64::MAX × 2` and `100 × i64::MAX` (step 1) are `None`, and that a non-positive rate is @@ -1399,7 +1429,7 @@ included): | `fx_booked_positive_for_positive` | 41 | prove | 3.2 | | `fx_booked_refuses_overflow` | 41 | prove | 2.6 | | `split_by_weights_sums` | 18 | prove | 23.9 | -| `split_by_weights_within_one_step` | 42 | prove | 14.4 | +| `split_by_weights_within_one_step` | 42 | prove | 22 | | `split_by_weights_no_part_exceeds` | 18 | prove | 12.4 | | `split_by_weights_first_absorbs` | 18 | prove | 2.3 | | `split_by_weights_last_absorbs` | 18 | prove | 4.3 | diff --git a/plan/served.md b/plan/served.md index 3895d011..e3439de7 100644 --- a/plan/served.md +++ b/plan/served.md @@ -2198,6 +2198,7 @@ The owner decisions of 2026-10-16 (at the top of this document) replace the form | D-73 | A reversal's date (owner, 2026-11-08, the question tool: "Every reversal on or after") | **Every reversal MUST be dated on or after the entry it reverses, for every kind of entry (was enforced only for document reversals and schedule runs): a correction comes after what it corrects. bookspec BS-ledger-5 states it; the engine's `check_reversal` refuses an earlier date; the Lean model's `reverse` step requires it (unit L-G1).** Found when the Lean model was made executable. In the same pass, a close with nothing to close was confirmed to post no entry and still close the period (the engine's INVARIANT 5; an entry needs two lines), and BS-period-1 is worded to say so. | | D-74 | A refusal when several rules are broken (owner, 2026-11-08, the question tool: "Any broken rule counts") | **When one command breaks several rules, an engine may refuse it with any rule it actually breaks; bookspec's examples test one broken rule at a time, and the Lean-model differential test (L-G5) checks that the engine's reason is one of the rules the command breaks.** Found by L-G5: the engine checks each line as it is added, the model checks the date and the whole entry first, so a command with two faults was refused with different words. | | D-75 | Foreign amounts and FX rates are bounded (owner, 2026-11-08, the question tool: "Cap them at 10 places") | **A new line's foreign amount and its FX rate take at most 10 decimal places each, as a base amount already does (B-28's bounds; never on replay), so foreign × rate always fits a Decimal exactly and the booked base amount is rounded once.** Found by the K-U1 review: with a 26-place foreign amount, rust_decimal rounded the product to 28 places before the engine rounded it to the cent, booking a cent the exact product doesn't reach. | +| D-76 | A tie between shares (owner, 2026-11-09, the question tool: "Exact, from now on") | **When a split leaves cents over and two parts have the same exact remainder, the cent goes to the earlier part. The remainders ranked are the exact ones, `whole × weight − part × total`, never the difference of quotients rounded at Decimal's 28th digit.** Found by K-U10b: the docs and bookspec's Lean (`Apportion`) said a tie goes to the earlier part, and the engine ranked rounded quotients, so 20.00 by 4/1/1 came out 13.33 / 3.34 / 3.33 where the rule gives 13.34 / 3.33 / 3.33. No golden file moves; no part moves by more than a cent; a split between two parts, or by equal weights, cannot differ. Splits already posted are not recomputed (posted is forever). Of the engine's splits by largest remainder only one can differ: the K-1 worksheet's share of contributed property among the members' credits in one entry (`k1::share_property`), computed on reading, which divides by the credits' total. A convention's template split and the close rule of 2026-10-13 (`periods::allocate`, frozen for replay) split by shares that sum to one, where nothing is divided and the old ranking was already the exact one. Where a weight of 27 places makes a product past Decimal's 28 digits, the split is still made, ranked by the nearest figures Decimal holds. Kani then showed the same rule on whole numbers: a part whose share is exact never takes a leftover unit (5 by 2/3/5 is 1, 2, 2, not 2, 1, 2), and the harness asserts it. | ### 10.2 Deferred