merge: proportional shares in the kernel, one copy for six sites (K-U3; reviewed, fixes applied)
Six places computed a share as whole x weight / total, rounded it and handed out the leftover, each with its own copy: the K-1 property split, the tax-capital running split, a convention's split, a party's shares, the 1099 bucket split, the cash-flow split. They now call one kernel function, each keeping its own rounding, step and leftover recipient, so no figure moves: every golden and every test passes unchanged, and a review fuzzed 700,000 cases a site, old against new, as strings. Proved: eight Kani harnesses, bridge properties against an independent integer reference, and law 42 in bookspec's Lean (exact shares sum to the whole; a part is within one step of its share). Found and pinned: an exact tie between remainders goes where Decimal's 28th digit sends it, as it always did (K-U10 puts exact ranking to the owner, with the cents it moves); a product of two ten-place amounts can round (K-U10). Fixed in review: the first part of a first-absorbs split had lost its scale, and an inherited correction loop could run without end on absurd input. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
1ea3f9a226
18 files changed
+1614
-111
No files matched your search
Generated
+2
-2
@@ -788,7 +788,7 @@ dependencies = [
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "bookspec-checker"
|
name = "bookspec-checker"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
source = "git+https://git.swaits.com/swaits/bookspec?rev=00b7c541d784696961a760f0486e2fe7a5e7c003#00b7c541d784696961a760f0486e2fe7a5e7c003"
|
source = "git+https://git.swaits.com/swaits/bookspec?rev=6e1b99d5da3aa56c6476b6951aaa739ae0af8d97#6e1b99d5da3aa56c6476b6951aaa739ae0af8d97"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chrono",
|
"chrono",
|
||||||
"include_dir",
|
"include_dir",
|
||||||
@@ -801,7 +801,7 @@ dependencies = [
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "bookspec-runner"
|
name = "bookspec-runner"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
source = "git+https://git.swaits.com/swaits/bookspec?rev=00b7c541d784696961a760f0486e2fe7a5e7c003#00b7c541d784696961a760f0486e2fe7a5e7c003"
|
source = "git+https://git.swaits.com/swaits/bookspec?rev=6e1b99d5da3aa56c6476b6951aaa739ae0af8d97#6e1b99d5da3aa56c6476b6951aaa739ae0af8d97"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bookspec-checker",
|
"bookspec-checker",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
|||||||
@@ -33,8 +33,8 @@ num-rational = "0.4"
|
|||||||
toml = "1"
|
toml = "1"
|
||||||
# The specification lives in its own repository (P13 step 6, D-34, D-65),
|
# The specification lives in its own repository (P13 step 6, D-34, D-65),
|
||||||
# pinned to a commit.
|
# pinned to a commit.
|
||||||
bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "00b7c541d784696961a760f0486e2fe7a5e7c003" }
|
bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "6e1b99d5da3aa56c6476b6951aaa739ae0af8d97" }
|
||||||
bookspec-runner = { git = "https://git.swaits.com/swaits/bookspec", rev = "00b7c541d784696961a760f0486e2fe7a5e7c003" }
|
bookspec-runner = { git = "https://git.swaits.com/swaits/bookspec", rev = "6e1b99d5da3aa56c6476b6951aaa739ae0af8d97" }
|
||||||
ledger-package = { path = "../ledger-package" }
|
ledger-package = { path = "../ledger-package" }
|
||||||
ledger-import = { path = "../ledger-import" }
|
ledger-import = { path = "../ledger-import" }
|
||||||
ledger-store = { path = "../ledger-store" }
|
ledger-store = { path = "../ledger-store" }
|
||||||
|
|||||||
@@ -1717,9 +1717,7 @@ fn split_part(
|
|||||||
places: u32,
|
places: u32,
|
||||||
) -> Result<(Decimal, Decimal), LedgerError> {
|
) -> Result<(Decimal, Decimal), LedgerError> {
|
||||||
let whole = add(ours, theirs, "an entry's party shares")?;
|
let whole = add(ours, theirs, "an entry's party shares")?;
|
||||||
let part = amount
|
let part = crate::kernel::share_of(amount, ours, whole)
|
||||||
.checked_mul(ours)
|
|
||||||
.and_then(|x| x.checked_div(whole))
|
|
||||||
.ok_or_else(|| too_large("a payment's government part"))?;
|
.ok_or_else(|| too_large("a payment's government part"))?;
|
||||||
let part = crate::kernel::round_places(part, places, crate::kernel::Rounding::HalfToEven)
|
let part = crate::kernel::round_places(part, places, crate::kernel::Rounding::HalfToEven)
|
||||||
.ok_or_else(|| too_large("a payment's government part"))?;
|
.ok_or_else(|| too_large("a payment's government part"))?;
|
||||||
|
|||||||
@@ -454,27 +454,30 @@ pub fn check_id(id: &str) -> Result<(), String> {
|
|||||||
/// ([`crate::kernel::apportion`]): the parts sum to `amount` exactly
|
/// ([`crate::kernel::apportion`]): the parts sum to `amount` exactly
|
||||||
/// (INVARIANT 2).
|
/// (INVARIANT 2).
|
||||||
pub fn split(amount: Decimal, shares: &[Decimal], places: Option<u32>) -> Option<Vec<Decimal>> {
|
pub fn split(amount: Decimal, shares: &[Decimal], places: Option<u32>) -> Option<Vec<Decimal>> {
|
||||||
use crate::kernel::{Rounding, round_places};
|
use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with};
|
||||||
let exact: Vec<Decimal> = shares
|
|
||||||
.iter()
|
|
||||||
.map(|s| amount.checked_mul(*s))
|
|
||||||
.collect::<Option<_>>()?;
|
|
||||||
let Some(places) = places else {
|
let Some(places) = places else {
|
||||||
let mut parts = exact;
|
// No rounding: each part is amount × share, the last absorbing
|
||||||
crate::kernel::plug_last(amount, &mut parts)?;
|
// any difference (the exact split's own plug).
|
||||||
return Some(parts);
|
return split_by_weights_with(
|
||||||
|
amount,
|
||||||
|
shares,
|
||||||
|
Decimal::ONE,
|
||||||
|
Decimal::ONE,
|
||||||
|
Some,
|
||||||
|
Leftover::LastAbsorbs,
|
||||||
|
);
|
||||||
};
|
};
|
||||||
let mut parts: Vec<Decimal> = exact
|
// amount × share, each part truncated toward zero to `places`, the
|
||||||
.iter()
|
// leftover by largest remainder. The shares sum to one by the
|
||||||
.map(|e| round_places(*e, places, Rounding::TowardZero))
|
// conventions' own validation, so the total is one, never their sum.
|
||||||
.collect::<Option<_>>()?;
|
split_by_weights_with(
|
||||||
let remainders: Vec<Decimal> = exact
|
amount,
|
||||||
.iter()
|
shares,
|
||||||
.zip(&parts)
|
Decimal::ONE,
|
||||||
.map(|(e, p)| e.checked_sub(*p))
|
Decimal::new(1, places),
|
||||||
.collect::<Option<_>>()?;
|
|x| round_places(x, places, Rounding::TowardZero),
|
||||||
crate::kernel::apportion(amount, &mut parts, &remainders, Decimal::new(1, places))?;
|
Leftover::LargestRemainder,
|
||||||
Some(parts)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Conventions {
|
impl Conventions {
|
||||||
|
|||||||
@@ -718,14 +718,11 @@ fn vendor_part(payment: Decimal, share: Decimal, target: Decimal) -> Result<Deci
|
|||||||
} else if target.is_zero() {
|
} else if target.is_zero() {
|
||||||
Ok(Decimal::ZERO)
|
Ok(Decimal::ZERO)
|
||||||
} else {
|
} else {
|
||||||
let scaled = payment
|
let scaled = crate::kernel::share_of(payment, share, target).ok_or_else(|| {
|
||||||
.checked_mul(share)
|
LedgerError::TooLargeToCompute(format!(
|
||||||
.and_then(|x| x.checked_div(target))
|
"a vendor's share ({share}) of a payment of {payment}"
|
||||||
.ok_or_else(|| {
|
))
|
||||||
LedgerError::TooLargeToCompute(format!(
|
})?;
|
||||||
"a vendor's share ({share}) of a payment of {payment}"
|
|
||||||
))
|
|
||||||
})?;
|
|
||||||
kernel::round_places(scaled, 2, kernel::Rounding::HalfAwayFromZero).ok_or_else(|| {
|
kernel::round_places(scaled, 2, kernel::Rounding::HalfAwayFromZero).ok_or_else(|| {
|
||||||
LedgerError::TooLargeToCompute(format!(
|
LedgerError::TooLargeToCompute(format!(
|
||||||
"a vendor's share ({share}) of a payment of {payment}"
|
"a vendor's share ({share}) of a payment of {payment}"
|
||||||
@@ -752,28 +749,22 @@ fn split_share(b: [Decimal; 3], v: Decimal) -> Result<[Decimal; 3], LedgerError>
|
|||||||
}
|
}
|
||||||
let (av, ap) = (v.abs(), p.abs());
|
let (av, ap) = (v.abs(), p.abs());
|
||||||
let cent = Decimal::new(1, 2);
|
let cent = Decimal::new(1, 2);
|
||||||
let times = |x: Decimal| x.checked_mul(ap).ok_or_else(too_large);
|
|
||||||
let mut parts = [Decimal::ZERO; 3];
|
let mut parts = [Decimal::ZERO; 3];
|
||||||
let mut rems = [Decimal::ZERO; 3];
|
let mut rems = [Decimal::ZERO; 3];
|
||||||
for i in 0..3 {
|
for i in 0..3 {
|
||||||
if b[i].is_zero() {
|
if b[i].is_zero() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// The exact share is num / ap: rounded down to the cent, checked
|
// The exact share is |b[i]| × av ÷ ap, floored to the cent by
|
||||||
// exactly (the division alone rounds past 28 digits).
|
// multiplication (the division alone rounds past 28 digits); the
|
||||||
let num = b[i].abs().checked_mul(av).ok_or_else(too_large)?;
|
// kernel returns the exact floor and the exact remainder over the
|
||||||
let q = num.checked_div(ap).ok_or_else(too_large)?;
|
// common denominator ap.
|
||||||
let mut part =
|
let (part, rem) = kernel::share_floor_with(b[i].abs(), av, ap, cent, |x| {
|
||||||
kernel::round_places(q, 2, kernel::Rounding::TowardZero).ok_or_else(too_large)?;
|
kernel::round_places(x, 2, kernel::Rounding::TowardZero)
|
||||||
while times(part)? > num {
|
})
|
||||||
part = part.checked_sub(cent).ok_or_else(too_large)?;
|
.ok_or_else(too_large)?;
|
||||||
}
|
|
||||||
while times(part.checked_add(cent).ok_or_else(too_large)?)? <= num {
|
|
||||||
part = part.checked_add(cent).ok_or_else(too_large)?;
|
|
||||||
}
|
|
||||||
// The remainder, over the common denominator ap.
|
|
||||||
rems[i] = num.checked_sub(times(part)?).ok_or_else(too_large)?;
|
|
||||||
parts[i] = part;
|
parts[i] = part;
|
||||||
|
rems[i] = rem;
|
||||||
}
|
}
|
||||||
kernel::apportion(av, &mut parts, &rems, cent).ok_or_else(too_large)?;
|
kernel::apportion(av, &mut parts, &rems, cent).ok_or_else(too_large)?;
|
||||||
if v.is_sign_negative() {
|
if v.is_sign_negative() {
|
||||||
|
|||||||
@@ -34,7 +34,9 @@
|
|||||||
//! it) is shared among the members credited in proportion to their
|
//! it) is shared among the members credited in proportion to their
|
||||||
//! credits, to the base currency's minor unit (cents, whole yen),
|
//! credits, to the base currency's minor unit (cents, whole yen),
|
||||||
//! leftover units by largest remainder
|
//! 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
|
//! most its own credit, and the split depends on the order the
|
||||||
//! members are given only for a tied leftover cent (never on line
|
//! members are given only for a tied leftover cent (never on line
|
||||||
//! order). Joint property is joint (BS-partner-1's
|
//! order). Joint property is joint (BS-partner-1's
|
||||||
@@ -343,7 +345,7 @@ pub(crate) fn share_property(
|
|||||||
credits: &[Decimal],
|
credits: &[Decimal],
|
||||||
places: u32,
|
places: u32,
|
||||||
) -> Result<Vec<Decimal>, LedgerError> {
|
) -> Result<Vec<Decimal>, LedgerError> {
|
||||||
use crate::kernel::{Rounding, round_places};
|
use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with};
|
||||||
let too_large =
|
let too_large =
|
||||||
|| LedgerError::TooLargeToCompute("a member's share of contributed property".into());
|
|| LedgerError::TooLargeToCompute("a member's share of contributed property".into());
|
||||||
let total = credits
|
let total = credits
|
||||||
@@ -354,22 +356,18 @@ pub(crate) fn share_property(
|
|||||||
if whole <= Decimal::ZERO || total <= Decimal::ZERO {
|
if whole <= Decimal::ZERO || total <= Decimal::ZERO {
|
||||||
return Ok(vec![Decimal::ZERO; credits.len()]);
|
return Ok(vec![Decimal::ZERO; credits.len()]);
|
||||||
}
|
}
|
||||||
// whole × credit is exact; ÷ total is exact whenever the share is a
|
// whole × credit ÷ total, each part truncated toward zero to the
|
||||||
// whole number of units, so truncating never loses a unit it is owed.
|
// currency's places, the leftover units by largest remainder. The
|
||||||
let exact: Vec<Decimal> = credits
|
// kernel is the one copy of the shape (BS-partner-4's entry split).
|
||||||
.iter()
|
split_by_weights_with(
|
||||||
.map(|c| whole.checked_mul(*c).and_then(|x| x.checked_div(total)))
|
whole,
|
||||||
.collect::<Option<_>>()
|
credits,
|
||||||
.ok_or_else(too_large)?;
|
total,
|
||||||
let mut parts: Vec<Decimal> = exact
|
Decimal::new(1, places),
|
||||||
.iter()
|
|x| round_places(x, places, Rounding::TowardZero),
|
||||||
.map(|x| round_places(*x, places, Rounding::TowardZero))
|
Leftover::LargestRemainder,
|
||||||
.collect::<Option<_>>()
|
)
|
||||||
.ok_or_else(too_large)?;
|
.ok_or_else(too_large)
|
||||||
let remainders: Vec<Decimal> = exact.iter().zip(&parts).map(|(x, p)| x - p).collect();
|
|
||||||
crate::kernel::apportion(whole, &mut parts, &remainders, Decimal::new(1, places))
|
|
||||||
.expect("each part is short by under a unit, so the shortfall is under a unit per member");
|
|
||||||
Ok(parts)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The party a member (by name, as in wanderbooks.toml) is in the
|
/// The party a member (by name, as in wanderbooks.toml) is in the
|
||||||
|
|||||||
@@ -1,5 +1,308 @@
|
|||||||
//! U3: proportional shares, splitting a whole by weights without drift (kernel sweep).
|
//! Proportional shares and weighted splits: `whole × weight ÷ total`,
|
||||||
|
//! rounded to a step, the leftover handed out by a named policy. The
|
||||||
|
//! kernel sweep's U3 (`plan/kernel-sweep-audit.md` section 3): the six
|
||||||
|
//! local copies of this arithmetic (the K-1/1065 worksheet, the 1099
|
||||||
|
//! worksheet, the parties' shares, the conventions' template split and the
|
||||||
|
//! statement of cash flows' government split) call one implementation.
|
||||||
//!
|
//!
|
||||||
//! Empty in U0: the unit adds its arithmetic here, in this file alone, so
|
//! Division is not exact: [`share_of`] is the amount type's checked
|
||||||
//! no two sweep units ever edit the same file. The module root re-exports
|
//! division, so a `Decimal` quotient is rounded at 28 significant digits
|
||||||
//! it, keeping every path `crate::kernel::foo`.
|
//! (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::{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. 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 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One member's share of `whole`: `whole × weight ÷ total`.
|
||||||
|
///
|
||||||
|
/// ```text
|
||||||
|
/// GOAL: one definition of "share = whole x weight / total", the arithmetic
|
||||||
|
/// every proportional split in the engine rests on.
|
||||||
|
/// SOURCE: BS-partner-1 (partners share by the agreement; capital accounts
|
||||||
|
/// carry the allocations), BS-partner-3 (a party's part of an
|
||||||
|
/// entry), BS-partner-4 (the K-1 worksheet), BS-1099-1 (a payment
|
||||||
|
/// split by the parties' shares), BS-statement-3 rule 5 (the
|
||||||
|
/// government's part of a payment), BS-arap-3 (a document line's
|
||||||
|
/// exact amount).
|
||||||
|
/// INVARIANTS:
|
||||||
|
/// 1. Some(s) is the amount type's `checked_mul` of whole and weight,
|
||||||
|
/// then its checked division by total. For Decimal the product and
|
||||||
|
/// quotient are exact while they fit 96 bits and scale 28, and are
|
||||||
|
/// rounded at that edge (rust_decimal's checked operations, K-U10);
|
||||||
|
/// for a machine integer the division truncates toward zero. This is
|
||||||
|
/// the computation the six call sites made before U3, to the digit.
|
||||||
|
/// 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
|
||||||
|
/// 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
|
||||||
|
/// exact rational; the split's rounding makes the part exact to its
|
||||||
|
/// step.
|
||||||
|
/// 3. IF the product or the quotient is past the amount's range: SHOULD
|
||||||
|
/// be None.
|
||||||
|
/// ```
|
||||||
|
pub fn share_of<T: Amount>(whole: T, weight: T, total: T) -> Option<T> {
|
||||||
|
whole.checked_mul(weight)?.checked_div(total)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The largest whole multiple of `step` not above `whole × weight ÷ total`,
|
||||||
|
/// with the exact remainder scaled by `total`.
|
||||||
|
///
|
||||||
|
/// ```text
|
||||||
|
/// 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-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).
|
||||||
|
/// INVARIANTS:
|
||||||
|
/// 1. whole and weight are non-negative (the callers pass magnitudes).
|
||||||
|
/// Provided `part x total` and `(part + step) x total` are exact
|
||||||
|
/// (inside Decimal's 96-bit mantissa; true for every posted line),
|
||||||
|
/// Some((part, remainder)): part is a whole multiple of step,
|
||||||
|
/// part x total <= whole x weight, and (part + step) x total >
|
||||||
|
/// whole x weight. So part is the exact floor of the share to step,
|
||||||
|
/// whatever the quotient's rounding did. At Decimal's mantissa edge
|
||||||
|
/// the comparison product itself rounds, and the correction can keep
|
||||||
|
/// a step the exact rational would not (K-U10; pinned in the bridge).
|
||||||
|
/// 2. remainder = whole x weight - part x total, in [0, step x total)
|
||||||
|
/// when total and step are positive: the exact remainder below the
|
||||||
|
/// next step, scaled by total, never the rounded quotient's
|
||||||
|
/// difference (exact when the products are; the edge above inherits
|
||||||
|
/// 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.
|
||||||
|
/// 2. IF the quotient rounds up across a step (Decimal's 28 digits at
|
||||||
|
/// the edge), while the comparison products are exact: SHOULD still
|
||||||
|
/// be the exact floor, the correction taking the step back.
|
||||||
|
/// ```
|
||||||
|
pub fn share_floor_with<T: Amount>(
|
||||||
|
whole: T,
|
||||||
|
weight: T,
|
||||||
|
total: T,
|
||||||
|
step: T,
|
||||||
|
round: impl Fn(T) -> Option<T>,
|
||||||
|
) -> Option<(T, T)> {
|
||||||
|
if total <= T::ZERO || step <= T::ZERO {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let num = whole.checked_mul(weight)?;
|
||||||
|
let quotient = num.checked_div(total)?;
|
||||||
|
let mut part = round(quotient)?;
|
||||||
|
// The quotient may have rounded across the exact floor: take whole
|
||||||
|
// 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). 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))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
/// `remainders`, a scratch buffer for the largest-remainder policy).
|
||||||
|
///
|
||||||
|
/// ```text
|
||||||
|
/// GOAL: split a whole by weights without drift: the parts sum to the
|
||||||
|
/// whole exactly, each is within one step of the share the kernel
|
||||||
|
/// computes (the largest-remainder policy), and no part exceeds the
|
||||||
|
/// whole.
|
||||||
|
/// SOURCE: BS-partner-1 (partners share by the agreement; the largest
|
||||||
|
/// remainder is the owner's choice, 2026-10-13), BS-partner-3 (a
|
||||||
|
/// party's part of an entry), BS-partner-4 (the K-1 worksheet's
|
||||||
|
/// shares), 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 (a whole number of smallest units).
|
||||||
|
/// INVARIANTS:
|
||||||
|
/// 1. With total not zero and at least one weight, the parts sum to
|
||||||
|
/// whole exactly, whatever the policy: the largest-remainder policy
|
||||||
|
/// hands out the shortfall by [`apportion`], the first/last-absorbs
|
||||||
|
/// policies give the first or last part the whole less the others
|
||||||
|
/// ([`plug_last`] for the last). An empty weight list is an empty
|
||||||
|
/// split (the callers' existing answer).
|
||||||
|
/// 2. With total not zero, every part is the share `share_of` computes,
|
||||||
|
/// rounded by `round`; under the largest-remainder policy each part
|
||||||
|
/// is within one step of that share (`part x total - whole x weight`
|
||||||
|
/// is above `-total` and at most `total` when the step is one unit;
|
||||||
|
/// the upper bound is strict when the division keeps the fraction, as
|
||||||
|
/// `Decimal` does, and a machine integer's truncating division can
|
||||||
|
/// put a part exactly one step above, never more). That share is the
|
||||||
|
/// exact rational while the division and the comparison products are
|
||||||
|
/// exact; at Decimal's mantissa edge the quotient's rounding can put
|
||||||
|
/// 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.
|
||||||
|
/// 4. total of zero is the callers' "nothing to split by": every part is
|
||||||
|
/// zero (k1's and shares::split_first's existing answer), never a
|
||||||
|
/// division by zero.
|
||||||
|
/// 5. None when the slices' lengths differ, a share or a part is not
|
||||||
|
/// representable, the unit is not positive for the largest-remainder
|
||||||
|
/// policy, or apportion refuses (the shortfall is not rounding).
|
||||||
|
/// Never a panic. On None the contents of the buffers are not
|
||||||
|
/// 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
|
||||||
|
/// 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
|
||||||
|
/// zero total) or the largest-remainder handout of the whole (a
|
||||||
|
/// positive total with zero weights, as the conventions' template
|
||||||
|
/// split has always done).
|
||||||
|
/// ```
|
||||||
|
#[allow(clippy::too_many_arguments)] // one argument per split input and buffer
|
||||||
|
pub fn split_by_weights_into<T: Amount>(
|
||||||
|
whole: T,
|
||||||
|
weights: &[T],
|
||||||
|
total: T,
|
||||||
|
unit: T,
|
||||||
|
round: impl Fn(T) -> Option<T>,
|
||||||
|
policy: Leftover,
|
||||||
|
parts: &mut [T],
|
||||||
|
remainders: &mut [T],
|
||||||
|
) -> Option<()> {
|
||||||
|
if parts.len() != weights.len() || remainders.len() != weights.len() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if total == T::ZERO {
|
||||||
|
// Nothing to split by: the call sites' existing answer.
|
||||||
|
parts.fill(T::ZERO);
|
||||||
|
return Some(());
|
||||||
|
}
|
||||||
|
// The exact shares first, so a failure leaves parts untouched until
|
||||||
|
// every share is known; the buffer doubles as the largest-remainder
|
||||||
|
// scratch below.
|
||||||
|
for i in 0..weights.len() {
|
||||||
|
remainders[i] = share_of(whole, weights[i], total)?;
|
||||||
|
}
|
||||||
|
for i in 0..weights.len() {
|
||||||
|
parts[i] = round(remainders[i])?;
|
||||||
|
}
|
||||||
|
match policy {
|
||||||
|
Leftover::LargestRemainder => {
|
||||||
|
if unit <= T::ZERO {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
for i in 0..weights.len() {
|
||||||
|
remainders[i] = remainders[i].checked_sub(parts[i])?;
|
||||||
|
}
|
||||||
|
apportion(whole, parts, remainders, unit)
|
||||||
|
}
|
||||||
|
Leftover::LastAbsorbs => plug_last(whole, parts),
|
||||||
|
Leftover::FirstAbsorbs => {
|
||||||
|
// 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 left = whole.checked_sub(sum)?;
|
||||||
|
*first = first.checked_add(left)?;
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`split_by_weights_into`] allocating its two buffers: the shape the
|
||||||
|
/// call sites use.
|
||||||
|
pub fn split_by_weights_with<T: Amount>(
|
||||||
|
whole: T,
|
||||||
|
weights: &[T],
|
||||||
|
total: T,
|
||||||
|
unit: T,
|
||||||
|
round: impl Fn(T) -> Option<T>,
|
||||||
|
policy: Leftover,
|
||||||
|
) -> Option<Vec<T>> {
|
||||||
|
let mut parts = vec![T::ZERO; weights.len()];
|
||||||
|
let mut remainders = vec![T::ZERO; weights.len()];
|
||||||
|
split_by_weights_into(
|
||||||
|
whole,
|
||||||
|
weights,
|
||||||
|
total,
|
||||||
|
unit,
|
||||||
|
round,
|
||||||
|
policy,
|
||||||
|
&mut parts,
|
||||||
|
&mut remainders,
|
||||||
|
)?;
|
||||||
|
Some(parts)
|
||||||
|
}
|
||||||
@@ -33,6 +33,18 @@ pub trait Amount: Copy + Ord {
|
|||||||
/// `self / rhs` exactly, or `None` when `rhs` is zero or the quotient
|
/// `self / rhs` exactly, or `None` when `rhs` is zero or the quotient
|
||||||
/// is not a whole amount of `Self` (never a rounded share).
|
/// is not a whole amount of `Self` (never a rounded share).
|
||||||
fn checked_div_exact(self, rhs: Self) -> Option<Self>;
|
fn checked_div_exact(self, rhs: Self) -> Option<Self>;
|
||||||
|
/// `self / rhs` as the amount type divides: exact where the division
|
||||||
|
/// terminates, otherwise rounded at the type's precision (for
|
||||||
|
/// [`Decimal`], 28 significant digits), and truncating toward zero for
|
||||||
|
/// a machine integer. `None` when `rhs` is zero or the quotient cannot
|
||||||
|
/// be represented.
|
||||||
|
///
|
||||||
|
/// This is the engine's division, not a claim that the quotient is an
|
||||||
|
/// exact rational: [`Amount::checked_div_exact`] is that one. A
|
||||||
|
/// proportional share ([`crate::kernel::share_of`]) is this division,
|
||||||
|
/// so its result is the same figure every call site computed before
|
||||||
|
/// the kernel sweep's U3.
|
||||||
|
fn checked_div(self, rhs: Self) -> Option<Self>;
|
||||||
/// `self / rhs`, rounded once to the cent (the nearest whole minor
|
/// `self / rhs`, rounded once to the cent (the nearest whole minor
|
||||||
/// unit: a unit for a machine integer, two decimal places for
|
/// unit: a unit for a machine integer, two decimal places for
|
||||||
/// [`Decimal`] dollars), ties away from zero; never a negative zero.
|
/// [`Decimal`] dollars), ties away from zero; never a negative zero.
|
||||||
@@ -86,6 +98,9 @@ impl Amount for Decimal {
|
|||||||
let q = self.checked_div(rhs)?;
|
let q = self.checked_div(rhs)?;
|
||||||
(q.checked_mul(rhs) == Some(self)).then_some(q)
|
(q.checked_mul(rhs) == Some(self)).then_some(q)
|
||||||
}
|
}
|
||||||
|
fn checked_div(self, rhs: Self) -> Option<Self> {
|
||||||
|
Decimal::checked_div(self, rhs)
|
||||||
|
}
|
||||||
fn checked_div_round_cent(self, rhs: Self) -> Option<Self> {
|
fn checked_div_round_cent(self, rhs: Self) -> Option<Self> {
|
||||||
if rhs == Self::ZERO {
|
if rhs == Self::ZERO {
|
||||||
return None;
|
return None;
|
||||||
@@ -185,6 +200,9 @@ impl Amount for i32 {
|
|||||||
}
|
}
|
||||||
self.checked_div(rhs)
|
self.checked_div(rhs)
|
||||||
}
|
}
|
||||||
|
fn checked_div(self, rhs: Self) -> Option<Self> {
|
||||||
|
i32::checked_div(self, rhs)
|
||||||
|
}
|
||||||
fn checked_div_round_cent(self, rhs: Self) -> Option<Self> {
|
fn checked_div_round_cent(self, rhs: Self) -> Option<Self> {
|
||||||
if rhs == 0 {
|
if rhs == 0 {
|
||||||
return None;
|
return None;
|
||||||
@@ -237,6 +255,9 @@ impl Amount for i64 {
|
|||||||
}
|
}
|
||||||
self.checked_div(rhs)
|
self.checked_div(rhs)
|
||||||
}
|
}
|
||||||
|
fn checked_div(self, rhs: Self) -> Option<Self> {
|
||||||
|
i64::checked_div(self, rhs)
|
||||||
|
}
|
||||||
fn checked_div_round_cent(self, rhs: Self) -> Option<Self> {
|
fn checked_div_round_cent(self, rhs: Self) -> Option<Self> {
|
||||||
if rhs == 0 {
|
if rhs == 0 {
|
||||||
return None;
|
return None;
|
||||||
|
|||||||
@@ -120,6 +120,10 @@ pub struct MemberClose {
|
|||||||
/// (owner, 2026-10-13). A loss splits as the negation of the same gain.
|
/// (owner, 2026-10-13). A loss splits as the negation of the same gain.
|
||||||
/// Closes journaled under the rules of 2026-10-13 replay with it, in cents
|
/// Closes journaled under the rules of 2026-10-13 replay with it, in cents
|
||||||
/// whatever the currency; new closes split with [`allocate_cumulative`].
|
/// whatever the currency; new closes split with [`allocate_cumulative`].
|
||||||
|
/// The arithmetic equals [`crate::kernel::split_by_weights_with`] with
|
||||||
|
/// total one, the cent as its step, toward zero and
|
||||||
|
/// [`crate::kernel::Leftover::LargestRemainder`], the sign applied after;
|
||||||
|
/// it stays here, frozen, because posted closes replay with it.
|
||||||
pub fn allocate(
|
pub fn allocate(
|
||||||
amount: rust_decimal::Decimal,
|
amount: rust_decimal::Decimal,
|
||||||
shares: &[rust_decimal::Decimal],
|
shares: &[rust_decimal::Decimal],
|
||||||
@@ -180,6 +184,10 @@ pub fn allocate_last_absorbs(
|
|||||||
/// (replay of a legacy close with a huge journaled amount, BS-entry-4).
|
/// (replay of a legacy close with a huge journaled amount, BS-entry-4).
|
||||||
/// The same split, to the cent, for every amount [`allocate_last_absorbs`]
|
/// The same split, to the cent, for every amount [`allocate_last_absorbs`]
|
||||||
/// accepts: this is the frozen rule, only its overflow now an error.
|
/// accepts: this is the frozen rule, only its overflow now an error.
|
||||||
|
/// The arithmetic equals [`crate::kernel::split_by_weights_with`] with
|
||||||
|
/// total one, the cent as its step, half away from zero and
|
||||||
|
/// [`crate::kernel::Leftover::LastAbsorbs`]; it stays here, frozen,
|
||||||
|
/// because posted closes replay with it.
|
||||||
pub fn try_allocate_last_absorbs(
|
pub fn try_allocate_last_absorbs(
|
||||||
amount: rust_decimal::Decimal,
|
amount: rust_decimal::Decimal,
|
||||||
shares: &[rust_decimal::Decimal],
|
shares: &[rust_decimal::Decimal],
|
||||||
|
|||||||
@@ -1,5 +1,258 @@
|
|||||||
//! 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
|
//! The divisor is fixed in every harness: CBMC's bit-blasted division by
|
||||||
//! every file in `proofs/`, so a harness needs no change to the module
|
//! a symbolic `i64` did not finish in 30 minutes in K-U2
|
||||||
//! root or the recipe.
|
//! (`docs/proofs/k-u2.md`), and every split here divides by a total or a
|
||||||
|
//! 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
|
||||||
|
//! 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. 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
|
||||||
|
//! 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 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 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};
|
||||||
|
|
||||||
|
/// 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");
|
||||||
|
}
|
||||||
@@ -284,23 +284,22 @@ fn checked_sum(values: impl IntoIterator<Item = Decimal>) -> Option<Decimal> {
|
|||||||
/// part rounded toward zero to the cent, the cents left over to the first.
|
/// part rounded toward zero to the cent, the cents left over to the first.
|
||||||
/// None when a product or sum is past exact arithmetic.
|
/// None when a product or sum is past exact arithmetic.
|
||||||
fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option<Vec<Decimal>> {
|
fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option<Vec<Decimal>> {
|
||||||
use crate::kernel::{Rounding, round_places};
|
use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with};
|
||||||
let total = checked_sum(weights.iter().copied())?;
|
let total = checked_sum(weights.iter().copied())?;
|
||||||
if weights.is_empty() || total.is_zero() {
|
if weights.is_empty() || total.is_zero() {
|
||||||
return Some(vec![Decimal::ZERO; weights.len()]);
|
return Some(vec![Decimal::ZERO; weights.len()]);
|
||||||
}
|
}
|
||||||
let mut parts: Vec<Decimal> = weights
|
// magnitude × weight ÷ total, each part truncated toward zero to the
|
||||||
.iter()
|
// cent, the cents left over to the first (the legacy policy this
|
||||||
.map(|w| {
|
// split keeps). The kernel is the one copy of the shape.
|
||||||
magnitude
|
split_by_weights_with(
|
||||||
.checked_mul(*w)
|
magnitude,
|
||||||
.and_then(|x| x.checked_div(total))
|
weights,
|
||||||
.and_then(|x| round_places(x, 2, Rounding::TowardZero))
|
total,
|
||||||
})
|
Decimal::new(1, 2),
|
||||||
.collect::<Option<_>>()?;
|
|x| round_places(x, 2, Rounding::TowardZero),
|
||||||
let left = magnitude.checked_sub(checked_sum(parts.iter().copied())?)?;
|
Leftover::FirstAbsorbs,
|
||||||
parts[0] = parts[0].checked_add(left)?;
|
)
|
||||||
Some(parts)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What an entry's shares split, and what of it counts (the module's
|
/// What an entry's shares split, and what of it counts (the module's
|
||||||
@@ -452,8 +451,9 @@ fn original_target(
|
|||||||
|
|
||||||
/// Split `whole` (at most the sum of `sizes`) over `sizes` in proportion,
|
/// Split `whole` (at most the sum of `sizes`) over `sizes` in proportion,
|
||||||
/// to the cent, leftover cents by largest remainder (k1's
|
/// to the cent, leftover cents by largest remainder (k1's
|
||||||
/// share_property), ties to the earlier in `order` (each part's rank).
|
/// `share_property`), a tie in the rounded remainders to the earlier in
|
||||||
/// None past exact arithmetic.
|
/// `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<Vec<Decimal>> {
|
fn share_by(whole: Decimal, sizes: &[Decimal], order: &[usize]) -> Option<Vec<Decimal>> {
|
||||||
let ranked: Vec<Decimal> = order.iter().map(|&i| sizes[i]).collect();
|
let ranked: Vec<Decimal> = order.iter().map(|&i| sizes[i]).collect();
|
||||||
let shared = crate::k1::share_property(whole, &ranked, 2).ok()?;
|
let shared = crate::k1::share_property(whole, &ranked, 2).ok()?;
|
||||||
|
|||||||
@@ -365,7 +365,8 @@ fn too_large() -> LedgerError {
|
|||||||
/// 2. A member's exact running total is Σ whole × weight / Σ weights
|
/// 2. A member's exact running total is Σ whole × weight / Σ weights
|
||||||
/// over every split so far; their running total (Σ of their parts)
|
/// over every split so far; their running total (Σ of their parts)
|
||||||
/// is the largest-remainder rounding to the cent of the exact running
|
/// 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
|
/// exact, strictly. A negative running whole is rounded as its
|
||||||
/// magnitude and negated; a running whole of zero is rounded by the
|
/// 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
|
/// sign of the whole just split. So a run of losses mirrors the run
|
||||||
@@ -441,12 +442,11 @@ impl RunningSplit {
|
|||||||
Ok((sum > Decimal::ZERO).then_some(sum))
|
Ok((sum > Decimal::ZERO).then_some(sum))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `whole × weight / sum`, the exact share of one member.
|
/// `whole × weight / sum`, the exact share of one member, through
|
||||||
|
/// [`crate::kernel::share_of`] (the one definition of the shape; its
|
||||||
|
/// division is the engine's, rounded at 28 significant digits).
|
||||||
fn share(whole: Decimal, weight: Decimal, sum: Decimal) -> Result<Decimal, LedgerError> {
|
fn share(whole: Decimal, weight: Decimal, sum: Decimal) -> Result<Decimal, LedgerError> {
|
||||||
whole
|
crate::kernel::share_of(whole, weight, sum).ok_or_else(too_large)
|
||||||
.checked_mul(weight)
|
|
||||||
.and_then(|p| p.checked_div(sum))
|
|
||||||
.ok_or_else(too_large)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Split `whole` (to the cent) by `weights` (non-negative, one per
|
/// Split `whole` (to the cent) by `weights` (non-negative, one per
|
||||||
@@ -656,7 +656,8 @@ fn entry_wholes(
|
|||||||
/// their part: the pair leaves every later entry's cents as they
|
/// their part: the pair leaves every later entry's cents as they
|
||||||
/// would be without it. Its own parts (it reads as the contrary
|
/// would be without it. Its own parts (it reads as the contrary
|
||||||
/// kind, a distribution for a contribution) are split on its own,
|
/// 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(
|
fn entry_parts(
|
||||||
ledger: &Ledger,
|
ledger: &Ledger,
|
||||||
|
|||||||
@@ -2340,7 +2340,7 @@ fn every_claim_is_backed() {
|
|||||||
}
|
}
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
EXCEPTIONS.len(),
|
EXCEPTIONS.len(),
|
||||||
14,
|
15,
|
||||||
"the kernel exception list changes only on purpose"
|
"the kernel exception list changes only on purpose"
|
||||||
);
|
);
|
||||||
// No ordinary function may fall through the right-law check: the
|
// No ordinary function may fall through the right-law check: the
|
||||||
@@ -2519,16 +2519,21 @@ const EXCEPTIONS: &[(&str, &str, &str)] = &[
|
|||||||
"a Kani harness and a law",
|
"a Kani harness and a law",
|
||||||
"it is the Decimal/currency wrapper around `round_step`; the harnesses and law 40 are round_step's, and the bridge carries them to Decimal",
|
"it is the Decimal/currency wrapper around `round_step`; the harnesses and law 40 are round_step's, and the bridge carries them to Decimal",
|
||||||
),
|
),
|
||||||
|
(
|
||||||
|
"split_by_weights_with",
|
||||||
|
"a Kani harness and a law",
|
||||||
|
"it allocates two Vec buffers; every harness calls the fixed-array `split_by_weights_into` directly, and its law 18 is split_by_weights_into's",
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
/// The kernel functions the right-law check cannot apply to, pinned
|
/// The kernel functions the right-law check cannot apply to, pinned
|
||||||
/// exactly: each is excepted above, and lacks either a harness law or a
|
/// exactly: each is excepted above, and lacks either a harness law or a
|
||||||
/// cited rule for one. `movements` and `reversal` allocate, so every
|
/// cited rule for one. `movements`, `reversal` and
|
||||||
/// harness proves their fixed-array helper; `round_places`, `round_minor`
|
/// `split_by_weights_with` allocate, so every harness proves their
|
||||||
/// and `fx_booked_minor` are Decimal wrappers whose law is the inner
|
/// fixed-array helper; `round_places`, `round_minor` and `fx_booked_minor`
|
||||||
/// function's; `Direction::key` is a wire name and `MonthPart::is_valid` a
|
/// are Decimal wrappers whose law is the inner function's; `Direction::key`
|
||||||
/// range predicate, with no law at all. A new name here is a deliberate
|
/// is a wire name and `MonthPart::is_valid` a range predicate, with no law
|
||||||
/// widening, never a silent hole.
|
/// at all. A new name here is a deliberate widening, never a silent hole.
|
||||||
const SKIPPED: &[&str] = &[
|
const SKIPPED: &[&str] = &[
|
||||||
"movements",
|
"movements",
|
||||||
"reversal",
|
"reversal",
|
||||||
@@ -2537,6 +2542,7 @@ const SKIPPED: &[&str] = &[
|
|||||||
"round_places",
|
"round_places",
|
||||||
"round_minor",
|
"round_minor",
|
||||||
"fx_booked_minor",
|
"fx_booked_minor",
|
||||||
|
"split_by_weights_with",
|
||||||
];
|
];
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1,4 +1,669 @@
|
|||||||
//! 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,
|
//! `proofs/allocate.rs` proves the split on `i64` with fixed weights and
|
||||||
//! beside `main.rs` and the other units.
|
//! 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_into, 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<Vec<i128>> {
|
||||||
|
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::<i128>())?;
|
||||||
|
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<Vec<i128>> {
|
||||||
|
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<Vec<Decimal>> {
|
||||||
|
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<i128> {
|
||||||
|
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_with(
|
||||||
|
whole,
|
||||||
|
&weights,
|
||||||
|
10,
|
||||||
|
1,
|
||||||
|
|x| round_step(x, 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::<Vec<_>>(), 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::<Decimal>(), 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_with(
|
||||||
|
whole,
|
||||||
|
&weights,
|
||||||
|
10,
|
||||||
|
1,
|
||||||
|
|x| round_step(x, 1, Rounding::TowardZero),
|
||||||
|
Leftover::FirstAbsorbs,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let last = split_by_weights_with(
|
||||||
|
whole,
|
||||||
|
&weights,
|
||||||
|
10,
|
||||||
|
1,
|
||||||
|
|x| round_step(x, 1, Rounding::TowardZero),
|
||||||
|
Leftover::LastAbsorbs,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
prop_assert_eq!(
|
||||||
|
first.iter().map(|&p| i128::from(p)).collect::<Vec<_>>(),
|
||||||
|
reference_absorb(i128::from(whole), &[2, 3, 5], 10, 1, true).unwrap()
|
||||||
|
);
|
||||||
|
prop_assert_eq!(
|
||||||
|
last.iter().map(|&p| i128::from(p)).collect::<Vec<_>>(),
|
||||||
|
reference_absorb(i128::from(whole), &[2, 3, 5], 10, 1, false).unwrap()
|
||||||
|
);
|
||||||
|
prop_assert_eq!(first.iter().sum::<i64>(), whole);
|
||||||
|
prop_assert_eq!(last.iter().sum::<i64>(), 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<i128> = 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<Decimal> = 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::<Vec<_>>(),
|
||||||
|
i128::from(total),
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
prop_assert_eq!(got.iter().map(|&p| integer(p)).collect::<Vec<_>>(), 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::<Decimal>(), finest);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A zero total is zeros, whatever the weights.
|
||||||
|
assert_eq!(
|
||||||
|
split_by_weights_with(
|
||||||
|
dec(5),
|
||||||
|
&[dec(1), dec(2)],
|
||||||
|
Decimal::ZERO,
|
||||||
|
Decimal::ONE,
|
||||||
|
|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::<Vec<_>>();
|
||||||
|
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::<Vec<_>>(),
|
||||||
|
with.iter().map(Decimal::to_string).collect::<Vec<_>>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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::<Vec<_>>(),
|
||||||
|
["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::<Vec<_>>(),
|
||||||
|
["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
|
||||||
|
/// `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
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -21,7 +21,7 @@ zip = "9.0.1"
|
|||||||
workspace = true
|
workspace = true
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "00b7c541d784696961a760f0486e2fe7a5e7c003" }
|
bookspec-checker = { git = "https://git.swaits.com/swaits/bookspec", rev = "6e1b99d5da3aa56c6476b6951aaa739ae0af8d97" }
|
||||||
proptest = "1"
|
proptest = "1"
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
toml = "1"
|
toml = "1"
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
# 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<T: Amount>(whole: T, weight: T, total: T) -> Option<T>
|
||||||
|
|
||||||
|
pub fn share_floor_with<T: Amount>(
|
||||||
|
whole: T, weight: T, total: T, step: T,
|
||||||
|
round: impl Fn(T) -> Option<T>,
|
||||||
|
) -> Option<(T, T)>
|
||||||
|
|
||||||
|
pub fn split_by_weights_into<T: Amount>(
|
||||||
|
whole: T, weights: &[T], total: T, unit: T,
|
||||||
|
round: impl Fn(T) -> Option<T>, policy: Leftover,
|
||||||
|
parts: &mut [T], remainders: &mut [T],
|
||||||
|
) -> Option<()>
|
||||||
|
pub fn split_by_weights_with<T: Amount>(
|
||||||
|
whole: T, weights: &[T], total: T, unit: T,
|
||||||
|
round: impl Fn(T) -> Option<T>, policy: Leftover,
|
||||||
|
) -> Option<Vec<T>>
|
||||||
|
```
|
||||||
|
|
||||||
|
`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. The product is a
|
||||||
|
`Decimal::checked_mul`, which rounds at 96 bits too. 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, now bounded: past `MAX_CORRECTION_STEPS` steps in
|
||||||
|
either direction it returns `None` instead of walking without end.
|
||||||
|
|
||||||
|
`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. `split_by_weights_with` is the same split allocating its two
|
||||||
|
buffers; it and `share_floor_with` are the public API (`share_floor` and
|
||||||
|
`split_by_weights` had no engine caller and are gone).
|
||||||
|
|
||||||
|
`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 (three different weights, a tied
|
||||||
|
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.
|
||||||
|
|
||||||
|
| 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_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) |
|
||||||
|
| `split_by_weights_zero_total_is_zero` | 18 | 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` | 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.
|
||||||
|
|
||||||
|
`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. The loops also carry `MAX_CORRECTION_STEPS` now, so
|
||||||
|
a malformed input refuses; that bound only adds a condition inside the
|
||||||
|
same loops, and `unwind(4)` still holds.
|
||||||
|
|
||||||
|
Measured alone on this machine, 2026-11-09, with
|
||||||
|
`cargo kani -p ledger-core --exact --harness proofs::allocate::<name>`.
|
||||||
|
|
||||||
|
`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.
|
||||||
|
- `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.
|
||||||
|
- `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
|
||||||
|
old `plug_last` and the no-places conventions split.
|
||||||
|
- `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).
|
||||||
|
- `share_floor_refuses_past_the_correction_cap`: the review's
|
||||||
|
0.1113 × 5909471247797156928749568911.8 ÷ 0.11134381908633486049673
|
||||||
|
returns `None` promptly instead of hanging.
|
||||||
|
- `finding_the_quotients_rounding_can_cross_a_step`: the K-U10 case
|
||||||
|
below.
|
||||||
|
|
||||||
|
## Lean (bookspec, law 42)
|
||||||
|
|
||||||
|
`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. That pinned case
|
||||||
|
is the one no posted line reaches (the line cap is 10^15). The
|
||||||
|
product's rounding is reachable: a scale-10 line below the cap
|
||||||
|
multiplied by itself, `123456789.0123456789²`, gives
|
||||||
|
`15241578753238836.750190519988`, not the exact square. Both roundings
|
||||||
|
are K-U10 items: it is for K-U10 to settle whether the kernel should
|
||||||
|
refuse either 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 correction is bounded.** The floor harness's loops needed
|
||||||
|
`#[kani::unwind(4)]`, and the review found an input whose rounded
|
||||||
|
product put the estimate far from the exact floor, so the old loop
|
||||||
|
did not terminate: `0.1113 × 5909471247797156928749568911.8 ÷
|
||||||
|
0.11134381908633486049673`. The kernel now takes at most
|
||||||
|
`MAX_CORRECTION_STEPS` in each direction and returns `None` past the
|
||||||
|
cap; no figure the loop produced within the cap changes. The bridge's
|
||||||
|
`share_floor_refuses_past_the_correction_cap` pins the input, and its
|
||||||
|
exact `i128` reference carries the same law for every step and
|
||||||
|
magnitude.
|
||||||
|
6. **The first part keeps the old scale.** The old `shares::split_first`
|
||||||
|
computed `parts[0] + (whole − Σ parts)`; the first kernel version
|
||||||
|
computed `whole − Σ rest`. The values are equal, but the scale differs
|
||||||
|
in 665 of 400k fuzzed cases: 4860 by 6/0.7/0.5 gave `4050, 472.50,
|
||||||
|
337.50` and the kernel's `4050.00, …`; 902 by 1/0.000001/0.000001 gave
|
||||||
|
`902.00` and the kernel's `902`. That scale reaches `Part.amount`, so a
|
||||||
|
printed share moved. The kernel computes the old expression now (with
|
||||||
|
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.
|
||||||
@@ -5,10 +5,10 @@
|
|||||||
"type": "git",
|
"type": "git",
|
||||||
"subDir": "lean",
|
"subDir": "lean",
|
||||||
"scope": "",
|
"scope": "",
|
||||||
"rev": "00b7c541d784696961a760f0486e2fe7a5e7c003",
|
"rev": "6e1b99d5da3aa56c6476b6951aaa739ae0af8d97",
|
||||||
"name": "bookspec",
|
"name": "bookspec",
|
||||||
"manifestFile": "lake-manifest.json",
|
"manifestFile": "lake-manifest.json",
|
||||||
"inputRev": "00b7c541d784696961a760f0486e2fe7a5e7c003",
|
"inputRev": "6e1b99d5da3aa56c6476b6951aaa739ae0af8d97",
|
||||||
"inherited": false,
|
"inherited": false,
|
||||||
"configFile": "lakefile.toml"}],
|
"configFile": "lakefile.toml"}],
|
||||||
"name": "wanderbooks",
|
"name": "wanderbooks",
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ packagesDir = ".lake/packages"
|
|||||||
[[require]]
|
[[require]]
|
||||||
name = "bookspec"
|
name = "bookspec"
|
||||||
git = "https://git.swaits.com/swaits/bookspec"
|
git = "https://git.swaits.com/swaits/bookspec"
|
||||||
rev = "00b7c541d784696961a760f0486e2fe7a5e7c003"
|
rev = "6e1b99d5da3aa56c6476b6951aaa739ae0af8d97"
|
||||||
subDir = "lean"
|
subDir = "lean"
|
||||||
|
|
||||||
[[lean_lib]]
|
[[lean_lib]]
|
||||||
|
|||||||
Reference in new issue
Block a user