Abstract. Given a Lean library and a theorem one wishes to retain, which proofs can be removed, which arguments can be shared, and how does one check that the shorter proof still establishes the original statement? Flow Proof Optimizer brings together methods for tracing dependencies, finding repeated arguments and checking the resulting edits. The search starts with whole families of lemmas. For the theorems that must remain, it first asks whether one follows directly from another. It then looks inside their proofs for shared calculations and, finally, for individual steps that can be omitted. To test a shorter argument, Flow substitutes it for the old one and asks Lean to recompile the module containing the proof. When several proofs share a newly extracted lemma, Flow also expands each use of the lemma to check that it recovers the original argument and measures the saving across the whole edit. We follow the search in a four-module example that runs without a language model and compare the savings from two merged edits in the Lean community’s Riemann hypothesis project. Implementation at 1bc25e5.
1. Start from a theorem and work inward
In a Lean project that already builds, one first chooses the theorems to preserve. Each chosen theorem is a root. For each root, Lean records both its statement and the proof term, the expression constructed from the written proof and checked by Lean’s kernel. Flow follows the named declarations in the statement and proof term, then follows their references in turn. This reveals what the root depends on. A family outside that graph is a candidate for removal. If it can go, there is little point in shortening the proofs inside it. For the families that must stay, compare whole proofs. If neither proof can replace the other, look for a shared intermediate derivation. Within what remains, test individual steps. Figure 1 illustrates the decision at each of these four scales. Compiled dependency traversal.
Where should a simplification begin?
Does any proof we are keeping use this family?
A module contained 19 private lemmas about Fock pairings. The lemmas used one another, but no proof outside the family used their results.
| Declaration group | Before | After |
|---|---|---|
| Public theorems | Existing proofs | Same statements and proofs |
| Private pairing lemmas | 19 lemmas supporting an unused result | Entire family removed |
The family could be deleted in one edit, saving 372 lines. Shortening its individual proofs first would have spent effort on code that disappeared. Merged deletion
How Flow looks for this change
Starting from the theorems to keep, follow references in their statements and proof terms. A family outside those paths is a candidate. Check other callers, tactic registrations and public interfaces before deleting it. After an edit, trace the dependencies again. Backward trimming in clausal proofs uses a related idea: start at a result and trace its premises.
Can the special case use the general theorem?
Two Fock vacuum theorems established a Gaussian factorization. One proved it under general hypotheses. The special case had enough information to apply that theorem, but its proof repeated the calculation.
| Theorem | Before | After |
|---|---|---|
| General theorem | Prove the factorization | Prove the factorization |
| Special case | Prove the factorization again | Apply the general theorem |
Both statements stay. Moving the general theorem into a module the special case could import let its proof use the four facts already contained in its vacuum hypothesis. The calculation now appears once. Merged proof reuse
How Flow looks for this change
Flow uses fingerprints to group declarations before comparing their statements and proof terms. It standardizes binder and universe-parameter names while preserving binder kinds and argument order. Equal statements are one reason to compare two proofs (Figure 2). Reusing a more general theorem, as in this example, requires checking that its hypotheses hold for the special case.
What if the two proofs need different endings?
Two Hodge–Tate projection proofs used the same splitting and coordinate identity. They then applied the identity on opposite sides of a tensor product. Neither proof could replace the other in full.
| Proof | Before | After |
|---|---|---|
| First projection | Derive the identity → tensor on the right | Use shared identity → tensor on the right |
| Second projection | Derive the identity → tensor on the left | Use shared identity → tensor on the left |
The edit defines the splitting once and proves its coordinate identity in a shared lemma. Each projection keeps its own final argument, including the sign in the second projection. The merged change saves 20 lines. The pull request reports that the edited module compiled. Merged projection proofs
How Flow looks for this change
Flow searches both written proofs and compiled expressions for a common passage. On the text side, winnowing keeps the rightmost minimum fingerprint in a sliding window; a separate search also finds matches across a gap (Figure 2). In a scan of the Riemann hypothesis project at the revision labelled m41, this second search examined 14,447 tactic proofs and nominated 163 of 2,420 seeded pairs. On the term side, Flow can try abstracting different proofs of the same premise as an argument to a shared lemma. The typed comparison is related to Pfenning’s work on generalization; Rollini and colleagues studied sharing in resolution proofs. The merged projection diff shows which portion was actually shared.
Schleimer, Wilkerson and Aiken, Definition 1 · Gapped search · Measured revision · Pfenning on anti-unification · Resolution proof sharing, Algorithms 8–9 · Typed comparison.
Can one step be shortened without breaking what follows?
Inside a surviving proof, change one local step and ask Lean to check the rest of the argument. Two trials illustrate why that last check matters.
| Local step | Before | After |
|---|---|---|
| Proper-action instance | Construct the instance in several lines | Use inferInstance |
| Row bound | Introduce the bound hrow | Keep hrow |
In a retrospective check of the first example, we supplied the block that constructed the proper-action instance. Lean found inferInstance, and the module recompiled with seven fewer lines. In the second example, Flow removed the row bound in a trial, which made the later arithmetic tactic lia fail. That trial justified keeping the original step. Proper-action change
How Flow looks for this change
Lean records the source range of each tactic. This lets Flow remove a single binding while leaving its neighbor on the same line. Earlier tactic cleaners likewise tracked the later goals and the effects of local hypotheses. When a direct replacement looks plausible, Flow tries instance synthesis and Lean’s library search, then recompiles with the explicit answer. Figure 2 follows one such trial on a conjunction.
lean-gym cleaner · Evariste cleaner · Lean library search · Flow’s local replay.
2. How do we find a candidate for simplification?
Let p and q be propositions, with proofs hp and hq. Two lemmas, Demo.first and Demo.second, each establish the conjunction p ∧ q. The root theorem, Demo.result, proves (p ∧ q) ∧ (p ∧ q) by using the first lemma for the left conjunct and the second for the right. The dependency graph records a reference from the root to each lemma. Can one of their proofs be shortened while keeping both statements? Flow traces both dependencies and compares the written proofs. It reports that their opening step and last branch match. Between those matches, the second proof gives hp a new name, keep, then uses it immediately. The hypotheses hp and hq already prove p and q, respectively. That observation led us to select the entire four-line block and ask Lean to build the conjunction directly. Figure 2 shows the lines that Flow found and the replacement that Lean checked.
One conjunction, two derivations
Which proofs does the root use?
Demo.resultDemo.firstDemo.secondThe two edges are compiled references. A fourth module, Demo.Spare, lies outside the root module’s imports. No path from this root reaches its theorem Demo.unused.
What accounts for the different bodies?
apply And.intro · exact hp · exact id hq
apply And.intro · have keep := hp exact keep · exact id hq
Both proofs split the conjunction into two goals. For the first goal one proof uses hp immediately, while the other gives it the local name keep. That extra binding accounts for the difference between the two stored proof terms.
Which lines survive the gap?
apply And.intro · exact hp · exact id hq
apply And.intro · have keep := hp exact keep · exact id hq
The opening step and the last branch match even though the first branches differ. The scanner reports both pairs of line numbers. A reader can now inspect the intervening code alongside the matches.
Inspect the reported matches
left Demo.first right Demo.second shared_roots [Demo.result] ranges (left ↔ right) 8–8 ↔ 8–8 10–10 ↔ 11–11
These are the recorded names and inclusive line ranges, formatted for reading. Use these ranges to read both passages in their enclosing proofs. The intervening lines show what each branch contributes.
Can Lean close this block directly?
apply And.intro · have keep := hp exact keep · exact id hq
exact ⟨hp, hq⟩
We selected lines 8–11 and asked whether Lean could prove the conjunction directly. Lean found the expression ⟨hp, hq⟩, which pairs the two given proofs. Flow replaced all four lines with that expression and recompiled the module. The edit saves three lines and 50 UTF-8 bytes.
Run the example without AI
From the optimizer checkout, use its pinned Lean 4.37.0-rc1 toolchain and Python 3.11 or later. Build the scanner and example, then write the discovery report to a fresh output directory.
lake build proof-pairs (cd examples/tiny && lake build) python3 tools/workflow.py examples/tiny .flow/tiny --root Demo.result
In .flow/tiny/report.json, inspect the paths to the two lemmas and the matching ranges. To reproduce the last frame, supply the complete four-line block in the second proof.
python3 tools/provider_site.py examples/tiny Demo.Right examples/tiny/src/Demo/Right.lean 8 11
The command prints the replacement proof, the diff and the source savings. Walkthrough and toolchain.
3. What does a successful rewrite establish?
What must survive an edit depends on what it changes. For a deletion like the Fock pairing example, the question is whether anything we intend to keep still uses the declarations we propose to remove. Check uses outside the selected roots as well. A retained declaration may cite a private lemma, a source command may name it, or a tactic may rely on its registration as an automatic rule. Also check which declarations must remain available to other users. If those checks leave no obligations, remove the family and rebuild the affected modules with the original public statements in place. For proofs that must stay, the question becomes whether the replacement still proves the original statement.
For a direct replacement, insert the proposed proof where the old one appeared and recompile the module. That is the test the conjunction passed in Figure 2. Flow’s provider probe performs this test on a block one selects. When the replacement invokes a more general theorem, Lean checks that the hypotheses available there supply the arguments the theorem needs. Provider probe.
In two larger trials, Lean’s library search could not recover the intermediate constructions: a 25-line proof of surjectivity for Schur monomials and a 21-line proof of openness in a global norm theorem both remained in place. A failed search leaves open whether a shorter proof exists. If one recognizes the missing construction, one can look it up by its mathematical name in the documentation of the imported modules. A promising lemma can then be tried in the proof. If recompilation fails, the original argument stays in place. Recorded trials and source locations.
Extracting a shared lemma poses a stronger question. Can one recover each original derivation by expanding the new call? Flow takes the variables and hypotheses used in a local argument and makes them parameters of the new lemma. It places the lemma where both proofs can refer to it, substitutes a call for each passage, and compiles the edited modules in isolation. In strict replay, Flow expands the new lemma and permitted auxiliary definitions, simplifies function applications and local bindings, and compares the resulting proof terms with the originals. To accept an extraction it also requires net reductions in source lines, UTF-8 bytes and distinct expression nodes across the measured proof bodies, including the new lemma’s cost. An expression node represents one subexpression; counting a repeated subexpression once measures sharing. A different mathematical argument can prove exactly the same theorem and still fail this comparison. Its successful Lean check can be reported separately; Flow does not accept it as a replayed extraction. Extractor · Replay implementation.
Each caller must pass this comparison after the permitted reductions. Then count the new lemma and all replacements in the complete edit. Lean’s kernel supplies type checking; Flow adds the expression comparison and size tests. de Moura and Ullrich on Lean 4.
How the extractor chooses a local proof block
Consider a local claim introduced with have. Its proof might be a chain of equalities written with calc. A by inside one step proves just that step. Similarly, a function can contain a tactic proof in its body, even when the function itself is passed as an argument to another lemma. In both cases the extractor skips the enclosing have as a candidate at that location. A nested have with its own tactic block remains eligible. This keeps each proposed lemma attached to the claim its proof actually establishes. Examples of the proof blocks selected.
For each candidate block, Flow asks Lean to record its goal, local parameters and the constants in the goal. A tactic such as all_goals can run one source block against several goals. When that location yields several records, the extractor sets it aside and continues with independently recorded locations. Flow compares the constants in the recorded goals to choose blocks that might use the same lemma. Only compiling and replaying the proposed calls establishes that the sharing works. What Lean records · How Flow selects proof blocks.
4. What changed in two merged patches?
The first two panels of Figure 1 lead to different kinds of savings. How much disappears when an entire family can be removed? In the Fock pairing change (#1337), the answer depended on who used its final result. Nineteen private lemmas developed pairing, tensor-product and Gram-matrix identities. Their final monomial identity had no caller, and the rest of the module used none of the intermediate results. Removing the complete block preserved the module’s public declarations. There was no reason to simplify the nineteen proofs individually. Fock pairing diff.
The Fock vacuum change (#4575) posed the next question. Two theorems had to stay, but both used the same Gaussian factorization. Could one use the other’s proof? The factorization expresses a function restricted to the reals as a Gaussian factor times an entire function. One theorem established the general factorization. The vacuum hypothesis in the special case supplied the four facts needed to apply the general factorization. Moving the general theorem into a module the special case could import allowed the shorter proof to invoke it directly. Across the two files the patch added 15 lines and removed 97. The project README reports a structural replay of the two proof terms for this reuse of an existing theorem. Across the two measured bodies, the union of distinct expression nodes fell from 32,151 to 24,207. Fock vacuum diff.
Two ways to shorten a proof library
Do these savings establish that the proof is as short as possible?
A smaller proof need not be a shortest proof. To make a minimum-size claim one must specify the allowed transformations and what is counted. A separate Lean development does this for expressions that record proofs of equality. Reflexivity proves that an object equals itself. If p proves that two objects are equal, following it by reflexivity leaves both endpoints unchanged. Reversing p exchanges them. The four allowed reductions are shown below.
Stump and Tan analyze an equality-proof algebra; Ramos and colleagues give reductions on equality paths. For the project’s four rules, Lean proves that fully reducing a labelled equality proof with fixed endpoints gives an expression of minimum size among those equivalent under the four rules, counting each constructor in the expression once per occurrence. The library edits in Figure 3 allow different transformations. The four-rule theorem gives no minimum size for those proofs. Stump and Tan · Ramos et al., §4 · Four checked rules.
After a large accepted edit, rebuild and trace dependencies again from the same roots. Removing a call can leave behind a whole family of unused lemmas; if so, return to that coarser opportunity before trimming individual steps. Compare the finished edit with the current destination branch and inspect open pull requests for overlapping changes. Build the affected modules in import order, then read the diff from the perspective of the next person to use the theorem. After a deletion, are the independently useful results still available? If two proofs now share a lemma, can one find it from either proof and see why its hypotheses hold? Upstream overlap report.
Optional: Reviewing a candidate with AI
Flow can find two proofs with matching passages even when the reason for the match is unclear. At that point one can ask a language model a mathematical question. Do both proofs construct the same object? Would a symmetry turn the first argument into the second? Figure 4 follows one such candidate from the choice of a theorem through the decision to keep or discard an edit.
How a candidate moves between Flow, the reviewer and Lean
Inspect the review input for the example in Figure 2
After running the four-module example, the following command prints the first pair in its report together with the matched source. With no model command supplied, the JSON stays on the terminal.
python3 tools/review.py .flow/tiny/report.json 0 --source examples/tiny/src
The pair is Demo.first and Demo.second. The root Demo.result depends on both. A model adapter reads this JSON on standard input and returns its advice on standard output. Adapter examples.
A proof of partial Hecke duality illustrates the question. It had separate calculations for the two directions of an equivalence. Its forward implication held for any pair of complementary indices. Exchanging those indices allowed the same implication to be applied to the dual lattice. Taking the dual a second time returned the original lattice, giving precisely the converse and eliminating the second calculation. Merged argument.
On the return trip the complementary indices exchange places. The same implication now supplies the reverse direction of the theorem.
This is the kind of symmetry one might ask a model to look for at step 3. The evidence for the Hecke example is the merged Lean proof. It establishes that the symmetry works and leaves open who first recognized it.
References
- M. J. H. Heule, W. A. Hunt Jr. and N. Wetzler (2013). Trimming while Checking Clausal Proofs. Section IV traces premises backward from the empty clause. In Lean the starting points are the selected theorems, and compiled constant references supply the edges.
- S. Schleimer, D. S. Wilkerson and A. Aiken (2003). Winnowing: Local Algorithms for Document Fingerprinting. Definition 1 specifies the rightmost-minimum rule used in the contiguous-run search.
- S. F. Rollini, R. Bruttomesso, N. Sharygina and A. Tsitovich (2014). Resolution Proof Transformation for Compression and Interpolation. Algorithms 8–9 illustrate how merging resolution nodes exposes sharing. Comparing Lean terms also requires preserving binding structure.
- F. Pfenning (1991). Unification and Anti-Unification in the Calculus of Constructions. Anti-unification asks what two expressions have in common after abstracting their differences. Pfenning studies a higher-order pattern fragment. Flow tests a restricted set of local parameters at the actual calls.
- A. Stump and L.-Y. Tan (2005). The Algebra of Equality Proofs. Analyzes equality proofs built from reflexivity, symmetry, transitivity and assumptions.
- A. F. Ramos, R. J. G. B. de Queiroz and A. G. de Oliveira (2015). On the Identity Type as the Type of Computational Paths. Section 4 gives reductions for equality paths, including symmetry and transitivity.
- L. de Moura and S. Ullrich (2021). The Lean 4 Theorem Prover and Programming Language. Describes the elaborator and kernel underlying the checks on the edited proofs.
- D. Selsam, OpenAI. lean-gym proof cleaner. Tracks remaining goals while pruning tactic regions in Lean 3.
- Meta. Evariste tactic cleaner. Documents the effect that a hypothesis can have on later tactic execution.
- K. Rögnvaldsson, N. Mündler-Sasahara, J. Dekoninck and M. Vechev (2026). LeanLean: Benchmarking Repository-Scale Lean Proof Compression. Their study of 64 repositories measures source reduction and elaboration cost separately.
- Anthropic (2026). Formalizing Fermat’s Last Theorem. Describes the Columbia team’s Prove2Me interface for navigating statements and documentation.
- Lean developers. Lean.Meta.Tactic.LibrarySearch. The pinned Lean 4.37.0-rc1 implementation used to test for an existing provider in context.
- R. Takehi, J. Teoh, A. Zhang and O. Khattab (2026). Sparks of Weight-Space Programming. Its step-through presentation of a single experiment inspired Figure 2.



