Skip to content
PL & Formal Methods · Formal Verification

Lean 4 Theorem-Proving Backend

Architecture of weyl-lean, the four-stage verification pipeline, untrusted translation to Lean 4 / Mathlib, sandboxed tactic search, axiom auditing, and end-to-end proof example.

Weyl’s core type checker λWeyl\lambda_{\mathrm{Weyl}} deliberately restricts itself to a polynomial-time decidable fragment of index theories and refinements. Theoretical physics, however, routinely relies on universally quantified algebraic and categorical identities—such as “for every finite group GG and subgroup HH, the ribbon boundary projector AHA_H is idempotent and modular-invariant” or “for all G,KG, K, [AvK,TlK]=0[A_v^K, T_l^K] = 0.” Rather than polluting the core type checker with undecidable dependent types, Weyl routes these proof obligations through the orchestration-layer crate weyl-lean to a Lean 4 theorem-proving backend.

Why Lean 4 Is a Backend Rather Than Weyl’s Core

Lean 4 excels at minimal-TCB kernel certification inside an axiomatically closed system, whereas Weyl’s primary workload is deterministic 107–10810^7\text{–}10^8-term series expansion, external-memory merge-sorting, truncation-error tracking, and ED oracle comparison—objects that are not theorems at all. Weyl therefore adopts a complementary division of labor: high-throughput symbolic and numerical kernels stay in Rust with full control over memory layout and SIMD, while Lean 4 acts as an independent theorem backend for universal claims, string-diagram chains, and type-system metatheory.

weyl-lean Architecture and Four-Stage Pipeline ​

weyl-lean sits in the orchestration layer (depending on weyl-types and weyl-mcp, never entering the numerical kernel dependency graph). Every theorem declaration flows through four stages in weyl-lean/src/lib.rs:

rust
pub struct InstanceComparison {
    pub group: String,
    pub claim: String,
    pub holds: usize,
    pub fails: usize,
    pub skipped: usize,             // cocycle instances outside Q skip Lean decide
    pub disagreement: Option<String>,
}

pub enum ClaimStatus {
    Proved(ProofReport),            // fresh Lean kernel + clean axiom audit
    Unproved(ProofReport),          // budget exhausted; residual goals saved for handoff
    Assumed { cite: String },       // axiom cite(...), propagated as unproved hypothesis
}

pub enum TheoremStatus {
    /// Stage 1: exact finite-group evaluation found a counterexample; Lean is never invoked.
    Refuted(eval::Counterexample),
    /// Stage 3: two-sided instance comparison disagreed; the translator itself has a bug.
    TranslationMismatch(InstanceComparison),
    /// Stage 4: per-claim verdict (Proved, Unproved, or Assumed).
    Checked(Vec<(String, ClaimStatus)>),
}

In the first stage, exact finite-group falsification (eval::falsify) evaluates every claim inside Weyl’s exact kernel over the finite groups listed in falsify (such as S3,D4,Q8,A4S_3, D_4, Q_8, A_4) before Lean is ever invoked; any counterexample immediately halts the pipeline with TheoremStatus::Refuted, filtering false conjectures at negligible cost. Each surviving claim then enters formal translation (translate::translate_claim), which lowers it into a LeanStatement targeting WeylLib and Mathlib together with a human-readable correspondence table mapping every Weyl subexpression to its Lean term.

Because the translator is not in the TCB, the third stage runs a two-sided instance comparison (compare_instances) to guard against proving a mistranslated proposition: weyl-lean emits concrete finite-group instances from Weyl’s own Cayley tables, asks Lean’s kernel to decide each translated instance, and checks case-by-case agreement with Stage 1 while auditing #print axioms, aborting with TranslationMismatch on any discrepancy. Only claims that pass comparison enter the fourth stage, sandboxed tactic search and kernel certification (prove::search and Sandbox::check), where tactics are proposed inside a budgeted sandbox and logged, and a claim becomes ClaimStatus::Proved only after a fresh Lean process accepts the entire file with clean axioms.

Translation from Weyl HIR/SIR to Lean 4 and Mathlib ​

