From 5b1596f977b1c0dc377df8d6e1c759ddb5311554 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 14:48:59 -0700 Subject: [PATCH 1/2] fix(core): the audit checks a close's split at the allocation's unit audit::closes took its unit as minor_units().unwrap_or(2), while the members allocation splits at allocation_places() (minor_units().unwrap_or(MAX_LINE_SCALE)). For a currency code with no minor unit the audit therefore checked a split made at the finest a line carries against a cent: far looser than the split it checks, so real drift passed. Add Currency::allocation_unit(), the one helper that turns allocation_places() into an amount, and take the audit's unit from it, so the split and its check cannot drift apart (BS-partner-1 statement 4: the allocation is the split to the base currency's smallest unit). A JPY close is now checked at a whole yen. Test: a_jpy_close_is_checked_at_the_allocations_unit (BS-partner-1 statement 4, WB-ledger-16 invariant 8). Co-Authored-By: Muse Wonder 1.0 --- crates/ledger-core/src/audit.rs | 7 +- crates/ledger-core/src/money.rs | 11 ++++ crates/ledger-core/tests/audit_branches.rs | 74 ++++++++++++++++++++++ docs/spec/claims/ledger.md | 6 +- 4 files changed, 96 insertions(+), 2 deletions(-) diff --git a/crates/ledger-core/src/audit.rs b/crates/ledger-core/src/audit.rs index 80e70507..34ae6acb 100644 --- a/crates/ledger-core/src/audit.rs +++ b/crates/ledger-core/src/audit.rs @@ -474,7 +474,12 @@ pub fn check_control(checks: &[crate::arap::ControlCheck]) -> Vec { } fn closes(ledger: &Ledger, through: NaiveDate) -> Vec { - let unit = Decimal::new(1, ledger.base_currency().minor_units().unwrap_or(2)); + // The unit the allocation itself splits to, from the one helper both + // sides use (`Currency::allocation_unit`, on `allocation_places`): + // for a currency with no minor unit the split is far finer than a + // cent, and the audit must not check it at a cent (BS-partner-1 + // statement 4). + let unit = ledger.base_currency().allocation_unit(); let mut out = Vec::new(); for p in ledger.list_periods() { if p.status != PeriodStatus::Closed || p.end > through { diff --git a/crates/ledger-core/src/money.rs b/crates/ledger-core/src/money.rs index c2d133da..d0f0afb0 100644 --- a/crates/ledger-core/src/money.rs +++ b/crates/ledger-core/src/money.rs @@ -69,6 +69,17 @@ impl Currency { self.minor_units().unwrap_or(crate::kernel::MAX_LINE_SCALE) } + /// One allocation unit as an amount: `1` at [`Self::allocation_places`] + /// (a cent, a whole yen, a thousandth of a dinar, the finest a line + /// carries for a code with no minor unit). This is the one place that + /// turns the places into an amount, so a split and a check of that + /// split take their unit from the same rule and cannot drift apart + /// (BS-partner-1 statement 4: the allocation is the split of the + /// amount to the base currency's smallest unit). + pub fn allocation_unit(&self) -> Decimal { + Decimal::new(1, self.allocation_places()) + } + /// The three-letter code, e.g. `"USD"`. pub fn code(&self) -> &str { std::str::from_utf8(&self.0).expect("currency codes are ASCII by construction") diff --git a/crates/ledger-core/tests/audit_branches.rs b/crates/ledger-core/tests/audit_branches.rs index 02c53c1c..fa0827a0 100644 --- a/crates/ledger-core/tests/audit_branches.rs +++ b/crates/ledger-core/tests/audit_branches.rs @@ -311,6 +311,80 @@ fn a_close_split_drifts_by_the_regime_it_was_made_under() { ); } +/// BS-partner-1 statement 4 (the allocation is the split to the base +/// currency's smallest unit) and WB-ledger-16 invariant 8: a JPY close is +/// checked at the allocation's unit -- a whole yen, JPY having no minor +/// unit below it -- not at a cent. A drift of half a yen is under that +/// unit; a drift of a whole yen after the true-up is not. +#[test] +fn a_jpy_close_is_checked_at_the_allocations_unit() { + // The one helper both the split and its audit use. + assert_eq!(Currency::JPY.allocation_unit(), dec("1")); + assert_eq!(Currency::USD.allocation_unit(), dec("0.01")); + // A code ISO 4217 gives no minor unit splits at the finest a line + // carries, so its audit unit is that, not a cent. + assert_eq!( + Currency::new("XAU").unwrap().allocation_unit(), + dec("0.0000000001") + ); + let yen = Currency::JPY.allocation_unit(); + let m = |running: &str, exact: &str| MemberSplit { + capital: 3001, + share: dec("0.5"), + part: dec(running), + running: dec(running), + exact: dec(exact), + }; + // Half a yen of drift is under one yen (it would be fifty cents' + // worth of drift at a cent unit, and flagged there). + assert!(audit::check_split(1, "Jan", &[m("100.5", "100")], yen, true).is_empty()); + // A whole yen after the true-up is a finding (statement 5's >= unit). + let f = audit::check_split(1, "Jan", &[m("101", "100")], yen, true); + assert_eq!(codes(&f), ["close_split_drifts"]); + + // End to end: a yen members close splits in whole yen and the audit + // of the closed period raises no close finding. + let mut l = Ledger::new(Currency::JPY); + let cash = l + .add_account("1000", "Bank", AccountType::Asset, None, false) + .unwrap(); + let revenue = l + .add_account("4000", "Sales", AccountType::Revenue, None, false) + .unwrap(); + let caps: Vec = ["3001", "3002"] + .iter() + .map(|c| { + l.add_account(c, c, AccountType::Equity, None, false) + .unwrap() + }) + .collect(); + let e = l.create_entry(d(1, 5), "sale"); + l.add_line(e, cash, Side::Debit, Money::new(dec("101"), Currency::JPY)) + .unwrap(); + l.add_line(e, revenue, Side::Credit, Money::new(dec("101"), Currency::JPY)) + .unwrap(); + l.post_entry(e).unwrap(); + let jan = l.create_period("2026-01", d(1, 1), d(1, 31)).unwrap(); + let members = caps + .iter() + .map(|&capital| MemberClose { + capital, + share: dec("0.5"), + distributions: None, + }) + .collect(); + l.close_period_to(jan, &CloseTo::Members(members)).unwrap(); + // 101 yen at 50/50 splits 51 / 50 whole yen (exact 50.5 each). + let balances: Vec = caps.iter().map(|&a| l.account_balance(a).unwrap()).collect(); + assert_eq!(balances, [dec("51"), dec("50")]); + let f = run(&l, &Settings::default(), &all_receipts(&l), d(12, 31)); + assert!( + !codes(&f).contains(&"close_split_drifts"), + "{:?}", + codes(&f) + ); +} + /// BS-partner-1 statement 6 and 8 (WB-partner-1): a count is trued up by /// the first close under the cumulative rule that posts an entry, not by /// a close of an older rule or one that posts nothing; the books say so diff --git a/docs/spec/claims/ledger.md b/docs/spec/claims/ledger.md index e5918872..91ac471e 100644 --- a/docs/spec/claims/ledger.md +++ b/docs/spec/claims/ledger.md @@ -519,7 +519,10 @@ INVARIANTS: rule that posted an entry (its true-up, statement 6; the close journals its rule and whether it posted), a member's running total MUST be under one minor unit from its exact share, so a drift of a - unit or more is a finding. Before that true-up the count may still + unit or more is a finding. The unit is the allocation's own + (`Currency::allocation_unit`, on `allocation_places`: a whole yen + for JPY, the finest a line carries for a code with no minor unit), + never a cent taken separately. Before that true-up the count may still carry the rounding of closes made under the older rules, so only a drift beyond one unit is. Closes under the older rules are not read. SCENARIOS: @@ -552,6 +555,7 @@ journal feature `audits`. (`the_cash_flow_check_says_what_it_found`, `control_accounts_report_differences_unattached_lines_and_overpaid_documents`, `a_close_split_drifts_by_the_regime_it_was_made_under`, +`a_jpy_close_is_checked_at_the_allocations_unit`, `a_count_is_trued_up_by_the_first_cumulative_close_that_posts`, `a_reversal_without_its_own_receipt_is_info_and_only_when_the_policy_would_cover_it`, `the_bar_setting_parses_what_it_names_and_refuses_the_rest`, From 02087ef3fb6742514421c420b0b7279c4c23cac9 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 9 Nov 2026 14:49:44 -0700 Subject: [PATCH 2/2] fix(core): a legacy close's drift before its true-up is the rule's, not one unit Before a count is trued up, check_split flagged any drift beyond one unit. BS-partner-1 statement 6 allows a legacy last-absorbs close more than that with four or more members, so the audit raised a false finding on legitimate legacy books. The rule does not state an audit bound; this bound is DERIVED from statement 6's per-member facts, and the derivation is in check_split's spec block: with n members and unit u, each member but the last was rounded to within u/2, and the last absorbed the sum of those roundings, so |e_last| <= (n-1)*u/2. Floored at u (statement 6's allowance for each run break and each per-close close), the pre-true-up bound is B(n) = max(u, (n-1)*u/2): 1.5 units with four members, 2 with five. A drift of exactly B(n) is legitimate and not flagged; past it is. After the true-up, statement 5's strict bound still holds: a drift of a unit or more is flagged. WB-ledger-16 invariant 8 now states B(n) and marks it derived. Tests: a_legacy_last_absorbs_close_drifts_by_member_count_before_its_true_up (BS-partner-1 statement 6 before the true-up, statement 5 after it; WB-ledger-16 invariant 8): four- and five-member closes at their largest legitimate drift are not flagged, one unit past it they are, and after the true-up the strict >= unit bound holds. Co-Authored-By: Muse Wonder 1.0 --- crates/ledger-core/src/audit.rs | 44 ++++++++++++-- crates/ledger-core/tests/audit_branches.rs | 68 +++++++++++++++++++++- docs/spec/claims/ledger.md | 15 ++++- 3 files changed, 117 insertions(+), 10 deletions(-) diff --git a/crates/ledger-core/src/audit.rs b/crates/ledger-core/src/audit.rs index 34ae6acb..7d4053dc 100644 --- a/crates/ledger-core/src/audit.rs +++ b/crates/ledger-core/src/audit.rs @@ -189,7 +189,7 @@ pub const CODES: &[CodeRow] = &[ CodeRow { code: "close_split_drifts", severity: Severity::Failure, - predicate: "a member's running share of the closes is more than a minor unit from its exact share", + predicate: "a member's running share of the closes drifts past the bound its regime allows from its exact share", }, CodeRow { code: "schedule_behind", @@ -501,8 +501,33 @@ fn closes(ledger: &Ledger, through: NaiveDate) -> Vec { /// that posted an entry ([`crate::Ledger::member_close_trued_up`]). Until /// then the count may still carry the rounding of closes made under the /// older rules, which the first such close trues up (BS-partner-1 -/// statement 6; WB-partner-1), so only a drift beyond a unit is raised. -/// Once trued up, a drift of a unit or more is raised: the bound is strict. +/// statement 6; WB-partner-1). +/// +/// ```text +/// SOURCE: BS-partner-1 statement 5 (after a close that posts, a member's +/// total MUST be under one smallest unit from their exact share); +/// BS-partner-1 statement 6 (the rounding left by an earlier rule +/// is trued up by the first close that posts: a last-absorbs close +/// rounded each member but the last to within half a unit, and +/// the last absorbed up to half a unit for each of the others -- +/// a unit with three members, more with four or more); WB-ledger-16 +/// invariant 8. +/// DERIVED: the rule states those per-member facts; it does not state an +/// audit bound. The pre-true-up bound below is derived from them: +/// with n members and unit u under last-absorbs, member i (not last) +/// carries rounding e_i with |e_i| <= u/2, and the last member's part +/// is the remainder, so e_last = -(e_1 + ... + e_{n-1}) and +/// |e_last| <= (n-1) * u/2. The largest drift any member of one such +/// close may legitimately carry is therefore (n-1)*u/2: u with three +/// members, 3u/2 with four, 2u with five. Statement 6 also allows +/// under u per member for each break in an earlier run and for each +/// per-close close, so the allowance is floored at u: +/// B(n) = max(u, (n-1)*u/2). A drift past B(n) is raised; a drift of +/// exactly B(n) is legitimate (every non-last tie rounding the same +/// way reaches it), so the pre-true-up test is strict (> B(n)). +/// Once trued up, statement 5's bound is strict the other way: a +/// drift of a unit or more is raised (>= u). +/// ``` pub fn check_split( period: u64, name: &str, @@ -510,11 +535,22 @@ pub fn check_split( unit: Decimal, trued_up: bool, ) -> Vec { + // B(n) as derived above: (n-1)*u/2, floored at u. `unit` is a power + // of ten and n is small, so the product and the halving are exact. + let legacy_bound = { + let others = Decimal::new(split.len().saturating_sub(1) as i64, 0); + let last = others * unit / Decimal::new(2, 0); + if last > unit { last } else { unit } + }; split .iter() .filter(|m| { let drift = (m.running - m.exact).abs(); - if trued_up { drift >= unit } else { drift > unit } + if trued_up { + drift >= unit + } else { + drift > legacy_bound + } }) .map(|m| { Finding::new( diff --git a/crates/ledger-core/tests/audit_branches.rs b/crates/ledger-core/tests/audit_branches.rs index fa0827a0..ce998cf8 100644 --- a/crates/ledger-core/tests/audit_branches.rs +++ b/crates/ledger-core/tests/audit_branches.rs @@ -361,8 +361,13 @@ fn a_jpy_close_is_checked_at_the_allocations_unit() { let e = l.create_entry(d(1, 5), "sale"); l.add_line(e, cash, Side::Debit, Money::new(dec("101"), Currency::JPY)) .unwrap(); - l.add_line(e, revenue, Side::Credit, Money::new(dec("101"), Currency::JPY)) - .unwrap(); + l.add_line( + e, + revenue, + Side::Credit, + Money::new(dec("101"), Currency::JPY), + ) + .unwrap(); l.post_entry(e).unwrap(); let jan = l.create_period("2026-01", d(1, 1), d(1, 31)).unwrap(); let members = caps @@ -375,7 +380,10 @@ fn a_jpy_close_is_checked_at_the_allocations_unit() { .collect(); l.close_period_to(jan, &CloseTo::Members(members)).unwrap(); // 101 yen at 50/50 splits 51 / 50 whole yen (exact 50.5 each). - let balances: Vec = caps.iter().map(|&a| l.account_balance(a).unwrap()).collect(); + let balances: Vec = caps + .iter() + .map(|&a| l.account_balance(a).unwrap()) + .collect(); assert_eq!(balances, [dec("51"), dec("50")]); let f = run(&l, &Settings::default(), &all_receipts(&l), d(12, 31)); assert!( @@ -385,6 +393,60 @@ fn a_jpy_close_is_checked_at_the_allocations_unit() { ); } +/// BS-partner-1 statement 6 and WB-ledger-16 invariant 8: before the +/// true-up, a legacy last-absorbs close's largest legitimate drift is +/// derived (the rule states the per-member facts, not the bound): with +/// n members and unit u, each member but the last was rounded to within +/// u/2, and the last absorbed the sum of those roundings, up to +/// (n-1)*u/2 -- so 3u/2 with four members and 2u with five (floored at +/// u, which statement 6's per-close and run allowances give). At that +/// drift a close is not flagged; one unit past it, it is. After the +/// true-up, BS-partner-1 statement 5's strict bound holds instead: a +/// drift of a unit or more is flagged. +#[test] +fn a_legacy_last_absorbs_close_drifts_by_member_count_before_its_true_up() { + let unit = dec("0.01"); + // A split of `n` members whose last-listed member carries `drift` + // (running against an exact 1.00) and whose others are exact. + let split = |n: usize, drift: &str| -> Vec { + (0..n) + .map(|i| { + let running = if i + 1 == n { + dec("1.00") + dec(drift) + } else { + dec("1.00") + }; + MemberSplit { + capital: 3001 + i as u64, + share: dec("0.25"), + part: running, + running, + exact: dec("1.00"), + } + }) + .collect() + }; + // Four members: largest legitimate drift 3 * 0.005 = 0.015, either way. + assert!(audit::check_split(1, "Jan", &split(4, "0.015"), unit, false).is_empty()); + assert!(audit::check_split(1, "Jan", &split(4, "-0.015"), unit, false).is_empty()); + // One unit past it (0.025) is flagged, exactly one member. + let f = audit::check_split(1, "Jan", &split(4, "0.025"), unit, false); + assert_eq!(codes(&f), ["close_split_drifts"]); + // Five members: largest legitimate drift 4 * 0.005 = 0.02. + assert!(audit::check_split(1, "Jan", &split(5, "0.02"), unit, false).is_empty()); + assert!(audit::check_split(1, "Jan", &split(5, "-0.02"), unit, false).is_empty()); + let f = audit::check_split(1, "Jan", &split(5, "0.03"), unit, false); + assert_eq!(codes(&f), ["close_split_drifts"]); + // After the true-up the same splits answer to statement 5: the + // four-member split at its legacy bound is past one unit, so it is + // flagged, and one just under a unit is not. + let f = audit::check_split(1, "Jan", &split(4, "0.015"), unit, true); + assert_eq!(codes(&f), ["close_split_drifts"]); + assert!(audit::check_split(1, "Jan", &split(4, "0.009"), unit, true).is_empty()); + let f = audit::check_split(1, "Jan", &split(4, "0.01"), unit, true); + assert_eq!(codes(&f), ["close_split_drifts"]); +} + /// BS-partner-1 statement 6 and 8 (WB-partner-1): a count is trued up by /// the first close under the cumulative rule that posts an entry, not by /// a close of an older rule or one that posts nothing; the books say so diff --git a/docs/spec/claims/ledger.md b/docs/spec/claims/ledger.md index 91ac471e..de69d519 100644 --- a/docs/spec/claims/ledger.md +++ b/docs/spec/claims/ledger.md @@ -522,9 +522,17 @@ INVARIANTS: unit or more is a finding. The unit is the allocation's own (`Currency::allocation_unit`, on `allocation_places`: a whole yen for JPY, the finest a line carries for a code with no minor unit), - never a cent taken separately. Before that true-up the count may still - carry the rounding of closes made under the older rules, so only a - drift beyond one unit is. Closes under the older rules are not read. + never a cent taken separately. Before that true-up the count may + still carry the rounding of closes made under the older rules, so + only a drift beyond B(n) is a finding, where B(n) = max(one unit, + (n-1) half-units) for n members: a unit with three or fewer + members, 1.5 units with four, 2 units with five. B(n) is DERIVED: + BS-partner-1 statement 6 states the per-member facts it comes from + (a last-absorbs close rounded each member but the last to within + half a unit, and the last absorbed up to half a unit for each of + the others; under a unit for each run break and each per-close + close), not the bound itself. Closes under the older rules are not + read. SCENARIOS: 1. The same books audited twice through one day: one run, one workpaper; the second call files and journals nothing. @@ -556,6 +564,7 @@ journal feature `audits`. `control_accounts_report_differences_unattached_lines_and_overpaid_documents`, `a_close_split_drifts_by_the_regime_it_was_made_under`, `a_jpy_close_is_checked_at_the_allocations_unit`, +`a_legacy_last_absorbs_close_drifts_by_member_count_before_its_true_up`, `a_count_is_trued_up_by_the_first_cumulative_close_that_posts`, `a_reversal_without_its_own_receipt_is_info_and_only_when_the_policy_would_cover_it`, `the_bar_setting_parses_what_it_names_and_refuses_the_rest`,