From 24b59e7b8502b1423b93a015ec9c57acccef5d7f Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 00:14:26 -0700 Subject: [PATCH] refactor(core): proportional shares in the kernel, one copy The K-1/1065 worksheet, the 1099 worksheet, the parties' shares, the conventions' template split and the cash-flow government split each computed "whole x weight / total, round, hand out the leftover" for themselves. Six copies meant six places for a rounding or sign change to reach a filed figure. Put the shape in kernel::allocate: share_of (the engine's division, rounded at Decimal's 28 significant digits, truncating on a machine integer), share_floor_with (the exact floor to a step by multiplication, the 1099 correction loop's arithmetic), and split_by_weights_with (the split, with the leftover policy named: largest remainder, first absorbs, last absorbs; the running policy stays apportion_cumulative). Each site keeps its own mode, step, sign and leftover policy, so every figure is the same to the digit; the frozen periods rules only gain a doc line naming the kernel policy they equal. Amount gains checked_div, the engine's division as distinct from checked_div_exact. All goldens and existing tests pass unchanged. Co-Authored-By: DeepSeek V4.1 Flash --- crates/ledger-core/src/cashflow.rs | 4 +- crates/ledger-core/src/conventions.rs | 41 +-- crates/ledger-core/src/form1099.rs | 37 +-- crates/ledger-core/src/k1.rs | 30 +-- crates/ledger-core/src/kernel/allocate.rs | 303 +++++++++++++++++++++- crates/ledger-core/src/kernel/entries.rs | 21 ++ crates/ledger-core/src/periods.rs | 8 + crates/ledger-core/src/shares.rs | 25 +- crates/ledger-core/src/tax_capital.rs | 9 +- 9 files changed, 394 insertions(+), 84 deletions(-) diff --git a/crates/ledger-core/src/cashflow.rs b/crates/ledger-core/src/cashflow.rs index bcb5f819..3ca95f19 100644 --- a/crates/ledger-core/src/cashflow.rs +++ b/crates/ledger-core/src/cashflow.rs @@ -1717,9 +1717,7 @@ fn split_part( places: u32, ) -> Result<(Decimal, Decimal), LedgerError> { let whole = add(ours, theirs, "an entry's party shares")?; - let part = amount - .checked_mul(ours) - .and_then(|x| x.checked_div(whole)) + let part = crate::kernel::share_of(amount, ours, whole) .ok_or_else(|| too_large("a payment's government part"))?; let part = crate::kernel::round_places(part, places, crate::kernel::Rounding::HalfToEven) .ok_or_else(|| too_large("a payment's government part"))?; diff --git a/crates/ledger-core/src/conventions.rs b/crates/ledger-core/src/conventions.rs index c2f42041..c8045cc4 100644 --- a/crates/ledger-core/src/conventions.rs +++ b/crates/ledger-core/src/conventions.rs @@ -454,27 +454,30 @@ pub fn check_id(id: &str) -> Result<(), String> { /// ([`crate::kernel::apportion`]): the parts sum to `amount` exactly /// (INVARIANT 2). pub fn split(amount: Decimal, shares: &[Decimal], places: Option) -> Option> { - use crate::kernel::{Rounding, round_places}; - let exact: Vec = shares - .iter() - .map(|s| amount.checked_mul(*s)) - .collect::>()?; + use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with}; let Some(places) = places else { - let mut parts = exact; - crate::kernel::plug_last(amount, &mut parts)?; - return Some(parts); + // No rounding: each part is amount × share, the last absorbing + // any difference (the exact split's own plug). + return split_by_weights_with( + amount, + shares, + Decimal::ONE, + Decimal::ONE, + Some, + Leftover::LastAbsorbs, + ); }; - let mut parts: Vec = exact - .iter() - .map(|e| round_places(*e, places, Rounding::TowardZero)) - .collect::>()?; - let remainders: Vec = exact - .iter() - .zip(&parts) - .map(|(e, p)| e.checked_sub(*p)) - .collect::>()?; - crate::kernel::apportion(amount, &mut parts, &remainders, Decimal::new(1, places))?; - Some(parts) + // amount × share, each part truncated toward zero to `places`, the + // leftover by largest remainder. The shares sum to one by the + // conventions' own validation, so the total is one, never their sum. + split_by_weights_with( + amount, + shares, + Decimal::ONE, + Decimal::new(1, places), + |x| round_places(x, places, Rounding::TowardZero), + Leftover::LargestRemainder, + ) } impl Conventions { diff --git a/crates/ledger-core/src/form1099.rs b/crates/ledger-core/src/form1099.rs index 055d1c9b..11f11279 100644 --- a/crates/ledger-core/src/form1099.rs +++ b/crates/ledger-core/src/form1099.rs @@ -718,14 +718,11 @@ fn vendor_part(payment: Decimal, share: Decimal, target: Decimal) -> Result Result<[Decimal; 3], LedgerError> } let (av, ap) = (v.abs(), p.abs()); 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 rems = [Decimal::ZERO; 3]; for i in 0..3 { if b[i].is_zero() { continue; } - // The exact share is num / ap: rounded down to the cent, checked - // exactly (the division alone rounds past 28 digits). - let num = b[i].abs().checked_mul(av).ok_or_else(too_large)?; - let q = num.checked_div(ap).ok_or_else(too_large)?; - let mut part = - kernel::round_places(q, 2, kernel::Rounding::TowardZero).ok_or_else(too_large)?; - while times(part)? > num { - part = part.checked_sub(cent).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)?; + // The exact share is |b[i]| × av ÷ ap, floored to the cent by + // multiplication (the division alone rounds past 28 digits); the + // kernel returns the exact floor and the exact remainder over the + // common denominator ap. + let (part, rem) = kernel::share_floor_with(b[i].abs(), av, ap, cent, |x| { + kernel::round_places(x, 2, kernel::Rounding::TowardZero) + }) + .ok_or_else(too_large)?; parts[i] = part; + rems[i] = rem; } kernel::apportion(av, &mut parts, &rems, cent).ok_or_else(too_large)?; if v.is_sign_negative() { diff --git a/crates/ledger-core/src/k1.rs b/crates/ledger-core/src/k1.rs index ffbce2f0..7df03c34 100644 --- a/crates/ledger-core/src/k1.rs +++ b/crates/ledger-core/src/k1.rs @@ -343,7 +343,7 @@ pub(crate) fn share_property( credits: &[Decimal], places: u32, ) -> Result, LedgerError> { - use crate::kernel::{Rounding, round_places}; + use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with}; let too_large = || LedgerError::TooLargeToCompute("a member's share of contributed property".into()); let total = credits @@ -354,22 +354,18 @@ pub(crate) fn share_property( if whole <= Decimal::ZERO || total <= Decimal::ZERO { return Ok(vec![Decimal::ZERO; credits.len()]); } - // whole × credit is exact; ÷ total is exact whenever the share is a - // whole number of units, so truncating never loses a unit it is owed. - let exact: Vec = credits - .iter() - .map(|c| whole.checked_mul(*c).and_then(|x| x.checked_div(total))) - .collect::>() - .ok_or_else(too_large)?; - let mut parts: Vec = exact - .iter() - .map(|x| round_places(*x, places, Rounding::TowardZero)) - .collect::>() - .ok_or_else(too_large)?; - let remainders: Vec = 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) + // whole × credit ÷ total, each part truncated toward zero to the + // currency's places, the leftover units by largest remainder. The + // kernel is the one copy of the shape (BS-partner-4's entry split). + split_by_weights_with( + whole, + credits, + total, + Decimal::new(1, places), + |x| round_places(x, places, Rounding::TowardZero), + Leftover::LargestRemainder, + ) + .ok_or_else(too_large) } /// The party a member (by name, as in wanderbooks.toml) is in the diff --git a/crates/ledger-core/src/kernel/allocate.rs b/crates/ledger-core/src/kernel/allocate.rs index df525221..36e82d58 100644 --- a/crates/ledger-core/src/kernel/allocate.rs +++ b/crates/ledger-core/src/kernel/allocate.rs @@ -1,5 +1,300 @@ -//! 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 -//! no two sweep units ever edit the same file. The module root re-exports -//! it, keeping every path `crate::kernel::foo`. +//! Division is not exact: [`share_of`] is the amount type's checked +//! division, so a `Decimal` quotient is rounded at 28 significant digits +//! (and a machine integer's is truncated), never an exact rational. Every +//! invariant below is stated of that computation, and of the parts after +//! the named leftover policy, which do sum to the whole exactly. See +//! `docs/proofs/k-u3.md` for the one place the quotient's rounding can +//! change a rounded part (Decimal's edge, K-U10). + +use super::round::Rounding; +use super::{Amount, apportion, plug_last, round_step}; + +/// What a split does with the units its rounded parts leave over. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Leftover { + /// Each part is rounded down; the units left over go one each to the + /// largest remainders (ties to the earlier part). [`apportion`]. + LargestRemainder, + /// The last part becomes the whole less the others. [`plug_last`]. + LastAbsorbs, + /// The first part becomes 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 +/// division is the only step that can round; a `Some` is always the +/// amount type's quotient, 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(whole: T, weight: T, total: T) -> Option { + 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-1099-1 (a payment split into its buckets to the cent), +/// BS-entry-3 (amounts are exact; round only where a rule says +/// to), BS-partner-1 (largest remainder). +/// 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. +/// 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( + whole: T, + weight: T, + total: T, + step: T, + round: impl Fn(T) -> Option, +) -> 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). + while part.checked_mul(total)? > num { + part = part.checked_sub(step)?; + } + loop { + let next = part.checked_add(step)?; + if next.checked_mul(total)? > num { + break; + } + part = next; + } + let remainder = num.checked_sub(part.checked_mul(total)?)?; + Some((part, remainder)) +} + +/// [`share_floor_with`] with [`round_step`] as the first estimate: the +/// exact floor of `whole × weight ÷ total` to `step`, in `mode`'s +/// direction (only `TowardZero` is the floor; the correction makes the +/// result exact either way). +pub fn share_floor( + whole: T, + weight: T, + total: T, + step: T, + mode: Rounding, +) -> Option<(T, T)> { + share_floor_with(whole, weight, total, step, |x| round_step(x, step, mode)) +} + +/// 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. +/// 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 tied cent to the first). +/// 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( + whole: T, + weights: &[T], + total: T, + unit: T, + round: impl Fn(T) -> Option, + 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 => { + let Some((first, rest)) = parts.split_first_mut() else { + return Some(()); + }; + let mut others = T::ZERO; + for &p in rest.iter() { + others = others.checked_add(p)?; + } + *first = whole.checked_sub(others)?; + Some(()) + } + } +} + +/// [`split_by_weights_into`] allocating its two buffers: the shape the +/// call sites use. +pub fn split_by_weights_with( + whole: T, + weights: &[T], + total: T, + unit: T, + round: impl Fn(T) -> Option, + policy: Leftover, +) -> Option> { + 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) +} + +/// [`split_by_weights_with`] with [`round_step`] as the rounding: the +/// generic spelling for a caller whose parts carry a whole number of +/// `step`s. +pub fn split_by_weights( + whole: T, + weights: &[T], + total: T, + step: T, + mode: Rounding, + policy: Leftover, +) -> Option> { + split_by_weights_with( + whole, + weights, + total, + step, + |x| round_step(x, step, mode), + policy, + ) +} diff --git a/crates/ledger-core/src/kernel/entries.rs b/crates/ledger-core/src/kernel/entries.rs index 07144ab2..d99f8965 100644 --- a/crates/ledger-core/src/kernel/entries.rs +++ b/crates/ledger-core/src/kernel/entries.rs @@ -33,6 +33,18 @@ pub trait Amount: Copy + Ord { /// `self / rhs` exactly, or `None` when `rhs` is zero or the quotient /// is not a whole amount of `Self` (never a rounded share). fn checked_div_exact(self, rhs: Self) -> Option; + /// `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 / rhs`, rounded once to the cent (the nearest whole minor /// unit: a unit for a machine integer, two decimal places for /// [`Decimal`] dollars), ties away from zero; never a negative zero. @@ -86,6 +98,9 @@ impl Amount for Decimal { let q = self.checked_div(rhs)?; (q.checked_mul(rhs) == Some(self)).then_some(q) } + fn checked_div(self, rhs: Self) -> Option { + Decimal::checked_div(self, rhs) + } fn checked_div_round_cent(self, rhs: Self) -> Option { if rhs == Self::ZERO { return None; @@ -185,6 +200,9 @@ impl Amount for i32 { } self.checked_div(rhs) } + fn checked_div(self, rhs: Self) -> Option { + i32::checked_div(self, rhs) + } fn checked_div_round_cent(self, rhs: Self) -> Option { if rhs == 0 { return None; @@ -237,6 +255,9 @@ impl Amount for i64 { } self.checked_div(rhs) } + fn checked_div(self, rhs: Self) -> Option { + i64::checked_div(self, rhs) + } fn checked_div_round_cent(self, rhs: Self) -> Option { if rhs == 0 { return None; diff --git a/crates/ledger-core/src/periods.rs b/crates/ledger-core/src/periods.rs index f0ba5d29..4de68e29 100644 --- a/crates/ledger-core/src/periods.rs +++ b/crates/ledger-core/src/periods.rs @@ -120,6 +120,10 @@ pub struct MemberClose { /// (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 /// 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( amount: 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). /// The same split, to the cent, for every amount [`allocate_last_absorbs`] /// 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( amount: rust_decimal::Decimal, shares: &[rust_decimal::Decimal], diff --git a/crates/ledger-core/src/shares.rs b/crates/ledger-core/src/shares.rs index d70ed17b..092910ce 100644 --- a/crates/ledger-core/src/shares.rs +++ b/crates/ledger-core/src/shares.rs @@ -284,23 +284,22 @@ fn checked_sum(values: impl IntoIterator) -> Option { /// part rounded toward zero to the cent, the cents left over to the first. /// None when a product or sum is past exact arithmetic. fn split_first(magnitude: Decimal, weights: &[Decimal]) -> Option> { - use crate::kernel::{Rounding, round_places}; + use crate::kernel::{Leftover, Rounding, round_places, split_by_weights_with}; let total = checked_sum(weights.iter().copied())?; if weights.is_empty() || total.is_zero() { return Some(vec![Decimal::ZERO; weights.len()]); } - let mut parts: Vec = weights - .iter() - .map(|w| { - magnitude - .checked_mul(*w) - .and_then(|x| x.checked_div(total)) - .and_then(|x| round_places(x, 2, Rounding::TowardZero)) - }) - .collect::>()?; - let left = magnitude.checked_sub(checked_sum(parts.iter().copied())?)?; - parts[0] = parts[0].checked_add(left)?; - Some(parts) + // magnitude × weight ÷ total, each part truncated toward zero to the + // cent, the cents left over to the first (the legacy policy this + // split keeps). The kernel is the one copy of the shape. + split_by_weights_with( + magnitude, + weights, + total, + Decimal::new(1, 2), + |x| round_places(x, 2, Rounding::TowardZero), + Leftover::FirstAbsorbs, + ) } /// What an entry's shares split, and what of it counts (the module's diff --git a/crates/ledger-core/src/tax_capital.rs b/crates/ledger-core/src/tax_capital.rs index aeb89a2d..12b68b15 100644 --- a/crates/ledger-core/src/tax_capital.rs +++ b/crates/ledger-core/src/tax_capital.rs @@ -441,12 +441,11 @@ impl RunningSplit { 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 { - whole - .checked_mul(weight) - .and_then(|p| p.checked_div(sum)) - .ok_or_else(too_large) + crate::kernel::share_of(whole, weight, sum).ok_or_else(too_large) } /// Split `whole` (to the cent) by `weights` (non-negative, one per