weyl-lean/src/translate.rs maps Weyl’s algebraic declarations onto Mathlib and Weyl’s companion library WeylLib:

Weyl Surface / IR ConstructLean 4 / Mathlib TargetNotes
G : finite group(G : Type) [Group G] [Fintype G] [DecidableEq G]Standard finite-group typeclasses
H : subgroup of G(H : Subgroup G) [DecidablePred (· ∈ H)]Subgroup with decidable membership
μ : 2-cocycle on HgroupCohomology.cocycles₂ H (Units K)Mathlib group cohomology 2-cocycle
Ribbon(G) basis F[g,h]F[g, h]WeylLib.RibbonAlg G KFinitely supported G×G→KG \times G \to K, K=Q(ζn)K = \mathbb{Q}(\zeta_n)
1/|H| Σ_{h₁,h₂∈H} F[h₁,h₂]Ribbon.boundary H (AHA_H)Pattern-recognized and cross-checked in Stage 3
1/|H| Σ alt_μ(h₁,h₂) F[h₁,h₂]Ribbon.twisted H μTwisted boundary, altμ(g,h)=μ(g,h)/μ(h,g)\mathrm{alt}_\mu(g,h) = \mu(g,h)/\mu(h,g)
1/|G| Σ_{h∈G} F[1,h]Ribbon.vacuum G (Ω\Omega)Vacuum projector
String-diagram SIR chainMonoidalCategory / BraidedCategory chainAssociator/unitor steps discharged via coherence

Untrusted Translation Discipline

Recognizing explicit sums as library constants (Ribbon.boundary H, Ribbon.vacuum G) inside translate::recognize is purely an untrusted optimization. Because Weyl’s kernel evaluates the raw sum literally during eval::evaluate_claim while Lean decides the recognized form during compare_instances, any translation bug surfaces immediately on non-abelian test groups such as S3S_3 or Q8Q_8.

Proof Obligation Extraction and Tactic Pipelines ​

weyl-lean supports both automated search (prove automatically within <budget>) and explicit literature citations (axiom cite("..."), which record ClaimStatus::Assumed and propagate as unproved hypotheses). For automated search, the sandbox exposes four MCP tools sharing the weyl-mcp protocol and replay log format: lean_goal_state inspects remaining proof goals and local hypotheses, lean_apply_tactic executes a candidate tactic or block on the active goal and returns updated goals, errors, or timeouts, lean_search_lemma queries WeylLib and Mathlib by type signature, and lean_check runs full-file verification in a fresh Lean process.

Two built-in search policies drive these tools. The recorded policy (--policy recorded) replays deterministic recorded tactic scripts for CI regression checks and toolchain upgrades, whereas the portfolio policy (--policy portfolio) executes a budgeted sequence of automated pipelines—unfolding algebra definitions via simp [Ribbon.mul_def, Ribbon.S_def, Ribbon.T_def], re-indexing finite sums (Finset.sum_mul, Equiv.mulLeft), and closing goals with ring, abel, field_simp, and WeylLib lemmas (Ribbon.card_inv_mul_card)—before falling back to a budgeted LLM tactic proposer.

Every attempt is appended to <dir>/<theorem>.<claim>.jsonl with timestamps, goal hashes, tactics, and residual goal states for deterministic replay and human handoff when a budget expires:

json
{
  "step": 3,
  "theorem": "ssb_boundary",
  "claim": "claim_0",
  "policy": "portfolio",
  "tactic": "simp only [Ribbon.mul_apply, Ribbon.boundary_apply]",
  "elapsed_ms": 42,
  "remaining_goals": 1,
  "status": "ok"
}

String-Diagram SIR Lowering & Metatheory Formalization ​

Beyond finite-group ribbon identities, weyl-lean covers two additional formalization domains: string-diagram chains and the planned formalization of λWeyl\lambda_{\mathrm{Weyl}} metatheory.

String-Diagram Chains ​

