Skip to content
Claude + Lean 4: Audit AI Proofs Before You Trust Them — ContentBuffer guide

Claude + Lean 4: Audit AI Proofs Before You Trust Them

K
Kodetra Technologies··15 min read Intermediate

Summary

A Python gate that catches sorry, rogue axioms, vacuous hypotheses and bad defs in AI Lean proofs

Last Friday, Anthropic mathematician Levent Alpöge posted a note saying he believes that, working with Claude, he found a proof of the Riemann Hypothesis. He did not ship a paper. He shipped Lean code, reportedly around 17 million lines of it. Within days several mathematicians, including MIT's Andrew Sutherland, said they had compiled it on their own machines. And yet nobody serious is calling it settled. Kevin Buzzard pointed out that nobody yet understands what the proof shows, and the open question everyone keeps circling is a simple one: does the formal statement actually say what the Riemann Hypothesis says?

That question is the whole game for anyone using an LLM to write proofs, and it applies at every scale. Lean is ruthless about the proof. It is completely indifferent to whether you asked it to prove the right thing. A model that can't find a proof has plenty of ways to produce something that compiles anyway: a stray sorry, a convenient axiom, hypotheses that contradict each other, or a definition that quietly means something else.

In this guide you'll build proof_audit.py, a small Python harness that sits between Claude and your trust. Claude drafts the Lean, Lean checks the proof, the harness checks everything Lean doesn't, and a second, blind Claude call reads the statement back to you in plain English. Every Lean output in this post is real, produced with Lean 4.36.0 (released November 16, 2026).

What you'll build

  • A static gate that refuses to even compile code containing sorry, admit, axiom, native_decide or unsafe.
  • An axiom audit using #print axioms, so anything beyond Lean's three standard axioms fails the run.
  • A vacuity check that asks Lean whether the theorem's hypotheses can prove False by themselves.
  • Definition sanity checks: known-true and known-false facts you write once and run against every definition the model introduces.
  • A Claude draft-and-repair loop that feeds Lean errors back to the model, plus a blind back-translation step that compares the formal statement to your intended claim.

Prerequisites

  • Python 3.10+ and pip install anthropic (tested with SDK 2.14.0).
  • An ANTHROPIC_API_KEY environment variable for the Claude steps. The Lean checks run without one.
  • Lean 4. The cleanest route is elan, Lean's toolchain manager, from the official install page at lean-lang.org. If you only need a single binary, the release index at release.lean-lang.org lists direct downloads; unzip it and point LEAN_BIN at bin/lean.
  • Basic familiarity with Lean syntax helps, but every snippet below is explained. We stick to core Lean (no Mathlib) so the examples compile in well under a second.
# single-binary install used for this guide (Linux x86_64)
curl -sSfL -o lean.zip https://releases.lean-lang.org/lean4/v4.36.0/lean-4.36.0-linux.zip
unzip -q lean.zip
export LEAN_BIN=$PWD/lean-4.36.0-linux/bin/lean
$LEAN_BIN --version
# Lean (version 4.36.0, x86_64-unknown-linux-gnu, commit 611c117b..., Release)

Step 1: See the five ways a proof can lie

Before writing any tooling, it's worth watching Lean accept things you shouldn't trust. Save this as traps.lean and run lean traps.lean:

theorem sum_sq_ge (a b : Nat) : 2 * a * b ≤ a * a + b * b := by
  sorry

theorem bogus (n : Nat) (h : n < 0) : n * n = 7 := by omega

def MyPrime (n : Nat) : Prop := ∀ d, d ∣ n → d = 1 ∨ d = n
theorem one_is_prime : MyPrime 1 := by
  intro d hd
  left
  exact Nat.dvd_one.mp hd

axiom magic : ∀ n : Nat, n = n + 1
theorem cheat : (2 : Nat) = 3 := by have := magic 2; omega

theorem nd : 2^20 % 7 = 4 := by native_decide

#print axioms sum_sq_ge
#print axioms bogus
#print axioms one_is_prime
#print axioms cheat
#print axioms nd

The real output:

traps.lean:1:8: warning: declaration uses `sorry`
'sum_sq_ge' depends on axioms: [sorryAx]
'bogus' depends on axioms: [propext, Quot.sound]
'one_is_prime' depends on axioms: [propext]
'cheat' depends on axioms: [magic]
'nd' depends on axioms: [nd._native.native_decide.ax_1_1]

Read that carefully. There are no errors. The sorry only produces a warning, so a CI job that checks the exit code passes. bogus proves that a natural number squared is 7, and its axiom list looks perfectly clean, because the hypothesis n < 0 can never hold. one_is_prime proves 1 is prime because the definition forgot 2 ≤ n. cheat proves 2 = 3 by assuming nonsense. And native_decide trusts the compiler, which shows up as an extra axiom.

Two of the five (bogus and one_is_prime) are invisible to #print axioms. Those are the statement-level failures, and they're exactly the kind of thing people are still checking in the Riemann proof.

Step 2: Model a candidate proof

We ask Claude to return the theorem in pieces rather than as one blob of Lean. Splitting the binders (variables and hypotheses) from the conclusion is what makes the vacuity check possible later.

from dataclasses import dataclass, field

@dataclass
class Candidate:
    name: str
    binders: str          # e.g. "(a b : Nat) (h : a ≤ b)"
    conclusion: str       # e.g. "a + 3 ≤ b + 5"
    proof: str            # tactic block, starting with "by"
    prelude: str = ""     # defs the statement depends on

    @property
    def statement(self) -> str:
        return f"theorem {self.name} {self.binders} : {self.conclusion}"

    def source(self) -> str:
        return f"{self.prelude}\n\n{self.statement} := {self.proof}\n"

@dataclass
class Report:
    passed: bool = True
    findings: list[str] = field(default_factory=list)
    lean_errors: list[str] = field(default_factory=list)
    axioms: list[str] = field(default_factory=list)

    def fail(self, msg): self.passed = False; self.findings.append("FAIL " + msg)
    def warn(self, msg): self.findings.append("WARN " + msg)

Step 3: Run Lean and gate the escape hatches

The static gate runs before compiling. If a candidate contains an escape hatch we don't want to spend a compile on it, and we don't want to accidentally run something marked unsafe. Note the gate checks the prelude too, since that's where a model would declare an axiom.

import os, re, subprocess, tempfile

LEAN = os.environ.get("LEAN_BIN", "lean")
STANDARD_AXIOMS = {"propext", "Classical.choice", "Quot.sound"}
FORBIDDEN = [r"\bsorry\b", r"\badmit\b", r"^\s*axiom\b", r"\bnative_decide\b",
             r"\bunsafe\b", r"@\[implemented_by", r"@\[extern"]

def run_lean(src: str, timeout: int = 120) -> tuple[int, str]:
    with tempfile.NamedTemporaryFile("w", suffix=".lean", delete=False) as f:
        f.write(src)
        path = f.name
    try:
        p = subprocess.run([LEAN, path], capture_output=True, text=True, timeout=timeout)
        return p.returncode, (p.stdout + p.stderr).replace(path, "<file>")
    except subprocess.TimeoutExpired:
        return 124, "timeout"
    finally:
        os.unlink(path)

def static_gate(c, r):
    for pat in FORBIDDEN:
        if re.search(pat, c.source(), flags=re.MULTILINE):
            r.fail(f"forbidden construct matched /{pat}/")

def compile_and_axioms(c, r):
    code, out = run_lean(c.source() + f"\n#print axioms {c.name}\n")
    r.lean_errors = [l for l in out.splitlines() if ": error" in l or l == "timeout"]
    if code != 0 or r.lean_errors:
        r.fail(f"Lean rejected the proof ({len(r.lean_errors)} error lines)")
        return
    m = re.search(rf"'{re.escape(c.name)}' depends on axioms: \[(.*?)\]", out)
    r.axioms = [a.strip() for a in m.group(1).split(",")] if m else []
    extra = set(r.axioms) - STANDARD_AXIOMS
    if extra:
        r.fail(f"non-standard axioms: {sorted(extra)}")

Why keep the axiom check if the static gate already blocks axiom and sorry? Defense in depth. Regexes can be dodged (a macro, an import from another file in a bigger project), while #print axioms reports what the kernel actually depends on. Lean's own docs describe propext, Classical.choice and Quot.sound as the standard axioms; anything else deserves a human's eyes. Also note the output format: a theorem with no axioms prints 'dec' does not depend on any axioms, which our regex simply treats as an empty list.

Step 4: Catch vacuous theorems

This is the check most people skip, and it's the cheapest one to add. Take the theorem's binders, keep every hypothesis, and ask Lean to prove False. If it can, the hypotheses are contradictory and the theorem holds for no inputs at all.

VACUITY_TACTIC = "first | omega | simp_all | decide"

def vacuity(c, r):
    if not c.binders.strip():
        return  # no binders, nothing to contradict
    src = f"{c.prelude}\n\nexample {c.binders} : False := by {VACUITY_TACTIC}\n"
    code, _ = run_lean(src)
    if code == 0:
        r.fail("VACUOUS: the hypotheses alone prove False, so the theorem says nothing")

For (n : Nat) (h : n < 0), Lean happily proves False with omega, so the check fires. For a sane statement like (a b : Nat) (h : a ≤ b) it fails with a counterexample (omega could not prove the goal), which is what you want. A passing vacuity check is evidence, not proof: our three tactics won't find every contradiction. If you use Mathlib, add linarith, nlinarith and aesop to the list.

Step 5: Sanity-check every definition

A wrong definition is the nastiest failure because the theorem, the proof and the axiom list all look fine. The fix is old-fashioned: write down a few facts you know about the concept, and make Lean settle each one in both directions.

def sanity(c, checks, r):
    """checks: (lean_prop, expected_truth, tactic_that_settles_it)"""
    for prop, expected, tactic in checks:
        yes, _ = run_lean(f"{c.prelude}\n\nexample : {prop} := {tactic}\n")
        no, _ = run_lean(f"{c.prelude}\n\nexample : ¬ ({prop}) := {tactic}\n")
        actual = True if yes == 0 else False if no == 0 else None
        if actual is None:
            r.warn(f"sanity: could not settle `{prop}` with `{tactic}`")
        elif actual != expected:
            r.fail(f"sanity: `{prop}` is {actual} under your definitions, expected {expected}")

def audit(c, checks=None):
    r = Report()
    static_gate(c, r)
    if not r.passed:
        return r  # never compile code that smuggles in an escape hatch
    compile_and_axioms(c, r)
    if r.passed:
        vacuity(c, r)
        sanity(c, checks or [], r)
    defs = re.findall(r"^\s*(?:def|abbrev|structure|inductive|class)\s+(\S+)", c.prelude, re.M)
    if defs:
        r.warn(f"human must read these definitions: {defs}")
    return r

Now run all five traps through it (demo.py):

from proof_audit import Candidate, audit

cases = {
  "honest": Candidate("add_gap", "(a b : Nat) (h : a ≤ b)", "a + 3 ≤ b + 5", "by omega"),
  "sorry": Candidate("am_gm_nat", "(a b : Nat)", "2 * a * b ≤ a * a + b * b", "by sorry"),
  "vacuous": Candidate("square_is_seven", "(n : Nat) (h : n < 0)", "n * n = 7", "by omega"),
  "native": Candidate("pow_mod", "", "2 ^ 20 % 7 = 4", "by native_decide"),
  "bad_def": Candidate("one_prime", "", "MyPrime 1",
      "by\n  intro d hd\n  exact Or.inl (Nat.dvd_one.mp hd)",
      prelude="def MyPrime (n : Nat) : Prop := ∀ d, d ∣ n → d = 1 ∨ d = n"),
}
checks = [("MyPrime 1", False, "by\n  intro d hd\n  exact Or.inl (Nat.dvd_one.mp hd)")]
for label, c in cases.items():
    r = audit(c, checks if label == "bad_def" else None)
    print(f"[{label}] passed={r.passed} axioms={r.axioms}")
    for f in r.findings: print("   ", f)
[honest] passed=True axioms=['propext', 'Quot.sound']
[sorry] passed=False axioms=[]
    FAIL forbidden construct matched /\bsorry\b/
[vacuous] passed=False axioms=['propext', 'Quot.sound']
    FAIL VACUOUS: the hypotheses alone prove False, so the theorem says nothing
[native] passed=False axioms=[]
    FAIL forbidden construct matched /\bnative_decide\b/
[bad_def] passed=False axioms=['propext']
    FAIL sanity: `MyPrime 1` is True under your definitions, expected False
    WARN human must read these definitions: ['MyPrime']

Four traps caught, one honest proof passed. Swap in the corrected definition def MyPrime (n : Nat) : Prop := 2 ≤ n ∧ ∀ d, d ∣ n → d = 1 ∨ d = n with the check ("MyPrime 1", False, "by\n intro h\n have := h.1\n omega") and the same audit passes, still with the warning that a human has to read the definition. That warning never goes away, on purpose.


Step 6: Let Claude draft and repair

Now plug in the model. Claude returns JSON in the shape of a Candidate; we audit it and send every failure back, including raw Lean errors. One line in the repair prompt matters more than it looks: do not weaken the statement. Without it, models under pressure will add a hypothesis or narrow a type until the goal becomes easy.

import json, re
import anthropic
from proof_audit import Candidate, audit

MODEL = "claude-opus-5-5"
client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

DRAFT_SYSTEM = """You write Lean 4 (core library only, no Mathlib).
Return ONLY a JSON object with keys: name, prelude, binders, conclusion, proof.
- prelude: any defs the statement needs ("" if none)
- binders: explicit binders and hypotheses, e.g. "(a b : Nat) (h : a ≤ b)"
- proof: a tactic proof starting with "by"
Never use sorry, admit, axiom, native_decide, or unsafe."""

def ask(system, user, max_tokens=2000):
    msg = client.messages.create(model=MODEL, max_tokens=max_tokens, system=system,
                                 messages=[{"role": "user", "content": user}])
    return "".join(b.text for b in msg.content if b.type == "text")

def parse_json(text):
    m = re.search(r"\{.*\}", text, re.S)
    if not m:
        raise ValueError(f"no JSON in reply: {text[:200]}")
    return json.loads(m.group(0))

def draft_and_repair(claim, rounds=4):
    prompt = f"Formalize and prove this claim:\n{claim}"
    for i in range(1, rounds + 1):
        c = Candidate(**parse_json(ask(DRAFT_SYSTEM, prompt)))
        report = audit(c)
        print(f"round {i}: passed={report.passed} {report.findings}")
        if report.passed:
            return c, report
        prompt = (f"Claim:\n{claim}\n\nYour last attempt:\n{c.source()}\n\n"
                  "It failed these checks:\n" + "\n".join(report.findings + report.lean_errors[:15]) +
                  "\n\nFix it. Do not weaken the statement to make it easier.")
    raise RuntimeError("no passing proof within budget")

To test the loop without spending tokens, monkeypatch ask with replies a model commonly produces for 2ab ≤ a² + b² over the naturals. The Lean checks stay real:

import json, claude_loop
PROOF = """by
  rcases Nat.le_total a b with h | h
  · obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le h
    simp only [Nat.mul_add, Nat.add_mul, Nat.mul_assoc, Nat.mul_comm k a]
    omega
  · obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le h
    simp only [Nat.mul_add, Nat.add_mul, Nat.mul_assoc, Nat.mul_comm k b]
    omega"""
base = {"name": "two_mul_le_sq_add_sq", "prelude": "", "binders": "(a b : Nat)",
        "conclusion": "2 * a * b ≤ a * a + b * b"}
replies = iter([json.dumps({**base, "proof": "by omega"}),
                json.dumps({**base, "proof": "by grind"}),
                json.dumps({**base, "proof": PROOF})])
claude_loop.ask = lambda system, user, max_tokens=2000: next(replies)
cand, rep = claude_loop.draft_and_repair("2ab <= a^2 + b^2 for naturals", rounds=4)
print(cand.statement, "| axioms:", rep.axioms)
round 1: passed=False ['FAIL Lean rejected the proof (1 error lines)']
round 2: passed=False ['FAIL Lean rejected the proof (1 error lines)']
round 3: passed=True []
theorem two_mul_le_sq_add_sq (a b : Nat) : 2 * a * b ≤ a * a + b * b | axioms: ['propext', 'Quot.sound']

Both early failures are instructive. omega only does linear arithmetic, so it treats a * b as an opaque atom and reports a fake counterexample. grind in 4.36 has a ring normalizer but still can't close this nonlinear inequality on its own. The working proof splits on which number is bigger, writes b = a + k, expands, and normalizes the products (Nat.mul_assoc turns 2 * a * a into 2 * (a * a)) so that what's left is linear in the atoms a*a, a*k and k*k, which omega can finish. Those error messages are exactly what you want the model to see on the next round.

Step 7: Audit the statement blind

The proof passing tells you Lean is satisfied. It tells you nothing about whether the theorem is the one you wanted. So we make a fresh Claude call that sees only the statement and definitions, never the proof and never your original claim, and ask it to say literally what the statement asserts. A second call compares that reading to your claim.

BACK_SYSTEM = """You are given a Lean 4 theorem statement and the definitions it uses,
but NOT the proof and NOT the claim it was meant to capture.
Say in plain English exactly what it asserts. Be literal: mention every hypothesis,
every type (Nat subtraction truncates, Nat division floors), and every quirk of the definitions."""

JUDGE_SYSTEM = """Compare an intended mathematical claim against a literal reading of a formal statement.
Return ONLY JSON: {"verdict": "match" | "weaker" | "stronger" | "different",
"issues": [short strings]}. 'weaker' means the formal statement proves less than the claim."""

def audit_statement(claim, c):
    reading = ask(BACK_SYSTEM, f"{c.prelude}\n\n{c.statement}")
    verdict = parse_json(ask(JUDGE_SYSTEM, f"CLAIM:\n{claim}\n\nLITERAL READING:\n{reading}\n\n"
                                           f"FORMAL STATEMENT:\n{c.prelude}\n{c.statement}"))
    verdict["reading"] = reading
    return verdict

Hiding the claim from the back-translator is the point. If the model can see what the theorem was supposed to say, it tends to read that meaning into the Lean. Blind, it has to describe what's actually there. Here's the shape of what you want back for a statement that drifted. Say the claim was "for all integers a and b, (a − b) + b = a" and the model formalized it over Nat with an extra (h : b ≤ a):

{
  "verdict": "weaker",
  "issues": [
    "formal statement is over natural numbers, claim is over integers",
    "adds hypothesis b ≤ a, which the claim does not have"
  ],
  "reading": "For natural numbers a and b with b ≤ a, subtracting b from a and adding b back gives a. ..."
}

(This JSON is illustrative of the format; your model's wording will differ. Treat anything other than "match" as a stop.) Back-translation is a second opinion, not a verifier. It is itself an LLM reading Lean, and it can be wrong. Its job is to make the human review faster and harder to skip.


Worked example: a mini review pipeline for a math team

Picture a small team using Claude to formalize lemmas for a paper. Here's a workflow that holds up:

  • Pin the statement first, by hand. A human writes the prelude, binders and conclusion and gets them reviewed before any proving starts. Claude is only allowed to fill in proof. The draft loop rejects any candidate whose statement string differs from the pinned one.
  • Write sanity checks alongside every definition. Two or three per definition: a smallest positive case, a smallest negative case, an edge case like 0 or 1.
  • Run audit() in CI on every commit, failing the build on any FAIL line. Remember the raw Lean exit code alone would have passed the sorry case.
  • Run audit_statement() only when the statement changes, and attach the back-translation to the pull request so the reviewer reads plain English next to the Lean.
  • Keep the human gate. The human must read these definitions warning should map to a required reviewer.

The pinning step is the simplest version of what the Riemann discussion is really about. When Lean accepts 17 million lines, the remaining risk sits almost entirely in the small number of lines that state the theorem and define the objects. Concentrate your human attention there.

Common pitfalls

  • Trusting the exit code. sorry is a warning, not an error. Lean exits 0. Always gate on the source text and on #print axioms.
  • Letting the model edit the statement during repair. If the repair loop can change binders or conclusion, you will eventually get a proof of an easier theorem. Pin the statement or diff it every round.
  • Nat arithmetic surprises. In Lean, 5 - 7 = 0 and 7 / 2 = 3 on Nat. A claim about integers or reals formalized over Nat can become true for boring reasons. Tell the back-translator to call this out, as the prompt above does.
  • Silent definition drift. The MyPrime example is a toy, but real cases look the same: a missing lower bound, ≤ where you meant <, a Finset.range n that stops one short.
  • Weak vacuity tactics. If the vacuity check can't find False, that's a good sign, not a proof. Contradictions that need real math will slip through, so pair it with sanity checks.
  • native_decide and friends. Fine for exploration, but it adds a compiler-trust axiom (in 4.36 it shows up as a generated name like nd._native.native_decide.ax_1_1). Allowlist it explicitly if your project accepts that, never by default.
  • Timeouts as passes. A run that hits the timeout must fail. run_lean returns code 124 and the line timeout, both of which fail the compile step.
  • Version drift. Tactic behavior changes between Lean releases (grind is evolving fast). Pin the toolchain with a lean-toolchain file and record it in the report.

Quick reference

CheckWhat it catchesHowCost
Static gatesorry, admit, axiom, native_decide, unsafeRegex over source, before compiling~0 ms
CompileProofs that don't worklean file.lean, any error line fails~0.3 s core Lean
#print axiomsSmuggled axioms, sorryAx, compiler trustAllowlist: propext, Classical.choice, Quot.soundSame run
VacuityContradictory hypothesesexample binders : False := by first | omega | simp_all | decide1 extra compile
Sanity checksWrong definitionsProve prop or ¬prop for known facts2 compiles per fact
Blind back-translationStatement says something other than the claimClaude reads statement only, then a judge call compares2 API calls
Human reviewEverything the above missesRead every def and the theorem lineMinutes, non-negotiable

Next steps

  • Add Mathlib via a Lake project and extend VACUITY_TACTIC with linarith, nlinarith and aesop.
  • Pin statements: compare c.statement against a reviewed string every repair round and fail on any change.
  • Run the back-translation with two different models and flag disagreements between their readings.
  • Read Alpöge's note (alpo.ge/remark.pdf) and follow the Lean Zulip thread to see how professional mathematicians audit a giant machine proof in real time.
  • Read the Lean 4 documentation on axioms and #print axioms at lean-lang.org to understand what each standard axiom buys you.

Sources: TechCrunch, "AI claimed a solution to the 167-year-old Riemann hypothesis, and a human did too" (Nov 20, 2026); The Next Web coverage of Alpöge's claim (Nov 22, 2026); Levent Alpöge, alpo.ge/remark.pdf; Lean 4.36.0 release index at release.lean-lang.org; Anthropic Messages API docs at docs.claude.com.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,605 newsletter subscribers.

Also get