feat(core): prove the accounting laws (Kani + Lean); fix three engine gaps

The money arithmetic every invariant rests on now lives in one kernel,
ledger-core/src/kernel.rs: signing a line, totals, net, per-account
movements, reversal, normal balances, trial-balance columns, closing
lines, and the rounding plug for member splits. It is generic over a
checked `Amount` trait. The engine runs it on Decimal (validate,
movements, reverse_entry, account_balance, close_period_to, allocate,
trial_balance): there is one copy of the arithmetic, and it is the one
under proof.

Three layers, docs/verification.md maps every law to its proofs:

- Kani (src/proofs.rs): 17 harnesses prove the kernel at i64 for every
  input up to 4 lines over 3 accounts. An entry is accepted exactly
  when it is two or more positive, in-range lines whose debits equal
  credits; accepted entries net to zero; grouping by account loses
  nothing; a reversal mirrors and cancels its original; trial-balance
  columns balance iff the books net to zero; closing lines zero their
  accounts and a close balances however the net is split; the plug
  makes parts sum to the whole. No panics, no overflow. kani::cover!
  shows the proofs are not vacuous.
- Lean 4 (verify/lean): 24 headline theorems for books of any size. The
  ledger is a state machine (add account, draft, post, reverse, open,
  close), and in every reachable state the books net to zero, the trial
  balance balances (as of any date), and the accounting equation holds.
  Posting only appends ("posted is forever"), closed periods are
  frozen, a close zeroes revenue and expenses and credits exactly the net
  income, and period statements add up. Audit.lean shows standard axioms
  only, no sorry.
- Bridge (tests/kernel_bridge.rs): the Decimal and i64 kernels agree.

What the proofs found (each one missed by every test, fuzzer, and
mutant):

- The engine accepted negative line amounts; only MCP refused them. Now
  NegativeAmountLine: direction is the side's job.
- Summing lines near Decimal::MAX panicked. Lines are now capped at one
  quadrillion and ten decimal places (AmountOutOfRange), which keeps
  every realistic sum exact, and the kernel's sums are checked.
- FX conversion (foreign_amount * fx_rate) could panic the same way; it
  is now a checked multiply.
- Kani itself: 0.68 mis-models symbolic-length copy_from_slice
  (model-checking/kani#4904) and reported a reversal that doesn't net to
  zero. The counterexample, replayed natively, passes, and a 15-line
  standalone crate reproduces the bug. Harnesses avoid bulk copies, and
  a should_panic canary will flag the upstream fix.

`just prove` runs it all (Kani memory- and time-capped, fails on an
unsatisfiable cover or a non-standard Lean axiom). AGENTS.md now makes
formal coverage part of every core change.

Also, docs: GnuCash is *an* oracle, never *the* oracle (Stephen). The
spec is accounting principles, proved. Golden files are recomputed from
principles. External implementations (GnuCash, the old Sheet, QBO/Xero)
are cross-checks whose disagreements get adjudicated, never obeyed.
docs/oracle.md gains "Who is right"; AGENTS, README, architecture,
roadmap, parity, and STATUS are reworded to match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GWVo7x3UHw5kwCUaWxiejX
This commit is contained in:
swaitsandClaude Opus 5.5 committed 2026-10-13 11:12:13 -06:00
1 parent d5c4e38b18
commit 3609bf065e
31 files changed
+2682 -131

No files matched your search

+292
View File
@@ -0,0 +1,292 @@
//! The accounting kernel: the arithmetic every bookkeeping invariant rests
//! on, in one place.
//!
//! Each function here is small, pure, and generic over [`Amount`]. The
//! engine runs it on [`Decimal`]; the Kani harnesses in `proofs.rs` run the
//! very same code on machine integers and prove it correct for every input
//! within their bounds; and the Lean model in `verify/lean` proves the
//! laws it implements hold for books of any size. See
//! `docs/verification.md` for which proof covers which law.
//!
//! The laws, in the order they appear:
//!
//! * a line's signed amount is `+amount` for a debit, `-amount` for a credit;
//! * an entry is acceptable when it has two or more lines, every amount is
//! positive and in range, and its debits equal its credits exactly;
//! * an acceptable entry nets to zero, account by account summed;
//! * a reversal flips every side, so it is acceptable exactly when the
//! original is, and the two together net every account to zero;
//! * an account's balance is its movement read on its normal side, so the
//! balances satisfy the accounting equation whenever movements net to
//! zero;
//! * a trial balance puts each movement in exactly one column, so its
//! columns differ by the net of all movements;
//! * a closing line zeroes the account it closes;
//! * an allocation's parts sum to the whole, to the last unit.
use crate::{AccountType, Side};
use rust_decimal::Decimal;
/// What the kernel needs of a money amount: exact, ordered, and checked
/// arithmetic that reports overflow instead of rounding or wrapping.
pub trait Amount: Copy + Ord {
/// Zero.
const ZERO: Self;
/// `self + rhs`, or `None` when it cannot be represented exactly.
fn checked_add(self, rhs: Self) -> Option<Self>;
/// `-self`, or `None` when it cannot be represented.
fn checked_neg(self) -> Option<Self>;
/// True when the amount is small and precise enough for a journal line
/// (see [`MAX_LINE_AMOUNT`] and [`MAX_LINE_SCALE`] for [`Decimal`]).
fn in_line_range(self) -> bool;
/// `self - rhs`, or `None` when it cannot be represented exactly.
fn checked_sub(self, rhs: Self) -> Option<Self> {
self.checked_add(rhs.checked_neg()?)
}
}
/// The largest amount one journal line may carry: one quadrillion units of
/// the base currency. Far beyond any real transaction, and far enough
/// below [`Decimal::MAX`] that no realistic sum of lines can overflow.
pub const MAX_LINE_AMOUNT: Decimal = Decimal::from_parts(0xA4C6_8000, 0x0003_8D7E, 0, false, 0);
/// The most decimal places a journal line may carry. Cents need two;
/// foreign-currency lines (amount times rate) need more; ten keeps every
/// sum of lines exact as long as the total stays under 7.9 quintillion.
pub const MAX_LINE_SCALE: u32 = 10;
impl Amount for Decimal {
const ZERO: Self = Decimal::ZERO;
fn checked_add(self, rhs: Self) -> Option<Self> {
Decimal::checked_add(self, rhs)
}
fn checked_neg(self) -> Option<Self> {
Some(-self)
}
fn in_line_range(self) -> bool {
self.abs() <= MAX_LINE_AMOUNT && self.normalize().scale() <= MAX_LINE_SCALE
}
}
impl Amount for i64 {
const ZERO: Self = 0;
fn checked_add(self, rhs: Self) -> Option<Self> {
i64::checked_add(self, rhs)
}
fn checked_neg(self) -> Option<Self> {
i64::checked_neg(self)
}
fn in_line_range(self) -> bool {
// Scaled down with the same headroom as Decimal's range: lines
// this size can be summed many times over without overflow.
self.unsigned_abs() <= (1 << 40)
}
}
/// Why the kernel rejected an entry's lines.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineError<T> {
/// Fewer than two lines.
TooFewLines,
/// A line with a zero amount.
ZeroAmount,
/// A line with a negative amount: direction is the side's job.
NegativeAmount,
/// A line too large or too precise for a journal line.
OutOfRange,
/// Debits and credits differ.
Unbalanced {
/// Sum of debit lines.
debits: T,
/// Sum of credit lines.
credits: T,
},
}
/// The other side.
pub fn flip(side: Side) -> Side {
match side {
Side::Debit => Side::Credit,
Side::Credit => Side::Debit,
}
}
/// A line's signed amount: positive for a debit, negative for a credit.
pub fn signed<T: Amount>(side: Side, amount: T) -> Option<T> {
match side {
Side::Debit => Some(amount),
Side::Credit => amount.checked_neg(),
}
}
/// Total debits and total credits of some lines.
pub fn totals<T: Amount>(lines: impl IntoIterator<Item = (Side, T)>) -> Option<(T, T)> {
let mut debits = T::ZERO;
let mut credits = T::ZERO;
for (side, amount) in lines {
match side {
Side::Debit => debits = debits.checked_add(amount)?,
Side::Credit => credits = credits.checked_add(amount)?,
}
}
Some((debits, credits))
}
/// The net of some lines: debits minus credits.
pub fn net<T: Amount>(lines: impl IntoIterator<Item = (Side, T)>) -> Option<T> {
let mut total = T::ZERO;
for (side, amount) in lines {
total = total.checked_add(signed(side, amount)?)?;
}
Some(total)
}
/// Check an entry's lines: two or more, every amount positive and within
/// line range, debits equal to credits. Accounts and currencies are the
/// caller's to check; this is the arithmetic.
pub fn check_lines<T: Amount>(lines: &[(Side, T)]) -> Result<(), LineError<T>> {
if lines.len() < 2 {
return Err(LineError::TooFewLines);
}
for &(_, amount) in lines {
if amount == T::ZERO {
return Err(LineError::ZeroAmount);
}
if amount < T::ZERO {
return Err(LineError::NegativeAmount);
}
if !amount.in_line_range() {
return Err(LineError::OutOfRange);
}
}
let (debits, credits) = totals(lines.iter().copied()).ok_or(LineError::OutOfRange)?;
if debits != credits {
return Err(LineError::Unbalanced { debits, credits });
}
Ok(())
}
/// Net movement per account (debits minus credits), in order of first
/// appearance.
pub fn movements<K: Copy + Eq, T: Amount>(
lines: impl IntoIterator<Item = (K, Side, T)>,
) -> Option<Vec<(K, T)>> {
let lines: Vec<_> = lines.into_iter().collect();
let Some(&(first, _, _)) = lines.first() else {
return Some(Vec::new());
};
// At most one account per line.
let mut out = vec![(first, T::ZERO); lines.len()];
let n = movements_into(&lines, &mut out)?;
out.truncate(n);
Some(out)
}
/// [`movements`] into a caller's buffer, without allocating: returns how
/// many accounts it wrote, or `None` on overflow or if `out` is too small.
pub fn movements_into<K: Copy + Eq, T: Amount>(
lines: &[(K, Side, T)],
out: &mut [(K, T)],
) -> Option<usize> {
let mut n = 0;
for &(account, side, amount) in lines {
let delta = signed(side, amount)?;
match out[..n].iter_mut().find(|(k, _)| *k == account) {
Some((_, total)) => *total = total.checked_add(delta)?,
None => {
*out.get_mut(n)? = (account, delta);
n += 1;
}
}
}
Some(n)
}
/// The lines of a reversing entry: every side flipped, accounts and
/// amounts unchanged.
pub fn reversal<K: Copy, T: Amount>(lines: &[(K, Side, T)]) -> Vec<(K, Side, T)> {
lines.iter().map(|&line| reverse_line(line)).collect()
}
/// One line of a reversing entry: the side flipped, account and amount
/// unchanged.
pub fn reverse_line<K, T: Amount>((account, side, amount): (K, Side, T)) -> (K, Side, T) {
(account, flip(side), amount)
}
/// An account's balance read on its normal side: positive is a normal
/// balance, negative a contra balance.
pub fn normal_balance<T: Amount>(account_type: AccountType, movement: T) -> Option<T> {
match account_type.normal_side() {
Side::Debit => Some(movement),
Side::Credit => movement.checked_neg(),
}
}
/// A movement in trial-balance columns: `(debit, credit)`, one of them
/// zero, both non-negative.
pub fn columns<T: Amount>(movement: T) -> Option<(T, T)> {
if movement > T::ZERO {
Some((movement, T::ZERO))
} else {
Some((T::ZERO, movement.checked_neg()?))
}
}
/// The line that zeroes an account with this movement: the opposite side,
/// for the same amount. `None` for a zero movement (nothing to close).
pub fn closing_line<T: Amount>(movement: T) -> Option<(Side, T)> {
if movement > T::ZERO {
Some((Side::Credit, movement))
} else if movement < T::ZERO {
Some((Side::Debit, movement.checked_neg()?))
} else {
None
}
}
/// The line that credits `credit` to an account (a negative credit is a
/// debit). `None` for zero. This is [`closing_line`]: crediting `c` and
/// zeroing a movement of `c` are the same line.
pub fn credit_line<T: Amount>(credit: T) -> Option<(Side, T)> {
closing_line(credit)
}
/// Make rounded parts sum to the whole: the last part becomes `whole`
/// minus the others, absorbing every unit of rounding. Returns `None` on
/// overflow, leaving `parts` unchanged.
pub fn plug_last<T: Amount>(whole: T, parts: &mut [T]) -> Option<()> {
let Some((last, rest)) = parts.split_last_mut() else {
return Some(());
};
let mut others = T::ZERO;
for &p in rest.iter() {
others = others.checked_add(p)?;
}
*last = whole.checked_sub(others)?;
Some(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn max_line_amount_is_one_quadrillion() {
assert_eq!(MAX_LINE_AMOUNT, Decimal::from(1_000_000_000_000_000u64));
assert!(MAX_LINE_AMOUNT.in_line_range());
assert!(!(MAX_LINE_AMOUNT + Decimal::ONE).in_line_range());
assert!("0.0000000001".parse::<Decimal>().unwrap().in_line_range());
assert!(!"0.00000000001".parse::<Decimal>().unwrap().in_line_range());
// Trailing zeros are not precision.
assert!("1.000000000000".parse::<Decimal>().unwrap().in_line_range());
}
#[test]
fn credit_line_sides() {
assert_eq!(credit_line(5i64), Some((Side::Credit, 5)));
assert_eq!(credit_line(-5i64), Some((Side::Debit, 5)));
assert_eq!(credit_line(0i64), None);
}
}