Implemented across weylc diagram, weyl-egraph::diagram, and weyl-lean::diagram, a theory of string diagrams consists of a signature (objects and generators), rewrite rules, statements, and interpretations. A diagram is stored in layers, each representing a node between wires, with its open hypergraph maintained as a derived view. Only two kinds of step exist: exchanging two layers whose nodes share no wire, and replacing an occurrence of one side of a rule by the other. For a braided signature, the braiding laws (cancellation, naturality in every generator and crossing—and hence Yang–Baxter) are generated as rules. A proof is a list of steps, found by bidirectional search or proposed from outside, and always replayed. Each step exports as three calc lines in Mathlib's MonoidalCategory / BraidedCategory—regroup with monoidal, rewrite with the hypothesis, whisker_exchange, or a naturality lemma, and flatten with monoidal—and Lean's kernel checks the chain.

text
$ weylc diagram examples/lagrangian_algebra.wdiag --lean
instance electric: a model (every rule holds exactly)
instance fermionic: NOT a model, it violates comm; not used
theorem inner_swap: PROVED for every braided monoidal category: 3 step(s) using assoc, comm,
                    checked by Lean (axioms: propext, Classical.choice, Quot.sound); holds in electric
      A ⊗ β[A,A] ; mu ⊗ A ; mu
    = A ⊗ β[A,A] ; A ⊗ mu ; mu   [assoc]
    = A ⊗ mu ; mu   [comm]
    = mu ⊗ A ; mu   [← assoc]
theorem false_unit: REFUTED: the two sides differ in the model electric

In instance mode (weyl-topo::fusion), the same diagrams are evaluated exactly over Q(ζn)\mathbb{Q}(\zeta_n) in a multiplicity-free braided fusion category given by its FF and RR symbols (built in: Fibonacci, Ising, semion, ZN\mathbb{Z}_N, D(ZN)D(\mathbb{Z}_N); the pentagon and both hexagons are verified before the data is used). Objects may be direct sums of simple objects, so an algebra such as A=1⊕eA = 1 \oplus e in the toric code is an interpretation, and a statement is tested in every model before a proof is sought. Not covered are fusion multiplicities, non-abelian D(G)D(G) data, duals (cups and caps) as built-in structure, and e-graph saturation—the search is a bounded breadth-first one.

λWeyl\lambda_{\mathrm{Weyl}} Metatheory Draft ​

weyl-lean is also planned to formalize several core metatheoretic statements about the type system in Lean 4 rather than relying solely on paper proofs. Currently weyl/lean/WeylLib/ contains only lemmas about physical models and no formalization of λWeyl\lambda_{\mathrm{Weyl}} typing judgments (see Type System §8):

Planned TargetCurrent StatusPlanned Approach & Rationale
Index theory laws (bicharacters, ideal lattice ⊕/⊛\oplus / \circledast, R(G)R(G))Not startedIntended to instantiate existing Mathlib structures
Conjecture 1 (Pauli & Majorana fragment + region-class lemma)Not startedCovering Gen, Mul, Add, Sum, Sub
Selection rule Sel & Conjecture 5 (Exact non-interference)Not startedCharacter orthogonality + logical-relations proof
Conjecture 2 (Built-in kernel rewrite preservation)Not startedOne Lean lemma per built-in rewrite rule; currently checked at run time
pCUT Expand flow convergenceCited axiomCross-checked on Stage A exact 14th-order oracle
Surface parser & elaboratorOut of scopeElaborated core terms are re-typechecked to keep the TCB small

Certificate Checking, Axiom Auditing, and Caching ​

Whether tactics originate from the built-in portfolio or an LLM proposer, a proposer’s output never becomes a conclusion on its own. Sandbox::check enforces three strict invariants. First, a fresh Lean 4 process verifies the complete .lean artifact from scratch to eliminate any stale interactive state. Second, #print axioms <theorem_name> is appended and parsed by lean::foreign_axioms, permitting only standard Lean axioms (propext, Classical.choice, Quot.sound) alongside explicitly declared axiom cite(...) entries. Third, all escape hatches are forbidden: both sorry and native_decide are rejected, since native_decide would pull the Lean compiler and runtime back into the TCB.

Certified proofs are cached by (theorem_ast_hash, weyl_lib_rev, mathlib_rev). Lean and Mathlib versions are pinned, and nightly CI re-verifies every built-in theorem from scratch.

