Skip to content

fix: make kernel is_def_eq caching order-independent - #14806

Merged
leodemoura merged 4 commits into
masterfrom
kernel_is_def_eq_trans
Aug 18, 2026
Merged

leodemoura merged 4 commits into
masterfrom
kernel_is_def_eq_trans

Conversation

@leodemoura

Copy link
Copy Markdown
Member

This PR fixes a soundness issue in the kernel.

TL;DR. The kernel cached successful is_def_eq queries in a union-find structure. Because the implemented is_def_eq is sound but incomplete, and therefore not transitive, the transitive closure computed by the union-find made a query's result depend on the order of earlier queries: is_def_eq(v0, v2) could return false on its own but true after is_def_eq(v0, v1) and is_def_eq(v1, v2) had succeeded. A crafted input used this to build a recursor whose type and computation rule disagreed, and derive False. The fix replaces the union-find with a plain cache keyed on the query pair, so is_def_eq is again a function of its two arguments. The issue was reported by Daniel Selsam (OpenAI) using their internal models. An OpenAI agent then produced two distinct exploits based on it. Both exploits are also caught by nanoda, and both are caught by the new lean-inductive-models developed by Joachim Breitner.

This PR makes the kernel's definitional equality check independent of the order in which queries are made. The kernel cached successful is_def_eq queries in a union-find structure; because of this, the result returned by is_def_eq could depend on which queries had been made before. With a carefully constructed input this allowed the kernel to build a recursor whose type and computation rule were inconsistent, from which False could be derived.

Definitional equality, as specified, is an equivalence relation: it is reflexive, symmetric, and transitive. That specification is correct. The kernel's is_def_eq is an implementation of this relation, and like any such implementation it is sound but incomplete: it never reports two terms as equal unless they really are definitionally equal, but it can fail to prove a valid equality because it uses a fixed reduction strategy that may get stuck. As a consequence there exist terms v0, v1, v2 for which is_def_eq(v0, v1) and is_def_eq(v1, v2) both succeed while is_def_eq(v0, v2), asked on its own, returns false. In other words, the implemented test is not transitive even though the relation it approximates is.

To avoid repeated work, the kernel recorded successful queries in a union-find structure (equiv_manager) and consulted it before doing any real work. Every pair merged into that structure is genuinely definitionally equal, and since definitional equality is transitive, the transitive closure the union-find computes contains only true equalities. The cache is therefore sound in isolation. The problem is that the implemented is_def_eq is incomplete, so exposing this transitive closure changes its observable result: once is_def_eq(v0, v1) and is_def_eq(v1, v2) have been recorded, a later is_def_eq(v0, v2) is answered true from the union-find, whereas the same query made in isolation returns false. The value returned by is_def_eq(v0, v2) thus depends on the order of the preceding queries. Any code that assumes is_def_eq is a function of its two arguments can be broken by this. Recursor construction is one such consumer: it decides which constructor fields are recursive by calling is_def_eq and does so more than once while building a recursor, and it relies on getting the same answer each time.

The fix replaces the union-find with a plain cache keyed on the query pair, matching the isDefEq cache used by the elaborator. Kernel expressions contain no metavariables, so a query's result is a function of its two arguments; both positive and negative results can be cached and shared across queries while remaining order-independent. This restores determinism: is_def_eq(v0, v2) now returns the same answer regardless of history. The elaborator already uses a plain cache with no union-find, so this does not change which terms elaboration accepts.

The issue was reported by Daniel Selsam (OpenAI) using their internal models. An OpenAI agent then produced two distinct exploits based on it. Both exploits are also caught by nanoda, and both are caught by the new lean-inductive-models developed by Joachim Breitner.

**TL;DR.** The kernel cached successful `is_def_eq` queries in a union-find structure. Because the implemented `is_def_eq` is sound but incomplete, and therefore not transitive, the transitive closure computed by the union-find made a query's result depend on the order of earlier queries: `is_def_eq(v0, v2)` could return `false` on its own but `true` after `is_def_eq(v0, v1)` and `is_def_eq(v1, v2)` had succeeded. A crafted input used this to build a recursor whose type and computation rule disagreed, and derive `False`. The fix replaces the union-find with a plain cache keyed on the query pair, so `is_def_eq` is again a function of its two arguments. The issue was reported by Daniel Selsam (OpenAI) using their internal models. An OpenAI agent then produced two distinct exploits based on it. **Both exploits are also caught by nanoda, and both are caught by the new lean-inductive-models developed by Joachim Breitner.**

This PR makes the kernel's definitional equality check independent of the order in which queries are made. The kernel cached successful `is_def_eq` queries in a union-find structure; because of this, the result returned by `is_def_eq` could depend on which queries had been made before. With a carefully constructed input this allowed the kernel to build a recursor whose type and computation rule were inconsistent, from which `False` could be derived.

Definitional equality, as specified, is an equivalence relation: it is reflexive, symmetric, and transitive. That specification is correct. The kernel's `is_def_eq` is an implementation of this relation, and like any such implementation it is sound but incomplete: it never reports two terms as equal unless they really are definitionally equal, but it can fail to prove a valid equality because it uses a fixed reduction strategy that may get stuck. As a consequence there exist terms `v0`, `v1`, `v2` for which `is_def_eq(v0, v1)` and `is_def_eq(v1, v2)` both succeed while `is_def_eq(v0, v2)`, asked on its own, returns `false`. In other words, the implemented test is not transitive even though the relation it approximates is.

To avoid repeated work, the kernel recorded successful queries in a union-find structure (`equiv_manager`) and consulted it before doing any real work. Every pair merged into that structure is genuinely definitionally equal, and since definitional equality is transitive, the transitive closure the union-find computes contains only true equalities. The cache is therefore sound in isolation. The problem is that the implemented `is_def_eq` is incomplete, so exposing this transitive closure changes its observable result: once `is_def_eq(v0, v1)` and `is_def_eq(v1, v2)` have been recorded, a later `is_def_eq(v0, v2)` is answered `true` from the union-find, whereas the same query made in isolation returns `false`. The value returned by `is_def_eq(v0, v2)` thus depends on the order of the preceding queries. Any code that assumes `is_def_eq` is a function of its two arguments can be broken by this. Recursor construction is one such consumer: it decides which constructor fields are recursive by calling `is_def_eq` and does so more than once while building a recursor, and it relies on getting the same answer each time.

The fix replaces the union-find with a plain cache keyed on the query pair, matching the `isDefEq` cache used by the elaborator. Kernel expressions contain no metavariables, so a query's result is a function of its two arguments; both positive and negative results can be cached and shared across queries while remaining order-independent. This restores determinism: `is_def_eq(v0, v2)` now returns the same answer regardless of history. The elaborator already uses a plain cache with no union-find, so this does not change which terms elaboration accepts.

The issue was reported by Daniel Selsam (OpenAI) using their internal models. An OpenAI agent then produced two distinct exploits based on it. Both exploits are also caught by nanoda, and both are caught by the new lean-inductive-models developed by Joachim Breitner.
@leodemoura

Copy link
Copy Markdown
Member Author

!bench-mathlib

@leodemoura leodemoura changed the title This PR fixes a soundness issue. fix: make kernel is_def_eq caching order-independent Aug 17, 2026
@digama0

digama0 commented Aug 17, 2026 •

Copy link
Copy Markdown
Collaborator

Can we instead construct an annotation system or cache for the "is recursive" checks so that we commit to the first answer and don't re-ask the question? E.g. using additional fields in InductiveInfo. (The verification hasn't gotten to this point but for sure I will not be able to rely on isDefEq being deterministic, regardless of this caching change. So I don't think this fix will work for lean4lean.)

@leodemoura

Copy link
Copy Markdown
Member Author

Can we instead construct an annotation system or cache for the "is recursive" checks so that we commit to the first answer and don't re-ask the question?

You can, but we would be fixing one instance of the more general issue. There are probably other places where this assumption is made. The AI agents will be looking for similar exploits elsewhere. They read the kernel PR bug fixes.

Regarding lean4lean, you should use whatever approach simplifies your proof.

@github-actions github-actions Bot added the toolchain-available A toolchain is available for this PR, at leanprover/lean4-pr-releases:pr-release-NNNN label Aug 17, 2026
@leanprover-bot

Copy link
Copy Markdown
Collaborator

Reference manual CI status:

  • ❗ Reference manual CI can not be attempted yet, as the nightly-testing-2026-08-14 tag does not exist there yet. We will retry when you push more commits. If you rebase your branch onto nightly-with-manual, reference manual CI should run now. You can force reference manual CI using the force-manual-ci label. (2026-08-17 23:08:00)

@github-actions github-actions Bot added the mathlib4-nightly-available A branch for this PR exists at leanprover-community/mathlib4-nightly-testing:lean-pr-testing-NNNN label Aug 17, 2026
@leodemoura
leodemoura added this pull request to the merge queue Aug 17, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/batteries that referenced this pull request Aug 17, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/mathlib4-nightly-testing that referenced this pull request Aug 17, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 17, 2026
@leodemoura
leodemoura enabled auto-merge August 18, 2026 00:00
@leodemoura
leodemoura added this pull request to the merge queue Aug 18, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/batteries that referenced this pull request Aug 18, 2026
mathlib-nightly-testing Bot pushed a commit to leanprover-community/mathlib4-nightly-testing that referenced this pull request Aug 18, 2026
@mathlib-lean-pr-testing mathlib-lean-pr-testing Bot added the builds-mathlib CI has verified that Mathlib builds against this PR label Aug 18, 2026
@mathlib-lean-pr-testing

mathlib-lean-pr-testing Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Mathlib CI status (docs):

Merged via the queue into master with commit d108aae Aug 18, 2026
28 checks passed
@nomeata

nomeata commented Aug 18, 2026

Copy link
Copy Markdown
Collaborator

!bench mathlib

@leanprover-radar

leanprover-radar commented Aug 18, 2026 •

Copy link
Copy Markdown

