Skip to content

fix: looseBVarRange_eq proves False on its own - #5

Merged
vasnesterov merged 1 commit into
masterfrom
fix/loosebvarrange-axiom
Aug 22, 2026
Merged

vasnesterov merged 1 commit into
masterfrom
fix/loosebvarrange-axiom

Conversation

@vasnesterov

Copy link
Copy Markdown
Owner

Draft: the build is red on purpose. The correction is right; discharging it
is not plumbing, and the reason why is the most interesting thing here.

The bug

@[simp] axiom looseBVarRange_eq (e : Expr) : e.looseBVarRange = e.looseBVarRange'

Expr.looseBVarRange is a 20-bit field read ((data >>> 44).toUInt32), so
< 2^20 is provable with no axiom at all. looseBVarRange' is unbounded:
(Expr.bvar 1048575).looseBVarRange' = 2^20. So the axiom proves False on
its own
— it needs neither mkData_eq nor the repo's bv_decide-backed
looseBVarRange_le:

'contradiction_alone' depends on axioms: [propext, Quot.sound, Expr.looseBVarRange_eq]

C agrees the value is unrepresentable: lean_expr_mk_data calls
lean_internal_panic.

Guard 2 whitelists this axiom by name, so it sits in kernel_sound's trusted
cone — an inconsistent base makes the theorem provable vacuously while the guard
reports success. Latent today only because Verify/Soundness.lean imports
nothing from the refinement layer.

The fix

Expr.BVarBounded, a hereditary per-subterm bound. Hereditary is necessary,
not cautious: looseBVarRange' (.lam _ t b) = max t.lBR (b.lBR - 1), so a bound
on the parent does not bound b.

Plus BVarBounded.looseBVarRange'_le, proved and axiom-free — the
machine-checked evidence that the condition actually blocks the refutation
rather than merely looking plausible: under it the model range obeys the same
bound the packed field does, so the two sides are no longer forced apart.

Not the tempting repair of replacing the RHS with
if e.looseBVarRange' ≤ 2^20-1 then … else 0. That reifies Lean's
panic! = default convention, but the C function aborts — the corrected
axiom would then be a different false statement, claiming the checker keeps
running with range 0.

What breaks — exactly four declarations

Declaration File
BetaReduce.cheapBetaReduce Verify/Typing/Lemmas.lean:1973
TypeChecker.Inner.isDefEqLambda.WF Verify/TypeChecker/IsDefEq.lean:9
TypeChecker.Inner.isDefEqForall.WF Verify/TypeChecker/IsDefEq.lean:79
TypeChecker.Inner.inferType'.WF Verify/TypeChecker/InferType.lean:413

The list is exhaustive: established by stubbing each site and rebuilding until
all 1197 jobs completed, so nothing else in the tree depended on the
unconditional form. All stubs reverted; git diff touches only Axioms.lean.

Why this is not a small repair — and a finding about the checker

The cheap route (add the bound to TrExprS/VLCtx well-formedness) is
provably insufficient, because of inferType'.WF.

In its .bvar branch the only context is h : (Expr.bvar i).looseBVarRange = 0,
from the checker's own if e.hasLooseBVars then throw guard, and the goal is
that the following panic! "unreachable code has been reached" is WF. The old
proof rewrote h to i + 1 = 0. The corrected axiom gives only
i + 1 ≤ 2^20 - 1, and inferType'.WF's hypotheses are

(h1 : e.FVarsIn (· ∈ c.vlctx.fvars))
(hinf : inferOnly = true → ∃ e', c.TrExprS e e')

— hinf is conditional, so on the inferOnly = false path there is no
TrExprS e at all
. An invariant on TrExprS cannot reach this goal.

Read honestly, that is a statement about the checker, not a proof artifact:
inferType' applied to Expr.bvar 1048575 passes the hasLooseBVars guard —
the packed field reads 0 — and falls into unreachable code.
The real
executable can never build that term, because lean_expr_mk_data aborts first.
Which is exactly why this has to be an assumption that is checked, not one
that is proved away. It is the same 20-bit field and the same
silent-degradation mechanism as the hasLooseBVars non-conservativity bug
already in bugs-found.md.

cheapBetaReduce cascades similarly: the obligation propagates to sites where
e is the inferred type returned by a recursive call, so discharging it means
proving the checker's own outputs are BVarBounded.

The honest fix touches Lean4Lean/TypeChecker.lean plus the mutual WF recursion
across Verify/TypeChecker/{Basic,InferType,IsDefEq,WHNF,Reduce}.lean —
several hundred lines — and should probably thread an explicit check from
addDecl rather than an invariant.

Caveats on the correction itself

  • @[simp] is now nearly inert. The side goal e.BVarBounded has no simp
    equations, so simp will essentially never discharge it — which is partly why
    only four sites broke. Whoever finishes this should add unfolding lemmas or
    make BVarBounded an inductive.
  • It is a Prop-valued recursive def, so not decide-able. A checked
    precondition needs a Bool-valued version plus a soundness lemma; probably
    worth defining that way from the start.
  • Not machine-checked: that BVarBounded is not too weak. The new lemma
    shows it bounds the model range; that a binder's own mkData argument is
    automatically in range once its children are was verified only as arithmetic,
    not against the real mkData chain.
  • .lit is unconstrained. Fine today because TrExprS expands it via
    toConstructor, which is closed and bvar-free — a silent dependency.
  • The bound is 2^20 - 1, not 2^20. Deliberate: it matches the C check and
    the repo's existing mkData_looseBVarRange.

Note on the freeze

Verify/Axioms.lean is frozen per CLAUDE.md; this is a proposal for sign-off.
Axiom names are unchanged, so guard 1's list still matches.

🤖 Generated with Claude Code

Expr.looseBVarRange is a 20-bit field read, so `< 2^20` is provable with
no axiom at all, while looseBVarRange' is unbounded. At
`Expr.bvar 1048575` the model gives 2^20 and the field gives 0, so the
axiom proves False on its own -- it needs neither mkData_eq nor the
repo's bv_decide-backed looseBVarRange_le.

Adds Expr.BVarBounded, a hereditary per-subterm bound, as the side
condition. Hereditary because a binder's model range is a max involving
its children, so a top-level bound does not constrain them. Also proves
BVarBounded.looseBVarRange'_le, which is the machine-checked evidence
that the condition actually blocks the refutation rather than merely
looking plausible: under it the model range obeys the same bound the
packed field does, so the two sides are no longer forced apart.

The build is red, deliberately: four declarations acquire the new
obligation and discharging them is not plumbing. The full list was
established by stubbing each site and rebuilding until all 1197 jobs
completed, so nothing else in the tree depended on the unconditional
form.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@vasnesterov
vasnesterov merged commit b3250c8 into master Aug 22, 2026
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