End-to-End Example: Lowering .weyl to Lean 4 ​

Consider the built-in ssb_boundary theorem for spontaneous symmetry-breaking boundaries of quantum doubles D(G)D(G):

weyl
theorem ssb_boundary:
  for all G : finite group,  H : subgroup of G
  define A ≔ 1/|H| Σ_{h₁, h₂ ∈ H} F[h₁, h₂]
  define Ω ≔ 1/|G| Σ_{h ∈ G} F[1, h]
  claim  A A = A
  claim  A Ω = Ω
  claim  S[A] = A   and   T[A] = A
  prove automatically within 2 h
  falsify on G ∈ {S₃, D₄, Q₈, A₄}

For the first claim A A = A, weyl-lean lowers the obligation into the following Lean 4 theorem and verifies the synthesized proof:

lean
import WeylLib.Ribbon

theorem ssb_boundary_claim_0
    {G : Type} [Group G] [Fintype G] [DecidableEq G]
    (H : Subgroup G) [DecidablePred (· ∈ H)] :
    Ribbon.mul (Ribbon.boundary (K := ℚ) H) (Ribbon.boundary (K := ℚ) H) =
      Ribbon.boundary (K := ℚ) H := by
  ext ⟨g, h⟩
  simp only [Ribbon.mul_apply, Ribbon.boundary_apply]
  by_cases hg : g ∈ H
  · by_cases hh : h ∈ H
    · simp [hg, hh, Finset.sum_filter, H.mul_mem_cancel_left]
      ring
    · simp [hg, hh]
  · simp [hg]

#print axioms ssb_boundary_claim_0
-- 'ssb_boundary_claim_0' depends on axioms: [propext, Classical.choice, Quot.sound]

Run the full pipeline or inspect built-in theorems (modular_relations, ssb_boundary, twisted_boundary, and the intentional counterexample boundary_is_the_vacuum) from the CLI:

bash
# List all built-in theorems
weylc theorem

# Prove ssb_boundary with the portfolio policy and log traces
weylc theorem ssb_boundary --policy portfolio --trace-dir target/lean-traces

# Counterexample check: refuted immediately on Z₂ / S₃ in Stage 1 without launching Lean
weylc theorem boundary_is_the_vacuum

Universal lattice stabilizer identities (such as theorem for all G, K : [A_v^K, T_l^K] = 0 in non-abelian quantum doubles) follow the exact same pipeline: Stage 1 falsifies against concrete GroupQudit<G> normal forms, and check_theorem enforces hard wall-clock and tactic limits via ProofBudget:

rust
pub fn check_theorem(
    project: &LeanProject,
    theorem: &Theorem,
    budget: ProofBudget,
    compare_on: Option<&[&str]>,
    policy_for: &mut dyn FnMut(&str) -> Box<dyn TacticPolicy>,
) -> Result<TheoremStatus, String>

If the budget expires before all subgoals close, the pipeline returns ClaimStatus::Unproved(report) with the exact remaining Lean goal states and hypotheses preserved for human handoff.

Lattice-Operator Theorems and WeylLib ​

Theorems about the operators of a lattice model are read by weylc itself (crates/weylc/src/gauge_model.rs) and go through the same stages with matrices in place of ribbon elements: an operator on configurations E → G is a Matrix (E → G) (E → G) R, which Lean's kernel can evaluate on a small lattice by decide +kernel.

WeylLean (WeylLib.Gauge)
|a⟩⟨b| on edge lGauge.ketbra l a b
∏_{l out of v} / ∏_{l into v}Gauge.prodOut Λ v / Gauge.prodInto Λ v
projector onto holonomy(∂p) = 1Gauge.holProj Λ p
Σ_p, Σ_{v ∈ ∂Λ}, Σ_{v ∉ ∂Λ}Gauge.sumAll, Gauge.sumOn Λ.bdyV, Gauge.sumOff Λ.bdyV
Σ_{k ∈ K}∑ x : G, if x ∈ K then … else 0

A lattice is plain data (out, into : V → List E, bdy : P → List (E × Bool), boundary sets). Statements that need it to be a real lattice take one hypothesis:

lean
structure Lattice.WellFormed (Λ : Lattice V E P) : Prop where
  simple : ∀ v, Λ.SimpleAt v          -- no edge listed twice at a vertex
  apart  : ∀ v w, v ≠ w → Λ.Apart v w -- an edge has one source and one target
  closed : ∀ v p, Λ.ClosedAt v p      -- the path around every plaquette is closed

The hypothesis is emitted only when the statement needs it. The kernel checks it on the lattice it computes on, and every comparison file asks Lean to prove lat.WellFormed for the comparison lattice.

These statements about the quantum double with a boundary of type KK (examples/quantum_double_boundary.weyl) are proved from .weyl source for every finite group, subgroup and well-formed lattice, after falsification and Lean agreement on Z2\mathbb{Z}_2, S3S_3, D4D_4:

StatementLean lemma closing it
[A_v^K, T_l^K] = 0Gauge.left_commute_diag, Gauge.right_commute_diag
[A_v, B_p] = 0, [A_v^K, B_p] = 0Gauge.vertexOp_commute_holProj
[B_p, B_q] = 0Gauge.holProj_commute
[A_v, A_w] = 0, [A_v^K, A_w^K] = 0Gauge.vertexOp_commute (and rfl at v = w)
[B_p, T_l^K] = 0Gauge.holProj_commute_diag
[T_l^K, T_m^K] = 0Gauge.diag_commute_diag
A_v^g · A_v^h = A_v^{g h}Gauge.vertexOp_mul

Limits

The two-sided comparison currently runs on tiny lattices only—the smallest cylinder for Z2\mathbb{Z}_2, and one vertex with a loop edge and one plaquette for groups of order 3 to 8—with larger groups reported as skipped. In addition, [A_v, T_l^K] = 0 and [A_v, A_w^K] = 0 hold only for a bulk vertex v; because a theorem statement cannot yet restrict a free index to v ∉ ∂Λ, the claim all terms of H commute is still reported as checked on instances rather than proved in general. Finally, proofs are recorded scripts tried before the portfolio search, and a recorded script carries no special authority: it is a proposal like any other, and only Lean's kernel decides.

WeylLib also holds theorems that are not yet reachable from surface syntax:

FileContent
Twisted.leanFor every abelian HH and 2-cocycle μ\mu, the twisted boundary element satisfies the four boundary conditions (twisted_boundary, reachable as a built-in theorem)
DoubleCoset.leanSectors.card_sectors: ∣K\G/K∣⋅∣K∣2\lvert K\backslash G/K\rvert \cdot \lvert K\rvert^2 counts the triples (a,b,v)(a, b, v) with avb−1=va v b^{-1} = v (Burnside)
Duality.leanCreating/probing duality of D(G)D(G) anyons for every finite group: Pa=dim⁡a∣G∣S[Ma]P^a = \tfrac{\dim a}{\lvert G\rvert} S[M^a], S[Ma]=∑bSbaMbS[M^a] = \sum_b S_{ba} M^b, and Ma=∣G∣∑bSab‾ Pb/dim⁡bM^a = \lvert G\rvert \sum_b \overline{S_{ab}}\, P^b / \dim b

Duality.lean takes column orthogonality of the centralizer characters as a hypothesis (Mathlib has row orthonormality only), so its characters are abstract functions with the standard properties rather than Mathlib's FDRep characters. It also proves that the right-hand side ∣G∣∑bSab‾ S[Mb]\lvert G\rvert \sum_b \overline{S_{ab}}\, S[M^b] equals ∣G∣ Ma\lvert G\rvert\, M^a, so that form of the inverse relation holds only for the trivial group.

Strict Boundary with the Error Lattice

weyl-lean accepts only Exact-grade propositions; any term carrying Trunc or Epi is rejected by the type checker before reaching theorem. Passing Stage 1 falsification never promotes “holds on {S3,D4,Q8,A4}\{S_3, D_4, Q_8, A_4\}” into a universal theorem—only a Stage 4 Lean kernel certificate confers universal validity.

Weyl v0.1 · MIT License