diff --git a/crates/ledger-core/src/proofs/allocate.rs b/crates/ledger-core/src/proofs/allocate.rs index 83afb7bb..da3f7a69 100644 --- a/crates/ledger-core/src/proofs/allocate.rs +++ b/crates/ledger-core/src/proofs/allocate.rs @@ -1,5 +1,253 @@ -//! U3 proof harnesses: proportional shares (kernel sweep). +//! U3 proof harnesses: proportional shares and weighted 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. +//! 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. +//! +//! ```text +//! GOAL: the parts of a weighted split sum to the whole exactly, each +//! part is within one step of its exact share (largest remainder), +//! no part exceeds the whole, and a zero total or all-zero weights +//! is the callers' answer rather than a division by zero. +//! SOURCE: BS-partner-1 (partners share by the agreement; largest +//! remainder), BS-1099-1 (a payment's buckets), BS-statement-3 +//! rule 5 (the government's part), BS-arap-3 (a document line's +//! exact amount), BS-ledger-1 (whole smallest units). +//! 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. +//! 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 +//! largest remainder, and refuse once the shortfall needs as many +//! 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. +//! 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. + +use crate::kernel::{self, Leftover, Rounding, share_floor_with, share_of, split_by_weights_into}; + +/// The number of parts the fixed-array harnesses explore. +const N: usize = 3; + +/// The tied weights: 20% / 30% / 50%, so the remainders differ. +const WEIGHTS: [i64; N] = [2, 3, 5]; +/// Their total. +const TOTAL: i64 = 10; + +/// Split `whole` by the fixed weights at the fixed total, unit and mode. +fn split(whole: i64, unit: i64, policy: Leftover) -> Option<([i64; N], [i64; N])> { + let mut parts = [0i64; N]; + let mut remainders = [0i64; N]; + split_by_weights_into( + whole, + &WEIGHTS, + TOTAL, + unit, + |x| kernel::round_step(x, unit, Rounding::TowardZero), + policy, + &mut parts, + &mut remainders, + )?; + Some((parts, remainders)) +} + +/// A whole the split harnesses explore: 0 to 1,000. +fn any_whole() -> i64 { + let whole: i64 = kani::any(); + kani::assume((0..=1_000).contains(&whole)); + whole +} + +/// The parts sum to the whole exactly, by largest remainder. +#[kani::proof] +fn split_by_weights_sums() { + let whole = any_whole(); + let (parts, _) = split(whole, 1, Leftover::LargestRemainder).expect("in range"); + let sum = parts[0] + parts[1] + parts[2]; + assert_eq!(sum, whole); + kani::cover!(whole % TOTAL != 0, "a shortfall handed out"); + kani::cover!(parts[2] > parts[1], "the largest weight takes more"); +} + +/// 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`. +/// +/// 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. +#[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); + } + kani::cover!( + parts + .iter() + .enumerate() + .any(|(i, &p)| p * TOTAL != whole * WEIGHTS[i]), + "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" + ); +} + +/// No part is negative or above the whole (the weights are in [0, total]). +#[kani::proof] +fn split_by_weights_no_part_exceeds() { + let whole = any_whole(); + let (parts, _) = split(whole, 1, Leftover::LargestRemainder).expect("in range"); + for &p in &parts { + assert!(0 <= p && p <= whole); + } + kani::cover!(parts[1] > 0, "a middle part takes its share"); +} + +/// First absorbs: the first part is the whole less the others, and no +/// part is above the whole. +#[kani::proof] +fn split_by_weights_first_absorbs() { + let whole = any_whole(); + let (parts, _) = split(whole, 1, Leftover::FirstAbsorbs).expect("in range"); + assert_eq!(parts[0], whole - parts[1] - parts[2]); + assert_eq!(parts[0] + parts[1] + parts[2], whole); + for &p in &parts { + assert!(0 <= p && p <= whole); + } + kani::cover!(parts[1] != 0 && parts[2] != 0, "the others take theirs"); +} + +/// Last absorbs: the last part is the whole less the others, and no part +/// is above the whole. +#[kani::proof] +fn split_by_weights_last_absorbs() { + let whole = any_whole(); + let (parts, _) = split(whole, 1, Leftover::LastAbsorbs).expect("in range"); + assert_eq!(parts[2], whole - parts[0] - parts[1]); + assert_eq!(parts[0] + parts[1] + parts[2], whole); + for &p in &parts { + assert!(0 <= p && p <= whole); + } + kani::cover!(parts[0] != 0 && parts[1] != 0, "the others take theirs"); +} + +/// A zero total is zeros; all-zero weights with a positive total hand the +/// whole out by largest remainder, and refuse once the shortfall needs as +/// many units as there are parts. +#[kani::proof] +fn split_by_weights_zero_total_is_zero() { + let whole = any_whole(); + let mut p = [0i64; N]; + let mut r = [0i64; N]; + split_by_weights_into( + whole, + &WEIGHTS, + 0, + 1, + |x| kernel::round_step(x, 1, Rounding::TowardZero), + Leftover::LargestRemainder, + &mut p, + &mut r, + ) + .expect("a zero total is not a division by zero"); + assert_eq!(p, [0, 0, 0]); + + let zeros = [0i64; N]; + let mut p = [0i64; N]; + let mut r = [0i64; N]; + let got = split_by_weights_into( + whole, + &zeros, + TOTAL, + 1, + |x| kernel::round_step(x, 1, Rounding::TowardZero), + Leftover::LargestRemainder, + &mut p, + &mut r, + ); + assert_eq!(got.is_some(), whole < N as i64); + if got.is_some() { + assert_eq!(p[0] + p[1] + p[2], whole); + } + kani::cover!( + whole < N as i64, + "zero weights, a shortfall within the parts" + ); +} + +/// `share_of` is the product and then the division: an overflowing +/// product or a zero total is `None`, never a panic. +#[kani::proof] +fn share_of_refuses_overflow() { + let whole: i64 = kani::any(); + assert_eq!(share_of(whole, 2, 1), whole.checked_mul(2)); + assert_eq!(share_of(whole, 1, 0), None); + let big: i64 = kani::any(); + kani::assume(big > i64::MAX / 2); + assert_eq!(share_of(big, 2, 1), None); + kani::cover!(big == i64::MAX, "the largest amount"); + kani::cover!( + whole.checked_mul(2).is_some() && whole != 0, + "a product in range" + ); +} + +/// `share_floor_with` is the exact floor to the step even when the first +/// estimate rounds up across it: the part is a multiple of the step, one +/// more step would pass the share, and the remainder is exact. +#[kani::proof] +#[kani::unwind(4)] +fn share_floor_is_the_exact_floor() { + let whole: i64 = kani::any(); + kani::assume((0..=100).contains(&whole)); + let weight: i64 = kani::any(); + kani::assume((0..=10).contains(&weight)); + // A step of ten with half-away's first estimate: `whole x weight / + // total` near a half step (5) rounds up to ten, and the correction + // takes it back to the exact floor (zero). Smaller bounds than the + // split harnesses: the correction's multiplications and the + // symbolic quotient were past an hour at 1,000 x 100 (K-U3 note). + let step = 10; + let (part, rem) = share_floor_with(whole, weight, TOTAL, step, |x| { + kernel::round_step(x, step, Rounding::HalfAwayFromZero) + }) + .expect("in range"); + let num = whole * weight; + assert_eq!(part % step, 0); + assert!(part * TOTAL <= num); + assert!((part + step) * TOTAL > num); + assert_eq!(rem, num - part * TOTAL); + assert!(0 <= rem && rem < step * TOTAL); + kani::cover!(rem > 0, "a remainder below the next step"); + kani::cover!(part == 0 && num >= 5 * TOTAL, "the estimate corrected down"); +} diff --git a/crates/ledger-core/tests/kernel_bridge/allocate.rs b/crates/ledger-core/tests/kernel_bridge/allocate.rs index 5921b8ce..328c02b9 100644 --- a/crates/ledger-core/tests/kernel_bridge/allocate.rs +++ b/crates/ledger-core/tests/kernel_bridge/allocate.rs @@ -1,4 +1,456 @@ -//! U3 bridge properties: proportional shares (kernel sweep). +//! U3 bridge properties: proportional shares and weighted splits (kernel +//! sweep). //! -//! Empty in U0: the unit adds its `Decimal`-vs-integer properties here, -//! beside `main.rs` and the other units. +//! `proofs/allocate.rs` proves the split on `i64` with fixed weights and +//! totals; the engine runs the same code on `Decimal`. These properties +//! check that both instantiations agree, that the `Decimal` split agrees +//! with an independent exact `i128` reference (integer products and +//! remainders, sharing no code with the kernel) for weights summing to one +//! and to arbitrary totals, that each leftover policy matches its own +//! reference, and the edges: zero weights, one member, many members, +//! `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, +}; +use proptest::prelude::*; +use rust_decimal::Decimal; + +use super::dec; + +fn parse(text: &str) -> Decimal { + text.parse().expect("a decimal literal") +} + +/// An independent exact reference for a largest-remainder split, all in +/// the smallest unit: floor each exact share to `step`, then hand the +/// shortfall out by largest remainder (ties to the earlier part). No +/// kernel code and no `Decimal`. +fn reference(whole: i128, weights: &[i128], total: i128, step: i128) -> Option> { + if total == 0 { + return Some(vec![0; weights.len()]); + } + if total < 0 || step <= 0 { + return None; + } + let mut parts = Vec::with_capacity(weights.len()); + let mut rems = Vec::with_capacity(weights.len()); + for &w in weights { + let num = whole.checked_mul(w)?; + let part = num.div_euclid(total).div_euclid(step).checked_mul(step)?; + parts.push(part); + rems.push(num.checked_sub(part.checked_mul(total)?)?); + } + let mut shortfall = whole.checked_sub(parts.iter().sum::())?; + if shortfall < 0 { + return None; + } + let mut units = 0usize; + while shortfall >= step { + shortfall -= step; + units += 1; + if units == parts.len() { + return None; + } + } + for i in 0..parts.len() { + let rank = (0..rems.len()) + .filter(|&j| rems[j] > rems[i] || (rems[j] == rems[i] && j < i)) + .count(); + let mut add = 0i128; + if rank < units { + add += step; + } + if rank == 0 { + add += shortfall; + } + parts[i] = parts[i].checked_add(add)?; + } + Some(parts) +} + +/// The first/last-absorbs reference: floor each share to `step`, then give +/// the first or last part the whole less the others. +fn reference_absorb( + whole: i128, + weights: &[i128], + total: i128, + step: i128, + first: bool, +) -> Option> { + if total == 0 { + return Some(vec![0; weights.len()]); + } + let mut parts = Vec::with_capacity(weights.len()); + for &w in weights { + let num = whole.checked_mul(w)?; + parts.push(num.div_euclid(total).div_euclid(step).checked_mul(step)?); + } + if parts.is_empty() { + return Some(parts); + } + let others: i128 = if first { + parts[1..].iter().sum() + } else { + parts[..parts.len() - 1].iter().sum() + }; + let absorbed = whole.checked_sub(others)?; + if first { + parts[0] = absorbed; + } else { + *parts.last_mut()? = absorbed; + } + Some(parts) +} + +/// The exact floor to `step` and its remainder, in integers. +fn reference_floor(whole: i128, weight: i128, total: i128, step: i128) -> (i128, i128) { + let num = whole * weight; + let part = (num / total / step) * step; + (part, num - part * total) +} + +/// The engine's split at `places`, largest remainder, through +/// `round_places` (the call sites' scale-preserving rounding). +fn decimal_split( + whole: Decimal, + weights: &[Decimal], + total: Decimal, + places: u32, + policy: Leftover, +) -> Option> { + split_by_weights_with( + whole, + weights, + total, + Decimal::new(1, places), + |x| round_places(x, places, Rounding::TowardZero), + policy, + ) +} + +/// A Decimal that is a whole number of cents, as that count. +fn cents(parts: &[Decimal]) -> Vec { + parts + .iter() + .map(|d| (d * Decimal::from(100)).normalize().mantissa()) + .collect() +} + +/// A Decimal that is a whole number, as that integer. +fn integer(d: Decimal) -> i128 { + d.normalize().mantissa() +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(2000))] + + /// The `i64` kernel (the Kani model, in cents) and the `Decimal` + /// kernel (the engine, in dollars) agree, value for value, where the + /// shares divide exactly: the `i64` quotient is then the same exact + /// share, so the largest-remainder recipient is the same. (Where a + /// share does not divide, the `i64` quotient truncates and the + /// Decimal one keeps the fraction; the property below carries the + /// laws Kani proves, which do not depend on the recipient.) + #[test] + fn i64_and_decimal_agree(k in 0i64..=100_000) { + let whole = k * 10; + let weights = [2i64, 3, 5]; + let narrow = split_by_weights( + whole, + &weights, + 10, + 1, + Rounding::TowardZero, + Leftover::LargestRemainder, + ) + .unwrap(); + let wide = decimal_split( + dec(whole), + &[dec(2), dec(3), dec(5)], + dec(10), + 2, + Leftover::LargestRemainder, + ) + .unwrap(); + prop_assert_eq!(narrow.into_iter().map(dec).collect::>(), wide); + } + + /// The laws Kani proves on `i64` hold on `Decimal` for every whole, + /// remainder or not: the parts sum to the whole, each is within one + /// step of its exact share (scaled by the total), and none exceeds + /// the whole. + #[test] + fn decimal_split_satisfies_the_kani_laws(whole in 0i64..=1_000_000) { + let parts = decimal_split( + dec(whole), + &[dec(2), dec(3), dec(5)], + dec(10), + 2, + Leftover::LargestRemainder, + ) + .unwrap(); + prop_assert_eq!(parts.iter().sum::(), dec(whole)); + for (i, &p) in parts.iter().enumerate() { + prop_assert!(p >= Decimal::ZERO && p <= dec(whole)); + let drift = p * Decimal::from(10) - dec(whole) * Decimal::from([2, 3, 5][i]); + let bound = Decimal::new(1, 1); + prop_assert!(drift > -bound && drift < bound); + } + } + + /// The exact `i128` reference: weights over an arbitrary total (2/3/5 + /// of 10), the engine's cents. + #[test] + fn decimal_matches_the_exact_reference(whole in 0i64..=1_000_000) { + let want = reference(i128::from(whole), &[2, 3, 5], 10, 1).unwrap(); + let got = decimal_split( + dec(whole), + &[dec(2), dec(3), dec(5)], + dec(10), + 2, + Leftover::LargestRemainder, + ) + .unwrap(); + prop_assert_eq!(cents(&got), want); + } + + /// The exact reference with weights summing to one (0.5 / 0.3 / 0.2): + /// the total is one, so the exact share is the product, and the + /// reference sees the same weights as 5/3/2 of 10. + #[test] + fn decimal_matches_the_exact_reference_weights_sum_to_one(whole in 0i64..=1_000_000) { + let want = reference(i128::from(whole), &[5, 3, 2], 10, 1).unwrap(); + let got = decimal_split( + dec(whole), + &[parse("0.5"), parse("0.3"), parse("0.2")], + Decimal::ONE, + 2, + Leftover::LargestRemainder, + ) + .unwrap(); + prop_assert_eq!(cents(&got), want); + } + + /// First and last absorb: the same floors, the first or last part + /// taking the whole less the others. + #[test] + fn leftovers_at_each_policy(whole in 0i64..=1_000_000) { + let weights = [2i64, 3, 5]; + let first = split_by_weights( + whole, + &weights, + 10, + 1, + Rounding::TowardZero, + Leftover::FirstAbsorbs, + ) + .unwrap(); + let last = split_by_weights( + whole, + &weights, + 10, + 1, + Rounding::TowardZero, + Leftover::LastAbsorbs, + ) + .unwrap(); + prop_assert_eq!( + first.iter().map(|&p| i128::from(p)).collect::>(), + reference_absorb(i128::from(whole), &[2, 3, 5], 10, 1, true).unwrap() + ); + prop_assert_eq!( + last.iter().map(|&p| i128::from(p)).collect::>(), + reference_absorb(i128::from(whole), &[2, 3, 5], 10, 1, false).unwrap() + ); + prop_assert_eq!(first.iter().sum::(), whole); + prop_assert_eq!(last.iter().sum::(), whole); + } + + /// Zero weights: a positive total hands the whole out by largest + /// remainder while it fits one unit per part, and refuses past that; + /// a zero total is zeros. One member takes everything; many members + /// agree with the reference. + #[test] + fn zero_weights_one_member_and_many( + whole in 0i64..=100_000, + members in 1usize..=10, + ) { + let zeros = vec![Decimal::ZERO; 3]; + let got = decimal_split(dec(whole), &zeros, dec(10), 2, Leftover::LargestRemainder); + let want = reference(i128::from(whole), &[0, 0, 0], 10, 1); + prop_assert_eq!(got.map(|p| cents(&p)), want); + + let one = decimal_split(dec(whole), &[Decimal::ONE], Decimal::ONE, 2, Leftover::LargestRemainder).unwrap(); + prop_assert_eq!(one, vec![dec(whole)]); + + let weights = vec![Decimal::ONE; members]; + let want = reference(i128::from(whole), &vec![1i128; members], members as i128, 1).unwrap(); + let got = decimal_split(dec(whole), &weights, Decimal::from(members), 2, Leftover::LargestRemainder).unwrap(); + prop_assert_eq!(cents(&got), 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. + #[test] + fn share_floor_matches_the_exact_reference( + whole in 0i64..=1_000_000, + weight in 0i64..=1_000, + total in 1i64..=1_000, + step in 1i64..=100, + ) { + let want = reference_floor(i128::from(whole), i128::from(weight), i128::from(total), i128::from(step)); + let got = share_floor_with( + Decimal::from(whole), + Decimal::from(weight), + Decimal::from(total), + Decimal::from(step), + |x| round_step(x, Decimal::from(step), Rounding::TowardZero), + ) + .unwrap(); + prop_assert_eq!((integer(got.0), integer(got.1)), want); + } +} + +/// The hand-checked table: the shapes the six call sites produce, at the +/// scale they produce them. +#[test] +fn split_at_the_call_sites_scales() { + // k1's property split: 401 by credits 750/250 to cents. + let got = decimal_split( + Decimal::from(401), + &[Decimal::from(750), Decimal::from(250)], + Decimal::from(1000), + 2, + Leftover::LargestRemainder, + ) + .unwrap(); + assert_eq!(got, vec![parse("300.75"), parse("100.25")]); + + // A cent split 50/50 (the tied cent to the first). + let got = decimal_split( + dec(1), + &[parse("0.5"), parse("0.5")], + Decimal::ONE, + 2, + Leftover::LargestRemainder, + ) + .unwrap(); + assert_eq!(got, vec![parse("0.01"), parse("0.00")]); + + // Whole yen: 101 by 51/51, the tied yen to the first. + let got = decimal_split( + Decimal::from(101), + &[Decimal::from(51), Decimal::from(51)], + Decimal::from(102), + 0, + Leftover::LargestRemainder, + ) + .unwrap(); + assert_eq!(got, vec![Decimal::from(51), Decimal::from(50)]); + + // The exact split with no rounding: amount x share, the last plugs. + let got = split_by_weights_with( + Decimal::from(7), + &[parse("0.5"), parse("0.5")], + Decimal::ONE, + Decimal::ONE, + Some, + Leftover::LastAbsorbs, + ) + .unwrap(); + assert_eq!(got, vec![parse("3.5"), parse("3.5")]); +} + +/// The edges: `Decimal::MAX`, a product past it, a zero total, scale 28. +/// Each is `None` or exact, never a panic. +#[test] +fn decimal_edges_are_none_or_exact() { + assert_eq!(share_of(Decimal::MAX, Decimal::from(2), Decimal::ONE), None); + assert_eq!( + share_of(Decimal::MAX, Decimal::ONE, Decimal::MAX), + Some(Decimal::ONE) + ); + assert_eq!(share_of(Decimal::ONE, Decimal::ONE, Decimal::ZERO), None); + + assert_eq!( + share_floor_with( + Decimal::MAX, + Decimal::from(2), + Decimal::ONE, + Decimal::ONE, + Some + ), + None + ); + assert_eq!( + split_by_weights_with( + Decimal::MAX, + &[Decimal::from(2)], + Decimal::ONE, + Decimal::ONE, + Some, + Leftover::LargestRemainder + ), + None + ); + + // The finest amount: the quotient may not be representable, but the + // split is never a panic and, when it is Some, still sums. + let finest = parse("0.0000000000000000000000000001"); + let got = split_by_weights_with( + finest, + &[Decimal::ONE, Decimal::ONE], + Decimal::from(2), + finest, + Some, + Leftover::LargestRemainder, + ); + if let Some(parts) = got { + assert_eq!(parts.iter().sum::(), finest); + } + + // A zero total is zeros, whatever the weights. + assert_eq!( + split_by_weights( + dec(5), + &[dec(1), dec(2)], + Decimal::ZERO, + Decimal::ONE, + Rounding::TowardZero, + Leftover::LargestRemainder + ), + Some(vec![Decimal::ZERO, Decimal::ZERO]) + ); +} + +/// 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 +/// `whole / total` just above `whole`; the kernel's quotient rounds up to +/// `whole + 0.01`, so the largest-remainder split refuses (a part above +/// the whole is never emitted), and `share_floor_with` keeps the rounded +/// step because the comparison product rounds to the same figure. No +/// posted line reaches this edge (the line cap is 10^15); it is pinned so +/// a future change to the division or multiplication cannot move it +/// silently. +#[test] +fn finding_the_quotients_rounding_can_cross_a_step() { + let whole = Decimal::try_from_i128_with_scale(7923000000000000000000000099i128, 2).unwrap(); + let total = Decimal::try_from_i128_with_scale(9999999999999999999999999999i128, 28).unwrap(); + let rounded = Decimal::try_from_i128_with_scale(7923000000000000000000000100i128, 2).unwrap(); + assert_eq!(share_of(whole, Decimal::ONE, total), Some(rounded)); + assert_eq!( + share_floor_with(whole, Decimal::ONE, total, Decimal::new(1, 2), |x| { + round_places(x, 2, Rounding::TowardZero) + }) + .map(|(part, _)| part), + Some(rounded) + ); + assert_eq!( + decimal_split(whole, &[Decimal::ONE], total, 2, Leftover::LargestRemainder), + None + ); +} diff --git a/docs/proofs/k-u3.md b/docs/proofs/k-u3.md new file mode 100644 index 00000000..4a7805ce --- /dev/null +++ b/docs/proofs/k-u3.md @@ -0,0 +1,212 @@ +# K-U3: proportional shares and weighted splits + +Status: landed 2026-11-09. The kernel sweep's U3 +(`plan/kernel-sweep-audit.md` section 3): the six local copies of +"share = whole × weight ÷ total, round, hand out the leftover" call one +implementation; the laws are proved on `i64` by Kani, checked on +`Decimal` against an independent exact reference, and stated once in +bookspec's Lean. + +## The API + +```rust +pub enum Leftover { LargestRemainder, LastAbsorbs, FirstAbsorbs } + +pub fn share_of(whole: T, weight: T, total: T) -> Option + +pub fn share_floor_with( + whole: T, weight: T, total: T, step: T, + round: impl Fn(T) -> Option, +) -> Option<(T, T)> +pub fn share_floor( + whole: T, weight: T, total: T, step: T, mode: Rounding, +) -> Option<(T, T)> + +pub fn split_by_weights_into( + whole: T, weights: &[T], total: T, unit: T, + round: impl Fn(T) -> Option, policy: Leftover, + parts: &mut [T], remainders: &mut [T], +) -> Option<()> +pub fn split_by_weights_with( + whole: T, weights: &[T], total: T, unit: T, + round: impl Fn(T) -> Option, policy: Leftover, +) -> Option> +pub fn split_by_weights( + whole: T, weights: &[T], total: T, step: T, mode: Rounding, + policy: Leftover, +) -> Option> +``` + +`share_of` is `whole × weight ÷ total` through the new +`Amount::checked_div`: `Decimal::checked_div` (exact where it terminates, +rounded at 28 significant digits otherwise) for the engine, truncating +integer division for a machine integer. That is the computation every +call site made before U3, to the digit. + +`share_floor_with` is the exact floor of a share to a step, found by +multiplication rather than by trusting the quotient, plus the exact +remainder scaled by `total`. It is the arithmetic of the 1099 worksheet's +old correction loop; the loop is gone. + +`split_by_weights_into` is the split itself. The caller supplies the +total (not necessarily the sum of the weights: the conventions' shares +sum to one, the K-1 and party splits to their own total) and the +rounding function (the call sites pass `round_places`, whose scale rule +is what preserves the filed figures' scale; the Kani model passes +`round_step`). The leftover policy is explicit: largest remainder, +first absorbs, or last absorbs. The cumulative policy stays +`apportion_cumulative`, the running version, which `tax_capital` already +used. + +`Amount::checked_div` is the one trait addition. It is documented as the +engine's division, not an exact-rational claim; `checked_div_exact` is +that one. + +## Kani harnesses (`crates/ledger-core/src/proofs/allocate.rs`) + +All at `i64`, fixed arrays (no symbolic-length `Vec`, no +`copy_from_slice`), each with `kani::cover!`. 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, and every split divides by a total or a +step. The fixed weights are 2/3/5 of 10 (a tied split with three +different remainders), 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 at +any size and the bridge checks the `Decimal` engine. + +| Harness | Law | Verification | +|---|---|---| +| `split_by_weights_sums` | 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` | 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_no_part_exceeds` | no part is negative or above the whole | 12.4 s (1 cover) | +| `split_by_weights_first_absorbs` | the first part is the whole less the others; the sum is the whole; no part exceeds it | 8.7 s (1 cover) | +| `split_by_weights_last_absorbs` | the last part is the whole less the others; the sum is the whole; no part exceeds it | 8.7 s (1 cover) | +| `split_by_weights_zero_total_is_zero` | a zero total is zeros; all-zero weights hand the whole out by largest remainder while the shortfall fits, and refuse past it | 4.2 s (1 cover) | +| `share_of_refuses_overflow` | `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` | 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.3 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. + +`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 +the harness ran past an hour at 1,000 × 100. With the bound and smaller +bounds (whole to 100, weight to 10, total 10, step 10) it verifies in +5.3 s. The bound is enough because half-away's first estimate is at most +one step above the exact floor and the increment loop at most one step +below; the bridge's exact reference carries the law for every other +step and magnitude. + +Measured alone on this machine, 2026-11-09, with +`cargo kani -p ledger-core --exact --harness proofs::allocate::`. + +`just prove` (fast set): **80 harnesses**, 0 failures. The recipe's +1800-second batch cap was hit twice while the shared machine carried a +load average of 26-33 (the log's completed harnesses all passed, the +batch was killed while the rest ran); the same fast set run manually +with `-j 8` verified **80 of 80 harnesses, 0 failures** (the heaviest +harness 500.8 s, the run inside its 3600-second cap). Lean: +`verify/lean` 151 theorems, standard axioms only. + +## Bridge (`crates/ledger-core/tests/kernel_bridge/allocate.rs`) + +- `i64_and_decimal_agree`: the Kani model in cents and the engine in + dollars agree value for value where the shares divide exactly (the + `i64` quotient is then the same exact share, so the largest-remainder + recipient is the same). +- `decimal_split_satisfies_the_kani_laws`: for every whole, remainder or + not, the `Decimal` parts sum to the whole, each is within one step of + its share (strictly, scaled by the total), and none exceeds the whole. +- `decimal_matches_the_exact_reference`: an independent `i128` reference + (integer products and remainders, no kernel code and no `Decimal`) + over weights 2/3/5 of 10, whole in cents. +- `decimal_matches_the_exact_reference_weights_sum_to_one`: the same + reference with weights 0.5/0.3/0.2 and total one. +- `leftovers_at_each_policy`: first and last absorbs against their own + reference; the parts still sum. +- `zero_weights_one_member_and_many`: zero weights (the handout and the + refusal past one unit per part), one member, and one to ten equal + members, against the reference. +- `share_floor_matches_the_exact_reference`: `share_floor_with` against + the exact `i128` floor for non-terminating totals (3, 7, 11), any step + to 100; the quotient's 28-digit rounding is corrected. +- `split_at_the_call_sites_scales`: the K-1 property split (401 by + 750/250), a cent 50/50, whole yen (101 by 51/51), and the exact + 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. +- `finding_the_quotients_rounding_can_cross_a_step`: the K-U10 case + below. + +## Lean (bookspec, branch `k-u3`) + +`lean/Bookspec/Apportion.lean`, law 42 in `spec/laws.md`, headline +theorems in `lean/Audit.lean`. Build: `lake build && lake env lean +Audit.lean`, standard axioms only; `cargo test --workspace`, `render -- +--check` and `scripts/spec-floors.sh main` pass. + +- `Apportion.exact_shares_sum` — with the weights summing to `W`, the + exact shares' numerators `x · w_i` sum to `x · W`; no weight is lost or + invented. +- `Apportion.shares_of_near` — a split part is within one step of its + exact share, gain or loss. It is `allocW_drift` under the name the + kernel's split uses; nothing is reproved. + +BS-partner-1's invariants now link `exact_shares_sum` and +`shares_of_near` (the split's own framing of the existing +`allocW_drift` bound). `Apportion.apportion_sum`, `apportion_drift` and +the `allocW_*` theorems were reused, not restated. + +## Findings + +1. **No behaviour change for posted values.** Every golden and every + existing test passes unchanged. The six sites keep their own rounding + mode, step, leftover policy, sign handling and error: + - `tax_capital::RunningSplit::share` (used by `split` and `unsplit`) + → `share_of`; + - `k1::share_property` → `split_by_weights_with`, total = Σ credits, + `10^-places`, toward zero, largest remainder (`shares::share_by` + reaches it through this); + - `conventions::split` → `split_by_weights_with`, total = one, + `10^-places`, toward zero, largest remainder; no places → identity + rounding, last absorbs; + - `shares::split_first` → `split_by_weights_with`, total = Σ weights, + the cent, toward zero, first absorbs; + - `form1099::vendor_part` → `share_of` then `round_places` (the + `payment == target` and `target == 0` short cuts stay); + `form1099::split_share` → `share_floor_with` per bucket then + `apportion` (the hand-rolled correction loop is gone); + - `cashflow::split_part` → `share_of` then `round_places`. + `periods::allocate` and `periods::allocate_last_absorbs` are frozen + replay rules: their arithmetic is untouched, and their doc comments + now name the kernel policy each equals. `k1.rs`'s test helper named + `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. +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. + Pinned by `finding_the_quotients_rounding_can_cross_a_step`: the exact + share is just above the whole, the quotient rounds to one cent above + it, the largest-remainder split refuses (a part above the whole is + never emitted), and the floor keeps the rounded step. No posted line + reaches this edge (the line cap is 10^15); it is for K-U10 to settle + whether the kernel should refuse the quotient's rounding outright. +4. **One panic became a refusal.** `k1::share_property`'s old + `apportion(...).expect(...)` would panic at the edge above (a + shortfall of one unit per part is not rounding); the kernel returns + `None` and the site reports `TooLargeToCompute`. Unreachable with + line-capped credits, and the bar is no panic. +5. **The floor harness's loops needed a bound.** Without + `#[kani::unwind(4)]` the correction loops were intractable; the + bridge's exact `i128` reference carries the same law for every step + and magnitude, including the non-terminating divisions the bound + harness does not reach.