Skip to content

fix: recognizer calls isDefEq on untyped input (4/4) - #10

Merged
vasnesterov merged 2 commits into
masterfrom
fix/primitive-typecheck-before-compare
Aug 22, 2026
Merged

vasnesterov merged 2 commits into
masterfrom
fix/primitive-typecheck-before-compare

Conversation

@vasnesterov

Copy link
Copy Markdown
Owner

Split out of #2, as requested. 4 of 4 — this one was not in that PR; it was
found afterwards while assembling the correctness proof.

The bug

checkPrimitiveDef runs before checkConstantVal, so when it is called
neither v.type nor v.value has been type-checked. Every Nat branch
nonetheless calls TypeChecker.isDefEq on them.

A successful isDefEq is recorded in the EquivManager
(st.eqvManager.addEquiv t s). TypeChecker.VState.WF's ectx field demands
EquivManager.WF, whose defeq field demands EquivManager.IsDefEqE, and that
can relate terms of different head shape only through its defeq constructor —
which needs TrExprS witnesses on both sides. Untyped input has none, so
checkPrimitiveDef.WF's postcondition is false.

Not a soundness hole: checkConstantVal rejects the witness immediately
after, and so does Lean's own kernel. It is a broken postcondition, which blocks
the proof at the recognizer boundary.

It has a second instance

The equations' right-hand sides mention other primitives — Nat.pred in the
sub branch, Nat.add in mul, the boolean combinator in land/lor/xor —
whose types VEnv.HasPrimitives never pins. It constrains their behaviour
at numerals
only, so Nat.add (mul y x) y need not be well-typed either, and
comparing it pollutes the cache the same way. Found when the proof needed a
Π-type for Nat.pred that nothing supplies.

The fix

Four helpers that type-check before comparing: checkPrimValue, checkIsType,
checkedIsDefEq, checkedTypeIs. The sixteen Nat branches match against the
inferred type of v.value rather than the declared v.type — which
checkConstantVal still enforces a moment later.

Witness transcript

Built by hand and run against pristine master and against this branch:

=== BEFORE (master) ===
witness A (bad declared type, real value): .ok true; bad type in EquivManager: true;  merged with `Nat → Nat`: true
witness B (good declared type, bad value): REJECTED -- invalid form for primitive def Nat.pred
control (the real Nat.pred):               .ok true; bad type in EquivManager: false; merged: false

=== AFTER ===
witness A: .ok true; bad type in EquivManager: false; merged: false
witness B: REJECTED -- unknown constant 'NoSuchType'
control:   unchanged

One correction to how I described this earlier: the fix does not make the
recognizer reject witness A — it makes it stop looking at v.type altogether,
so the garbage redex never reaches isDefEq and the cache comes back clean. The
declaration is still rejected by checkConstantVal, as before. Witness B shows
the value side: master fed the untyped value to isDefEq and failed only on
the equation mismatch; the branch rejects at checkType v.value.

Deliberately left out, to stay independent of #8

The defeq1/defeq2 sites keep plain isDefEq. They get under a binder by
comparing ∀ _ : Nat, e₁ with ∀ _ : Nat, e₂ where e₁ : Nat, so those terms
are not well-typed and checkType rejects them — pre-checking requires binding
a real free variable, which is #8's rewrite. So the untyped-RHS instance
survives at those sites on this branch; #8 closes it by routing them through the
checkedIsDefEq this branch supplies. A comment at defeq1/defeq2 records
exactly that.

Cost

Measured over exactly what addDefinition runs — this recognizer followed by the
body check, in one M.run, best of 5 × 40 iterations, all primitives:
65.2 ms after vs 63.4 ms before, ~0.08% of the 83 s the arena's init test
spends on 53090 declarations. The body check afterwards shares the recognizer's
inferTypeC entries.

lake build lean4lean green including the compile-time self-test, and a full
lake exe lean4lean Init replay passes — which is what actually exercises
checkType v.value at the moment each primitive is declared, something the
self-test cannot do since it runs in an environment that already contains them.

Error messages change: checkType throws where the old code returned a
rejection. addDecl's accepted set is unchanged.

🤖 Generated with Claude Code

