merge: the control, aging and reconciliation identities in the kernel (K-U8; reviewed, fixes applied)

Three identities the books rest on are kernel functions now, proved
rather than only summed: an aging's five buckets add to the document
total (aging_total), a control account's difference from its documents
and unattached lines (control_difference), and the K-1 reconciliation's
total (reconciliation_total). Kani proves each, None exactly on
overflow; bridge properties check them against an exact integer
reference and the replaced chains on 20,000 cases, scale included; law
46 in bookspec's Lean. The CPA package's aging now refuses a total past
exact arithmetic instead of panicking. The harnesses found the integer
model's subtraction negating first, so x - MIN was refused where it fits;
i64 and i32 now use the native subtraction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-11-09 13:52:10 -07:00
commit 8aa0ed985d
9 files changed
+815 -33

No files matched your search

+8 -4
View File
@@ -1355,10 +1355,14 @@ pub struct AgingRow {
impl AgingRow {
/// Total outstanding; refused past exact arithmetic.
pub fn total(&self) -> Result<Decimal, LedgerError> {
[self.days_30, self.days_60, self.days_90, self.days_90_plus]
.into_iter()
.try_fold(self.current, Decimal::checked_add)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{}'s aging total", self.name)))
crate::kernel::aging_total(
self.current,
self.days_30,
self.days_60,
self.days_90,
self.days_90_plus,
)
.ok_or_else(|| LedgerError::TooLargeToCompute(format!("{}'s aging total", self.name)))
}
/// Add `other`'s buckets to this row's; refused past exact arithmetic.
+115 -4
View File
@@ -1,5 +1,116 @@
//! U8: control and aging, what is due or overdue (kernel sweep).
//! U8: control, aging and reconciliation totals (kernel sweep).
//!
//! 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`.
//! Three identities the books state by name, each a short chain of exact
//! additions and subtractions: an aging row's five buckets sum to what is
//! owed (BS-arap-1), a control account's balance less its documents and its
//! unattached lines is its difference, which is always zero (BS-arap-2), and
//! a member's book capital less tax capital is their reconciliation total
//! (BS-partner-4). Naming them here puts them under proof rather than
//! leaving each a hand-written sum at its call site. The sums reuse
//! [`super::total`]; the chains of differences are checked one step at a
//! time, so none of them can panic or round.
use super::{Amount, total};
/// What an aging row owes: its five buckets, current, 1-30, 31-60, 61-90
/// and over 90 days, added exactly.
///
/// ```text
/// GOAL: an aging row's total is exactly the sum of its five buckets, so
/// the buckets partition what is owed and no bucket is lost or
/// counted twice in the total.
/// SOURCE: BS-arap-1 (an aging puts each open balance in exactly one
/// bucket, so the buckets sum to the open balances); BS-entry-3,
/// BS-entry-4 (exact, no panic).
/// INVARIANTS:
/// 1. Some(t): t = current + b30 + b60 + b90 + b90p, exactly.
/// 2. The order of the buckets does not change a total that exists
/// for in-range figures; aging_total of five zeros is Some(0).
/// 3. None when a running sum cannot be represented; NEVER a rounded or
/// wrapped figure, never a panic.
/// SCENARIOS:
/// 1. IF a customer owes 100.00 current and 40.00 over 90 days past due:
/// - SHOULD total 140.00
/// BECAUSE every bucket counts once.
/// 2. IF the buckets are Decimal::MAX and 1 in any two places:
/// - SHOULD be None
/// BECAUSE the sum is not representable.
/// ```
pub fn aging_total<T: Amount>(current: T, b30: T, b60: T, b90: T, b90p: T) -> Option<T> {
total([current, b30, b60, b90, b90p])
}
/// A control account's difference: its balance less what its documents
/// still owe on it, less its unattached lines.
///
/// ```text
/// GOAL: the control check's difference is the balance less the documents
/// and the unattached lines, exactly; it is zero whenever the
/// balance is those two sums, which it always is, as both sides sum
/// the same lines.
/// SOURCE: BS-arap-2 (a control account's balance equals the sum of its
/// documents plus its unattached lines); BS-ledger-8; BS-entry-4.
/// INVARIANTS:
/// 1. Some(d): d = balance - documents - unattached, exactly.
/// 2. control_difference(documents + unattached, documents, unattached)
/// = Some(0), and conversely Some(0) means balance = documents +
/// unattached: the difference vanishes exactly when the account
/// agrees with its subledger.
/// 3. None when a step cannot be represented; NEVER a rounded or
/// wrapped figure, never a panic.
/// SCENARIOS:
/// 1. IF the balance is 150.00, the documents 100.00 and one unattached
/// line 50.00:
/// - SHOULD be 0
/// BECAUSE 150.00 = 100.00 + 50.00.
/// 2. IF the balance is 100.00 and the documents 90.00 with nothing
/// unattached:
/// - SHOULD be 10.00
/// BECAUSE the account holds 10.00 no document explains.
/// ```
pub fn control_difference<T: Amount>(balance: T, documents: T, unattached: T) -> Option<T> {
balance
.checked_sub(documents)
.and_then(|d| d.checked_sub(unattached))
}
/// A member's book capital less their tax capital, by cause: the
/// beginning difference, plus the built-in gain, plus property without a
/// basis, less property distributed (all at book).
///
/// ```text
/// GOAL: the reconciliation total is exactly book ending less tax ending
/// as far as the books know it: what contributing and distributing
/// property does to the two capitals is the only way they part.
/// SOURCE: BS-partner-4 (the book-to-tax capital reconciliation: book
/// ending less tax ending = beginning (book less tax) + built-in
/// gain share + property without a basis (at book) - property
/// distributed (at book)); BS-asset-4 (the section 704(c)
/// built-in gain); BS-entry-4.
/// INVARIANTS:
/// 1. Some(t): t = beginning + built_in_gain + without_basis -
/// distributed, exactly.
/// 2. For any book and tax capital rows that differ only by those
/// causes (tax contributions = book contributions less the gain and
/// the property without a basis; tax distributions = book
/// distributions less what was distributed), book ending less tax
/// ending = reconciliation_total (Lean: Bookspec.Reconcile).
/// 3. None when a step cannot be represented; NEVER a rounded or
/// wrapped figure, never a panic.
/// SCENARIOS:
/// 1. IF two members jointly contribute a laptop worth 1,440.00 whose
/// basis is 1,688.40 (no other activity):
/// - SHOULD give each a total of -124.20
/// BECAUSE book property is 720.00 and tax 844.20.
/// ```
pub fn reconciliation_total<T: Amount>(
beginning: T,
built_in_gain: T,
without_basis: T,
distributed: T,
) -> Option<T> {
beginning
.checked_add(built_in_gain)?
.checked_add(without_basis)?
.checked_sub(distributed)
}
+12
View File
@@ -180,6 +180,12 @@ impl Amount for i32 {
fn checked_add(self, rhs: Self) -> Option<Self> {
i32::checked_add(self, rhs)
}
// The native subtraction: the default negates `rhs` first and so
// refused `x - MIN` even where the difference fits (found by the
// K-U8 harnesses: `None` must mean overflow, and only overflow).
fn checked_sub(self, rhs: Self) -> Option<Self> {
i32::checked_sub(self, rhs)
}
fn checked_neg(self) -> Option<Self> {
i32::checked_neg(self)
}
@@ -234,6 +240,12 @@ impl Amount for i64 {
fn checked_add(self, rhs: Self) -> Option<Self> {
i64::checked_add(self, rhs)
}
// The native subtraction: the default negates `rhs` first and so
// refused `x - MIN` even where the difference fits (found by the
// K-U8 harnesses: `None` must mean overflow, and only overflow).
fn checked_sub(self, rhs: Self) -> Option<Self> {
i64::checked_sub(self, rhs)
}
fn checked_neg(self) -> Option<Self> {
i64::checked_neg(self)
}
+3 -4
View File
@@ -7494,10 +7494,9 @@ impl Ledger {
}
}
let documents_total = doc_totals.get(&account).copied().unwrap_or_default();
let difference = balance
.checked_sub(documents_total)
.and_then(|d| d.checked_sub(unattached_sum))
.ok_or_else(too_large)?;
let difference =
crate::kernel::control_difference(balance, documents_total, unattached_sum)
.ok_or_else(too_large)?;
out.push(arap::ControlCheck {
role: role.key.to_string(),
account,
+118
View File
@@ -3,3 +3,121 @@
//! Empty in U0: the unit adds its Kani harnesses here; `just prove` scans
//! every file in `proofs/`, so a harness needs no change to the module
//! root or the recipe.
use super::any_amount;
use crate::kernel::{self, Amount};
/// An aging row's total is exactly the sum of its five buckets, for
/// **any** five `i64` figures (the edge included): `Some(t)` means `t` is
/// the true sum (checked in `i128`, which holds any five `i64`s), and
/// whenever every bucket is within a journal line's range the total
/// exists. Five fixed figures, no `Vec`; no bound is fixed beyond the
/// five buckets an aging row has.
#[kani::proof]
fn aging_total_is_sum() {
let b: [i64; 5] = core::array::from_fn(|_| kani::any());
let spec: i128 = b.iter().map(|&v| i128::from(v)).sum();
let got = kernel::aging_total(b[0], b[1], b[2], b[3], b[4]);
if let Some(t) = got {
assert_eq!(i128::from(t), spec);
kani::cover!(t != 0, "a nonzero total exists");
}
// `None` only on overflow: whenever every running prefix fits in
// `i64` (not only inside the line-range box), the total exists.
let mut run: i128 = 0;
let mut fits = true;
for &v in &b {
run += i128::from(v);
fits &= i64::try_from(run).is_ok();
}
if fits {
assert!(got.is_some(), "every prefix fits, so the total exists");
kani::cover!(run != 0, "a nonzero total from fitting prefixes");
}
if b.iter().all(|v| v.in_line_range()) {
assert!(got.is_some(), "in-range buckets always total");
kani::cover!(
b.iter().all(|&v| v != 0) && got.is_some(),
"five nonzero buckets"
);
}
// The all-in-range case on its own: the total is the sum, for a
// positive owing and negative (credit) buckets alike.
let a: [i64; 5] = core::array::from_fn(|_| any_amount());
let spec: i128 = a.iter().map(|&v| i128::from(v)).sum();
let t = kernel::aging_total(a[0], a[1], a[2], a[3], a[4]).expect("in-range figures total");
assert_eq!(i128::from(t), spec);
kani::cover!(
a.iter().any(|&v| v < 0) && a.iter().any(|&v| v > 0),
"mixed signs"
);
}
/// The control difference is `balance - documents - unattached`, exactly,
/// and it vanishes exactly when the balance is the documents plus the
/// unattached lines: the BS-arap-2 identity. For any three `i64`s: `Some(d)`
/// means `d` is the true difference (checked in `i128`); a balance that is
/// the sum of the other two (when that sum fits) differs by `Some(0)`; and
/// `Some(0)` means the balance is that sum.
#[kani::proof]
fn control_difference_identity() {
let (balance, docs, unattached): (i64, i64, i64) = (kani::any(), kani::any(), kani::any());
let spec = i128::from(balance) - i128::from(docs) - i128::from(unattached);
let got = kernel::control_difference(balance, docs, unattached);
// `None` only on overflow: whenever both steps fit in `i64`, it exists.
let first = i128::from(balance) - i128::from(docs);
if i64::try_from(first).is_ok() && i64::try_from(spec).is_ok() {
assert!(got.is_some(), "both steps fit, so the difference exists");
kani::cover!(spec != 0, "a nonzero difference from fitting steps");
}
if let Some(d) = got {
assert_eq!(i128::from(d), spec);
if d == 0 {
assert_eq!(
i128::from(balance),
i128::from(docs) + i128::from(unattached)
);
kani::cover!(docs != 0 && unattached != 0, "agrees with both parts");
} else {
kani::cover!(true, "a nonzero difference");
}
}
// The agreeing books: a balance of the documents plus the unattached
// lines (in range, so the sum fits) has no difference.
let (docs, unattached) = (any_amount(), any_amount());
let balance = docs + unattached;
assert_eq!(
kernel::control_difference(balance, docs, unattached),
Some(0)
);
kani::cover!(
docs > 0 && unattached < 0,
"documents with a credit unattached"
);
}
/// The reconciliation total is `beginning + built_in_gain + without_basis
/// - distributed`, exactly, for **any** four `i64`s when it exists
/// (checked in `i128`); and whenever the four are within a journal line's
/// range it exists.
#[kani::proof]
fn reconciliation_total_identity() {
let f: [i64; 4] = core::array::from_fn(|_| kani::any());
let spec = i128::from(f[0]) + i128::from(f[1]) + i128::from(f[2]) - i128::from(f[3]);
let got = kernel::reconciliation_total(f[0], f[1], f[2], f[3]);
if let Some(t) = got {
assert_eq!(i128::from(t), spec);
kani::cover!(t != 0, "a nonzero total");
}
// `None` only on overflow: whenever every running prefix fits in
// `i64`, the total exists.
let p1 = i128::from(f[0]) + i128::from(f[1]);
let p2 = p1 + i128::from(f[2]);
if [p1, p2, spec].iter().all(|&p| i64::try_from(p).is_ok()) {
assert!(got.is_some(), "every prefix fits, so the total exists");
kani::cover!(spec != 0, "a nonzero total from fitting prefixes");
}
if f.iter().all(|v| v.in_line_range()) {
assert!(got.is_some());
}
}
+6 -4
View File
@@ -274,10 +274,12 @@ pub struct Reconciliation {
impl Reconciliation {
/// Book ending less tax ending (as far as known).
pub fn total(&self) -> Option<Decimal> {
self.beginning
.checked_add(self.built_in_gain_704c)?
.checked_add(self.property_without_basis)?
.checked_sub(self.property_distributed)
crate::kernel::reconciliation_total(
self.beginning,
self.built_in_gain_704c,
self.property_without_basis,
self.property_distributed,
)
}
}