Gant Street

Six bugs Lean 4 caught in our TypeScript accounting engine

How we borrowed the AWS Cedar model: proving accounting math and agent rules in Lean 4, testing TypeScript against a 70-line Lean oracle, and stopping before proofs became busywork.

Published
Reading time
5 min
Table of Contents
  1. How the oracle works
  2. Six bugs our unit tests missed
  3. Stopping silent proof drift
  4. Knowing where to stop
  5. Run the checks yourself

A tax entry balanced to zero. Our TypeScript engine rejected it as unbalanced anyway.

Here is the one-line ternary bug that caused it in packages/kernel/src/accounting.ts:

- entries.set(accountId, prior === undefined || order < prior.order
-   ? { id, amount, order }
-   : { id: prior.id, amount: prior.amount.add(amount), order: prior.order });
+ entries.set(accountId, prior === undefined
+   ? { id, amount, order }
+   : order < prior.order
+     ? { id, amount: prior.amount.add(amount), order }
+     : { id: prior.id, amount: prior.amount.add(amount), order: prior.order });

See the mistake? Two tax lines hit the same account. When the second line arrived with a lower sort order, our code kept the new line and dropped the first amount.

Every unit test passed because our test fixtures arrived in sorted order. We found the bug only when we tried to prove in Lean 4 that tax drafts keep exact totals.

Fig. 01The one-line overwrite in addPosting
INCOMING TAX LINESEVALUATOR (addPosting)MAP & BALANCE CHECKLINE 1 (ARRIVES FIRST)account: tax_payableorder: 2 amount: $80.00LINE 2 (ARRIVES SECOND)account: tax_payableorder: 1 amount: $40.00MATCHING INVOICE DEBITreceivable: +$120.00CONDITION CHECKprior === undef || order < prior.order1 < 2 => TRUE (takes top branch)? TRUE BRANCH (OVERWRITES!){ id, amount: $40.00, order: 1 }Drops prior.amount ($80.00)!: FALSE BRANCH (ADDS AMOUNTS){ id: prior.id, prior + amount }Not reached when order < prior.orderentries["tax_payable"]order: 1$40.00$80.00 silently overwrittenJOURNAL BALANCE CHECKDebits: $120.00Credits: $40.00REJECTED: SHORT $80.00
Out-of-order bug: Line 2 has a lower sort order (1 < 2), so the ternary takes the overwrite branch and erases Line 1's $80.00. Switch to Sorted inputto see why every unit test passed, or Fixed ternary to see the proof-backed fix.

We built Rastrata so a small business can let Claude Code, Codex, or another AI agent run its books. That setup creates a sharp risk. Prompts cannot guard money. One quiet edge case drops a penny, breaks a balance sheet, or lets an agent step outside its lane.

So we borrowed the AWS Cedar model. We proved our core math and access rules in Lean 4. Then we built a 70-line Lean oracle and tested our TypeScript code against it.

That workflow caught six real bugs in working TypeScript code. It also taught us where to stop writing proofs.


How the oracle works

We do not run Lean in production. Our app runs in TypeScript on Bun and SQLite so builds stay fast and one binary runs anywhere. Lean acts as a proved reference model and a strict test oracle.

proofs/Oracle.lean (70 lines) wraps our proved Lean functions into a small JSON-over-stdio program. In CI, we send the same inputs to both the Lean binary and our TypeScript kernel. Both must return the exact same value or error code.

Fig. 02Differential oracle & Cedar gate
SAME JSON TEST INPUT SENT TO BOTH ENGINES{ "op": "operations.commit", "bookStatus": "read_only", "planAction": "post" }PRODUCTION RUNTIME (TYPESCRIPT / BUN)http.ts: early gate checked wrong permissionTS OUT: ALLOW (skipped second gate)LEAN 4 ORACLE (proofs/Oracle.lean, 70 LINES)Cedar model: read-only books block every writeLEAN OUT: DENY (read_only_book)DIFFERENTIAL COMPARATOR (TS OUTPUT === LEAN OUTPUT)DIVERGENCE: TypeScript allowed a write that Lean Cedar proved forbiddenCI FAILED
Bug #6 caught before launch: Random auth tests sent operations.commiton a read-only book to both TypeScript and Lean. Click Next → to see the fix match Lean, or switch scenarios above to inspect Bugs #2 and #3.

Six bugs our unit tests missed

# Area What broke How we caught it
1 Tax lines Out-of-order lines overwrote an earlier amount Tax proof failed
2 Journal check Posting IDs like toString hit Object.prototype Oracle mismatch
3 Hashing Lone UTF-16 surrogates caused hash collisions Oracle mismatch
4 Timestamps String sorting broke across time zones Timeline proof
5 Inventory Prep counted 1 move; validator counted 2 Transfer proof
6 Read-only auth Commit checked the wrong permission on locked books Random auth tests

1. Tax lines overwrote each other

You saw the diff above. When two tax lines shared an account and arrived out of order, the first amount vanished. Multi-line and reverse-charge tax drafts then came up short and failed balance checks.

2. A prototype crash on journal IDs

Our journal check looked up posting IDs in a plain JavaScript object without Object.hasOwn. Any ID named toString, constructor, or __proto__ hit Object.prototype and crashed. Lean had no prototype chain, so our oracle caught the crash right away.

3. Hash collisions from bad Unicode strings

JavaScript strings allow broken half-characters called lone UTF-16 surrogates. When UTF-8 encodes them, every broken character turns into the same replacement symbol (U+FFFD). Two different keys then produced the same hash. Lean allows valid Unicode only, so we updated TypeScript to reject broken strings up front.

4. Text sorting on timestamps

Several date rules compared ISO timestamps with < and >. Text sorting breaks when two dates use different UTC offsets or uneven decimal digits (.5Z vs .500Z). Proving those date rules forced us to write compareInstants. It handles years 0000 to 9999 and any offset without Date.parse bugs.

5. A mismatch on inventory limits

Our transfer prep counted a transfer as one move against the 10,000-layer cap. The validator counted both sides as two moves. Near the limit, the engine could build a transfer that its own validator refused. The proof exposed the gap before any real book hit it.

6. A read-only bug on commit permissions

We model access rules with Cedar in Lean 4. Even in full-access mode, no AI agent token can mint keys, change billing, or delete a business. Another theorem proves that read-only books block every write.

We ran random tests comparing our Lean access model against TypeScript HTTP routing. One case failed on operations.commit. That endpoint learns its real write permission only after loading the saved plan. On read-only books, the early gate checked the wrong permission and skipped the second check.


Stopping silent proof drift

Engineers are right to distrust big Lean 4 claims in 2026. A person or coding agent can weaken a theorem so broken code still passes. Or they can sneak in a shortcut.

Our checker (proofs/check.py) guards against both:

  • No shortcuts. It scans every Lean file and fails on proof escape hatches or unchecked stubs.
  • Locked theorem statements. It reads every theorem header up to := and checks it against HEAD. A new commit can clean up a proof, but it cannot change what an old theorem promises.
Fig. 03How proofs/check.py stops silent proof drift
proofs/Rastrata/Kernel/Journal/Admission.leanLOCKED AGAINST HEAD (ABOVE :=) [CHANGED!]theorem admitted_journal_balances(h : admitJournal snap j = .ok (.admitted hash))+ (h_sorted : isSorted j.postings) -- weakened!: (j.postings.map (amount)).sum = 0 :=:= LOCK BOUNDARYPROOF BODY (BELOW :=, FREE TO SIMPLIFY)bysimp [admitJournal, h_sorted, balance_check]CI GUARD (proofs/check.py)1. Scan proof escape hatchesPASS: zero unchecked stubs2. Diff headers up to := vs HEADFAIL: signature alteredCOMMIT BLOCKEDOld theorem promise changed
Header drift blocked: Adding isSorted above := would quietly weaken the balance guarantee. check.py compares every theorem header againstHEAD and fails the build. Try Valid refactor to see what passes.

Here is one locked rule from proofs/Rastrata/Kernel/Journal/Admission.lean. Every accepted journal entry must sum to zero.

theorem admitted_journal_balances {snapshot : JournalAdmissionSnapshot}
    {journal : JournalTransaction} {hash : ContentHash}
    (hw : ∀ posting ∈ journal.postings, posting.bookValue.amount.WF)
    (h : admitJournal snapshot journal = .ok (.admitted hash)) :
    (journal.postings.map (·.bookValue.amount.toRat)).sum = 0

Knowing where to stop

We proved our core math (0.1 + 0.2 = 3/10), journal rules, tax, schedules, inventory, and Cedar access rules. By then, proofs/ held about 100,000 lines across 109 Lean files covering 15,000 lines of TypeScript. Most of those theorems are small helper steps backing a few core rules.

Next in line were book.ts (325 KB) and codec.ts (81 KB). Both are stateful glue and storage code.

We stopped the Lean mirror right there. Proving 400 KB of stateful glue would slow every release and catch few bugs.

Instead, we kept Lean on the core math, balance, and access rules. That core runs against 21,321 oracle checks plus random auth tests. For book.ts and codec.ts, we wrote stateful fast-check property tests in TypeScript.

Proofs guard the math core where quiet bugs destroy trust. They never replace real-world testing.

Lean 4 will not stop a bank CSV from flipping debit signs. It will not fix a flaky bank feed. It cannot tell whether a $1,500 Zelle payment went to a contractor or an owner draw.

Good software puts proofs on the hard core and keeps humans in the loop for judgment calls.


Run the checks yourself

The Lean proofs, check.py, the 70-line oracle, and the TypeScript kernel live at github.com/Gant-Street/rastrata.

git clone https://github.com/Gant-Street/rastrata.git
cd rastrata/proofs && python3 check.py
cd .. && bun test packages/kernel