Formal Verification & Software Testing

Lean 4 + Python
Differential Testing

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.

Lean 4.22+ Python 3.12 + uv pytest + Hypothesis JSON Lines Oracle
Key Idea: Prove invariants on a clean Lean 4 model, then fuzz-test your production Python code against it automatically.
LEAN 4 SPEC & PROOFS Executable Model Kernel-Checked Theorems ✓ Ground Truth Oracle PYTHON PRODUCTION tictactoe/game.py Fast, Idiomatic Python System Under Test DIFFERENTIAL TESTING pytest + Hypothesis (1000s of games) X X X O O ==
01 / Motivation

The Assurance Gap in Traditional Software Testing

Traditional unit tests check only the edge cases you remember to write. Property-based testing goes further — but still hits a ceiling.

STATE SPACE COVERAGE & CONFIDENCE → MATHEMATICAL RIGOR → Unit Tests pytest examples Checks known inputs Property-Based Testing Hypothesis 1000s of random inputs + shrinking ? Assurance Gap No universal proof (∀ inputs) No trusted test oracle

Limit 1 Unit Tests Miss Edge Cases

Example-based tests only verify scenarios you explicitly imagined. Subtle combinations and boundary bugs slip straight through.

Next Step Property-Based Testing

Tools like Hypothesis automatically generate thousands of inputs — let's look at how it works and where it still hits the Test Oracle Problem.

01b / Property-Based Testing

Meet Hypothesis: Property-Based Testing in Python

Instead of hand-writing fixed examples, declare input strategies and let Hypothesis hunt for edge cases automatically.

1. Strategy st.lists(0..11) Defines input shape 2. Generate 100s–1000s of inputs Empty, dupes, bounds 3. Assert Property Run Python function Check invariant / oracle On Failure → Auto-Shrink 4. Minimal Counterexample (Saved to .hypothesis DB) [11, 2, 0, 7, 4, 1, 6, 8] ──shrink──▶ [2, 0, 4, 1, 6]
Hypothesis Quick Example
from hypothesis import given, strategies as st

@given(xs=st.lists(st.integers()))
def test_sort_idempotent(xs):
    assert sorted(sorted(xs)) == sorted(xs)

Benefits Why Developers Love Hypothesis

  • Finds blind-spot edge cases: Automatically tries empty lists, duplicates, negative/huge numbers, and rare combinations.
  • 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.

STATE SPACE COVERAGE & CONFIDENCE → MATHEMATICAL RIGOR → Unit Tests pytest examples Checks known inputs Property-Based Testing Hypothesis / Plausible 1000s of random inputs + shrinking Formal Verification Lean 4 Executable Spec Universal proofs (∀ inputs) Sweet Spot (VGD) Lean 4 Oracle + Hypothesis

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.

~5–6 µs Lean 4 eval latency 10M+ / night Differential random tests Zero Spec-to-Prod Drift in Production Fast Rust speed + Lean 4 mathematical assurance

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.

Single Lean 4 Codebase Types + Executable Functions + Theorems 1. TRUSTED PROOF KERNEL Elaborator & Type Checker Checks every theorem & #guard Zero runtime trust needed 2. NATIVE C COMPILER IR → C → Native Binary Proof terms erased at compile time Microsecond execution speed lake test Mathematical Guarantee lake build Fast Test Oracle Binary

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.
  • Plausible — Built-in QuickCheck-style counterexample finder.
02b / Lean 4 Basics

What Does It Mean to "Run" a Spec — and Why Native?

Turning a mathematical specification into a fast, standalone ground-truth calculator (Test Oracle).

WHAT "RUNNING A SPEC" MEANS Concrete Input [0, 3, 1, 4, 2] from Hypothesis Executable Spec playMoves Computable def Expected Output won("X") Ground Truth! Unlike static Markdown/math specs, Lean 4 computes the exact answer for any input. WHY THE NATIVE COMPILER MATTERS (lake build) Spec + Proofs def + theorem + Main.lean Proof Erasure Theorems stripped → Optimized C code Native Binary ~5–6 µs / call (AWS Cedar benchmark) Interpreter (#eval / lean --run): Slow — too costly for 10,000s of fuzz tests Native Binary (lake build): 1,000s–10,000s checks/sec in pytest!

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)
inductive Player where
  | X | O
  deriving BEq, DecidableEq, Repr

-- 2. Record / Dataclass
structure GameState where
  board  : List (Option Player)
  turn   : Player
  status : GameStatus

-- 3. Pure Total Function (executable!)
def Player.other : Player → Player
  | .X => .O
  | .O => .X

-- 4. Theorem (checked by Lean kernel at build time)
theorem other_involutive (p : Player) :
    p.other.other = p := by
  cases p <;> rfl

-- 5. Elaboration-time assertion (fails build if false)
#guard Player.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.

1. HYPOTHESIS Random Input Generator moves = [0, 4, 1, 9, 2] • Out-of-bounds & duplicates • Auto-shrinks failing cases JSON list[int] 2A. LEAN 4 EXECUTABLE SPEC tictactoe_oracle (Native Binary) Invariants mathematically proved in Proofs.lean expected = {"ok": false, "error": ...} 2B. PYTHON PRODUCTION CODE tictactoe/game.py :: play_moves() Fast, readable, idiomatic production Python actual = {"ok": false, "error": ...} 3. DIFFERENTIAL ASSERTION assert actual == expected ✓ Match → Python obeys verified spec ✗ Mismatch → Shrink to minimal bug repro
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.

Anatomy of a Typical Production Application 80–90% Application Shell & Ecosystem (Keep in Python / Go / Rust) Web / API (FastAPI) Cloud SDKs & DBs AI/ML (PyTorch/NumPy) Low ROI for formal proofs — needs mature libraries & fast iteration 10–20% Critical Core Logic (AuthZ, Billing, State Machines) Production Code (Python) Optimized for speed Caches, batching, NumPy, idiomatic for the team Hard to prove directly Diff ↔ Test Executable Spec (Lean 4) Optimized for clarity Pure recursion, simple algebraic data types Easy to prove formally!

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.

LAYER 1: Strict 1-to-1 Boundary Contract (JSON Schema) Identical inputs, outputs, nulls, and error codes across Python & Lean LAYER 2: Behavioral Equivalence (Hypothesis Differential Test) Verify Python(x) == Lean(x) across 1,000s of normal & error paths LAYER 3: Branch Coverage (100%) + Mutation Testing (mutmut) Prove every Python branch is exercised & any bug injection gets caught BLIND SPOT: What if BOTH Python & Lean have the same spec bug? Differential testing alone won't flag matching bugs in both implementations. → Caught by Lean 4 Formal Proofs (Proofs.lean invariants fail to prove!)

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.

Clean Division of Labor: Lean Proofs verify spec correctness; Differential + Mutation Testing verify Python↔Lean mapping.
04 / Sample Architecture

Tic-Tac-Toe Sample Setup: Anatomy of the Repo

6 small, focused files work together in lean4-tictactoe-test/.

Project Directory Tree
lean4-tictactoe-test/
├── pyproject.toml           # uv + pytest + hypothesis
├── tictactoe/
│   └── game.py              # Step 1: Production Python
├── lean_spec/
│   ├── lean-toolchain       # Pins Lean v4.22.0
│   ├── lakefile.toml        # Build + testDriver config
│   ├── TicTacToe/
│   │   ├── Spec.lean        # Step 2: Executable Spec
│   │   └── Proofs.lean      # Step 3: Theorems + #guard
│   └── Main.lean            # Step 4: JSON Lines Oracle
└── tests/
    ├── conftest.py          # Step 5: Persistent fixture
    ├── test_unit.py         # Standard unit tests
    └── test_differential.py # Step 6: Hypothesis tests
STEP 1 tictactoe/game.py Pure Python state machine returning JSON-compatible dicts STEP 2 lean_spec/TicTacToe/Spec.lean Clean Lean 4 reference model (Player, Board, applyMove) STEP 3 lean_spec/TicTacToe/Proofs.lean Formal invariants (theorem) + compile-time #guard checks STEP 4 lean_spec/Main.lean Compiled native binary: persistent stdin/stdout JSON Lines loop STEP 5 tests/conftest.py Session-scoped pytest fixture spawning the oracle once STEP 6 tests/test_differential.py Hypothesis fuzzing comparing Python vs. Lean 4 on 1000+ cases
Step 1 of 6 Production Python

Decouple Pure Business Logic from I/O

Keep the core rules pure and deterministic in tictactoe/game.py with a clean JSON-compatible contract.

tictactoe/game.py
def apply_move(state: GameState, pos: int):
    if state.status != "ongoing":
        return None, "game_over"
    if pos < 0 or pos >= 9:
        return None, "out_of_bounds"
    if state.board[pos] is not None:
        return None, "cell_occupied"

    new_board = _place(state.board, pos, state.turn)
    if _has_won(new_board, state.turn):
        return GameState(new_board, state.turn, "won", state.turn), None
    if all(c is not None for c in new_board):
        return GameState(new_board, state.turn, "draw", None), None
    return GameState(new_board, _other(state.turn), "ongoing", None), None

def play_moves(moves: list[int]) -> dict:
    state = initial_state()
    for pos in moves:
        state, err = apply_move(state, pos)
        if err:
            return {"ok": False, "error": err}
    return state.to_dict()

Design Principle: Functional Core

  • Immutable state: @dataclass(frozen=True) with tuple board avoids mutation bugs.
  • Explicit error codes: Returning "game_over" / "out_of_bounds" / "cell_occupied" maps 1-to-1 to Lean's Except.
  • Replayable entrypoint: play_moves(moves) takes a plain list of ints — ideal for fuzzing!

Shared JSON Wire Contract

Success:

{"ok": true, "board": ["X", ...], "turn": "O", "status": "ongoing", "winner": null}

Error:

{"ok": false, "error": "cell_occupied"}

Step 2 of 6 Executable Specification

Modeling the Rules Cleanly in Spec.lean

The specification is short, declarative, and directly executable — serving as the single source of truth.

lean_spec/TicTacToe/Spec.lean
inductive GameStatus where
  | ongoing | won (p : Player) | draw
  deriving BEq, DecidableEq, Repr

def applyMove (s : GameState) (pos : Nat)
    : Except String GameState :=
  if s.status != .ongoing then
    .error "game_over"
  else if pos ≥ 9 then
    .error "out_of_bounds"
  else if cellAt s.board pos != none then
    .error "cell_occupied"
  else
    let board' := s.board.set pos (some s.turn)
    if hasWon board' s.turn then
      .ok { board := board', turn := s.turn, status := .won s.turn }
    else if isFull board' then
      .ok { board := board', turn := s.turn, status := .draw }
    else
      .ok { board := board', turn := s.turn.other, status := .ongoing }

def playMoves (moves : List Nat) : Except String GameState :=
  moves.foldlM applyMove initialState
Type Mapping: Python ↔ Lean 4 Python (game.py) Lean 4 (Spec.lean) Literal["X", "O"] inductive Player Player | None Option Player (State | None, err) Except String State for pos in moves: moves.foldlM applyMove Zero external Lean deps (no Mathlib) → builds in seconds!
Step 3 of 6 Formal Proofs & Compile-Time Checks

Proving Spec Invariants in Proofs.lean

Before trusting the oracle, Lean's kernel mathematically verifies its properties during lake test.

lean_spec/TicTacToe/Proofs.lean
-- 1. Universal Theorems (hold for ALL states & moves)
theorem applyMove_rejects_finished_game
    (s : GameState) (pos : Nat)
    (hdone : s.status ≠ .ongoing) :
    applyMove s pos = .error "game_over" := by
  unfold applyMove; simp [hdone]

theorem applyMove_rejects_out_of_bounds
    (s : GameState) (pos : Nat)
    (hongoing : s.status = .ongoing) (hge : pos ≥ 9) :
    applyMove s pos = .error "out_of_bounds" := by
  unfold applyMove; simp [hongoing, hge]

theorem applyMove_preserves_board_length ... :
    s'.board.length = s.board.length := ...

-- 2. Elaboration-time concrete assertions
#guard playMoves [0, 0] == .error "cell_occupied"
#guard playMoves [0, 3, 1, 4, 2, 5] == .error "game_over"

lakefile.toml Native lake test

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!
Steps 4 & 5 of 6 Fast Bridge

Persistent JSON Lines Oracle (Main.lean + conftest.py)

Spawning a subprocess per test case is slow. A persistent stdin/stdout pipe achieves thousands of checks per second.

pytest (conftest.py fixture) tictactoe_oracle (Main.lean) 1. Spawn ONCE per pytest session (Popen) REPEAT 1,000+ TIMES (Hypothesis loop) stdin: {"moves": [0, 3, 1, 4, 2]}\n (flush) stdout: {"ok":true,"status":"won","winner":"X",...}\n (flush) Close stdin (EOF) → clean process exit
lean_spec/Main.lean (excerpt)
partial def loop (stdin stdout : IO.FS.Stream) : IO Unit := do
  let line ← stdin.getLine
  if line.isEmpty then return ()
  let resp := match Json.parse line.trim >>= fromJson? with
    | .ok (req : PlayRequest) => resultToJson (playMoves req.moves)
    | .error err => ...
  stdout.putStrLn resp.compress
  stdout.flush   -- critical: prevents pipe deadlock!
  loop stdin stdout
tests/conftest.py (excerpt)
@pytest.fixture(scope="session")
def lean_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.

tests/test_differential.py
# Strategy 1: Chaotic sequences (bounds, duplicates, post-win)
@settings(max_examples=500)
@given(moves=st.lists(
    st.integers(min_value=0, max_value=11),
    max_size=12,
))
def test_random_move_sequences_match_lean_spec(lean_oracle, moves):
    assert play_moves(moves) == lean_oracle.play(moves)

# Strategy 2: Permutations of 0..8 (deep wins & draws)
@settings(max_examples=500)
@given(moves=st.permutations(list(range(9))))
def test_full_game_permutations_match_lean_spec(lean_oracle, moves):
    for k in range(len(moves) + 1):
        seq = moves[:k]
        assert play_moves(seq) == lean_oracle.play(seq)
Hands-On Experiment: Delete Diagonal (2, 4, 6) 1. Subtle bug in tictactoe/game.py: - (2, 4, 6), # forgotten anti-diagonal win! 2. test_unit.py → 5 PASSED (False Confidence!) Unit tests only checked top row (0, 1, 2) and draw. 3. test_differential.py → FAILED & SHRUNK! Falsifying example: moves=[2, 0, 4, 1, 6] Lean 4 Oracle: {"status": "won", "winner": "X"} Python Actual: {"status": "ongoing", "winner": null} Hypothesis shrinks to the shortest 5-move counterexample automatically
05 / Production Adoption

CI Pipeline & Where to Apply This Pattern

Integrate Lean 4 + Python cleanly in CI, and focus formal specs where bugs are most expensive.

1. lake test Verify theorems & #guard (Pinned via lean-toolchain) 2. lake build Compile native Oracle CLI (Cache .lake in CI) 3. uv run pytest Unit + Hypothesis Diff Tests (1000s of random cases) ✓ High-Assurance Release Ready

High ROI Best Fit for Lean 4 + Python

  • Authorization & Policy Engines (RBAC / ABAC / IAM rules)
  • Billing, Pricing & Ledger Logic (discounts, quotas, balances)
  • State Machines & Workflows (order lifecycle, protocol states)
  • Parsers, Serializers & Compilers (round-trip & equivalence)

Low ROI Stick to Regular pytest

  • I/O Glue Code (REST handlers, DB queries, SDK wrappers)
  • Simple CRUD & UI (no complex invariants to prove)
  • Heuristic / Fuzzy ML Outputs (no exact mathematical oracle)
Try it locally: cd lean_spec && lake test && lake build && cd .. && uv run pytest -v
06 / Tooling Positioning

Hypothesis vs. Plausible: Where Does Each Fit?

Both are QuickCheck-style Property-Based Testing tools — but they test different layers at different stages.

STAGE 1 (OPTIONAL): INSIDE LEAN 4 Plausible (by plausible) Sanity-check draft specs & theorems Finds counterexamples BEFORE proving STAGE 2: LEAN 4 KERNEL Formal Proofs (lake test) Prove invariants universally (∀) Builds trusted native oracle STAGE 3 (CORE): PYTHON CI Hypothesis (uv run pytest) Differential Testing: Python ↔ Lean 4 Guards production Python on every PR

Core in Sample Hypothesis (Python Side)

  • Target: Verifies that your Python production code matches the Lean 4 oracle.
  • When it runs: Every local run & CI pipeline (uv run pytest).
  • Role: The primary engine driving Differential Testing in this sample.

Optional Power-Up Plausible (Lean 4 Side)

  • Target: Checks whether your Lean 4 spec / theorem statement is actually true before investing time proving it.
  • Why omitted here: Intentionally excluded from our minimal Tic-Tac-Toe sample to keep zero external Lean dependencies.
  • When to add: Add via Lake once your domain specs & invariants grow complex.
07 / Summary & Next Steps

Key Takeaways & Resources to Get Started

Bring mathematical assurance to your Python codebase — without rewriting your app.

1 Hypothesis Finds Bugs, Lean 4 Proves Truth

Hypothesis excels at generating adversarial inputs and shrinking failures; Lean 4 eliminates the Test Oracle Problem.

2 Dual Power: Kernel + Native Compiler

Lean 4's kernel mathematically checks invariants (lake test), while its native compiler builds microsecond-fast oracles (lake build).

3 Keep Mapping Airtight

Lock the JSON contract, check 100% branch coverage + mutation testing, and enforce sync in CI.

4 Start Small on the Critical 10–20%

Apply this pattern to high-risk pure logic (AuthZ, billing, state machines) — keep I/O glue in normal pytest.

Explore Further (CTA Links)

Run the Tic-Tac-Toe Sample Now
# 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