Repository navigation
Description
Prerequisites
- Check that your issue is not already filed:
https://github.com/leanprover/lean4/issues - Reduce the issue to a minimal, self-contained, reproducible test case.
Avoid dependencies to Mathlib or Batteries. - Test your test case against the latest nightly release, for example on
https://live.lean-lang.org/#project=lean-nightly
(You can also use the settings there to switch to “Lean nightly”) - When reporting a perceived soundness bug: Does it affect
lake check --paranoid?
If in doubt, please reach out on [email protected] for responsible disclosure.
(Not a soundness bug: the kernel rejects a valid proof.)
Description
The kernel's definitional equality check unfolds lazily when it compares two bare projections
s.i =?= t.i, but not when it compares two applied projections s.i a =?= t.i a. For an applied
projection, the kernel reduces s and t to constructors before it compares them. If that
reduction is expensive, the kernel does the expensive work even when one delta step makes s and
t syntactically equal.
Since mathlib4#41506, Mathlib's Set is a structure with one field Mem : α → Prop, so a ∈ s
unfolds to the applied projection s.Mem a. A kernel check of a ∈ s =?= a ∈ t with s and t
syntactically different can now take this path. Before mathlib4#41506, Set α was α → Prop,
and a ∈ s unfolded to s a. Lazy delta reduction then unfolded the head constant of s or t
and compared the arguments.
Context
is_def_eq_core in src/kernel/type_checker.cpp calls lazy_delta_proj_reduction only when both
sides are projections:
if (is_proj(t_n) && is_proj(s_n) && proj_sname(t_n) == proj_sname(s_n) && proj_idx(t_n) == proj_idx(s_n)) {For s.i a, t_n is an application whose head is a projection, so this branch does not apply.
Lazy delta reduction does not help either. If neither side has a constant head,
lazy_delta_reduction_step returns DefUnknown. Its special case for projection applications,
try_unfold_proj_app, applies only when exactly one side has a constant head. The next step,
whnf_core(t_n) with cheap_proj = false, calls whnf on the projected structure and reduces it
to a constructor. This code is the same in v4.35.0, v4.36.0 and on master.
We found this in a downstream project after a toolchain and Mathlib update. A proof about a
VCVio computation that samples a 2^32-bit value checked on Lean v4.35.0 with a Mathlib from before
mathlib4#41506. After the update, the kernel refused it. The proof compares memberships in the
support of two forms of the computation. The kernel now reduces the support set to a constructor,
which runs the computation and evaluates 2 ^ (2 ^ 32).
Steps to Reproduce
The file below has no dependencies other than Lean. It adds each theorem with addDecl, so only
the kernel checks them. Additional Information explains why it bypasses the elaborator.
import Lean
open Lean Meta Elab Term
/-- A structure with one predicate field, like Mathlib's `Set` since mathlib4#41506. -/
structure PSet (α : Type) where
Mem : α → Prop
instance : Membership α (PSet α) := ⟨fun s a => s.Mem a⟩
/-- Reducing `big n` to a constructor computes `2 ^ n`. -/
def big (n : Nat) : PSet Nat := if 2 ^ n = 0 then ⟨fun _ => True⟩ else ⟨fun a => a = 0⟩
/-- `small` unfolds to `big (2 ^ 32)` in one delta step. -/
def small : PSet Nat := big (2 ^ 32)
/-- The same construction with a function type, like Mathlib's `Set` before mathlib4#41506. -/
def FSet (α : Type) := α → Prop
instance : Membership α (FSet α) := ⟨fun s a => s a⟩
def bigF (n : Nat) : FSet Nat := if 2 ^ n = 0 then fun _ => True else fun a => a = 0
def smallF : FSet Nat := bigF (2 ^ 32)
/-- Elaborate a statement `∀ xs, P → Q` and add the theorem `fun xs h => h` with `addDecl`.
The elaborator does not unify `P` with `Q`, so only the kernel checks that they are
definitionally equal. -/
def addIdentityTheorem (name : Name) (stmt : Term) : TermElabM Unit := do
let type ← elabType stmt
synthesizeSyntheticMVarsNoPostponing
let type ← instantiateMVars type
let value ← forallTelescope type fun xs _ => mkLambdaFVars xs xs.back!
addDecl (.thmDecl { name, levelParams := [], type, value })
/-- `#add_identity_theorem name : ∀ xs, P → Q` runs `addIdentityTheorem`. -/
elab "#add_identity_theorem " name:ident " : " stmt:term : command =>
Command.liftTermElabM <| addIdentityTheorem name.getId stmt
-- Accepted: the kernel compares the bare projections `small.Mem` and `(big (2 ^ 32)).Mem` with
-- `lazy_delta_proj_reduction`, which unfolds `small` before it reduces either structure.
#add_identity_theorem bare : ∀ P : (Nat → Prop) → Prop, P small.Mem → P (big (2 ^ 32)).Mem
-- Accepted: with a function type, `smallF a` and `bigF (2 ^ 32) a` have constant heads, and lazy
-- delta reduction unfolds `smallF` to make them syntactically equal.
#add_identity_theorem functionType : ∀ a : Nat, a ∈ smallF → a ∈ bigF (2 ^ 32)
-- Rejected: `a ∈ small` unfolds to the applied projection `small.Mem a`. The kernel reduces
-- `small` to a constructor before it compares the two sides, so it evaluates `2 ^ (2 ^ 32)`:
-- "(kernel) the kernel refused to evaluate `Nat.pow` because its second argument does not fit in
-- a 32-bit unsigned integer".
#add_identity_theorem applied : ∀ a : Nat, a ∈ small → a ∈ big (2 ^ 32)- Save the file as
Kernel.lean. - Run
lean Kernel.lean.
Expected behavior: The kernel accepts all three theorems. For applied, the kernel unfolds
small to big (2 ^ 32), as it does for bare and functionType, and the two sides become
syntactically equal.
Actual behavior: The kernel accepts bare and functionType, and rejects applied:
Kernel.lean:51:0: error: (kernel) the kernel refused to evaluate `Nat.pow` because its second argument does not fit in a 32-bit unsigned integer
The size limits only make the extra work visible. If 2 ^ 28 replaces 2 ^ 32 in the file, the
kernel accepts bare and functionType and rejects applied because "the result would exceed the
maximum numeral size". If 2 ^ 20 replaces 2 ^ 32, the kernel accepts all three theorems, and
for applied it computes 2 ^ (2 ^ 20).
Versions
4.35.04.36.04.38.0-nightly-2026-11-19
The result is the same on all three versions. OS: Linux x86_64.
Additional Information
The reproduction bypasses the elaborator because the elaborator fails on these statements for a
different reason. With the definitions above, a proof that uses a hypothesis h : a ∈ small fails
to elaborate, even when the expected type is exactly the type of h:
-- warning: exponent 4294967296 exceeds the threshold 256, exponentiation operation was not evaluated
-- error: maximum recursion depth has been reached
-- The `constructorNameAsVariable` linter also fails here (leanprover/lean4#16612).
theorem identity : ∀ a : Nat, a ∈ small → a ∈ small := fun _ h => hThe same happens with FSet and smallF, and on all three versions. So it does not depend on
the projection, and this issue does not cover it.
A downstream workaround is to avoid kernel checks of a ∈ s =?= a ∈ t where s and t differ.
Rewrite with equation lemmas, whose right-hand sides match the definition bodies exactly, and
generalize expensive arguments before applying a lemma.
Impact
Add 👍 to issues you consider important. If others are impacted by this issue, please ask them to add 👍 to it.
Activity
refactor(pfunctor): make the free monad's return predicate inductive (#…
Add perf test for lazy delta on applied projections (#381)
chore(deps): pin PolyFun's inductive return predicate and retire the …
rudygt commentedon Nov 24, 2026
+1, we hit this on the Riemann Hypothesis formalization
(leanprover-community/riemann-hypothesis, Lean
v4.37.0-rc1).On a random sample of 300 of its modules, kernel type checking is 15% of compile time, against 2 to 3% on PFR and
Carleson. The worst module (60 lines) spends 18.5 s in the kernel and 68 ms in elaboration, much of it in applied
projections such as
(CochainComplex.singleFunctor (Shv R) 0).obj Gcompared with anabbrevdefined in anothermodule.
One difference from the reproduction above: there, unfolding
smallmakes both sides syntactically equal. In ourcase the two sides never become syntactically equal. They come from definitions with the same source in different
modules, and each module's elaborator abstracts the proofs in them into its own auxiliary theorems (
fA._proof_1vs
fB._proof_1), so the projected structures differ only in proof arguments.Lean-only reproduction (two modules; ~1 s of kernel time, ~1 ms with both definitions in one module)
A.lean:B.lean:This was found with the help of an AI assistant (Claude).
Compare applied projections by their structures, lazily (#633, lean4#…
Docs for #633/#634: OVERVIEW §14 departure (lean4#16613), DESIGN records
Merge: applied projections compared lazily (lean4#16613); Expr hash m…
nomeata commentedon Nov 26, 2026
I tried to apply this change to con-leche, but sure enough something else broke. Claude says:
Why comparing applied projections lazily slowed
perf/ite-taken-branchThe change (for lean4#16613): when both sides apply the same projection to
equally many arguments,
s.i a₁ … aₙ =?= t.i b₁ … bₙ, first unfoldsandtlazily. Once they agree, compare the arguments pairwise. Only if thatfails, go on as the official kernel does (reduce
sandttoconstructors and project). This helps when one unfolding makes
sandtequal and the arguments are already equal.
But in Lean code the structure of an applied projection is nearly always a
class instance, and instance fields are applied to the program's data. In
ite-taken-branch,piAis computed byand evaluating it goes through
ForIn.forInandbindofId'sinstances, which are projections of one instance applied to the loop's
intermediate states. When such a pair meets in the comparison, the
instances agree at once, so the checker compares arguments that are two
points of the same computation. That costs far more than evaluating, and
the evaluation still follows.
Measured (instructions:u): with the change, con-leche passes the 230 s
limit (con-ron, its port, runs out of memory). Without it: 81 G. With the
loop rewritten as plain recursion (same
Array.set!andt[i]!, no monadinstances), both versions need 78.5 G.
General point: comparing the arguments of two applications with the same
head constant is a standard heuristic (the official kernel does it in lazy
delta reduction). Doing the same for the same projection is a different
heuristic. It fires on every instance field (
bind,HAdd.hAdd, …)during evaluation, not only in lean4#16613's shape. So it needs testing on
evaluation-heavy input, not only on Init or Mathlib.
rudygt commentedon Nov 26, 2026
Thanks for trying it. We hit the same failure mode when we tried this in Lean's C++ kernel, and a bound on the attempt fixed it there. In case the numbers help:
Unbounded (for
a.i x =?= b.i y, compareaandblazily, then the arguments, else fall through): our original module went from 20.4 s of kernel time to 41 ms. But on a 300-module sample of the Riemann Hypothesis formalization, 16 modules got slower and total kernel time rose from 107.6 s to 111.4 s. The worst went from 0.22 s to 34.5 s. It made 125,153 attempts, and 121,740 of them failed. One failed attempt took 24 s comparingLinearMap.toAddHom f =?= LinearMap.toAddHom gfor anfandgthat agree only at the applied point, which the official kernel settles cheaply by reducing there.Bounded: the attempt uses only syntactic equality, the positive cache, proof irrelevance between applications of theorem constants with syntactically equal types, congruence, and lazy unfolding of definitions (never theorems). Each visited pair costs 1 and each unfolding 4, against a budget of 256 and a depth of 12. When the budget runs out, it falls through to the unchanged path. On the same sample, built twice with the same compiler: total kernel time 121.6 s → 63.6 s, 28 modules faster and 6 slower by more than 0.1 s (worst 16.5 s → 17.3 s). Lean's test suite shows no new failures.
Since you mention evaluation-heavy input, we also ran the 45 perf tests of lean-kernel-arena (
eee4eeb167) through Lean's own kernel, withdebug.skipKernelTCremoved. We used two clang builds of v4.37.0-rc1, one unpatched and one bounded:ite-taken-branch: 15.07 s → 15.00 s of kernel time. The check fires 3 times there, for 66 steps in total.proj-applied-struct: 17.2 s → under 0.1 s.proj-app-lazy-delta: 2.0 s → under 0.1 s.In the C++ kernel the check sits in
is_def_eq_coreafterlazy_delta_reductionand beforewhnf_corereduces the projections, so evaluation insidewhnfdoesn't go through it. That may be whyite-taken-branchis unaffected here, unlike in con-leche, which we haven't tested.The bounded patch (against v4.37.0-rc1)
(Investigated with an AI assistant, Claude. The numbers come from our runs.)
nomeata commentedon Nov 26, 2026
But bounds are even more arbitrary and guesswork. Here we really see the tension between efficiency and resilience.
The saner path is to give the kernel less wiggle room and make it more predictable, not more. And for heavy computation we should not be using kernel reduction anyways, but something much faster and much more predictable like #16493.