Benchmark results for leanprover-community/mathlib4-nightly-testing@c2b6e1b against leanprover-community/mathlib4-nightly-testing@2e5b65f are in. There are significant results. @nomeata

  • 🟥 build//instructions: +1.5T (+1.09%)

Large changes (5✅, 26🟥)

  • 🟥 build/module/Mathlib.Algebra.Category.CommBialgCat//instructions: +12.4G (+22.08%)
  • 🟥 build/module/Mathlib.Algebra.Category.Ring.Limits//instructions: +14.0G (+20.01%)
  • 🟥 build/module/Mathlib.Algebra.Homology.LocalCohomology//instructions: +241.5G (+2499.80%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.AffineScheme//instructions: +16.5G (+19.74%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.AffineSpace//instructions: +10.3G (+22.37%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.GammaSpecAdjunction//instructions: +24.5G (+32.72%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.IdealSheaf.Subscheme//instructions: +14.2G (+21.36%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.Modules.Tilde//instructions: +196.1G (+64.15%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.ProjectiveSpectrum.Basic//instructions: +27.3G (+54.60%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.ProjectiveSpectrum.Functor//instructions: +130.1G (+269.89%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.ProjectiveSpectrum.Scheme//instructions: +35.0G (+43.07%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.ProjectiveSpectrum.StructureSheaf//instructions: +28.2G (+81.72%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.Sites.ElladicCohomology//instructions: +115.1G (+762.84%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.Spec//instructions: +18.9G (+36.52%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.SpreadingOut//instructions: +42.6G (+190.65%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.Stalk//instructions: +6.9G (+26.47%)
  • 🟥 build/module/Mathlib.Analysis.Normed.Module.Alternating.Uncurry.Fin//instructions: +5.1G (+13.49%)
  • 🟥 build/module/Mathlib.CategoryTheory.Abelian.Indization//instructions: +75.4G (+722.32%)
  • 🟥 build/module/Mathlib.CategoryTheory.Sites.SheafCohomology.Basic//instructions: +197.7G (+502.82%)
  • 🟥 build/module/Mathlib.CategoryTheory.Sites.SheafCohomology.MayerVietoris//instructions: +188.1G (+319.31%)
  • and 10 more
  • and 1 hidden

Medium changes (25✅, 47🟥)

  • ✅ build/module/Mathlib.Algebra.Category.Grp.Colimits//instructions: -5.1G (-17.83%)
  • ✅ build/module/Mathlib.Algebra.Category.ModuleCat.Ext.Basic//instructions: -3.8G (-24.74%) (reduced significance based on absolute threshold)
  • ✅ build/module/Mathlib.Algebra.Category.ModuleCat.Ext.DimensionShifting//instructions: -1.5G (-13.87%)
  • ✅ build/module/Mathlib.Algebra.Category.ModuleCat.Presheaf.Pushforward//instructions: -3.5G (-9.04%)
  • ✅ build/module/Mathlib.Algebra.Category.ModuleCat.Sheaf.Colimits//instructions: -2.3G (-13.72%)
  • ✅ build/module/Mathlib.Algebra.Category.ModuleCat.Sheaf.PushforwardContinuous//instructions: -19.4G (-15.91%)
  • 🟥 build/module/Mathlib.Algebra.Category.Ring.Adjunctions//instructions: +4.5G (+19.49%)
  • 🟥 build/module/Mathlib.Algebra.Category.Ring.Under.Basic//instructions: +2.2G (+13.93%)
  • 🟥 build/module/Mathlib.Algebra.Homology.BifunctorShift//instructions: +7.2G (+10.77%)
  • 🟥 build/module/Mathlib.Algebra.Lie.Cochain//instructions: +4.2G (+10.94%)
  • 🟥 build/module/Mathlib.Algebra.Lie.Derivation.Killing//instructions: +1.4G (+10.49%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.AffineTransitionLimit//instructions: +19.9G (+9.92%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.Group.Affine//instructions: +11.9G (+11.87%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.Morphisms.RingHomProperties//instructions: +9.0G (+17.62%)
  • ✅ build/module/Mathlib.AlgebraicGeometry.Morphisms.UniversallyClosed//instructions: -2.9G (-15.22%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.Normalization//instructions: +14.0G (+10.09%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.PointsPi//instructions: +2.0G (+10.95%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.PullbackCarrier//instructions: +1.7G (+5.71%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.Scheme//instructions: +4.6G (+7.35%)
  • 🟥 build/module/Mathlib.AlgebraicGeometry.Sites.Affine//instructions: +2.9G (+29.15%)
  • and 52 more

Small changes (74✅, 160🟥)

  • ✅ build/module/Aesop.Tree.Data//instructions: -92.4M (-1.58%)
  • ✅ build/module/Batteries.Data.Array.Match//instructions: -39.1M (-1.35%)
  • ✅ build/module/Batteries.Data.Array.Merge//instructions: -201.3M (-3.65%) (reduced significance based on absolute threshold)
  • ✅ build/module/Batteries.Data.Array.Scan//instructions: -232.4M (-2.27%)
  • ✅ build/module/Batteries.Data.BinaryHeap.Basic//instructions: -152.6M (-1.95%)
  • ✅ build/module/Batteries.Data.Fin.Basic//instructions: -32.2M (-1.03%)
  • ✅ build/module/Batteries.Data.Fin.Coding//instructions: -398.6M (-3.19%) (reduced significance based on absolute threshold)
  • ✅ build/module/Batteries.Data.Fin.Fold//instructions: -111.0M (-2.56%)
  • ✅ build/module/Batteries.Data.List.Interleave//instructions: -145.1M (-2.35%)
  • ✅ build/module/Batteries.Data.Nat.Bisect//instructions: -271.4M (-2.22%) (reduced significance based on absolute threshold)
  • ✅ build/module/Batteries.Data.String.Legacy//instructions: -78.4M (-1.70%)
  • ✅ build/module/Batteries.Data.UInt//instructions: -50.1M (-1.49%)
  • ✅ build/module/Batteries.Data.Vector.Basic//instructions: -303.9M (-3.95%) (reduced significance based on absolute threshold)
  • ✅ build/module/Batteries.Data.Vector.Lemmas//instructions: -88.4M (-1.37%)
  • 🟥 build/module/Mathlib.Algebra.Algebra.Pi//instructions: +601.5M (+4.97%)
  • ✅ build/module/Mathlib.Algebra.Category.BialgCat.Monoidal//instructions: -1.0G (-2.87%)
  • 🟥 build/module/Mathlib.Algebra.Category.CommAlgCat.Basic//instructions: +1.3G (+7.49%)
  • 🟥 build/module/Mathlib.Algebra.Category.CommHopfAlgCat//instructions: +3.1G (+4.13%)
  • ✅ build/module/Mathlib.Algebra.Category.Grp.Ulift//instructions: -1.9G (-15.39%)
  • ✅ build/module/Mathlib.Algebra.Category.Grp.Yoneda//instructions: -335.3M (-2.76%)
  • and 214 more

nomeata added a commit to leanprover/lean-kernel-arena that referenced this pull request Aug 18, 2026
#141)

Definitional equality is not transitive on three `Acc.rec`-based values:
proof
irrelevance relates `a ≡ b` and `b ≡ c`, but not `a ≡ c`. Three ways to
turn
that into `False`:

* rec-missing-ih: in the affected kernels the defeq cache is a
union-find
structure, i.e. it closes that relation transitively, but it is only
consulted
for expressions with equal hashes. A crafted collision therefore makes a
K-like reduction fire in the pass that builds the minor premises of a
recursor
and not in the pass that builds its rules, so the `step` minor premise
takes an
  induction hypothesis that its rule does not supply.  Fixed by
leanprover/lean4#14806. Frozen as a static export file, since the
malformed
  recursor comes out of the kernel's own inductive-type elaborator; the
  reproducer is kept alongside it.

* proj-of-stuck-prop: the same reduction decides the result sort of an
inductive
family, which is a `Prop` when checked under `_kernel_fresh.0` and stuck
for
  the closed instantiation, so a `Bool` field can be projected out of a
proposition that proof irrelevance applies to. Fixed by
leanprover/lean4#14807,
  and its use of the cache by #14806.

* proj-of-subst-prop: the same projection, but reached without any help
from the
defeq cache — `P := a = b` and `Q := a = c` are definitionally equal
types
whose proofs behave differently under `Eq.rec`, so an inductive family
declared
over `P` is a family of propositions while its instance at a proof of
`Q` has a
  sort that does not reduce to `Prop`.  Needs no axioms.  Fixed by
  leanprover/lean4#14807.

All three were accepted by the official kernel at v4.28.0, v4.29.1,
v4.33.0 and
nightly-2026-08-01, which also re-derives the broken declarations when
replaying
the export data.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013aD597ZqUV1XrMPdveoaKt

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
kim-em pushed a commit that referenced this pull request Aug 21, 2026
This PR fixes a soundness issue in the kernel.

**TL;DR.** The kernel cached successful `is_def_eq` queries in a
union-find structure. Because the implemented `is_def_eq` is sound but
incomplete, and therefore not transitive, the transitive closure
computed by the union-find made a query's result depend on the order of
earlier queries: `is_def_eq(v0, v2)` could return `false` on its own but
`true` after `is_def_eq(v0, v1)` and `is_def_eq(v1, v2)` had succeeded.
A crafted input used this to build a recursor whose type and computation
rule disagreed, and derive `False`. The fix replaces the union-find with
a plain cache keyed on the query pair, so `is_def_eq` is again a
function of its two arguments. **The issue was reported by Daniel Selsam
(OpenAI) using their internal models. An OpenAI agent then produced two
distinct exploits based on it. Both exploits are also caught by nanoda,
and both are caught by the new lean-inductive-models developed by
Joachim Breitner.**

This PR makes the kernel's definitional equality check independent of
the order in which queries are made. The kernel cached successful
`is_def_eq` queries in a union-find structure; because of this, the
result returned by `is_def_eq` could depend on which queries had been
made before. With a carefully constructed input this allowed the kernel
to build a recursor whose type and computation rule were inconsistent,
from which `False` could be derived.

Definitional equality, as specified, is an equivalence relation: it is
reflexive, symmetric, and transitive. That specification is correct. The
kernel's `is_def_eq` is an implementation of this relation, and like any
such implementation it is sound but incomplete: it never reports two
terms as equal unless they really are definitionally equal, but it can
fail to prove a valid equality because it uses a fixed reduction
strategy that may get stuck. As a consequence there exist terms `v0`,
`v1`, `v2` for which `is_def_eq(v0, v1)` and `is_def_eq(v1, v2)` both
succeed while `is_def_eq(v0, v2)`, asked on its own, returns `false`. In
other words, the implemented test is not transitive even though the
relation it approximates is.

To avoid repeated work, the kernel recorded successful queries in a
union-find structure (`equiv_manager`) and consulted it before doing any
real work. Every pair merged into that structure is genuinely
definitionally equal, and since definitional equality is transitive, the
transitive closure the union-find computes contains only true
equalities. The cache is therefore sound in isolation. The problem is
that the implemented `is_def_eq` is incomplete, so exposing this
transitive closure changes its observable result: once `is_def_eq(v0,
v1)` and `is_def_eq(v1, v2)` have been recorded, a later `is_def_eq(v0,
v2)` is answered `true` from the union-find, whereas the same query made
in isolation returns `false`. The value returned by `is_def_eq(v0, v2)`
thus depends on the order of the preceding queries. Any code that
assumes `is_def_eq` is a function of its two arguments can be broken by
this. Recursor construction is one such consumer: it decides which
constructor fields are recursive by calling `is_def_eq` and does so more
than once while building a recursor, and it relies on getting the same
answer each time.

The fix replaces the union-find with a plain cache keyed on the query
pair, matching the `isDefEq` cache used by the elaborator. Kernel
expressions contain no metavariables, so a query's result is a function
of its two arguments; both positive and negative results can be cached
and shared across queries while remaining order-independent. This
restores determinism: `is_def_eq(v0, v2)` now returns the same answer
regardless of history. The elaborator already uses a plain cache with no
union-find, so this does not change which terms elaboration accepts.

The issue was reported by Daniel Selsam (OpenAI) using their internal
models. An OpenAI agent then produced two distinct exploits based on it.
Both exploits are also caught by nanoda, and both are caught by the new
lean-inductive-models developed by Joachim Breitner.

---------

Co-authored-by: Claude Fable 5 <[email protected]>
(cherry picked from commit d108aae)
kim-em pushed a commit that referenced this pull request Aug 21, 2026
This PR fixes a soundness issue in the kernel.

**TL;DR.** The kernel cached successful `is_def_eq` queries in a
union-find structure. Because the implemented `is_def_eq` is sound but
incomplete, and therefore not transitive, the transitive closure
computed by the union-find made a query's result depend on the order of
earlier queries: `is_def_eq(v0, v2)` could return `false` on its own but
`true` after `is_def_eq(v0, v1)` and `is_def_eq(v1, v2)` had succeeded.
A crafted input used this to build a recursor whose type and computation
rule disagreed, and derive `False`. The fix replaces the union-find with
a plain cache keyed on the query pair, so `is_def_eq` is again a
function of its two arguments. **The issue was reported by Daniel Selsam
(OpenAI) using their internal models. An OpenAI agent then produced two
distinct exploits based on it. Both exploits are also caught by nanoda,
and both are caught by the new lean-inductive-models developed by
Joachim Breitner.**

This PR makes the kernel's definitional equality check independent of
the order in which queries are made. The kernel cached successful
`is_def_eq` queries in a union-find structure; because of this, the
result returned by `is_def_eq` could depend on which queries had been
made before. With a carefully constructed input this allowed the kernel
to build a recursor whose type and computation rule were inconsistent,
from which `False` could be derived.

Definitional equality, as specified, is an equivalence relation: it is
reflexive, symmetric, and transitive. That specification is correct. The
kernel's `is_def_eq` is an implementation of this relation, and like any
such implementation it is sound but incomplete: it never reports two
terms as equal unless they really are definitionally equal, but it can
fail to prove a valid equality because it uses a fixed reduction
strategy that may get stuck. As a consequence there exist terms `v0`,
`v1`, `v2` for which `is_def_eq(v0, v1)` and `is_def_eq(v1, v2)` both
succeed while `is_def_eq(v0, v2)`, asked on its own, returns `false`. In
other words, the implemented test is not transitive even though the
relation it approximates is.

To avoid repeated work, the kernel recorded successful queries in a
union-find structure (`equiv_manager`) and consulted it before doing any
real work. Every pair merged into that structure is genuinely
definitionally equal, and since definitional equality is transitive, the
transitive closure the union-find computes contains only true
equalities. The cache is therefore sound in isolation. The problem is
that the implemented `is_def_eq` is incomplete, so exposing this
transitive closure changes its observable result: once `is_def_eq(v0,
v1)` and `is_def_eq(v1, v2)` have been recorded, a later `is_def_eq(v0,
v2)` is answered `true` from the union-find, whereas the same query made
in isolation returns `false`. The value returned by `is_def_eq(v0, v2)`
thus depends on the order of the preceding queries. Any code that
assumes `is_def_eq` is a function of its two arguments can be broken by
this. Recursor construction is one such consumer: it decides which
constructor fields are recursive by calling `is_def_eq` and does so more
than once while building a recursor, and it relies on getting the same
answer each time.

The fix replaces the union-find with a plain cache keyed on the query
pair, matching the `isDefEq` cache used by the elaborator. Kernel
expressions contain no metavariables, so a query's result is a function
of its two arguments; both positive and negative results can be cached
and shared across queries while remaining order-independent. This
restores determinism: `is_def_eq(v0, v2)` now returns the same answer
regardless of history. The elaborator already uses a plain cache with no
union-find, so this does not change which terms elaboration accepts.

The issue was reported by Daniel Selsam (OpenAI) using their internal
models. An OpenAI agent then produced two distinct exploits based on it.
Both exploits are also caught by nanoda, and both are caught by the new
lean-inductive-models developed by Joachim Breitner.

---------

Co-authored-by: Claude Fable 5 <[email protected]>
(cherry picked from commit d108aae)
nomeata added a commit that referenced this pull request Aug 21, 2026
The three kernel soundness regression tests added by #14806 and #14807 build
their exploit on `Acc.rec` at a `Bool` motive, which this branch forbids, so
they no longer elaborate. `Acc.rec'` cannot stand in: it is backed by
`Classical.choice` and has no iota rule, so the definitionally-distinct
reducts the tests rely on do not exist.

This mirrors the earlier removal of `tests/elab/casesOnAcc.lean`. It does cost
coverage for the `is_def_eq` cache and `is_prop` fixes; reinstating it needs an
exploit vehicle that does not go through a recursive `Prop` inductive.

Co-Authored-By: Claude Opus 5 <[email protected]>
nomeata pushed a commit to leanprover/lean-kernel-arena that referenced this pull request Nov 22, 2026
Bumps the `lean4lean` checker from `bce3448` (Lean v4.33.0-rc2) to
`932afa1` (Lean v4.36.0), the tip of lean4lean's `arena` branch.

This takes in lean4lean's ports of the kernel changes from v4.33.0
through v4.36.0, including:
- a fix to the inductive adder, which now reads every constructor field
from a single normalization (the issue fixed upstream in
leanprover/lean4#14806). At `bce3448`, lean4lean could be made to accept
a recursor missing an inductive hypothesis, and from that a proof of
`False`.
- bounds on the size of `Nat` literals and on the results of `Nat`
operations (leanprover/lean4#14849).
- removal of native reduction (leanprover/lean4#14953) and of
`etaExpand` (leanprover/lean4#15268).

The old rev stays reachable on lean4lean's `arena-v4.33.0-rc2` branch.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
github-actions Bot pushed a commit to argumentcomputer/lean4lean that referenced this pull request Nov 23, 2026
A constructor field's type was reduced separately by each of the checks and
constructions that read it: the positivity check, the recursive-argument
classification, and the inductive hypotheses of the recursor's minor premises and of
its computation rules. `whnf` is only specified to return *some* definitionally equal
expression (`whnf'.WF`), so those are independent results. A field can be read as
recursive in one of them and non-recursive in another, and then the recursor's `step`
minor premise binds an induction hypothesis that its rule does not supply, which
yields `False`. `bugs/rec-missing-ih` in the Lean Kernel Arena is that construction
tuned to the C++ kernel's free variables, and its lean4lean-tuned companion to
lean4lean's.

`checkConstructors` now reduces each field once, with `deepWhnfField`, and records the
result in `InductiveStats.ctors`. `checkPositivity`, `recArgIdx?` and
`mkRecInfos.mapIHConclusion` are reads of that one expression, so the recursor's type
and its computation rules are built from the same reading of every field by
construction, and nothing depends on repeated reductions agreeing.
[leanprover/lean4#14806](leanprover/lean4#14806) closed the
same hole upstream from the other end, by replacing the union-find `is_def_eq` cache
with an order-independent one.

The recorded normal forms are open terms, which is rare in this checker: each is
abstracted over the fields before it, so a reader closes it against its own field
binders. That is what lets a field's normal form outlive the local declarations it was
reduced under. The parameters are not abstracted, being free variables of
`checkInductiveTypes` and so the same variables at both ends.

Since the readers no longer reduce, what they do is walk a telescope, and each was
repeating the same two preparations on it. Both now happen once, when `CtorData` is
built:

* The block's parameters are stripped and instantiated, each checked against the
  corresponding type former's as it goes, so that the binders of `CtorData.type` are
  exactly the fields. `checkConstructors.loop`, `isLargeEliminator` and
  `mkRecInfos.loopCtorArgs` no longer carry a parameter index or push parameters onto
  their telescopes. A constructor type with fewer binders than the block has parameters
  is reported as an invalid return type, which is what the old code did by falling
  through to `isValidIndAppIdx` with an uninstantiated parameter in the conclusion.
* Type annotations are consumed on every domain of the spine, so each is already the
  type the field is declared at. That is also the whole of the question of what the
  positivity check should see: `deepWhnfField` opens with `whnf`, which strips `mdata`
  and unfolds `optParam` and `autoParam` like any other definition, so
  `checkPositivity` and `recArgIdx?` read the same expression either way. Consuming
  matters only for the declared binder type, and there it is what the C++ kernel does:
  `mk_local_decl` in `src/kernel/inductive.cpp` declares every local at
  `consume_type_annotations(binding_domain(t))`.

The three walks therefore descend into a binder's body without substituting, and
instantiate each domain and the result type from the binders accumulated so far as they
are reached, rather than instantiating the whole remaining type once per binder.

`loopUArgs` goes in favour of `mapIHConclusion`, which rebuilds a recursive field's
recorded normal form with its conclusion replaced, keeping the higher-order binders in
place. It introduces no local declaration and instantiates nothing; the old code opened
the telescope with fresh variables only to abstract them again with `mkForall`. Both
callers use it, with `Expr.forallE` for the minor premise's inductive hypothesis and
`Expr.lam` for the rule's recursive call, and `mkRecRules` builds the shared prefix
`I.rec params motives minors` once per type former of the block rather than once per
recursive field of every constructor.

`getElimLevel` loses its `partial`: `u` together with `u_1 ... u_n`, for `n` the number
of universe parameters, are `n + 1` distinct names, so the search always finds a free
one. `isValidIndAppIdx` takes the head and arguments already split, so the caller shares
one `withApp` with the instantiation of the result type, and `checkPositivity` drops to
`Except Exception Unit`, since reading the recorded normal form needs no reduction.

Field binders are still declared at their unreduced types, so the generated
declarations are unchanged: replaying `Init` gives exactly the 25 pre-existing harness
failures, the same set as before.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UghAC2dzYmCYmALdwaCngc
JsFlo added a commit to JsFlo/lean4lean that referenced this pull request Nov 28, 2026
…4806)

Successful `isDefEq` queries were recorded in a union-find (`EquivManager`) and are now
recorded in a set of pairs, `State.success`, as in the C++ kernel since
leanprover/lean4#14806. `quickIsDefEq` answers `.true` for two α-equivalent expressions
or for a pair that `isDefEq` has accepted before, and no longer for a pair that is only
connected through other pairs.

`isDefEq` is sound but incomplete, so it is not transitive, and a cache that is closed
under transitivity makes its answer depend on the queries before it. For `acc : Acc R x`,
`A := stuckOrZero acc` (`Acc.rec` is stuck) and `B := stuckOrZero (Acc.intro ..)`
(reduces to `0`), `A =?= B` and `B =?= 0` are accepted and `A =?= 0` is refuted. After
the first two, `A =?= 0` was still refuted, because the check at the entry of
`isDefEqCore'` gave up when the two hashes differed, but `(fun n => n) A =?= 0` was
accepted, because the check after the beta step looked at the classes. Lean's kernel
refutes both, and so does lean4lean now. This order dependence is what
`bugs/rec-missing-ih` in the Lean Kernel Arena is built on; ba5cc53 made the inductive
module independent of repeated reductions agreeing, and this makes `isDefEq` a function
of its two arguments again.

The hash test in front of the union-find also meant that a recorded equality was
normally not seen when the same pair came back at the entry of `isDefEqCore'`, since
definitional equalities do not preserve hashes, and the pair was decided again from
scratch. On terms shared as a DAG that is exponential: with an axiom `P`,
`Aₖ₊₁ := P Aₖ Aₖ` and `Bₖ₊₁ := P Bₖ Bₖ` over leaves that are equal after unfolding,
`Aₙ =?= Bₙ` took `3·2ⁿ - 2` calls of `isDefEqCore'` and now takes `3n + 1`. And deciding
a pair again has side effects: it can run a full `whnfCore` on a projection that the
first decision had left stuck, and the unfolded result stays in `whnfCoreCache`, where
`cheapProj := true` requests find it. A later comparison of that projection with a
third term then compares the unfolded bodies instead of the structures. That is what
happened on `New.Variety.tiltTheory` of lsernau/grh-lean@72fead10, a definition of
1,629 distinct subterms that uses ℂ_[p] with two proofs of `Fact p.Prime`: it took 132
minutes of a 155-minute run that peaked at 317 GiB
(https://math.mit.edu/~drew/shortgrh/, where the peak is given as 332 GB) and now
takes 0.25 s, against 0.21 s in Lean's kernel. On the `arena` branch,
`lean4lean --import` accepts all 216,568 declarations of that export in 40 min 03 s
at 6.2 GiB.

The union-find knew more than a set of pairs does, and some declarations are slower
without it, the same ones that Lean's kernel is slow on. `--fresh Init.System.IO` goes
from 23.9 s to 20.2 s, but the dependency closure of `tiltTheory` without `tiltTheory`
(77,192 declarations of Mathlib and of the proof) goes from 101 s to 136 s, against
117 s in Lean's kernel. Most of that is seven declarations; the largest,
`New.Variety.Comparison.id_pull`, goes from 19 ms to 5.2 s when checked on its own
(4.0 s in Lean's kernel). On whole exports the cost is larger: the export above takes
Lean's kernel 29 min 39 s on the same machine, and the compact edition of the same
proof, which `master` finishes, takes 32 min 08 s on `master`, 45 min 22 s with this
change and 33 min 19 s in Lean's kernel.

`Lean4Lean/EquivManager.lean`, `Lean4Lean/Verify/EquivManager.lean` (with `IsDefEqE`
and `RelevantEq`) and the union-find lemmas of `Std/Basic.lean` are removed. The
invariant of the new cache is `SuccessCache.WF`: both sides of a recorded pair
translate to definitionally equal terms. `quickIsDefEq.WF`, `isDefEq.WF` and
`VState.WF.ectx` keep their statements.

`Lean4Lean.Tests.DefEqCache` covers the set of pairs on its own, the towers and a
miniature of the `tiltTheory` failure (by counting `isDefEqCore'` calls, so nothing
depends on timing; a decided pair asked again costs one call and leaves no unfolded
projection in the cache, where it cost 327,679 and did), and the `Acc` example, at
`isDefEq` and through `addDecl`, compared with the native kernel. All but the first
were also run against the previous code, where each fails. A last section generates
its questions from fixed seeds: 2,400 equalities between generated terms, and 1,500
declarations that prove the accepted links of a generated chain before asking for
their composition (in 388 of them both links hold and the composition is refuted),
all get the verdict of Lean's kernel; and 2,880 questions get the same answer from
`isDefEq` in a fresh state, after the questions before them, and after all of them.
The previous code agrees with Lean's kernel on the single questions and fails the
other two.

`divergences.md`: the `checkConstructors` entry no longer says that the union-find is
kept, and the projection entry no longer names `EquivManager.isEquiv`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
legion-implementer Bot added a commit to sjawhar/lean4 that referenced this pull request Nov 28, 2026
… integration (release resolution)

The head of #13, which changes tests/elab/ack.lean's expected kernel unfold
counts to the kernel member's own (the counts before upstream's leanprover#14806:
`OfNat.ofNat` 176/174 and `Add.add`, `HAdd.hAdd` 60/58, `num: 3`), merged on
the previous integration commit.

The resolution: tests/elab/ack.lean keeps only the `OfNat.ofNat` line
(`max: 176, num: 1` and `max: 174, num: 1`). Where the kernel member meets
the release's other kernel members, the kernel still unfolds `OfNat.ofNat`
176 and 174 times, but `Add.add` and `HAdd.hAdd` fall below the diagnostics
threshold (50), so the release lists only the first. Measured in stage1
builds: r20 with only the kernel member, and the integration before this
merge, each give `max: 176, num: 1` / `max: 174, num: 1`; with this text the
integration's ctest of elab/ack.lean, elab/kernelDecLit.lean and
elab/grind_nestedDecidable_kernel_issue.lean passes.

Refs: LINUX-1736
Omp-Session: 01a21fea-50cc-71ef-b840-72b8c7ab62bb
Legion-Role: implementer
legion-implementer Bot added a commit to sjawhar/lean4 that referenced this pull request Nov 28, 2026
… closure (#13)

This member restores the union-find closure of `is_def_eq` successes for
declaration checks. With it, the kernel unfolds `OfNat.ofNat` and, at these
counts, `Add.add` and `HAdd.hAdd` in ack.lean's declaration checks as it did
before upstream's "fix: make kernel is_def_eq caching order-independent"
(leanprover#14806, d108aae): `[kernel] unfolded declarations (max: 176, num: 3)` with
`OfNat.ofNat ↦ 176`, `Add.add ↦ 60` and `HAdd.hAdd ↦ 60` in the first
diagnostics, and 174/58/58 in the other three. These are exactly the counts
that d108aae replaced with 86 and 84. The test's cases are unchanged; only
its expected diagnostics follow the member's behaviour.

Measured: with this member alone on v4.36.0-rc1 (c9afcdd), a stage1
build's `elab/ack.lean` gave these counts and failed against the old
expectations; with this change it passes, and so do
grind_nestedDecidable_kernel_issue.lean and the rest of the elab tests run.
v4.36.0-rc1 itself gives 86/84 and passes.

Part of LINUX-1736.

Omp-Session: 01a21fea-50cc-71ef-b840-72b8c7ab62bb
Legion-Role: implementer

Co-authored-by: legion-implementer[bot] <343353655+legion-implementer[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

builds-mathlib CI has verified that Mathlib builds against this PR changelog-other mathlib4-nightly-available A branch for this PR exists at leanprover-community/mathlib4-nightly-testing:lean-pr-testing-NNNN soundness toolchain-available A toolchain is available for this PR, at leanprover/lean4-pr-releases:pr-release-NNNN

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants