A practical walkthrough of using Lean 4 executable specifications
and formal proofs as a mathematically verified test oracle for
Python applications — demonstrated step by step with Tic-Tac-Toe.
Automatic Shrinking: Reduces noisy random failures into the smallest human-readable counterexample.
Regression Memory: Caches past failing inputs in .hypothesis/ and replays them first on future runs.
Downsides Where Hypothesis Alone Falls Short
The Test Oracle Problem: Generating inputs is easy, but checking exact outputs often forces you to re-implement the logic in tests.
Probabilistic, Not Exhaustive: Passing 500 random runs still cannot prove a bug doesn't exist in an untested corner.
Strategy Effort: Complex valid states require carefully written custom generators to avoid shallow or slow tests.
Bridge to Lean 4: Hypothesis excels at input generation & shrinking — Lean 4 fills its biggest gap by supplying a mathematically verified oracle.
01c / Closing the Gap
How Formal Verification Elevates Property-Based Testing
Adding a Lean 4 executable specification fills the upper-right gap — turning Hypothesis from guesswork into specification-backed testing.
Solved The Test Oracle Dilemma
Instead of rewriting fragile test expectations in Python, Hypothesis compares your code directly against a mathematically proved Lean 4 model.
Upgrade What Formal Verification Adds
Spec certainty: Core invariants are proved for all inputs (∀), not just sampled ones.
Zero duplicated bugs: The oracle is an independent, minimal, verified model.
Best of both worlds: Hypothesis explores deep runtime paths; Lean 4 guarantees the ground truth.
01d / Real-World Impact
Popular Use Cases & Proven Benefits in Production
Executable Specifications + Differential Testing (Lean 4 + PBT/Fuzzing) is already delivering measurable results across industry.
Flagship Case AWS Cedar — Authorization Policy Engine
AWS models Cedar's core authorizer & validator in Lean 4 and implements the production engine in Rust (powering AWS Verified Permissions). Instead of proving Rust directly, they bridge both with massive Differential Random Testing.
Proven Benefit: Mathematically proved core security invariants (e.g., forbid always overrides permit, validator soundness) while catching subtle edge-case bugs before production release.
FinTech & Billing
Use Case: Discount stacking, fee schedules, quota limits, and double-entry ledgers.
Prove conservation laws (no negative balance, exact rounding bounds) in Lean 4.
Hypothesis catches multi-rule interaction bugs in Python billing services.
Compilers & ML IR
Use Case: Query optimizers, DSLs, and neural-network lowering passes.
Prove semantic equivalence of rewrites in Lean 4 (grind / bv_decide).
Python harnesses fuzz thousands of ASTs to catch silent miscompilations.
AI Coding Agents
Use Case: Verifying LLM-generated code, migrations, and policy guardrails (2025–2026).
Agents emit both Python code and Lean 4 specs/proofs.
Lean kernel + Hypothesis form a deterministic gatekeeper before merge.
02 / Lean 4 Basics
What Makes Lean 4 Different from Older Proof Assistants?
Lean 4 unifies a dependently typed functional programming language, an interactive theorem prover, and a native C compiler.
Dual Nature Code + Proof Together
In Lean 4, functions and theorems live in the same language. There is no fragile "code extraction" step like in older theorem provers.
Modern Automation (2025–2026)
grind — SMT-style built-in tactic (congruence closure, E-matching, linear arithmetic).
bv_decide — SAT-backed bitvector & overflow proofs checked by the kernel.
Std.Do / mvcgen — Hoare-logic VC generation for do-notation code.
What Does It Mean to "Run" a Spec — and Why Native?
Turning a mathematical specification into a fast, standalone ground-truth calculator (Test Oracle).
1. Throughput Built for High-Volume Fuzzing
Proof terms exist only for the kernel and are erased at compile time. The remaining pure functions compile to fast C, enabling thousands of differential checks per second (or millions nightly).
2. Zero Extraction No Fragile Glue Layer
Older provers (Coq, Isabelle) required translating specs to OCaml/Haskell to run them. Lean 4 compiles your exact verified functions directly alongside Lean.Data.Json and IO.
3. Standalone Clean CI Integration
The output (tictactoe_oracle) is a self-contained binary. pytest calls it via subprocess.Popen without starting the Lean compiler or type-checker at test time.
02 / Lean 4 Basics
Essential Lean 4 Building Blocks in 60 Seconds
Just 5 keywords cover 90% of what you need to write executable software specifications.
Lean 4 Primer
-- 1. Algebraic Data Type (Enum / Tagged Union)inductivePlayerwhere
| X | O
derivingBEq, DecidableEq, Repr-- 2. Record / DataclassstructureGameStatewhere
board : List (OptionPlayer)
turn : Player
status : GameStatus-- 3. Pure Total Function (executable!)defPlayer.other : Player → Player
| .X => .O
| .O => .X
-- 4. Theorem (checked by Lean kernel at build time)theoremother_involutive (p : Player) :
p.other.other = p := bycases p <;> rfl-- 5. Elaboration-time assertion (fails build if false)#guardPlayer.X.other == .O
inductive & structure
Define strict, exhaustive domain models. Illegal states (like a player other than X/O) become unrepresentable at compile time.
def & Except
Functions are pure by default. Instead of raising runtime exceptions, return Except String GameState so every error path is explicit.
theorem & #guard
theorem proves a property for all possible inputs. #guard runs concrete sanity checks during compilation (lake test).
Toolchain: Managed by elan + lake (similar to rustup + cargo or uv).
03 / Core Concept
Combining Lean 4 with Python: Verification-Guided Development
Don't try to formally verify dynamic Python code directly. Instead, prove the Lean 4 spec and lock Python to it via Differential Testing.
Proven in Production: This is the same architecture used by AWS for the Cedar authorization engine (Lean 4 spec + Rust production + millions of nightly differential tests), adapted cleanly for Python + uv + Hypothesis.
03b / Architecture Trade-off
Wait — Why Not Just Build the Whole App in Lean 4?
Lean 4 can build real programs (its own compiler is in Lean 4!), but separating Spec and Production App wins in practice.
1. Ecosystem Libraries & Cloud Integrations
Lean 4 shines in math & verification, not Web frameworks, Cloud SDKs, ORMs, or AI/ML stacks. Rebuilding that ecosystem wastes time.
2. Provable ≠ Fast Decouple Clarity from Speed
Simple pure code is easy to prove; cached/vectorized production code breaks proofs on every refactor. Keeping them separate lets both excel.
3. Team Reality No Rewrite Needed
Existing Python teams keep shipping normally while a small group (or AI agents) maintains the Lean 4 spec for critical invariants.
Exception: For tiny, pure, ultra-critical cores (e.g., policy engine or parser), compiling Lean 4 to a C ABI shared library and calling it via Python FFI is a viable option.
03c / Mapping Assurance
How Do We Know Python & Lean 4 Are Mapped Correctly?
There is no automatic compiler proof linking Python to Lean — instead, 4 engineering layers keep the mapping airtight.
Contract Lock the I/O Boundary
Even if Python uses loops and Lean uses foldlM, matching the exact JSON response & error strings guarantees black-box alignment.
Audit Coverage & Mutation Testing
Run pytest --cov to verify 100% Python branch coverage under differential tests, and use mutation testing (mutmut) to ensure no unmapped logic slips by.
Zero Drift CI Enforces Sync
Editing only Python or only Lean immediately turns CI red — preventing silent divergence between spec and production code.
Setting testDriver = "TicTacToe" turns library elaboration itself into a test runner: if any theorem proof breaks or any #guard evaluates to false, lake test exits non-zero.
What These Proofs Guarantee
Safety: A finished game can never accept another move.
Bounds: Coordinates ≥ 9 are always rejected cleanly.
Structural integrity: Board length stays invariant (9) across every valid transition.
Pro Tip: For complex specs, try by plausible first to falsify buggy theorems before spending time proving them!
@pytest.fixture(scope="session")
deflean_oracle():
if not ORACLE_BIN.exists():
pytest.skip("Run: cd lean_spec && lake build")
oracle = LeanOracle(ORACLE_BIN)
try:
yield oracle
finally:
oracle.close()
Step 6 of 6 Differential Testing in Action
Catching Bugs Unit Tests Miss (test_differential.py)
Hypothesis explores both invalid/chaotic inputs and full legal games — then automatically shrinks any divergence to a minimal repro.
# 1. Verify proofs & build Lean 4 oracle
cd lean_spec && lake test && lake build
# 2. Run Python unit + Hypothesis differential tests
cd .. && uv sync && uv run pytest -v