vasnesterov and others added 2 commits August 22, 2026 15:08
checkPrimitiveDef runs before checkConstantVal, so neither v.type nor
v.value has been type-checked when it compares them. A successful isDefEq
is recorded in the EquivManager, whose well-formedness demands
translation witnesses on both sides, and untyped input has none -- so the
recognizer's postcondition was false.

Four helpers now type-check before comparing, and the sixteen Nat
branches match against the *inferred* type of v.value rather than the
declared v.type, which checkConstantVal enforces a moment later anyway.

The defect has a second instance, also closed here: the equations' right-
hand sides mention primitives whose *types* HasPrimitives never pins -- it
constrains their behaviour at numerals only -- so those terms need not be
well-typed either. Nat.xor's four boolean equations are the clearest case.

The defeq1/defeq2 sites are deliberately left alone: they compare
`forall _ : Nat, e` where e : Nat, so checkType rejects them, and
pre-checking requires binding a real free variable, which is a separate
fix. A comment records that.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Both this branch and #8 touch the two defeq1/defeq2 comparison lines --
#8 wraps them in withLocalDecl, this branch replaces isDefEq with
checkedIsDefEq. The combined result needs both, so the resolution is to
take both.

Note this also closes the untyped-right-hand-side instance at those
sites, which this branch deliberately left open while it had to stand
alone: with a real free variable bound, checkType accepts the bodies, so
they can now be routed through checkedIsDefEq like the rest.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@vasnesterov
vasnesterov merged commit 150b0bb into master Aug 22, 2026
@vasnesterov
vasnesterov deleted the fix/primitive-typecheck-before-compare branch August 22, 2026 14:36
vasnesterov pushed a commit that referenced this pull request Aug 23, 2026
… the statement's own fixpoint

New `Theory/Typing/ShapeSpine.lean` (389 lines, `[propext,
Quot.sound]`, no `sorryAx`, no axiom added).

**1. The propagated `iff` form composes at `trans` -- and it is FALSE.**
`typeShapeAgree_false`, machine-checked at `n = 1` over the empty
environment. The witness is `SubstCRefute`'s, lifted from a *substituted
conversion* to **a term with two types** -- the hypothesis
`SubstCRefute` explicitly declined to supply. With a closed `P` proved
to be a genuine Π-type (so the context is not junk), a variable is
typeable at `P` and, via `forallEDF` of the beta step, at a second Π
whose codomain is a variable. So one term has a **stuck** type and a
**sort** type: one sort-shaped, one not. The same witness refutes the
substitution form (`substShapeAgree_false`).

**2. Strong enough to close `AppCase`? The question inverts.** In the
usable disjointness reading the hereditary statement is **logically
equivalent to `SortForallEDisjoint` itself** (`SortForallEDisjointH.iff`,
and the handoff's literal phrasing collapses identically at
`SortForallEDisjointH₂.iff`). The collapse is one lemma,
`Apply.hasType`: a spine peeled off a type of `e` is a type of the
applied term, so quantifying over spines quantifies over terms -- **the
hereditary clause is derivable, not additional.** And `AppCase` follows
from `SortForallEDisjoint` in one line, because `Stratified.app`
already gives the application its instantiated type. **`AppCase` is the
statement's own fixpoint; nothing of equal strength can close it.**

**3. Cost not incurred** -- the row-zero check closed it before anything
was built. ~390 lines of pricing, of which the refutation was ~40
reusing `SubstCRefute.stuck`.

**Correction to the handoff's own row 5**, which had been committed and
relayed: *"shape-disjointness under substitution does not inherit
`SubstC`'s refutation, criterion pass machine-checked"* was **true of a
different statement**. The recorded `trans`-closure was for the version
stated about a **conversion**, where `SortLike` composes by `trans'`
with no induction. The version that does the work is about a
**substitution**, and it is false. Logged as trap #10, with trap #11 for
*a strengthening can be the same statement*.

**What survives, named rather than described:** `SubstDisj` -- shape
disjointness under substitution, hereditary. Not equivalent to the
target (two types, no common term, so `Apply.hasType` does not collapse
it); **satisfiable**, `SubstDisj.zero` beside `DefInv.zero`/`SubstC.zero`;
and it buys `applyDisj`. **Not claimed sufficient** -- *analysis, not
machine-checked*: a spine induction on typing closes `app` and `bvar`
but not `lam`, where bridging the body's two types under instantiation
needs an existence step only the refuted `∀∃` form supplies.

**Reading result on `docs/design-shape-lattice.md`:** its recorded
refutations are this same obstruction one altitude up -- `IsType.common`
false, every relativisation refuted, each because two compatible
Π-shapes need not share a codomain sort when their domains disagree.
Its one survivor, `common_sort`, reads the sort off **the term's
universe** rather than off the shapes. Nothing there is reusable as-is,
but **that survivor is the one idea in it this route has not tried.**

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
vasnesterov pushed a commit that referenced this pull request Aug 23, 2026
…t endpoints

Both gates failed. `Theory/Typing/PropShadow.lean`, new, sorry-free,
`[propext, Classical.choice, Quot.sound]`.

**Item 1 -- the Prop-shadow closes arithmetically and the case does
not.** `app_shadow_arith`: from the IH at `f` in shadow form, the two
codomain universes agree on propositionhood -- consuming **no `DefInv`
clause, no `SubstC`, and nothing about the argument**. So the literal
question answers **no**. But `app_shadow_of` prices the rest: the case
is about universes *after* instantiation, and closing that gap needs two
further statements, neither of them `SubstC`:

- **`InstLvl`** -- `SubstT` at **depth 0** with a closed target type.
  **Not refuted, not proved**: `SubstTRefute`'s witness is at depth 1,
  and `SubstCRefute`'s witness **satisfies** it (checked).
- **`PropUniq` at a subject that is not a subterm** of the application,
  so the running induction cannot supply it.

**And a cost §8 did not price: the other cases stop being free.** In the
full statement every non-`app` case closes by `trans` on the
shape-determined type; in the shadow, inversion delivers a *conversion*
and a universe must be carried across it (`LvlConvInv`, at an arbitrary
type). **Trap #10 in a third direction: weakening a conclusion also
weakens what every `trans`/`conv` step can transport, so a weakening is
not a weakening uniformly across an induction.**

**Item 2 -- the route's row zero is FALSE, machine-checked.** The
"regularity" statement `thesis-architecture.md` §8 proposed **as the
repair** -- that a `⊢ₙ₊₁` conversion's endpoints are each `⊢ₙ`-typeable
-- is refuted at `n+1 = 1` over `VEnv.empty` by `sortDF` on the domains
and `symm (beta …)` on the bodies, closed by `lamDF`. The right endpoint
has **no `⊢₀` type at all**.

Four checks make it decisive rather than an artifact: it uses **none of
this tree's `rfl` deviation** (rules verified line by line against
`axioms.tex:30-41`); the **left** endpoint *is* `⊢₀`-typeable, so it is
not a well-formedness accident; **both** endpoints are `⊢₁`-typeable, so
what fails is exactly the index **drop**; and it **survives at the level
of types** -- swap `lamDF` for `forallEDF` and the right Π-type has a
`⊢₁` universe and no `⊢₀` one, which is what `lvl` is defined on. The
context is `[]`, so it also survives the `⟦Γ⟧ ≠ ∅` side condition.

**The defect named:** §5 conflates a **rule's premises** with a
**conversion's endpoints**. The premise-free rules (`sortDF`, `lamDF`,
`forallEDF`) build conversions mentioning terms **no premise ever
typed**. Trap #17.

**Consequence: the stage-`n+1` obligations have no admissible order.**
(4)-before-(2) needs the stage-`n` model on a `⊢ₙ₊₁` conversion's
endpoints -- refuted. (2)-before-(4) is the branch blocked by `SubstC`.
And the obvious rescue -- restricting (4) to conversions with
`⊢ₙ`-typed endpoints -- **loses exactly the case the route existed
for**: a genuine `⊢₁` derivation whose endpoints have `⊢₀` universes and
whose `trans` node's middle term has none, so the restricted statement
does not compose at `trans` -- and `trans` is the route's stated "real
leverage".

**Not established, not claimed:** that part (4) is *false*; that item 1
fails for `n ≥ 1`; that `InstLvl` is false. **`PropTypeAgree` and
`SortForallEDisjoint` are untouched** -- handoff §5 and §9 stand
unchanged. §4's observation survives and is worth keeping: **a model
does give sort injectivity without confluence, at any index where it can
be built** -- but nothing builds it above `n = 0`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant