Files
wanderbooks/verify/lean/Wanderbooks/Basic.lean
T
swaitsandClaude Opus 5.5 3609bf065e 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
2026-10-13 11:12:13 -06:00

166 lines
5.1 KiB
Lean4

/-!
# Lines, sides, and nets
The vocabulary of double entry. Money is `Int`: an exact count of the
smallest unit the books use. Any finite set of exact decimals (what the
engine stores) scales to integers without loss, and every law here is a
law of addition, so `Int` is a faithful model.
Mirrors `crates/ledger-core/src/kernel.rs` (`flip`, `signed`, `net`,
`totals`) and `account.rs` (`Side`, `AccountType`, `normal_side`).
-/
namespace Wanderbooks
/-- Debit or credit. -/
inductive Side where
| debit
| credit
deriving DecidableEq, Repr
/-- The other side (`kernel::flip`). -/
def Side.flip : Side → Side
| .debit => .credit
| .credit => .debit
@[simp] theorem Side.flip_flip (s : Side) : s.flip.flip = s := by
cases s <;> rfl
theorem Side.flip_ne (s : Side) : s.flip ≠ s := by
cases s <;> simp [Side.flip]
/-- The five account types. -/
inductive AccountType where
| asset
| liability
| equity
| revenue
| expense
deriving DecidableEq, Repr
/-- The side that increases an account (`AccountType::normal_side`). -/
def AccountType.normal : AccountType → Side
| .asset | .expense => .debit
| .liability | .equity | .revenue => .credit
/-- A line's signed amount: `+a` for a debit, `-a` for a credit
(`kernel::signed`). -/
def signed : Side → Int → Int
| .debit, a => a
| .credit, a => -a
@[simp] theorem signed_debit (a : Int) : signed .debit a = a := rfl
@[simp] theorem signed_credit (a : Int) : signed .credit a = -a := rfl
theorem signed_flip (s : Side) (a : Int) : signed s.flip a = -signed s a := by
cases s <;> simp [Side.flip]
/-- One journal line. -/
structure Line where
account : Nat
side : Side
amount : Int
deriving DecidableEq, Repr
/-- A line's signed amount. -/
def Line.signed (l : Line) : Int := Wanderbooks.signed l.side l.amount
/-- The net of some lines: debits minus credits (`kernel::net`). -/
def net : List Line → Int
| [] => 0
| l :: ls => l.signed + net ls
/-- Total debits. -/
def debits : List Line → Int
| [] => 0
| l :: ls => (if l.side = .debit then l.amount else 0) + debits ls
/-- Total credits. -/
def credits : List Line → Int
| [] => 0
| l :: ls => (if l.side = .credit then l.amount else 0) + credits ls
@[simp] theorem net_nil : net [] = 0 := rfl
@[simp] theorem net_cons (l : Line) (ls : List Line) : net (l :: ls) = l.signed + net ls := rfl
theorem net_append (xs ys : List Line) : net (xs ++ ys) = net xs + net ys := by
induction xs with
| nil => simp
| cons x xs ih => simp only [List.cons_append, net_cons, ih]; omega
/-- The net is debits minus credits. -/
theorem net_eq_debits_sub_credits (ls : List Line) : net ls = debits ls - credits ls := by
induction ls with
| nil => rfl
| cons l ls ih =>
obtain ⟨a, s, m⟩ := l
cases s <;> simp [net, debits, credits, Line.signed, signed, ih] <;> omega
/-- A sum over a list of account codes. -/
def sumOver (f : Nat → Int) : List Nat → Int
| [] => 0
| a :: as => f a + sumOver f as
@[simp] theorem sumOver_nil (f : Nat → Int) : sumOver f [] = 0 := rfl
@[simp] theorem sumOver_cons (f : Nat → Int) (a : Nat) (as : List Nat) :
sumOver f (a :: as) = f a + sumOver f as := rfl
theorem sumOver_add (f g : Nat → Int) (as : List Nat) :
sumOver (fun a => f a + g a) as = sumOver f as + sumOver g as := by
induction as with
| nil => rfl
| cons a as ih => simp only [sumOver_cons, ih]; omega
theorem sumOver_neg (f : Nat → Int) (as : List Nat) :
sumOver (fun a => -f a) as = -sumOver f as := by
induction as with
| nil => rfl
| cons a as ih => simp only [sumOver_cons, ih]; omega
theorem sumOver_zero (as : List Nat) : sumOver (fun _ => 0) as = 0 := by
induction as with
| nil => rfl
| cons a as ih => simp [ih]
theorem sumOver_congr (f g : Nat → Int) (as : List Nat) (h : ∀ a ∈ as, f a = g a) :
sumOver f as = sumOver g as := by
induction as with
| nil => rfl
| cons a as ih =>
simp only [sumOver_cons]
rw [h a (by simp), ih (fun b hb => h b (by simp [hb]))]
/-- No code repeats (a chart's codes are unique). -/
def Distinct : List Nat → Prop
| [] => True
| a :: as => a ∉ as ∧ Distinct as
/-- Summing an indicator over codes that do not include `k` gives zero. -/
theorem sumOver_indicator_absent (k : Nat) (x : Int) (as : List Nat) (h : k ∉ as) :
sumOver (fun a => if k = a then x else 0) as = 0 := by
induction as with
| nil => rfl
| cons a as ih =>
have hka : k ≠ a := fun e => h (e ▸ List.mem_cons_self ..)
have hk : k ∉ as := fun hm => h (List.mem_cons_of_mem _ hm)
simp [hka, ih hk]
/-- Summing an indicator over distinct codes that include `k` picks out
exactly one term. -/
theorem sumOver_indicator (k : Nat) (x : Int) (as : List Nat) (hd : Distinct as)
(hk : k ∈ as) : sumOver (fun a => if k = a then x else 0) as = x := by
induction as with
| nil => simp at hk
| cons a as ih =>
obtain ⟨ha, hd⟩ := hd
by_cases e : k = a
· subst e
simp [sumOver_indicator_absent k x as ha]
· have : k ∈ as := by
cases hk with
| head => exact absurd rfl e
| tail _ h => exact h
simp [e, ih hd this]
end Wanderbooks