Kernel memory exhaustion in lazy_delta_proj_reduction on nested projections

Open
#16,973 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

  • #16974 by @joshlf — closed without merging

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
25/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Domain
compilers

Research direction

Start with src/kernel/type_checker.cpp, especially lazy_delta_proj_reduction around lines 1131–1148, and compare its projection handling with Lean.Meta.isDefEqProjDelta in src/Lean/Meta/ExprDefEq.lean. Run the standalone zero-import mre.lean reproducer with lean -M 768 mre.lean to observe the kernel memory failure. Done means the kernel checks the proof without expanding the unrelated recursive field, while the standalone projection edge cases continue to pass.

Written by the indexing model from the issue text.

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”)
    (Reproduced locally on 4.35.0 and 4.37.0-nightly-2026-11-14, and confirmed unchanged on master at commit 89f7d2bfc21e90bc026d06005dbbb9e0b0c127e6; not yet run in the live browser 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 times out or hits excessive memory consumption on a valid proof accepted by the elaborator.)
Description

When checking definitional equality of two matching bare projections t.idx =?= s.idx, type_checker::lazy_delta_proj_reduction in src/kernel/type_checker.cpp discards the outer projection (sname, idx) if t and s delta-unfold to unreduced inner projections (for example, Prod.1 on a pair-returning definition). As a result, the kernel equates the entire inner structure—including unrelated fields that were never projected—instead of reducing the inner projection and continuing with field idx.

Concretely, on master (89f7d2bfc21e90bc026d06005dbbb9e0b0c127e6):

  1. type_checker::is_def_eq_core (src/kernel/type_checker.cpp:1244-1268) reduces both sides with whnf_core(..., /*cheap_rec=*/false, /*cheap_proj=*/true) and dispatches matching projections to type_checker::lazy_delta_proj_reduction (L1131-1148).
  2. Inside the lazy_delta_proj_reduction loop, lazy_delta_reduction_step (L1013-1070) unfolds delta definitions via whnf_core(*unfold_definition(...), false, true), leaving any nested Proj unreduced (cheap_proj = true).
  3. On the next iteration, both sides are Proj nodes, so !d_t && !d_s (L1016-1017). Unlike the one-delta / one-projection cases (L1027-1028, L1034-1035), !d_t && !d_s does not call try_unfold_proj_app and immediately returns reduction_status::DefUnknown.
  4. Back in lazy_delta_proj_reduction (L1136-1145), reduce_proj_core sees an unreduced Proj instead of a matching constructor and returns none. Line L1145 then falls back to return is_def_eq_core(t_n, s_n);, dropping the outer projection (sname, idx) completely and comparing the whole inner struct.

In contrast, the elaborator's Lean.Meta.isDefEqProjDelta (src/Lean/Meta/ExprDefEq.lean:2314-2331) calls isDefEqDeltaStep, whose whnfCore uses Config.proj := .yesWithDelta. Meta therefore reduces the inner projection to a constructor, projects only field idx, and accepts the proof in ~2 ms, leaving the kernel to blow up on the emitted Eq.refl.

When an unrelated struct field contains a Nat-recursive function instantiated at d + N on one side and N on the other inside match/if/monadic bind combinators, dropping the outer projection causes is_def_eq_core to unroll all N steps and expand the recursive continuation exponentially (m_failure documented in src/kernel/type_checker.h:33-41 is also unused in quick_is_def_eq and only populated by is_def_eq_args at L1051-1058).

Context

This occurred in a proof comparing a record field extracted from a pair-returning definition parameterized by fuel depth d + N against the same function at default depth N, where the projected field does not depend on fuel while another field of the structure holds a fuel-bounded recursive function.

This issue is distinct from two related open kernel projection issues:

  • #16613 covers applied projections s.i a =?= t.i a, which do not enter lazy_delta_proj_reduction. Here both sides are bare projections s.i =?= t.i that do enter lazy_delta_proj_reduction, which then drops the outer projection when encountering an inner Proj.
  • #16880 covers whnf_core cache pollution in cheap_proj calls across earlier reductions in the same declaration. Here the failure occurs on a fresh declaration with no prior reductions.

No prior Lean Zulip discussion.

Steps to Reproduce

Save the following standalone file as mre.lean (zero imports):

-- Standalone MRE for Lean 4 kernel OOM:
-- 1) lazy_delta_proj_reduction drops projection when inner expr reduces to nested Proj
-- 2) is_def_eq_core compares monad-wrapped Nat-recursive fn at (d + N) vs N, blowing up exponentially

structure S where
  a : Nat
  b : Nat → Nat

def myBind (x : Option α) (f : α → Option β) : Option β :=
  match x with
  | none => none
  | some a => f a

def stepBody (flag : Bool) (k1 k2 : Option Nat) : Option Nat :=
  myBind (if flag then some 1 else some 2) fun v1 =>
  myBind (if v1 == 1 then some 3 else some 4) fun v2 =>
  myBind (if v2 == 3 then k1 else k2) fun v3 =>
  myBind (if v3 == 0 then k1 else k2) fun v4 =>
  some v4

def recVisit (flag : Bool) : Nat → Option Nat
  | 0 => none
  | fuel + 1 =>
    stepBody flag (recVisit flag fuel) (recVisit flag fuel)

def mkPair (flag : Bool) (fuel : Nat) : S × Unit :=
  ({ a := 0, b := fun _ => match recVisit flag fuel with | some n => n | none => 0 }, ())

def getS (flag : Bool) (fuel : Nat) : S :=
  (mkPair flag fuel).1

set_option profiler true

theorem mre_proj (flag : Bool) (d : Nat) :
    (getS flag (d + 8)).a = (getS flag 8).a := rfl

