Skip to content

fix: Nat equations checked on ill-typed pseudo-types (2/4) - #8

Merged
vasnesterov merged 1 commit into
masterfrom
fix/primitive-illtyped-defeq
Aug 22, 2026
Merged

vasnesterov merged 1 commit into
masterfrom
fix/primitive-illtyped-defeq

Conversation

@vasnesterov

Copy link
Copy Markdown
Owner

Split out of #2, as requested. 2 of 4. Independent of the siblings; applies
to pristine master.

The bug

To get under a binder, the recognizer compared

let defeq1 a b := isDefEq (.arrow q(Nat) a) (.arrow q(Nat) b)

∀ _ : Nat, Nat.add x 0 is not a type — its body has type Nat. So
TrExprS.forallE's hypothesis (env.IsType (ty' :: Δ.toCtx) body') is
unsatisfiable, no translation witness exists on either side, and every
specification for isDefEq requires one.

The consequence is stronger than "hard to prove": each of these checks carried
no semantic content whatsoever
with respect to the model. The recognizer was
running comparisons whose success could never be turned into a fact about the
abstract environment.

Nat.land and Nat.lor were additionally binding their Bool variable at type
Nat — the variable ranges over the Bool argument of the and/or
combinator. That is not merely untranslatable but plainly ill-typed.

The fix

Introduce genuine free variables with withLocalDecl, exactly as the Nat.div
and Nat.mod branches already did:

let defeqT1 (ty : Expr) (f g : Expr → Expr) : M Bool :=
  withLocalDecl `x .default ty fun x => isDefEq (f x) (g x)
let defeq1 := defeqT1 q(Nat)
let defeq2 (f g : Expr → Expr → Expr) : M Bool :=
  withLocalDecl `y .default q(Nat) fun y =>
  withLocalDecl `x .default q(Nat) fun x => isDefEq (f y x) (g y x)

All 22 call sites rewritten to lambda form; Nat.land/Nat.lor use
defeqT1 q(Bool). The defeq1 inside unfoldNatWellFounded (reached from
Nat.gcd and Nat.bitwise) gets the same treatment.

Behaviourally this is the same decision procedure.
isDefEq (.arrow Nat a) (.arrow Nat b) reduces via isDefEqForall, which
introduces exactly such a free variable. The only thing that actually changed is
the Bool-vs-Nat typing of the land/lor variable, and neither
combinator's reduction depends on it.

Testing

lake build lean4lean green, including the run_meta self-test over all 24
entries of Environment.primitives.

On the arena: the recognizer gets strictly stricter, and the combined change of
all four splits was arena-verified at 185 correct / 6 either / 0 incorrect,
the baseline. Each split is a subset of that strictness, so none can reject
anything the combined version accepted.

divergences.md is updated in #7, which carries the note for the whole series.

🤖 Generated with Claude Code

defeq1 and defeq2 compared `∀ _ : Nat, e₁` against `∀ _ : Nat, e₂` to get
under a binder. But `Nat.add x 0` is not a type, so TrExprS.forallE's
hypothesis is unsatisfiable -- no translation witness exists, and every
one of those checks carried no semantic content at all with respect to
the model.

They now compare under withLocalDecl-bound free variables, as the Nat.div
and Nat.mod branches already did. Same decision procedure: isDefEq on an
arrow reduces via isDefEqForall, which introduces exactly such a variable.

Nat.land and Nat.lor were additionally binding their Bool variable at
type Nat, which is not merely untranslatable but plainly ill-typed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@vasnesterov
vasnesterov merged commit 68df733 into master Aug 22, 2026
@vasnesterov
vasnesterov deleted the fix/primitive-illtyped-defeq branch August 22, 2026 14:35
vasnesterov pushed a commit that referenced this pull request Aug 22, 2026
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 pushed a commit that referenced this pull request Aug 23, 2026
…ditary shape agreement

**The explicit check: yes, it composes.** Stated as a **propagated
iff** -- `X ≡ₙ Y ⟹ (IsSortLike X ↔ IsSortLike Y) ∧ (IsPiLike X ↔
IsPiLike Y)` -- `trans` closes by composition, exactly as `PropConvInv`
does. **It does not inherit `SubstC`'s refutation.** A substituted term
can fail to preserve a conversion while still never turning a sort into
a Π.

**And the formulation matters.** Stated as `¬(sort(B[a]) ∧ Π(B'[a]))` --
the natural reading of "disjointness" -- `trans` **fails**, because the
middle term may be neither. Stated as the propagated iff, it closes.
**Same content, and only one of the two passes the criterion.**

**But having it is not enough to apply it.** In the `app` case,
`f : ∀A₀.B₀` with `B₀[a] ≡ .sort u`, and from `app_inv`
`f : ∀A₁.B₁` with `B₁[a] ≡ .forallE A B`. The iff gives the
contradiction **only if** `B₀[a] ≡ B₁[a]`, and getting there needs `f`'s
two Π-types related -- `uniq` at `f`, the broken thing.

So the app case's real requirement is a **hereditary** shape agreement:

> the types of a term agree on shape, **and** their codomains agree on
> shape after instantiation at any argument typed at both domains.

A shape-only weakening of unique typing, and the primitive to price
next. `docs/design-shape-lattice.md` and `Lean4Lean/Experimental/` aimed
at something of this form -- everything there is unproved and
`SExpr.ParamsExtra.extra_pat` is unsatisfiable as stated, **but the
shape of the idea is right and it should be read before rebuilding.**

Handoff brought fully current: the **sharpened criterion at the top of
§5** above the form it replaces, with the fifth row (shape-disjointness
under substitution, propagated, composes); **trap #8** -- *a negative
check licenses "not excluded", never "open"* -- with the history that
the phrasing was read as "a route exists" and cost a routed enquiry
whose first act was to correct the premise; **§10's four convergences**,
noting that impredicative formation forces the collapse and proof
irrelevance forces the identification; and **§9**'s
`SortForallEDisjoint` state including that a refutation is provably
impossible at the model's witness.

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

**Verdict: do not build it.** `docs/logrel-scope.md` is the decision
document; `Theory/Typing/LogRelRowZero.lean` is new, sorry-free,
`[propext, Quot.sound]`, in the default target.

**Two corrections to the premise, both load-bearing.** A logical
relation does **not** avoid a reduction relation -- it avoids
*confluence*; every such development, including both of this repo's own,
is built on weak-head reduction. And **the route is not untried**:
`Experimental/LogRel.lean` is a 379-line typed Kripke logical relation
that stops inside `fundamental`'s `trans` with `sorry` for every other
rule and no `Prop`/const/inductive case; `ShapeLogRel.lean` is its
coarsened version at 8435 lines, failing to build, with **the relation
itself `sorryAx`-backed**.

**Row-zero check 1 -- machine-checked, decisive, and it reaches past
this route.** `VEnv.WF` admits `VDecl.unsafeDef`, which typechecks
members in an environment already carrying the block's constants, so two
members naming each other install `f ≡ g` **and** `g ≡ f`.
`exists_wf_env_headStep_cycle` / `headStep_not_wf`: **there is a
`VEnv.WF` environment, one declaration step from empty, whose weak-head
reduction has a two-cycle between closed terms both well typed at
`∀ p : Prop, p`.**

**Every open statement in `Injectivity.lean` is quantified over exactly
that class, so no normalisation argument of any kind can establish them
as stated.** The repair is already done on the model side
(`TrEnv .safe → LeanWF`) and **not** on the algorithm side: `VContext`
carries an arbitrary `DefinitionSafety`, and `TrProj.uniq` /
`defeqDFC` / `weak'_inv` / `reduceRecursor.WF` all run there, because
the kernel genuinely δ-unfolds `partial` definitions. **Not claimed:
that the statements are false there.** Aiming a refutation of `sort_inv`
at such an environment is a cheap untried thread.

**Row-zero check 2 -- the two feared assumptions reverse.**
`imax_measure` / `imax_domain_unbounded`: where a Π-type is **not** a
proposition both component levels are bounded by its own, so a measure
exists; where it **is**, the domain's level is unbounded -- and that is
exactly where proof irrelevance makes recursion unnecessary.
**Impredicativity is confined to precisely the case proof irrelevance
trivialises.** Per trap #8 this licenses "not excluded", not "open". It
forces one design fact: the relation must be indexed by a *level
valuation*, since `imax u v` is `0` at some and `max u v` at others.

**What survives, delivers, and costs.** Nothing in the tree becomes
*wrong* -- the route adds no rule, unlike candidate 1 which made
`SubstCRefute` false. ~6500 lines carry over; ~2550 lines of the
stratified cone go **dead but stay true**. It delivers the whole family
at once from one lemma, **already proved sorry-free** in
`Experimental/LogRel.lean` -- so there is no cheaper sub-target inside
the route. Hard part named, and it is **not `Prop`**: generic inductive
families with nested declarations, canonicity, the ι-case. Two savings:
the abstract theory has no K-like reduction and no structure η, and
definitional η is free in a typed relation. One hidden cost:
`Params.pat_wf` needs `forallE_inv`, so the reduction relation must be
rebuilt un-gated.

**The cheaper target, answered negatively.** `PropUniq` +
`PropTypeAgree` is a weaker *statement*, not a cheaper *build*. A
derivation-directed interpretation relocates `PropUniq` to a coherence
obligation that **is `PropUniq`** -- trap #11 again, read straight off
the constructor list -- and a type-directed one removes `PropSplit` but
*is* a logical relation.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
vasnesterov pushed a commit that referenced this pull request Aug 23, 2026
…rk" was wrong at its own witness

**`sort_inv` was not refuted.** But the attempt returned better than a
null result.

**Machine-checked** (`Theory/Typing/CycleConv.lean`, new, sorry-free,
`[propext, Quot.sound]`): `loopEnv` declares two members at
`∀ p : Prop, p` with mutually recursive definitions. **Both are proofs
of one proposition**, and `IsDefEq.proofIrrel` identifies any two proofs
of a proposition **with no rule in the environment at all**. Hence
`loop_conv_iff`: `loopEnv`'s conversion **is** that of `loopEnv` minus
**both** defining equations -- an environment with **no rule at all**,
hence no delta step, hence **no cycle**, and `VEnv.WF` by two `.axiom`
steps with `∀ d ∈ ds, d.noUnsafe`.

`headStep_not_wf` stays true -- the reduction really does cycle. **What
does not follow is the claim made from it.** The sentence in
`logrel-scope.md` §1 and handoff §13(b) -- *"no normalisation argument
of any kind can establish them as stated"* -- **is wrong at its own
witness**: there the targets are no harder than at an axiom-only
environment. **The cycle breaks *reduction* without enlarging
*conversion*.**

The witness that **does** survive the collapse is built for whoever
restates the check: `propLoopEnv`, members declared at `.sort .zero`, so
they are *propositions* rather than proofs and the collapse recipe would
need a sort to be a proof. *Not proved (trap #8): that its conversion is
genuinely new -- only that this collapse argument does not reach it.*

**Why the refutation fails** *(analysis; its two load-bearing facts are
machine-checked)*: relating a sort to a non-sort needs `extra` (excluded
in every `VEnv.WF` env, `unsafeDef` included), or a function
discriminating two convertible arguments into different sorts (needs
large elimination from a non-subsingleton `Prop`, forbidden by
`LECond`), or `proofIrrel` with a sort as a **proof** -- which needs the
conversion being constructed. `unsafeDef` does not open it: member
values are checked in an environment carrying the block's **constants
but not its defeqs**. A fixpoint that cannot be entered from empty.

**The right environment class does not dissolve the obstruction.** The
weakest hypothesis excluding the cycle is `noUnsafe` (not `LeanWF`,
which also bans `.axiom`) -- already defined and already proved on the
model side. But `sort_inv`'s two open cases **are not environment
facts**: `trans`'s middle term is arbitrary in any environment, and
`proofIrrel` bites wherever propositions are inhabited, which
`sort_inv`'s **own hypotheses supply over `VEnv.empty` from the context
alone** (`empty_ctx_inconsistent`). `noUnsafe` buys δ-termination -- a
precondition for one technique, not a weaker goal.

**Consumers, by cone scan.** `Theory/SetModel/` is **not** in
`Injectivity.lean`'s cone. The three constant-disjointness statements
have **zero call sites in the whole tree**, their consumers being
themselves `sorry`, documentary, or **nonexistent**. `sort_inv` and
`forallE_inv_stratified` carry everything through one gateway,
`IsDefEq.uniq`, reaching ~230 uses in `Verify/`.

**The blocker, named for the `Verify/` stream rather than changed:**
every `Theory/` consumer takes `VEnv.WF` and would absorb a stronger
hypothesis free, but the three `Verify/` sites get it from
`VContext.Ewf`, and **`VContext.safety` is unconstrained and provably
non-`.safe` on real paths** -- `Environment.lean` *rejects* a `.safe`
mutual block, so `addMutual` always runs at `.partial`/`.unsafe`, while
`TrEnv'.wf_noUnsafe` requires `.safe` as a literal. **So a
`noUnsafe`-restricted `Injectivity.lean` does not serve its own
consumers.** Worth their attention: **`kernel_sound` needs only the
`.safe` model, and a `partial` block contributes nothing to it, so its
check may need to be total but not sound.**

**Nothing already proved becomes restatable-but-false** -- strengthening
a hypothesis cannot falsify a proved theorem, and every witness survives
the smaller class.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
vasnesterov pushed a commit that referenced this pull request Sep 4, 2026
…gration had already been done, stronger

The lift works and is cheaper than the original — same statement, 293 fewer constants, being the prelude
the original inherited by position — with faithfulness proved by Iff.rfl twice and acyclicity with the
hole's own module demonstrated by a snippet importing both. Then the round found the work already existed
in `Theory/Typing`, with the context guard pushed onto its hypotheses, which is strictly stronger, and
cited nowhere in the audit that proposed the migration. So the verdict on my premise: the import-order
fact was real and irrelevant.

It buys nothing, and it measured that at the consumer position instead of arguing it: asking the tactic
to derive hole #8 from the new hypothesis returns **hole #8 itself**, with the hypothesis flagged unused.
The underlying reason was already machine-checked in-tree, and every consumer of this ingredient carries a
hypothesis proved equivalent to its own conclusion. The ingredient is genuinely independent — and too weak.

Rather than ship a relocation, it sharpened the wall from one counterexample to an unbounded one: at the
base level the conclusion is agreement of a single bit, constant across the whole non-Prop class, and the
deficit is infinite and unbounded with witnesses independent of the environment. The in-tree version had
one level pair. That converts "we could not make this work" into "nobody can", which is the difference
between a failed round and a closed question.

It then recommended **against** applying its own connecting import — an unused import into the module
holding two ~700-user holes — which is the opposite of the incentive to avoid looking like an orphan, and
it is right.

Two corrections owed to today's audit, and one new instrument-level gap: my three scripts are all tuned to
disprove claims of absence, and this was a claim of presence — "the migration has not been done". None of
them catches that. The rule that follows: before calling a migration un-attempted, grep for the name of
the thing to be migrated and read every hit. It found the prior work by grep, not by any script I
prescribed.

Honest limit, stated as an unfalsified implication: it refutes reading the strong conclusion off this
ingredient, not the implication itself, which would need a witness environment and a full inversion
metatheorem — the same normalisation obligation three open holes already share, now reached from a third
direction.

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