Skip to content

The primitive-definition recognizer did not establish what it claims - #15

Closed
vasnesterov wants to merge 1 commit into
masterfrom
fix/primitive-recognizer
Closed

vasnesterov wants to merge 1 commit into
masterfrom
fix/primitive-recognizer

Conversation

@vasnesterov

Copy link
Copy Markdown
Owner

Three defects in Environment.checkPrimitiveDef, each of which let a declaration pass the check without the property the abstract model then assumes of it.

This check is lean4lean-only (see divergences.md): Lean itself does not verify that primitives are declared with the right types and definitional behaviour, because it ships its prelude.

The defects

Recognition up to defeq where the model pins a syntactic type. Char.ofNat and String.ofList were recognized up to definitional equality, while the model pins their VConstant to a literal syntactic type and the translation reads the declared type off structurally. Declaring Char.ofNat at (fun _ : Nat => Nat → Char) Nat.zero passed the check and produced a different constant. They now compare with Expr.eqv, which is exactly what the translation sees through — and the toolchain declares both at the expected shape up to binder name.

Comparisons with no translation witness. The Nat equations were compared as ∀ _ : Nat, e₁ against ∀ _ : Nat, e₂ — a deliberately ill-typed pseudo-type used to get under a binder. Since Nat.add x 0 is not a type, those comparisons had no translation witness at all and therefore carried no semantic content. They are now checked under withLocalDecl-bound free variables, as the Nat.div and Nat.mod cases already were.

Verification

lake build Lean4Lean.Verify exit 0, verified on the current base.

🤖 Generated with Claude Code

…aims

Three defects in Environment.checkPrimitiveDef, each of which let a
declaration pass the check without the property the abstract model then
assumes of it. This check is lean4lean-only (see divergences.md): Lean
itself does not verify that primitives are declared with the right types
and definitional behaviour, because it ships its prelude.

Char.ofNat and String.ofList were recognized up to definitional equality
while the model pins their VConstant to a literal syntactic type, and the
translation reads the declared type off structurally. Declaring
Char.ofNat at `(fun _ : Nat => Nat → Char) Nat.zero` passed the check and
produced a different constant. They now compare with Expr.eqv, which is
exactly what the translation sees through -- the toolchain declares both
at the expected shape up to binder name.

The Nat equations were compared as `∀ _ : Nat, e₁` against
`∀ _ : Nat, e₂`, a deliberately ill-typed pseudo-type used to get under a
binder. Since `Nat.add x 0` is not a type, those comparisons had no
translation witness at all and so carried no semantic content. They are
now checked under withLocalDecl-bound free variables, as the Nat.div and
Nat.mod branches already did. Nat.land and Nat.lor were additionally
binding their Bool variable at type Nat.

And every arithmetic branch built Nat and Bool literals, and depended on
other primitives' semantics, without requiring any of them present. Each
was implied by a later checkType, but only by inverting "type checking
succeeded" -- and the witnesses the specification demands cannot be built
before that inversion is available. They are now explicit guards.

The recognizer is strictly stricter than before. Kernel Arena is
unchanged at 185 correct / 6 either / 0 incorrect, and the run_meta
self-test over all 24 entries of Environment.primitives still passes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@vasnesterov

Copy link
Copy Markdown
Owner Author

This PR doesn't touch critical files, so do whatever you think is right. Human review is only for critical files (axioms and main theorem statement)

@vasnesterov

Copy link
Copy Markdown
Owner Author

Closing — this branch is behind master, and merging it would regress the file.

master already carries all three defects' fixes, landed via #9, #10 and their siblings (2f1aa08 Char.ofNat/String.ofList recognized up to defeq, 7c41293 branches depending on constants they never required, 1cbb5bc isDefEq on untyped input). It has since gone further than this branch: master has checkedTypeIs, which type-checks both sides before comparing so each isDefEq has a translation on both sides. This branch predates that and still calls isDefEq (← checkType …) … directly.

So the merge conflict in Lean4Lean/Primitive.lean was master being ahead, not a divergence to resolve. Nothing here to salvage; the branch is kept.

vasnesterov pushed a commit that referenced this pull request Aug 23, 2026
…d a guard class the audit missed

**The systemic finding: a guard class §6/§7.1 did not account for.** Every
`@[extern]` C entry point in scope that takes a `Nat` begins with a
**`lean_is_scalar` bignum test -- before** the range test the audit
records. `LEAN_MAX_SMALL_NAT = SIZE_MAX >> 1`, so it fires at `2^63`.
§6 describes `lean_expr_instantiate_range` as "starts with
`if (b > e || e > sz) lean_internal_panic`" -- that is the function's
**second** statement, not its first. **Seven axioms in scope sit on that
guard**, and it resolves four different ways.

