Birth of Math Engineering: Refactoring a 300,000-Line Proof of the Riemann Hypothesis Without Knowing Lean
On November 20, 2026, Levent Alpöge and Claude released a Lean 4 proof of the Riemann Hypothesis: roughly 17 million lines of code across more than 175,000 files. Within a day, the Lean FRO and Mathlib Initiative verified that the exported proof passed independent checkers (Lean's kernel and nanoda) against Mathlib's vetted statement of the hypothesis, relying only on Lean's three standard axioms (propext, Classical.choice, and Quot.sound) with zero sorry placeholders.
Five days later, the community repository (leanprover-community/riemann-hypothesis) moved to a condensed edition of roughly 300,000 lines across 800+ files, and a compact edition has since been verified at around 76,000 lines.
Over the past week, I had over 20 refactoring pull requests merged into that repository. Here are three of them:
-
#9695:refactor(Weil): construct four complete Witt splittings from dual frames(30 net lines removed) -
#9452:refactor(OneLift): sum linear maps in the gluing construction(20 net lines removed) -
#9445:refactor(Seesaw): infer measurability in the Bessel cutoff argument(20 net lines removed)
I cannot write Lean, I do not know what a complete Witt splitting or a Bessel cutoff argument is, and I do not understand the proof.
My workflow was standard software engineering. I took two maintenance tools I had already built for normal codebases, dry-lint (a code-duplication linter for Python, TypeScript, and Lua) and [CI-esta](https://github.com/gigaverse-app/ci-esta) (a CI profiler and build-acceleration toolkit), and had coding agents (Claude and Codex) add Lean support. The linter found duplicated declarations and proof blocks; the agents refactored the Lean code to remove lines and reuse abstractions; Lean's kernel and CI verified that every change preserved the theorem. My role was supplying the token budget, auditing what the tools missed, and pushing the agents to generalize the tooling to find larger simplifications.
This post is a technical writeup of what we built, what we measured on a 300,000-line formal proof, and the bugs we found in our own tools along the way. In a follow-up piece, I will cover the broader theory of what I call mathematical engineering and what this implies for AI and mathematics.
1. Treating a 300,000-Line Proof as a Codebase
At 800+ files and roughly 22,000 declarations, a formal proof has the same maintenance problems as a large Python or TypeScript monorepo. Nobody can hold 22,000 declarations in working memory, so the same logic gets written repeatedly in different files.
When we pointed dry-lint at the Riemann repository, three distinct patterns of repetition showed up:
- Whole declarations that restate existing results.
dry-lint scancompares every declaration against every other and ranks the closest pairs. It surfaced a private lemma proving that a finite sum of continuous functions is continuous. Mathlib already provides this ascontinuous_finsetSum. Deleting the private proof and calling Mathlib at all seven call sites compiled cleanly. We also found dead branches that nothing downstream used; one PR we opened removed roughly 1,300 lines of an unreachable path through the proof. - Repeated blocks inside different proofs. Two unrelated theorems often share an identical multi-line tactic sequence in the middle of their proofs. Whole-declaration comparison misses this. We wrote a block-level matcher (
lean-proof-blocks) that reads tactic steps and flags repeated spans of lines so an agent can extract them into a single shared lemma. Nothing in the matcher turned out to be Lean-specific, so we generalized it intodry-lint blocksfor Python, TypeScript, and Lua as well. (The first repo we tested it on wasdry-lintitself, where it caught a nested-comment scanner we had accidentally written twice in the same file the day before.) - Proof families from compiler metadata. After a build, Lean records which lemmas each proof invokes. We added a pass (
lean-proof-families) that reads those build records and groups three or more declarations citing the same lemmas in the same order. Unlike the text-based passes, this one uses the compiler's own dependency data to surface shared arguments across a family of theorems.
In the first two days, dry-lint generated the candidates behind nearly 30 refactoring PRs, cutting over 2,000 lines while adding a few hundred.
Auditing the linter against the compiler
The most useful engineering lesson came from checking what our tool could not see.
A static analyzer that reports "no duplicates" is only meaningful if it actually parsed the repository. Because Lean records the location of every declaration during compilation, we could audit dry-lint's extractor directly against the compiler's ground truth:
| Extractor version | Declarations found (out of ~22,000) | Coverage |
|---|---|---|
| Initial grammar-based release | ~8,700 | under 40% |
| Grammar with error recovery | ~16,900 | ~77% |
| Source-text command boundary scanner | ~21,950 (missed 4 class abbrev) | ~99.98% |
Our first parser was silently blind to over 60% of the proof because custom notation and wrappers like omit ... in broke the grammar. Turning on strict validation (--require-complete) rejected almost every file in the repository.
Dropping the full grammar in favor of scanning top-level command boundaries directly from source text solved the problem. It raised coverage to nearly 100% on the Riemann proof and, without any tuning, scanned Mathlib's 240,000+ declarations with the same accuracy. Once coverage hit ~100%, the scan immediately caught the private continuous_finsetSum duplicate mentioned above.
Performance bottlenecks exposed by scale
Running a Python/TypeScript linter on ~22,000 declarations exposed two algorithmic slow paths that did not show up on smaller repos:
- Nearest-neighbor index pruning: A full scan originally took over 15 minutes because the index walked posting lists for common tokens that could never push a pair above the reporting threshold. Adding early termination once remaining tokens could not reach the floor cut full-repo scans to under 6 minutes with identical output.
- Block-matcher loop pruning: Dropping a proof from the search as soon as it had no match of the current length cut the one-line-mismatch mode on the Riemann proof from nearly 50 seconds down to ~8 seconds, with byte-identical output.
Both optimizations live in the shared engine, so Python and TypeScript scans got the same speedups for free.
2. Profiling and Accelerating Lean CI
In Lean, continuous integration is the trust boundary that lets maintainers accept PRs from contributors who do not understand the math. On every pull request in the Riemann repository, a green CI check enforces four invariants:
- Zero
sorryplaceholders (lake buildfails on warnings). - Standard foundations only (the five core theorems depend exclusively on Lean's three standard axioms).
- Exact statement matching against a separate challenge file via
comparator. - Independent verification of the exported proof by both Lean's kernel and
nanoda.
Because every refactor has to clear this gate, CI latency sets the pace of iteration. When we profiled the repository's GitHub Actions workflows with CI-esta on November 26, we found two completely different bottlenecks depending on which queue a job landed in:
- Fork runner saturation: GitHub showed over 1,700 queued PR build workflows. Five fork jobs that had started had waited 9 to 10 hours just to get a runner.
- Dependency hydration on the merge queue: On the merge queue, runner wait time was around 1 second and actual proof plus axiom checking took under 20 seconds, yet restoring caches consumed nearly 2 minutes of a 2.5-minute job. On a fresh runner,
lake builditself took 6 seconds while downloading and unpacking Mathlib took over 2 minutes.
Those two bottlenecks require different fixes.
Fix 1: Prehydrated Btrfs dependency seeds
To cut the 2-minute Mathlib download without weakening verification, we built restore-lean-packages in CI-esta. A runner operator builds a read-only dependency seed once outside the PR loop (a one-time ~3-minute job containing the pinned Lean toolchain, checkouts, and compiled .olean artifacts). At job start, the action verifies lean-toolchain, lakefile.toml, and lake-manifest.json byte-for-byte along with the pinned Git revisions of every package. On a mismatch, it falls back to the normal download path.
On a hit, it populates .lake/packages using Btrfs copy-on-write reflinks. Each job gets an isolated writable workspace sharing underlying disk blocks with the read-only seed until modified, while lake build and every axiom check run unchanged.
In paired replays on GitHub-hosted Linux runners (measured in a fork, not yet adopted on the upstream project's runners):
| Workload | Fresh Setup | Seeded (Btrfs) | Speedup |
|---|---|---|---|
| Batch proof (paired replay) | ~3m 54s | ~1m 50s | 2.1x |
| Source PR (median of 4 replays) | ~4m 32s | ~2m 04s | 2.2x |
| Batch proof (median of 4 replays) | ~4m 23s | ~2m 09s | 2.0x |
Restoring the seed took ~13 seconds on Btrfs (compared to ~49 seconds on ext4, showing how much copy-on-write reflinks matter here).
Fix 2: Targeted local retries and .olean signature checks
No cache speeds up a 10-hour runner queue. When a one-file cleanup broke a downstream BorelSpace instance in CayleyChart.lean, a contributor did not need a full CI run just to see if their fix worked.
We built ci-esta-lean retry to parse a failed Lake build log and print the exact lake build command for the failing modules. On a local checkout with baseline caches restored, that targeted build reproduced the exact CayleyChart diagnostic in ~16 seconds.
We also built ci-esta-lean compare to diff elaborated theorem types directly from compiled .olean files (ignoring binder and universe parameter names while preserving visibility and type structure). This lets a contributor verify locally that a refactor preserved the exact signatures of the five headline theorems before pushing to the queue.
Note on test selection: we checked whether our test-selection tool (pytest-selective) had a role inside Lean builds and found none. Lake already handles incremental module rebuilds from its own import graph; test selection only helped on the repository's Python automation tests.
3. What Went Wrong
Publishing only the wins hides the real engineering constraints. Here is what broke or backfired during the week:
1. Valid refactors that made the proof worse.
In normal software, duplicated code is a correctness bug because two copies drift apart. In Lean, a duplicate cannot be false; the kernel checks both. That means the kernel will happily accept a refactor that is shorter or more clever but harder to read. We withdrew two PRs after review:
- Two counting lemmas shared a three-line proof by induction. Merging them by reindexing a sum turned three clear lines into eight opaque ones. The reviewer rejected it as harder to follow.
- Several refactors merged two cases and dropped the comments enumerating those cases. Reviewers asked for the comments back every time.
2. Generating PRs faster than reviewers can read them.
The repository's guidelines ask contributors making one kind of change in many places to open a single PR and wait for feedback before scaling up. With dry-lint and coding agents, we opened nearly 30 PRs in two days. Automated tooling makes reviewer bandwidth etiquette much more important, and we should have throttled our submissions earlier.
3. Bugs in our own tools.
Auditing our own week of tool commits turned up real defects in every tool we shipped:
-
ci-esta-lean retryprinted a nonexistent+src.Lib...module name unless passed an explicit flag, and missed failures without line numbers (such as bad imports or OOM-killed compiler processes). -
ci-esta-lean preflightcould falsely report nothing needed building if a previous failure name was misspelled or the tree had uncommitted edits. - The dependency-seed action failed on runners with Python 3.10 instead of falling back cleanly as documented.
- Our first writeup claimed CI was 2x faster without making it clear enough in the title that the benchmark came from a fork replay rather than upstream adoption.
Every one of those defects is now fixed with regression tests.
4. Try It on Any Lean (or Code) Repository
Everything we built for the Riemann proof is open source and runs without API keys.
Find duplicated declarations and repeated proof blocks in a Lean project:
# Declarations that look alike uvx --from 'dry-lint[lean]>=1,<2' dry-lint scan --extractor lean --judge none --limit 30 # Repeated tactic blocks across proofs uvx --from 'dry-lint[lean]>=1,<2' dry-lint blocks --extractor lean --lines 4 Measure CI queue waits and extract targeted local retry commands from a failed Lake build:
# Measure runner wait time vs. cache hydration vs. actual work ci-esta-lean queue --repo OWNER/REPO --per-event 25 # Print the targeted lake build command for modules that failed in a CI log gh run view RUN_ID --log-failed | ci-esta-lean retry - Both dry-lint blocks and ci-esta retry work on Python, TypeScript, and Bun repositories as well.
Links: