Instance-typed mvar fallback from #14624 often runs a nested instance search that cannot succeed
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Aptitud para principiantes
- 42/100
- Tipo de issue
- Error
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Área
- compilers
Línea de trabajo
Start with Lean/Meta/ExprDefEq.lean, especially checkTypesAndAssign and synthInstanceTypedMVarAndUnify, then read the regression context in tests/elab/9077.lean. Run the provided fbmini2.lean reproduction with instance tracing and compare the trace across Lean versions. Done means the unnecessary nested Modu Q A search is avoided while the existing regression test and a focused test for this case pass.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
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.
Description
Since #14624 (the fix for #9077), when assigning an instance-argument metavariable fails its type check, checkTypesAndAssign (Lean/Meta/ExprDefEq.lean) falls back to synthInstanceTypedMVarAndUnify, which runs synthPending on the metavariable. In practice, most of those nested searches cannot succeed: the candidate being unified still has one of its own instance arguments open, and instance search has already failed for that argument (it is in the type class cache as a failure). The nested search then runs to failure anyway, and stuck results are not cached, so it can repeat.
The check itself is right, and this is not about reverting it: it would be enough to skip the nested search in that one situation and reject the assignment directly.
Context
We hit this while working on the RH cleanup (https://github.com/leanprover-community/riemann-hypothesis). Several slow instance searches happen there and in Mathlib itself, turning out to be in the nested search that #14624's fallback starts. Per my AI it was 1.5% of all heartbeats and 13% of instance search. We first suspected instance priorities, but switching the fallback off (as a measurement only) removed most of the cost, which is what led to the reproduction below.
Steps to Reproduce
/-!
Import-free copy of the shape behind the slow `map_sub` (Mathlib's `AddMonoidHomClass` for a ring hom).
* `AMHC F M` plays `AddMonoidHomClass`; `LMC F R M` plays `SemilinearMapClass` (the scalars `R` are an `outParam`,
and its `Modu R M` instance argument is therefore still a metavariable while `LMC` is searched);
* `fixedQ` plays `RingHomClass.toLinearMapClassNNRat`: over the fixed scalars `Q`, for a `DivSr` only;
* `A` is an `Sr` but not a `DivSr`, so `fixedQ` cannot apply, and `Modu Q A` does not exist.
`grep -c "new goal Modu Q A"` on the output counts the searches for `Modu Q A` that instance search starts while
trying `fixedQ`. No instance needs `Modu Q A` as a premise here: any such search comes from the unifier.
-/
set_option autoImplicit false
class AddMon (M : Type) where
zero : M
class Sr (R : Type) extends AddMon R where
one : R
class DivSr (R : Type) extends Sr R where
inv : R → R
class Modu (R M : Type) [Sr R] [AddMon M] where
smul : R → M → M
class LMC (F : Type) (R : outParam Type) (M : Type) [Sr R] [AddMon M] [Modu R M] : Prop where
ax : True
class AMHC (F M : Type) [AddMon M] : Prop where
ax : True
class RHC (F A : Type) [Sr A] : Prop where
ax : True
/-- The direct route; declared first, so tried last. -/
instance RHC.toAMHC (F A : Type) [Sr A] [RHC F A] : AMHC F A := ⟨trivial⟩
/-- The generic route. -/
instance LMC.toAMHC (F : Type) {R : Type} (M : Type) [Sr R] [AddMon M] [Modu R M] [LMC F R M] : AMHC F M :=
⟨trivial⟩
def Q : Type := Nat
instance : Sr Q := { zero := (0 : Nat), one := (1 : Nat) }
instance DivSr.toMod (A : Type) [DivSr A] : Modu Q A := ⟨fun _ a => a⟩
instance fixedQ (F A : Type) [DivSr A] [RHC F A] : LMC F Q A := ⟨trivial⟩
/-- Some ways to a `Modu Q _`, so that the failing search is visible in the trace. -/
class Tower (n : Nat) (A : Type) : Prop
instance modOfTower (A : Type) [Sr A] [Tower 0 A] : Modu Q A := ⟨fun _ a => a⟩
instance towerStep0 (A : Type) [Tower 1 A] : Tower 0 A := ⟨⟩
instance towerStep1 (A : Type) [Tower 2 A] : Tower 1 A := ⟨⟩
instance towerStep2 (A : Type) [Tower 3 A] : Tower 2 A := ⟨⟩
instance towerStep3 (A : Type) [Tower 4 A] : Tower 3 A := ⟨⟩
instance towerStep4 (A : Type) [Tower 5 A] : Tower 4 A := ⟨⟩
instance towerStep5 (A : Type) [Tower 6 A] : Tower 5 A := ⟨⟩
instance towerEnd (A : Type) [DivSr A] : Tower 6 A := ⟨⟩
def A : Type := Nat
instance : Sr A := { zero := (0 : Nat), one := (1 : Nat) }
def F : Type := A → A
instance : RHC F A := ⟨trivial⟩
set_option trace.Meta.synthInstance true in
example : AMHC F A := inferInstance
Save it as fbmini2.lean, run lean fbmini2.lean, then grep -c "new goal Modu Q A" on the trace output: 0 on v4.33.1, 1 on v4.35.0 through nightly-2026-11-25.
Expected behavior: no search for Modu Q A (no instance has it as a premise, so only the fallback can start one). That's how it is on v4.33.1.
Actual behavior: one such search on v4.35.0, v4.36.0, v4.37.0-rc1 and nightly-2026-11-25 (146 trace lines instead of 61).
In Mathlib, map_sub for a ring hom of a nested polynomial ring takes 9,611 heartbeats, of which almost all is three such nested searches (Module ℚ≥0/ℚ/ℂ on the polynomial ring). With the fallback switched off it is 1,151.
Across a large project (the RH formalization, 801 files), the fallback costs about 1.5% of all heartbeats and 13% of instance search.
A possible fix: skip the nested search when the value or the metavariable's type contains an unassigned instance-argument metavariable whose (metavariable-free) type is already a cached failure, and reject the assignment directly. We tried this as a prototype. It is AI-written, so please treat it as a sketch: https://gist.github.com/roy7/053f2c82baa046da20b7d7e27198b69f
tests/elab/9077.leanstill passes, and so does a new test in the patch. Lean's test suite: 4,955 of 4,957 tests pass (one skipped; one Lake cache test fails the same way without the patch).- With logging, the nested search never succeeded in that situation, in about 59,000 uses across Mathlib and the RH project. At Lean's default
maxSynthPendingDepth 1it never succeeded there either (about 42,000 uses in the RH project). - Every constant in both comes out identical, and most of the cost goes away (
map_sub9,611 → 1,226).
It isn't a proof that the skip is always safe: in principle unification could still fill such an argument some other way.
cc @datokrat (author of #14624)
Versions
v4.37.0-rc1 (0b77e129) and nightly-2026-11-25, Linux x86_64.
The analysis and prototype were done with an AI assistant (Claude Code). I checked the results with adversarial review by a separate model.
Impact
Add 👍 to issues you consider important. If others are impacted by this issue, please ask them to add 👍 to it.
- Lenguaje dominante
- Lean
- Estrellas
- 10.3k
- Forks
- 1.1k
- Merge medio
- 16 h 45 min
- PR fusionados (30 d)
- 361
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de leanprover/lean4
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
leanprover/lean4#16876 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
leanprover/lean4#16842 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
leanprover/lean4#16841 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 1/5 Menos de una hora Aptitud para principiantes 82/100
leanprover/lean4#16840 ·
Los mantenedores suelen responder en 1 día
-
doc: stray "public" in Bool and HEq documentationQuizá libre de nuevo Un pull request para esta issue se cerró sin fusionarse. Abierto
Dificultad 1/5 Menos de una hora Aptitud para principiantes 72/100
leanprover/lean4#16825 ·
Los mantenedores suelen responder en 1 día
Todos los issues de leanprover/lean4
Issues similares
-
bug core-lang
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
Call-argument syntax diagnostic needs example spacing and removal of confusing trailing sentenceAbierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
mw00/project-maya#1368 ·
Los mantenedores suelen responder en 2 días
-
test(bind-json): legacy Solidity fixture requires an unavailable solc on Linux ARM64Posiblemente ocupada Un pull request vinculado a esta issue está abierto o ya se fusionó. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
foundry-rs/foundry#18828 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
Los mantenedores suelen responder en 1 día