## #21 `Lean.Expr.liftLooseBVars_eq` is FALSE

    if (!lean_is_scalar(s) || !lean_is_scalar(d)) { lean_inc(e); return e; }

Witness `e := .bvar 0`, `s := 0`, `d := 2^63`. Both halves
machine-checked, deliberately **by different instruments**:

- C side, differential test on compiled code:
  `#eval idx ((Expr.bvar 0).liftLooseBVars 0 (2^63))` prints `"bvar 0"`.
- Model side, kernel reduction:
  `liftLooseBVars' (.bvar 0) 0 (2^63) = .bvar (2^63)`, and `≠ .bvar 0`.

So the axiom asserts `.bvar 0 = .bvar (2^63)`.

Worse than #26/digama0#27 in one specific way: **the call completes.** No
panic, no exotic input -- `2^63` is an ordinary literal and `.bvar 0` an
ordinary `Expr`. Only the *model's* output is not runtime-constructible,
which is why the two sides cannot be evaluated in one expression
(`#eval` of the model's answer trips `lean_expr_mk_data`'s own panic --
observed).

**Not an inconsistency**: `liftLooseBVars` is `opaque @[extern]` and the
toolchain has no core theorem about it, so there is no second fact to
contradict. Same category as #12/#17. Fix is `d < 2^63` or a `USize`
restatement -- frozen file, needs sign-off.

## Three failed attacks, recorded as failed attacks

- **#22, digama0#30** carry the same guard and **survive**: the C fallback
  coincides with the model on every input a real `Expr` can supply,
  with machine-checked agreement lemmas for both. One of the stream's
  own witnesses was wrong -- `(.bvar 7).lowerLooseBVars (2^63) 1`
  returns `bvar 7` from *both* sides -- and the correction is recorded
  rather than quietly dropped.
- **digama0#29 `abstractRange_eq`**, the only unconditional range axiom, also
  survives: its fallback uses `lean_array_size` and `Array.extract 0 n`
  clamps to the same thing, agreeing at **every** input, logical or not.
  Verdict unchanged, for a reason §7.1 did not state.

## #26/digama0#27: the side condition is necessary but NOT sufficient

`start ≤ stop ≤ subst.size` excludes the second guard, not the first --
`stop` may be non-scalar provided `subst.size` is too, which needs
`subst.size ≥ 2^63`: expressible, not constructible. Strictly weaker
than #21, no differential test possible. **Source reading only, and
marked as such.**

## The two other priority targets, answered

- **#17 `Expr.mkData_eq` -- no analogous consequence.**
  `lean_expr_mk_data` panics twice, and its hypothesis implies **both**
  are passed; the `approxDepth` clamp matches too. Unlike #12, correctly
  guarded.
- **#3 `PersistentArray.toList'_push` -- hypothesis adequate**, in the
  strongest available sense: `WF` is generated by `empty`/`push` only,
  and a reverse scan shows lean4lean uses **no other `PersistentArray`
  operation**. So `WF` is exactly the reachable set, not an
  approximation.

Not reached: #4-#7. **digama0#31's dependency on #15 deliberately not pursued**
-- #15 belongs to another stream's section, and a cross-section attack
run from one side only is the weaker version of the test.

**No `False` was derived.** §11.9 keeps the evidence strengths separate:
differential-test-plus-source, source-only, and proof are three
different things, and none of this is a proof.

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

