Skip to content

Kernel reduces structures to constructors before comparing applied projections #16613

Open

Description

@alexanderlhicks

Prerequisites

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)
  1. Save the file as Kernel.lean.
  2. 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.0
  • 4.36.0
  • 4.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 => h

The 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

  1. rudygt commented on Nov 24, 2026

    @rudygt

    +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 G compared with an abbrev defined in another
    module.

    One difference from the reproduction above: there, unfolding small makes both sides syntactically equal. In our
    case 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_1
    vs 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:

    /-- A structure with one function field. -/
    structure Box where
      val : Nat → Nat
    
    /-- Reducing `mk h` to a constructor needs a unary computation the kernel cannot shortcut. -/
    def mk (_ : 0 < 2) : Box :=
      if (List.replicate 20000 ()).length = 20000 then ⟨fun x => x⟩ else ⟨fun x => x + 1⟩
    
    /-- The proof argument becomes the auxiliary theorem `fA._proof_1` of this module. -/
    def fA (x : Nat) : Nat := (mk (Nat.lt_succ_of_lt Nat.zero_lt_one)).val x

    B.lean:

    import A
    import Lean
    
    open Lean Meta Elab Term
    
    /-- From leanprover/lean4#16613: add `fun xs h => h : ∀ xs, P → Q` with `addDecl`, so only the kernel
    checks that `P` and `Q` 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 })
    
    elab "#add_identity_theorem " name:ident " : " stmt:term : command =>
      Command.liftTermElabM <| addIdentityTheorem name.getId stmt
    
    /-- Same source as `fA`; its proof becomes `fB._proof_1`, a different constant, because the elaborator
    only reuses auxiliary proofs within a module. -/
    def fB (x : Nat) : Nat := (mk (Nat.lt_succ_of_lt Nat.zero_lt_one)).val x
    
    -- About 1 s in the kernel. With `fB` defined in `A.lean` instead, about 1 ms.
    #add_identity_theorem crossModule : ∀ x : Nat, fA x = 0 → fB x = 0

    This was found with the help of an AI assistant (Claude).

  2. nomeata commented on Nov 26, 2026

    @nomeata
    Collaborator

    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-branch

    The change (for lean4#16613): when both sides apply the same projection to
    equally many arguments, s.i a₁ … aₙ =?= t.i b₁ … bₙ, first unfold s and
    t lazily. Once they agree, compare the arguments pairwise. Only if that
    fails, go on as the official kernel does (reduce s and t to
    constructors and project). This helps when one unfolding makes s and t
    equal 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, piA is computed by

    for i in [0:n] do r := r.set! t[i]! i      -- in `Id`
    

    and evaluating it goes through ForIn.forIn and bind of Id's
    instances, 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! and t[i]!, no monad
    instances), 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.

  3. rudygt commented on Nov 26, 2026

    @rudygt

    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, compare a and b lazily, 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 comparing LinearMap.toAddHom f =?= LinearMap.toAddHom g for an f and g that 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, with debug.skipKernelTC removed. We used two clang builds of v4.37.0-rc1, one unpatched and one bounded:

    • All 45 outcomes are as expected on both builds, including the 8 rejections.
    • 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.
    • No other test changed beyond run-to-run noise, and no attempt used up its budget in any of the 45 tests.

    In the C++ kernel the check sits in is_def_eq_core after lazy_delta_reduction and before whnf_core reduces the projections, so evaluation inside whnf doesn't go through it. That may be why ite-taken-branch is unaffected here, unlike in con-leche, which we haven't tested.

    The bounded patch (against v4.37.0-rc1)
    diff --git a/src/kernel/type_checker.cpp b/src/kernel/type_checker.cpp
    index 62a53f8..6bb8bf5 100644
    --- a/src/kernel/type_checker.cpp
    +++ b/src/kernel/type_checker.cpp
    @@ -1136,6 +1136,80 @@ bool type_checker::is_def_eq_unit_like(expr const & t, expr const & s) {
         return is_def_eq_core(t_type, infer_type(s));
     }
     
    +/* Proof irrelevance restricted to applications of theorem constants whose propositions are syntactically equal,
    +   so that deciding it never requires a full definitional-equality check. */
    +bool type_checker::cheap_proof_irrel(expr const & t, expr const & s) {
    +    expr const & tf = get_app_fn(t);
    +    expr const & sf = get_app_fn(s);
    +    if (!is_constant(tf) || !is_constant(sf))
    +        return false;
    +    optional<constant_info> ti = env().find(const_name(tf));
    +    optional<constant_info> si = env().find(const_name(sf));
    +    if (!ti || !si || !ti->is_theorem() || !si->is_theorem())
    +        return false;
    +    expr t_type = infer_type(t);
    +    expr s_type = infer_type(s);
    +    return t_type == s_type || succeeded_before(t_type, s_type);
    +}
    +
    +/* Bounded attempt to show `t =?= s` using only syntactic equality, the positive cache, `cheap_proof_irrel`,
    +   congruence on projections and on applications with matching heads, and lazy head unfolding of definitions
    +   (theorems are never unfolded). `budget` counts work across the whole attempt: every visited pair costs 1 and
    +   every unfolding 4, so the walk over large, nearly-equal terms is bounded too. Returns false, meaning "unknown",
    +   as soon as `depth` or `budget` runs out or neither side can be unfolded. Every `true` is
    +   justified by delta reduction, congruence or proof irrelevance. */
    +bool type_checker::cheap_congr_eq(expr t, expr s, unsigned depth, unsigned & budget) {
    +    while (true) {
    +        if (t == s || succeeded_before(t, s))
    +            return true;
    +        if (depth == 0 || budget == 0)
    +            return false;
    +        budget--;
    +        if (cheap_proof_irrel(t, s))
    +            return true;
    +        if (is_proj(t) && is_proj(s)) {
    +            if (proj_sname(t) == proj_sname(s) && proj_idx(t) == proj_idx(s) &&
    +                cheap_congr_eq(proj_expr(t), proj_expr(s), depth - 1, budget))
    +                return true;
    +        } else if (is_app(t) && is_app(s) && get_app_num_args(t) == get_app_num_args(s)) {
    +            expr const & tf = get_app_fn(t);
    +            expr const & sf = get_app_fn(s);
    +            bool same_head =
    +                (is_constant(tf) && is_constant(sf) && const_name(tf) == const_name(sf) &&
    +                 is_def_eq(const_levels(tf), const_levels(sf))) ||
    +                (is_fvar(tf) && tf == sf) ||
    +                (is_proj(tf) && is_proj(sf) && proj_sname(tf) == proj_sname(sf) && proj_idx(tf) == proj_idx(sf) &&
    +                 cheap_congr_eq(proj_expr(tf), proj_expr(sf), depth - 1, budget));
    +            if (same_head) {
    +                expr a = t, b = s;
    +                bool args_ok = true;
    +                while (is_app(a)) {
    +                    if (!cheap_congr_eq(app_arg(a), app_arg(b), depth - 1, budget)) {
    +                        args_ok = false;
    +                        break;
    +                    }
    +                    a = app_fn(a);
    +                    b = app_fn(b);
    +                }
    +                if (args_ok)
    +                    return true;
    +            }
    +        }
    +        optional<constant_info> dt = is_delta(t);
    +        optional<constant_info> ds = is_delta(s);
    +        if (dt && dt->is_theorem()) dt = none_constant_info();
    +        if (ds && ds->is_theorem()) ds = none_constant_info();
    +        if (!dt && !ds || budget < 4)
    +            return false;
    +        budget -= 4;
    +        int c = (dt && ds) ? compare(dt->get_hints(), ds->get_hints()) : (dt ? -1 : 1);
    +        if (c <= 0)
    +            t = whnf_core(*unfold_definition(t), true, true);
    +        if (c >= 0)
    +            s = whnf_core(*unfold_definition(s), true, true);
    +    }
    +}
    +
     bool type_checker::is_def_eq_core(expr const & t, expr const & s) {
         scope_rec_depth guard;
         check_system("is_definitionally_equal", /* do_check_interrupted */ true);
    @@ -1188,6 +1262,15 @@ bool type_checker::is_def_eq_core(expr const & t, expr const & s) {
                 return true;
         }
     
    +    // Applied projections `a.i x_1 ... x_n =?= b.i y_1 ... y_n`: before `whnf` below reduces the projections (which
    +    // can unfold `a` and `b` completely), try a bounded congruence check that succeeds cheaply when `a` and `b` are
    +    // nearly identical, e.g. differ only in proof arguments. On "unknown" we fall through unchanged.
    +    if (is_app(t_n) && is_app(s_n) && is_proj(get_app_fn(t_n)) && is_proj(get_app_fn(s_n))) {
    +        unsigned budget = 256;
    +        if (cheap_congr_eq(t_n, s_n, 12, budget))
    +            return true;
    +    }
    +
         // Invoke `whnf_core` again, but now using `whnf` to reduce projections.
         expr t_n_n = whnf_core(t_n);
         expr s_n_n = whnf_core(s_n);
    diff --git a/src/kernel/type_checker.h b/src/kernel/type_checker.h
    index 4de2736..3159a17 100644
    --- a/src/kernel/type_checker.h
    +++ b/src/kernel/type_checker.h
    @@ -102,6 +102,8 @@ private:
         lbool try_string_lit_expansion(expr const & t, expr const & s);
         bool is_def_eq_app(expr const & t, expr const & s);
         lbool is_def_eq_proof_irrel(expr const & t, expr const & s);
    +    bool cheap_proof_irrel(expr const & t, expr const & s);
    +    bool cheap_congr_eq(expr t, expr s, unsigned depth, unsigned & budget);
         bool is_def_eq_unit_like(expr const & t, expr const & s);
         bool failed_before(expr const & t, expr const & s) const;
         void cache_failure(expr const & t, expr const & s);

    (Investigated with an AI assistant, Claude. The numbers come from our runs.)

  4. nomeata commented on Nov 26, 2026

    @nomeata
    Collaborator

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions