fix(core): the audit holds a close's split to under one unit once the count is trued up

BS-partner-1 statement 5 says that after a close that posts, each member's
running total MUST be under one smallest unit from its exact share. The audit
flagged drift only when it was greater than a unit, so exactly one unit passed.
The looser bound is right only until the first true-up (statement 6,
WB-partner-1): a count that still holds closes made under the older rules may
carry their rounding until a cumulative close posts.

A close records both facts replay needs: its rule (`MembersClosed.rule`) and
whether it posted (`closing_entry`). `Ledger::member_close_trued_up` says a
count has had a cumulative close that posted, at or before a given close, and
`audit::check_split` flags drift of a unit or more once it has, drift beyond a
unit before. Closes under the older rules are not read by the audit at all.

Tests: both regimes at the edge in either direction, and a count walked through
a per-close January, a non-posting February (not trued up), a posting March
(trued up) and a non-posting April (still trued up). WB-ledger-16 gains
invariant 8 for it. The same test file now cites WB-ledger-16 for the audit
(BS-ledger-13 is retired), and audit.rs's own invariant and scenario where
WB-ledger-16's numbering does not match.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-09 06:15:38 -07:00
1 parent 5fd382450b
commit 7ac1ef8c5a
5 files changed
+180 -33

No files matched your search

+19 -7
View File
@@ -1,4 +1,4 @@
//! The audit's statements checks (plan P8; BS-ledger-13): the books,
//! The audit's statements checks (plan P8; WB-ledger-16): the books,
//! read as an auditor would, through a date, as a list of findings.
//!
//! ```text
@@ -481,24 +481,36 @@ fn closes(ledger: &Ledger, through: NaiveDate) -> Vec<Finding> {
continue;
}
if let Some((_, split)) = ledger.member_close_split(p.id) {
out.extend(check_split(p.id, &p.name, &split, unit));
let trued_up = ledger.member_close_trued_up(p.id).unwrap_or(false);
out.extend(check_split(p.id, &p.name, &split, unit, trued_up));
}
}
out
}
/// One close's members: each one's running total of the closes must be
/// within a minor unit of its exact share (the cumulative rule,
/// `kernel::apportion_cumulative`).
/// under a minor unit from its exact share (the cumulative rule,
/// `kernel::apportion_cumulative`; BS-partner-1 statement 5).
///
/// `trued_up` says the count has had a close under the cumulative rule
/// 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.
pub fn check_split(
period: u64,
name: &str,
split: &[crate::periods::MemberSplit],
unit: Decimal,
trued_up: bool,
) -> Vec<Finding> {
split
.iter()
.filter(|m| (m.running - m.exact).abs() > unit)
.filter(|m| {
let drift = (m.running - m.exact).abs();
if trued_up { drift >= unit } else { drift > unit }
})
.map(|m| {
Finding::new(
"close_split_drifts",
@@ -670,7 +682,7 @@ fn settings_problems(problems: &[String]) -> Vec<Finding> {
}
// ---------------------------------------------------------------------------
// Scope, method and the attestation bar (BS-ledger-13; D-9)
// Scope, method and the attestation bar (WB-ledger-16; D-9)
// ---------------------------------------------------------------------------
/// What an audit covers.
@@ -763,7 +775,7 @@ impl Effort {
}
/// How an attestation was made, as the client says (self-reported: the
/// books record the claim, never prove it; BS-ledger-13).
/// books record the claim, never prove it; WB-ledger-16).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct Method {
/// The model that checked, as it names itself.
+26
View File
@@ -3965,6 +3965,7 @@ impl Ledger {
closed: Decimal::ZERO,
given: vec![Decimal::ZERO; members.len()],
order: Vec::new(),
trued_up: false,
};
for p in closed {
let Some(m) = &p.members_closed else {
@@ -3974,6 +3975,8 @@ impl Ledger {
break;
}
regime.since_seq = p.close_seq;
regime.trued_up |= matches!(m.rule, periods::MemberRule::Cumulative { .. })
&& p.closing_entry.is_some();
regime.order.clone_from(&m.members);
regime.closed += m.net;
for ((capital, _), part) in m.members.iter().zip(&m.parts) {
@@ -4018,6 +4021,24 @@ impl Ledger {
Some((since_seq, split))
}
/// Whether a closed members period's count has been trued up by the
/// close or an earlier one of its count: a close under the cumulative
/// rule that posted an entry has run the first true-up of the rounding
/// of closes under earlier rules (WB-partner-1), so each member's
/// running total is then strictly under one minor unit from exact
/// (BS-partner-1 statement 5). Before that, a count that holds closes
/// from the older rules may still be a unit or more away. `None` for a
/// period not closed to members.
pub fn member_close_trued_up(&self, id: PeriodId) -> Option<bool> {
let p = self.periods.get(&id)?;
let m = p.members_closed.as_ref()?;
let seq = p.close_seq?;
Some(
self.regime_where(&m.members, |q| q.close_seq <= Some(seq))
.trued_up,
)
}
/// The net closed by the run of cumulative members closes, with exactly
/// these members and shares, that ends with the latest close: zero if
/// the latest close was anything else (or there is none).
@@ -9639,6 +9660,11 @@ pub(crate) struct Regime {
/// count the next members close begins, when it is these members'
/// ([`Ledger::members_regime`]). Empty when there is none.
pub order: Vec<(AccountId, Decimal)>,
/// Whether a close under the cumulative rule that posted an entry is
/// among the count's closes: its true-up has run, so each member's
/// running total is then under one minor unit from exact
/// (BS-partner-1 statement 5).
pub trued_up: bool,
}
impl Regime {
+1
View File
@@ -196,6 +196,7 @@ fn seeds() -> Vec<(&'static str, Vec<Finding>)> {
exact: dec("1.05"),
}],
dec("0.01"),
true,
),
));
+122 -24
View File
@@ -7,7 +7,7 @@
//! GOAL: an audit says exactly what is wrong, in a fixed order, from the
//! ledger alone, and an attestation counts only against the bar the
//! books set.
//! SOURCE: BS-ledger-13; WB-ledger-16; BS-statement-1 (the statements an
//! SOURCE: WB-ledger-16; BS-statement-1 (the statements an
//! audit reads); BS-arap-2 (control accounts); BS-partner-1 (the
//! cumulative split a close must keep); BS-entry-5 (evidence);
//! DECISION D-9 (the bar), D-47 (a reversal's evidence is its
@@ -107,7 +107,7 @@ fn codes(f: &[Finding]) -> Vec<&'static str> {
// ---------------------------------------------------------------- the words
/// BS-ledger-13: a finding's severity comes from its code's row; a code no
/// WB-ledger-16: a finding's severity comes from its code's row; a code no
/// row names is a Failure (a check the table forgot is never softened).
/// Failures sort before warnings before info.
#[test]
@@ -131,7 +131,7 @@ fn a_finding_takes_its_codes_severity_and_an_unknown_code_is_a_failure() {
);
}
/// BS-ledger-13: what a finding is about, in words.
/// WB-ledger-16: what a finding is about, in words.
#[test]
fn a_subject_describes_itself_in_words() {
let cases = [
@@ -151,7 +151,7 @@ fn a_subject_describes_itself_in_words() {
}
}
/// BS-ledger-13, INVARIANT 4 (a check that cannot be made is a finding):
/// WB-ledger-16 invariant 1 (a check that cannot be made is a finding):
/// the statement of cash flows is tried by the caller. Nothing tried says
/// nothing; one that foots says nothing; one that does not foot, and one
/// that could not be made, each say so with the figures or the reason.
@@ -175,17 +175,20 @@ fn the_cash_flow_check_says_what_it_found() {
(f.code, f.severity),
("cash_flow_unfooted", Severity::Failure)
);
assert_eq!(
f.message,
"the sections sum to 40.00 but the cash accounts changed by 45.00"
// The finding carries both figures (the sentence is the engine's own).
assert!(
f.message.contains("40.00") && f.message.contains("45.00"),
"{}",
f.message
);
let unmade: Result<CashFlowFooting, String> = Err("no cash accounts named".into());
let f = audit::check_cash_flow(Some(&unmade)).unwrap();
assert_eq!(f.code, "cash_flow_unfooted");
assert_eq!(
f.message,
"the statement of cash flows cannot be made: no cash accounts named"
assert!(
f.message.contains("no cash accounts named"),
"the reason it could not be made is carried: {}",
f.message
);
}
@@ -256,11 +259,14 @@ fn control_accounts_report_differences_unattached_lines_and_overpaid_documents()
assert!(f.iter().all(|x| x.severity == Severity::Warning));
}
/// BS-partner-1 (the cumulative rule): a member's running total of the
/// closes may be at most one minor unit from its exact share; exactly one
/// is fine, one cent and a bit more is drift, in either direction.
/// BS-partner-1 statement 5 (the cumulative rule): after a close that
/// posts, a member's running total MUST be under one minor unit from its
/// exact share, so a drift of exactly one unit is raised, in either
/// direction. Statement 6 (WB-partner-1) lets a count that has not yet had
/// its first true-up carry the rounding of the older rules, so there
/// only a drift beyond one unit is raised.
#[test]
fn a_close_split_drifts_only_beyond_a_minor_unit() {
fn a_close_split_drifts_by_the_regime_it_was_made_under() {
let m = |running: &str, exact: &str| MemberSplit {
capital: 3001,
share: dec("0.3"),
@@ -269,14 +275,28 @@ fn a_close_split_drifts_only_beyond_a_minor_unit() {
exact: dec(exact),
};
let unit = dec("0.01");
assert!(audit::check_split(1, "Jan", &[m("0.32", "0.315")], unit).is_empty());
assert!(audit::check_split(1, "Jan", &[m("0.32", "0.31")], unit).is_empty());
assert!(audit::check_split(1, "Jan", &[m("0.31", "0.32")], unit).is_empty());
// Trued up: strictly under a unit is fine; a unit is drift.
assert!(audit::check_split(1, "Jan", &[m("0.32", "0.315")], unit, true).is_empty());
assert!(audit::check_split(1, "Jan", &[m("0.325", "0.32")], unit, true).is_empty());
assert!(audit::check_split(1, "Jan", &[m("0.32", "0.325")], unit, true).is_empty());
for (running, exact) in [("0.32", "0.31"), ("0.31", "0.32"), ("0.28", "0.3")] {
let f = audit::check_split(1, "Jan", &[m(running, exact)], unit, true);
assert_eq!(f.len(), 1, "{running} against {exact}");
assert_eq!(f[0].code, "close_split_drifts");
}
// Not yet trued up: a unit is the allowance; beyond it is drift.
assert!(audit::check_split(1, "Jan", &[m("0.32", "0.31")], unit, false).is_empty());
assert!(audit::check_split(1, "Jan", &[m("0.31", "0.32")], unit, false).is_empty());
assert_eq!(
audit::check_split(1, "Jan", &[m("0.32", "0.309")], unit, false).len(),
1
);
let f = audit::check_split(
4,
"Jan 2026",
&[m("0.31", "0.3"), m("0.28", "0.3"), m("0.33", "0.3")],
&[m("0.31", "0.3"), m("0.27", "0.3"), m("0.33", "0.3")],
unit,
false,
);
assert_eq!(
f.len(),
@@ -287,7 +307,85 @@ fn a_close_split_drifts_only_beyond_a_minor_unit() {
assert_eq!(f[0].subject, Subject::Period(4));
assert_eq!(
f[0].message,
"after the close of Jan 2026, account 3001 holds 0.28 of the closes where its exact share is 0.3"
"after the close of Jan 2026, account 3001 holds 0.27 of the closes where its exact share is 0.3"
);
}
/// 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
/// from what each close records (its rule and whether it posted).
#[test]
fn a_count_is_trued_up_by_the_first_cumulative_close_that_posts() {
let mut b = books();
let caps: Vec<u64> = ["3001", "3002"]
.iter()
.map(|c| {
b.l.add_account(c, c, AccountType::Equity, None, false)
.unwrap()
})
.collect();
let members = || -> Vec<MemberClose> {
caps.iter()
.map(|&capital| MemberClose {
capital,
share: dec("0.5"),
distributions: None,
})
.collect()
};
post(&mut b.l, d(1, 5), b.cash, b.revenue, "0.03");
let jan = b.l.create_period("2026-01", d(1, 1), d(1, 31)).unwrap();
let feb = b.l.create_period("2026-02", d(2, 1), d(2, 28)).unwrap();
let mar = b.l.create_period("2026-03", d(3, 1), d(3, 31)).unwrap();
let apr = b.l.create_period("2026-04", d(4, 1), d(4, 30)).unwrap();
let may = b.l.create_period("2026-05", d(5, 1), d(5, 31)).unwrap();
// January under the per-close rule: not a close the audit reads, and
// no true-up.
b.l.close_period_to(jan, &CloseTo::MembersPerClose(members()))
.unwrap();
assert_eq!(b.l.member_close_trued_up(jan), Some(false));
assert!(b.l.member_close_split(jan).is_none());
// February posts nothing under the cumulative rule: the count still
// carries January's rounding.
assert_eq!(
b.l.close_period_to(feb, &CloseTo::Members(members()))
.unwrap(),
None
);
assert_eq!(b.l.member_close_trued_up(feb), Some(false));
// March posts: the true-up has run, here and from then on.
post(&mut b.l, d(3, 5), b.cash, b.revenue, "0.01");
assert!(
b.l.close_period_to(mar, &CloseTo::Members(members()))
.unwrap()
.is_some()
);
assert_eq!(b.l.member_close_trued_up(mar), Some(true));
// April posts nothing, after the true-up: still trued up; February,
// before it, still is not.
assert_eq!(
b.l.close_period_to(apr, &CloseTo::Members(members()))
.unwrap(),
None
);
assert_eq!(b.l.member_close_trued_up(apr), Some(true));
assert_eq!(b.l.member_close_trued_up(feb), Some(false));
// The trued-up count is strictly within a unit of exact.
let (_, split) = b.l.member_close_split(apr).unwrap();
assert!(
split
.iter()
.all(|m| (m.running - m.exact).abs() < dec("0.01"))
);
// A period not closed to members has no answer; the audit is quiet.
assert_eq!(b.l.member_close_trued_up(may), None);
let f = run(&b.l, &Settings::default(), &all_receipts(&b.l), d(12, 31));
assert!(
!codes(&f).contains(&"close_split_drifts"),
"{:?}",
codes(&f)
);
}
@@ -356,8 +454,8 @@ fn set(l: &mut Ledger, key: &str, value: serde_json::Value) {
l.apply_settings(&made, &src, 1).unwrap();
}
/// BS-entry-5, INVARIANT 3 of the audit (only entries on or before the
/// date count): an uncovered entry dated after `through` is not yet a
/// audit.rs's own invariant 3 (only entries on or before the date count;
/// the evidence is BS-entry-5 statement 1): an uncovered entry dated after `through` is not yet a
/// finding, and one with a receipt never is.
#[test]
fn evidence_is_missing_only_through_the_date_and_only_without_a_receipt() {
@@ -414,8 +512,8 @@ fn a_reversal_without_its_own_receipt_is_info_and_only_when_the_policy_would_cov
assert!(run(&b.l, b.l.settings(), &have, d(12, 31)).is_empty());
}
/// BS-ledger-13 SCENARIO 2: a draft dated on or before the date is exactly
/// `draft_open`; one dated after is not mentioned.
/// audit.rs's own draft check (its scenario 2): a draft dated on or before
/// the date is exactly `draft_open`; one dated after is not mentioned.
#[test]
fn a_draft_is_open_only_through_the_date() {
let mut b = books();
@@ -435,7 +533,7 @@ fn a_draft_is_open_only_through_the_date() {
);
}
/// BS-ledger-13: the facts the caller reads from around the books are
/// WB-ledger-16: the facts the caller reads from around the books are
/// passed through as findings: a settings problem as it was worded, a
/// vendor paid in a way that could need a 1099 by name and amount.
#[test]
+12 -2
View File
@@ -491,6 +491,14 @@ INVARIANTS:
which is journaled as a decision.
7. Nothing here moves a figure. Every refusal leaves the journal
unchanged; every write waits for the feature `audits`.
8. `close_split_drifts` holds a members close to BS-partner-1
statement 5: once the count has had a close under the cumulative
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
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:
1. The same books audited twice through one day: one run, one
workpaper; the second call files and journals nothing.
@@ -508,7 +516,8 @@ SCENARIOS:
```
*Enforced:* `ledger_core::audit` (`statements`, `Finding`, `CODES`,
`AttestationBar::counts`, `Scope`, `Method`), `ledger_store::audit`
`AttestationBar::counts`, `Scope`, `Method`, `check_split`;
`Ledger::member_close_trued_up`), `ledger_store::audit`
(`Store::figure_head`, `integrity_findings`, `record_audit_run`,
`attest_receipt`, `review_entry`, `attest_period`, `run_for_period`,
`attestations`, `PROGRAM_VERSION`), `ledger_import::workpaper_pdf`,
@@ -519,7 +528,8 @@ journal feature `audits`.
`amount_mismatch_never_counts`), `tests/audit_branches.rs`
(`the_cash_flow_check_says_what_it_found`,
`control_accounts_report_differences_unattached_lines_and_overpaid_documents`,
`a_close_split_drifts_only_beyond_a_minor_unit`,
`a_close_split_drifts_by_the_regime_it_was_made_under`,
`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`,
`the_bar_counts_at_its_edges_and_only_asks_for_what_it_sets`); `ledger-store` `tests/audit.rs`