Neither possibility in the brief was right; the answer is a third.
**They are consistent** (the argued contradiction is dead), **they are
not provable** (their docstrings' claim is false), **and they become
provable under a side condition.**

New `Lean4Lean/Tests/AxiomConsistency.lean` (nothing imports it). It
works by **model exhibition** against `dataOf f` -- `Lean/Level.lean`'s
computed field with the opaque `mkData` replaced by `f` -- and checks
clause-by-clause by `rfl` that `dataOf mkData` is the real
`Level.data`.

- **§1** a clamping model (`min d (2^24-1)` instead of panic) validates
  **all three** of #12/#13/#14 by induction on `Level`. So they are
  **jointly consistent**, and §4's argument needed the *unconditional*
  `mkData_eq`: it dies with the `H : d < 2^24` repair.
- **§2** a zeroing model validates #12 but **refutes** #13/#14 on
  `succ^[2^24] (.param x)`. So **#13/#14 are independent of #12** --
  nothing constrains `mkData` at `d ≥ 2^24`, and they cannot be proved
  "using `mkData_eq` and friends" as their docstrings claim.
- **§3** `hasParam_eq_of_dep`, `hasMVar_eq_of_dep`, `depth_eq_of_dep`,
  each under `(h : dep l < 2^24)` -- proved **without** #13/#14. The
  hypothesis is verified load-bearing (§2 *is* the proof it must be) and
  satisfiable, and the qualified name was checked to be
  `Lean.Level.mkData_eq` rather than the `Expr` one.

**Joint-consistency survey (§12).** Mechanical: which free symbol each
axiom pins. The relation is a **DAG** -- verified no `X_eq : X = Total.X`
has `Total.X` reaching `X`. That splits the set:

- **Class (A), 23 axioms** -- each pins a free symbol to a total
  definable function. **Jointly consistent by topological
  interpretation.**
- **Class (B), 6 axioms** -- constrain a free symbol *through* a
  definable observation with provable properties. **Both historical
  `False`-proofs were in class (B)**, which is where attack effort
  belongs.

**Seven failed attacks recorded in §12.3, each with the step it fails
at**: #15+digama0#31 and digama0#30+digama0#31 (no shared constant -- independent opaques);
mutual definability of the ten substitution/abstraction primitives (all
independent opaques, the equivalences are **docstrings only**); #18 at
the `BVarBounded` boundary; off-by-one at both panic boundaries; #17's
unconditional form.

**The strongest single result:** an environment sweep over every
constant whose type mentions any of the 27 pinned opaques (private
manglings resolved, not grepped) returns 21 whitelisted axioms plus
exactly four auto-generated inert lemmas. **No theorem anywhere asserts
a behavioural property of any pinned opaque** -- so contradictions can
only arise *between* whitelisted axioms.

Unverified, stated as such: the `PersistentArray`/`PersistentHashMap`
three are the **highest residual risk** -- class (B), same shape as the
two that proved `False`; `WF` blocks the known counterexamples and no
new attack succeeded, but no model exists and building one means
proving the real HAMT algorithms correct. And the `Expr` analogue of §1
is hand-analysed, not mechanised.

Also noted: removing the two `TreeMap` axioms eliminated the only two
with **zero model freedom**.

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

**The criterion answered a different question than expected.** Asked
which side condition the consumers satisfy for free, an axiom-cone scan
(`Lean.collectAxioms`) over every non-internal `Lean4Lean.*` declaration
returned:

| axiom | dependents |
|---|---|
| **`Lean.Expr.liftLooseBVars_eq`** | **0** |
| the other 13 in scope | 35 - 162 each |

Zero for a structural reason, not by luck: **the checker never calls
`Expr.liftLooseBVars`.** No occurrence outside `Verify/` and
`Experimental/`, and the only textual matches inside `Verify/` are
theorems about the *model* `liftLooseBVars'`, none about the opaque
constant. The axiom is `@[simp]`, so it has no explicit call sites
either way -- and the cone scan is exactly what settles that, since a
`@[simp]` lemma that fires does appear in the proof term.

**So the fix is subtraction, not domestication:** deleting it cannot
break a proof, and it removes a live false axiom. Fallback if a reviewer
prefers to keep the statement: the C guard is
`!lean_is_scalar(s) || !lean_is_scalar(d)`, so **both** arguments need
bounding -- `s < 2^63 ∧ d < 2^63`, not `d < 2^63` alone. A `USize`
restatement does not fit without changing the signature.

**The guard class, stated as method in §11.1.** §7.1's entries describe
the *worker* functions faithfully; what they skip is the `extern "C"`
wrapper, which is where argument validation lives.

> For any `@[extern]` axiom, read the wrapper first and enumerate every
> early return before reading the algorithm.

A `Nat` crossing into C is boxed, hence always bignum-guarded, and the
guard either panics or silently substitutes a fallback the axiom must
then match. **Seven of fourteen axioms in scope sit on one.**

**Four more failed attacks (#4-#7), recorded with their failure step.**

- **#6 `findAux_isSome` survives** -- both sides use the *same* `==` and
  the functions are parallel clause-for-clause; the shared panic-index
  agrees whatever `default : Entry` is.
- **#4/#5 survive a non-reflexive `BEq`.** `PartialEquivBEq` requires
  symmetry and transitivity but **not** reflexivity, so
  `⟨fun _ _ => false⟩` is legal and `LawfulHashable` is vacuous -- a key
  can be inserted twice and the filter deletes nothing. Both axioms
  still hold. Hand-executed, not machine-checked, and marked so.
- **#7 `structEq_eq` survives, but §7.3's reason was wrong**, in a way
  worth keeping. It claims `Substring.Raw.Internal.beq` *is* the `BEq`
  instance. Not definitionally:
  `example : @Substring.Raw.Internal.beq = (· == ·) := rfl` **fails**.
  The identity holds *through the linker*, via an `@[extern]`/`@[export]`
  pairing -- weaker assurance, and the reason this axiom can never be
  discharged by unfolding. The attack it prompted (position-sensitivity
  like `Substring.Raw.sameAs`) fails under differential test, with both
  negative controls checked.

Still declined: **digama0#31's dependency on #15**, since from one side it is
the weaker test. Ready to pair with the `Level` stream.

§11.9 keeps the three evidence strengths separate and now names the cone
scan as the strongest instrument in the pass -- a complete search over
the environment rather than a sample -- which is why #21's
recommendation is *delete* rather than *weaken*.

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

**`ORCHESTRATOR.md`** -- orchestrator-only instructions, separate from
`CLAUDE.md` which is for every agent. Centrepiece: **prefer handoffs to
resumes.** A resumed agent carries a long, mostly irrelevant transcript
and drifts toward what it already believes; instead ask a stream at a
boundary to write `docs/handoff-<topic>.md` and point a **fresh** agent
at it. The handoff must carry what a newcomer cannot cheaply
reconstruct -- in particular **what was tried and failed, and the step
it failed at**, which is the half that gets lost and the most common
waste to re-derive. Also records the git gate, explicit-path staging,
one-file-one-stream with boundaries rather than arbitration, and
ruling on measurements rather than reasons.

**Audit §13.** No inconsistency found; one recorded justification
corrected, one risk bounded.

**digama0#31's "depends on 15" is a documentation artifact.** A
constant-dependency scan over statement, value and the `brecOn` helper
shows `Expr.eqv_eq`, `Expr.eqv'` and `eqv'._f` mention
`instLawfulBEqLevel` **nowhere**. What digama0#31 actually rests on is
different in kind and strictly weaker: that `BEq Level` is **the same
function** C uses, not that it is **lawful** -- the instance *is*
`Level.beq` definitionally, `Level.beq` is `@[extern "lean_level_eq"]`,
and `expr_eq_fn.cpp` compares levels with that same symbol.

**Why it is worth fixing:** if #15 were refuted -- if `lean_level_eq`
normalised and so were not structural -- **digama0#31 would be unaffected**,
because both sides of `eqv_eq` would use the same non-structural
comparison and still agree. The annotation invites the inference
*"refuting 15 propagates to 31"*, which is false. Same shape as §7.3:
right verdict, wrong recorded reason.

Bonus sweep: the `LawfulBEq Expr` route was re-run as an
environment-wide instance scan over the **whole import closure** rather
than core alone. The only such instance in scope is
`instLawfulBEqLevel`, and it is for `Level`. Route closed over the
closure.

**Container axioms: `WF` is the reachable set for #4/#5 too**, by a
longer chain. Only 7 distinct `PersistentHashMap`/`PersistentArray`
constants are referenced by any `Lean4Lean.*` declaration, and
`insert`/`find?` are not among them -- they arrive through
`ConstMap = SMap Name ConstantInfo`. `SMap.map₂` **defaults to empty**;
`fromHashMap` sets only `map₁` and the stage; `SMap.insert` is **the
only writer of `map₂`**; the single construction site is at stage 2, so
every later insert lands in `map₂` starting from `∅`. Hence every
reachable `PersistentHashMap` is `empty` followed by `insert`s --
exactly `WF`'s two generators. `erase`, `modify`, `insertIfNew`,
`ofList` are unreachable.

**What that buys, stated narrowly:** it rules out the failure mode that
actually produced a `False` here -- an axiom stated for arbitrary,
including malformed, structures -- since a hypothesis that is exactly
the reachable set cannot be applied outside its domain. It does **not**
make the axioms true *on* that domain: no model of the HAMT or the trie
exists, so an error in the algorithms themselves survives untouched.
**Class (B) risk is bounded, not removed**, and §13.5's evidence table
ends with the row `#4/#5 are true -- none, still no model`, which is the
point of the table.

Three more failed attacks recorded in §13.4.

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