Run:

lean -M 768 mre.lean

Expected behavior: lazy_delta_proj_reduction reduces the inner Prod.1 projection (mkPair) to the S constructor, projects field .a (0 =?= 0), and checks mre_proj in sub-millisecond kernel time without expanding S.b / recVisit.

Actual behavior: Elaboration finishes in 1.98ms (2.4ms on nightly), and then the kernel drops .a, compares S.b (recVisit flag (d + 8) vs recVisit flag 8), and aborts with excessive memory consumption:

  • On 4.35.0 (lean -M 768 mre.lean):
    mre.lean:34:8: error: (kernel) excessive memory consumption detected
    type checking took 6.03s
    
  • On 4.37.0-nightly-2026-11-14 (lean -M 768 mre.lean, 1024 MB memory cap):
    mre.lean:34:8: error: (kernel) excessive memory consumption detected
    type checking took 6.8s
    
  • With higher memory caps (e.g., 2048 MB) and a 15 s timeout, both 4.35.0 and 4.37.0-nightly-2026-11-14 time out past 15 s (15.40s / 1,427 MB peak RSS on 4.35.0, 15.34s / 1,024 MB peak RSS on 4.37.0-nightly-2026-11-14). Without -M (e.g., inside lake build on larger records), memory grows until OOM.
Versions
  • Lean (version 4.35.0, x86_64-unknown-linux-gnu, commit eb6cafb7290e8bd5f2937522d8d804f58f02bafc, Release)
  • Lean (version 4.37.0-nightly-2026-11-14, x86_64-unknown-linux-gnu, commit 62e0cf067af1febf28eee560a43bd4f72d23bfaa, Release)
  • Inspected master at 89f7d2bfc21e90bc026d06005dbbb9e0b0c127e6 (src/kernel/type_checker.cpp:1131-1148 is identical in structure).
  • OS: Linux x86_64.
Additional Information

A minimal fix in type_checker::lazy_delta_proj_reduction (src/kernel/type_checker.cpp:1136-1145 on 89f7d2bfc21e90bc026d06005dbbb9e0b0c127e6) avoids dropping the outer projection without changing lazy_delta_reduction_step (so non-nested lazy projection short-circuiting like expensive_1.i =?= expensive_2.i is preserved):

  1. Before calling reduce_proj_core, symmetrically check try_unfold_proj_app on t_n and s_n. If either reduces, check quick_is_def_eq(t_n, s_n) == l_true and break to continue the lazy_delta_proj_reduction loop (so if reducing an inner projection exposes another delta definition, lazy delta reduction continues).
  2. After reduce_proj_core(t_n, sname, i) and reduce_proj_core(s_n, sname, i), if exactly one side reduced to a matching constructor (t || s), return false instead of falling through to is_def_eq_core(t_n, s_n). Returning false lets is_def_eq_core (L1271-1274) reduce the outer projection via whnf_core and compare the projected field directly against s_c.idx (avoiding try_eta_struct across unrelated fields when one side is a constructor and the other is neutral, e.g., (badEta h).1 =?= h.1).
--- a/src/kernel/type_checker.cpp
+++ b/src/kernel/type_checker.cpp
@@ -1135,12 +1135,28 @@
         case reduction_status::DefEqual:   return true;
         case reduction_status::DefUnknown:
         case reduction_status::DefDiff:
+            if (auto t_new = try_unfold_proj_app(t_n)) {
+                t_n = *t_new;
+                if (auto s_new = try_unfold_proj_app(s_n))
+                    s_n = *s_new;
+                if (quick_is_def_eq(t_n, s_n) == l_true)
+                    return true;
+                break;
+            }
+            if (auto s_new = try_unfold_proj_app(s_n)) {
+                s_n = *s_new;
+                if (quick_is_def_eq(t_n, s_n) == l_true)
+                    return true;
+                break;
+            }
             size_t i;
             if (to_proj_idx(idx, i)) {
-                if (auto t = reduce_proj_core(t_n, sname, i)) {
-                if (auto s = reduce_proj_core(s_n, sname, i)) {
+                auto t = reduce_proj_core(t_n, sname, i);
+                auto s = reduce_proj_core(s_n, sname, i);
+                if (t && s)
                     return is_def_eq_core(*t, *s);
-                }}
+                if (t || s)
+                    return false;
             }
             return is_def_eq_core(t_n, s_n);
         }

Tested locally on a patched 4.35.0 kernel build (full upstream lean4 test suite not yet run):

  • lean -M 768 mre.lean: type checking 0.356ms (exit 0), down from 6.03s / excessive memory failure (0.377ms type checking / 0.72s wall / 476 MB peak RSS under a 2048 MB limit).
  • Single-bind (13.40s failure on 4.35.0 -> 0.868 ms type checking) and state-passing (6.27s failure -> 0.376 ms type checking at fuel 8; 0.488 ms at fuel 16) variants pass.
  • An 11-case standalone projection edge-case file (nested/triple projections, asymmetric constructor vs nested projection, neutral fvar fallback, applied projected function, dependent structure, String literal, Unit-like field vs fvar, Prop field, decide +kernel, eta-struct), negative/positive Lean.Kernel.isDefEq checks, and an asymmetric (badEta h).1 =?= h.1 constructor-vs-neutral Kernel.isDefEq check all pass.
Impact

Add 👍 to issues you consider important. If others are impacted by this issue, please ask them to add 👍 to it.

Authored by an AI agent acting on joshlf's behalf.

Dominant language
Lean
Stars
10.5k
Forks
1.2k
Avg merge
19h 36m
Merged PRs (30d)
323

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from leanprover/lean4

All issues in leanprover/lean4

Similar issues

More Compilers issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.