Skip to content

Bound BendTT model search and retain finite alternatives (#1181) - #1218

Merged
Lorenzobattistela merged 6 commits into
bendlang:mainfrom
oxura:fix/verdict-bounded-models
Oct 2, 2026
Merged

Lorenzobattistela merged 6 commits into
bendlang:mainfrom
oxura:fix/verdict-bounded-models

Conversation

@oxura

@oxura oxura commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1181.

Cause

A root with a ~ parameter needs a model of that parameter's type. model_at in safe.ts builds one by walking constructors. The issue's two shapes break that walk in two ways:

  • W<(n => Nat)> with C{g: Nat -> W<F>} overflows the stack. The path that stops cycles keyed each datatype as term_key(term_lower(F, d)). That key holds the absolute level of every binder inside F's arguments. A field under a ∀ raises d, so W<F> never meets its own key again.
  • Nest<A> with NCons{x: A, rest: Nest<Pair(A, A)>} grows memory without bound. Every step meets a genuinely new type, so no cycle check can end the walk. The type's key also doubles in size at each level.

Change (safe.ts only)

  • Cycle key: model_key is the same term_key(term_lower(F, d)), except that levels at or above d are written relative to d. A datatype under a ∀ field now meets its own key again. Free levels stay absolute, so they can't collide with bound ones.
  • Search: model_by keeps declaration order and searches in rounds of doubling depth, from MODEL_DEPTH = 8.
    • A round that cuts no branch returns exactly what an unbounded search would, so every model found today is unchanged.
    • When rounds keep cutting branches, the first model a cut round found is used, and only once the fuel runs out. The kernel still checks it.
  • Fuel: MODEL_FUEL = 1 << 22 is shared by all rounds. It counts a step per type visited and a step per character of each datatype key. A nested type whose key doubles at each level therefore runs out of fuel instead of memory. Running out means no model, so the def is out of scope.
  • λ bodies: a model λ's body is searched once and rebound with subst at each use, instead of re-running the search from a closure. Only the outer levels are fixed; binders inside the body still rebind.

Checks

On b4a9a028, against main 75cc3602:

  • gates/test.ts: PASS 1536 / 1536 (main: 1531 / 1531).
  • gates/perf.ts: 123 / 124, the same as main.
  • gates/ping.ts: PASS 46 / 46, the same as main.
  • gates/repo.ts: 48 / 49, the same as main. The failure is bend2/comp.ts at 64,251 tokens against its 64,000 cap, and this PR doesn't touch comp.ts. safe.ts goes from 21,139 to 21,624 tokens, under its 24k cap.
  • gates/safe.ts tests: 988 agree, 2 out of scope, 1 false reject (agree_32, also on main). Compared file by file with main, all 1542 existing files give the same exit code and the same output bytes. The only new entries are the 5 new tests.
  • tsc: the same 12 errors as main.

--verdict results on the issue's files and on the review's repros:

  • The issue's W<(n => Nat)> and Nest<Nat>: ALL PROOFS CHECK in about 0.1 s. On main they overflow the stack or run out of memory.
  • A type with no finite model (Grow, only GCons): out of scope in about 0.2 s.
  • A recursive first constructor before a finite leaf, with growing parameters: checks in under 0.15 s.
  • ~v: Vec(2000n): checks in 0.49 s.

Tests

  • tests/proof/model_search.bend: the issue's two shapes, a nested proof λ, and a runtime check that prints 7n.
  • tests/proof/model_no_base.bend: a required model that doesn't exist.
  • tests/proof/model_lambdas.bend and tests/proof/model_false.bend: a model λ's inner variables still bind, in both directions.
  • tests/proof/model_order.bend: constructors are tried in declaration order, including the earlier deep constructor at Vec(400n).

No changes to bend2/bend.ts, the gates or any caps.

🤖 Generated with Claude Code

Fresh hand verification (Linux, upstream 237c722)

Built the current Book-map / UTF-8-parser Lean source using Lean 4.34.0 in a fresh isolated cache. model_lambdas, model_order, and model_search report ALL PROOFS CHECK. A separate combined review witness for G's finite leaf, B's complete fallback, R<Id(Nat)> versus R, and Vec at 130, 400, 600 and 2000 also reports ALL PROOFS CHECK. This is local hand verification, not a new cluster/gate claim.

@oxura

oxura commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

Joint verification of #1215, #1216, #1218, #1219 and #1220 against main commit 0187512:

  • All five independent PR branches merge cleanly in one octopus merge. Documentation hunks were separated and shared wording shortened so the combined guide stays within the original cap.
  • Combined bun gates/repo.ts: PASS 49/49; no caps changed.
  • Real Lean 4.34.0-built BendTT kernel accepts all three new positive proof regressions, unchanged vec_safe_lookup, and the five reported grouping/label/model-search witnesses.
  • Four runtime regressions produce 5n, 6n, 7n, 204 on interpreter, emitted JS and native C. All four C programs were exercised with AddressSanitizer and UndefinedBehaviorSanitizer; no diagnostics.
  • The merged emitted fb3 value passes an added {main == (.False, ()) : Bool} oracle. The corresponding .True oracle fails in the actual kernel, so successful type-checking is not the only evidence of value preservation.
  • Kind-only and empty-datatype unsafe dependencies still reject with exit 1 and the expected dependency sets.
  • The genuinely required unavailable model rejects promptly; -o explicitly reports no model for reflexive~n as out of scope. Search-limit exhaustion remains fail-closed, not an unchecked placeholder.

The cluster-wide corpus gates were not run; this evidence is the local repository gate, actual CLI/compiler runs and actual kernel checks.

@Lorenzobattistela

Copy link
Copy Markdown
Collaborator

Thanks for this. Comparing the path's types with term_compare is the right fix for the W overflow.

But four files that pass --verdict on main fail on this branch:

  1. Rebound model λs freeze their inner variables (safe.ts:456). The subst swaps in level d but turns every other variable into a fixed B.Var(k, i). That includes variables bound inside the body, so a nested model λ ignores its argument once the model book applies it. Returning undefined for o.i > d fixes it.
law L:
  for ~f: @A: Type -> A -> A
  for ~h: @B: Type -> @c: Nat -> @b: B -> {f(B, b) == b : B}
  for x: Nat
  {f(Nat, x) == x : Nat}

def L(f, h, x):
  h(Nat, 0n, x)
main: ALL PROOFS CHECK. This PR: no model for L~h. Change the law to {f(B, b) == c : B} and the search instead finds a {==} that the kernel then rejects.
  1. The sort orders all constructors by field count, not only nullary ones first (safe.ts:464). A recursive constructor with one field now runs before a finite leaf with two fields and uses up the whole budget before the leaf is tried:
type G<-A: Type> is Type:
  Leaf{a: A, b: A}
  Grow{rest: G<Pair(A, A)>}

def reflexive(~n: G<Nat>) -> {n == n : G<Nat>}:
  {==}
main: ALL PROOFS CHECK in 0.07 s. This PR: no model after 4.7 s. Moving only the nullary constructors first (Number(a.n > 0) - Number(b.n > 0)) fixes this case.
  1. Any reordering changes which models existing files get. A ~ law that held of the old first-constructor model can stop holding:
type Shape is Data:
  Rect{w: Nat, h: Nat}
  Circle{r: Nat}

law shape_t:
  for ~mk: Nat -> Shape
  for ~ok: @x: Nat -> {is_rect(mk(x)) == True{} : Bool}
  for x: Nat
  {is_rect(mk(x)) == True{} : Bool}
main models mk as λx. Rect{0n, 0n} and checks. This PR picks Circle{0n}, so ok has no model. Even a nullary-first order changes types like Has{x} | Nothing{}.
  1. The depth limit of 128 rejects finite models that main finds. def reflexive(~v: Vec(130n)) -> {v == v : Vec(130n)}, with Vec(n) defined as Unit at zero and Nat & Vec(p) at a successor, checks on main in 0.07 s and is out of scope here.

Run time. The budget counts visits, but each visit runs a full term_compare against every entry on the path. The G case above makes about 466k comparisons per attempt, and Vec(120n) takes 0.51 s against main's 0.07 s. Two cheaper alternatives:

  • skip path entries with a different head (A.k !== F.k);
  • skip the path scan when h !== null.

Also, a failing ~ constant is searched in root_cols and again in def_emit, so each "no model" pays for all four attempts.

Suggestion. Instead of one shared budget plus a reorder, try iterative deepening: search in declaration order with a depth limit that grows each round, under the same total budget. That finds the shallowest model, keeps every model main picks today (fixing 2 and 3), and still ends Nest/Grow. It should also make the rebase with #1263, which changes the same function, simpler.

Smaller points:

  • Tests: the use_proof case never applies the model to real arguments, so it passes despite (1). Neither new test fails a gate if model search regresses, because the test gate doesn't run --verdict and gates/safe.ts exits 0. A tests/ file whose expected output shows the out-of-scope result would pin this behavior.
  • Constants: name 4096 and 128 (e.g. MODEL_FUEL and MODEL_DEPTH next to NAT_MAX). The header comment says "nullary constructors before its others" but the code sorts by arity.
  • Message: when the limit is hit, --verdict prints the generic "mismatch, open an issue" message, while the guide now calls it an expected out-of-scope limit.
  • Guide: the GUIDE.md rewrite drops the @unsafe code formatting and the "checks the proofs a second time" explanation. "Template-model search" and "out of scope" appear nowhere else in the guide. The file is at 7,947 of 8,000 tokens. I'd probably drop it.

Keep nested model binders scoped, search constructors in declaration
order across budgeted deepening rounds, and memoize spine comparisons
within each probe. Report model exhaustion distinctly from kernel
mismatches and pin real verdict regressions, including imported names.
@Lorenzobattistela

Copy link
Copy Markdown
Collaborator
  1. Please drop the gate changes. Changes to gates/ need Taelin's sign-off, so the local mode, the #> lines, the nonzero exit and the judge() reorder can't land in this PR. If you want --verdict expectations in the test corpus, please open a separate proposal for that. This has two knock-on effects:
  • The #> lines in the new tests have to go too. AGENTS.md also wants each test to end in its #| lines.
  • The main.ts message change has to go, or keep the Sorry - prefix. Main's gates/safe.ts and safe_node.ts look for Sorry - to spot out-of-scope files. Without it, the five out-of-scope tests are counted as "bend2 rejects" (494 vs 489, with 0 out of scope).
  1. A complete model is thrown away when a round runs out of budget (safe.ts:466). The break runs before fallback ??= v. A non-null v from model_at is always a complete term, so it is safe to keep.
type B<-A: Type> is Type:
  Fork{l: B<Pair(A, A)>, m: B<Pair(A, A)>, r: B<Pair(A, A)>}
  Tip{}

def reflexive(~b: B<Nat>) -> {b == b : B<Nat>}:
  {==}

This gives "no model (model search limit reached)". With fallback ??= v moved above the break, it checks in 88 ms.

  1. The cycle check unfolds definitions, so it cuts off models main kept. model_equal hands anything that isn't an ADT, λ or Qua to term_compare, which unfolds definitions. So R<Id(Nat)> counts as a repeat of R:
def Id(A: Type) -> Type:
  A

type R<-A: Type> is Type:
  C{rest: R<Nat>}
  N{}

law t:
  for ~mk: Nat -> R<Id(Nat)>
  for ~ok: @x: Nat -> {is_c(mk(x)) == True{} : Bool}
  for x: Nat
  {is_c(mk(x)) == True{} : Bool}

is_c(r: R<Id(Nat)>) returns True{} for C and False{} for N. Main picks C{N{}} and checks; this PR picks N{} and fails with no model for t~ok. The cycle check only needs to see the same type again, not a convertible one. A comparison that doesn't unfold definitions, or a key without binder levels as #1181 suggested, would keep main's choices. It would also replace about 57 lines that copy compare_go and would drift from it.

  1. Finite models past the step budget are still lost. The fixed depth limit is gone, but 4096 visits now set the limit:
  • ~v: Vec(300n): checks on main and here.
  • ~v: Vec(400n): checks on main; "no model (limit reached)" here.
  • ~v: Vec(600n): checks on main in 117 ms; "no model (limit reached)" here.
  • ~v: Vec(2000n): checks on main in 495 ms; "no model (limit reached)" here.

The fallback also changes model choice quietly. With model_order's Choice at Vec(400n), the budget runs out while deepening and mk gets Shallow{}. The error then reads no model for choice_t~ok, with no limit hint, because the limit was hit on mk. Main checks that file in 107 ms. Please either size the budget so this doesn't happen in practice, or let a model-search limit leave the root's other constants out of scope with that reason, instead of handing out a fallback model.

  1. Style.
  • safe.ts doesn't use one-line ifs without braces or inline try/catch. The PR adds eight, at safe.ts:510, 557, 566–575 and 596–597.
  • The new comments are capitalized prose. The file's comments are short lowercase fragments.

The core is close: dropping the gate changes and fixing 2 and 3 should leave a small diff. Without the #> gate, though, nothing in CI checks the verdict for these cases, so please describe what you checked by hand in the PR body.

oxura and others added 3 commits October 3, 2026 00:41
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…s counted from the search's depth, and it deepens in declaration order under a fuel of visits and key characters (bendlang#1181)

Narrow the PR to the fix bendlang#1181 needs: drop model_key's structural interner,
the e.models cache, the later-constant limit rule, the out-of-scope CLI
message and the tests for them. model_key is term_key on the lowered type
with bound levels relative to d; a key's length counts against the fuel,
so a nested type whose key doubles each level runs out instead of growing.

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

oxura commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review and merged corrections. Checked the final implementation: declaration order is retained, iterative deepening uses the named 8-depth / 2^22 work budget, complete cut-round models are retained, the cycle key stays structural, and nested lambda binders are left for rebinding. No gate, cap, GUIDE or CLI-message changes remain in this PR.

Fresh hand checks on upstream 237c7226, using a newly built real Lean 4.34.0 kernel including the Book-map and UTF-8-parser changes: model_lambdas, model_order, model_search, plus G's leaf, B's fallback, R<Id(Nat)> and Vec(130/400/600/2000) all give ALL PROOFS CHECK. Added this local evidence to the PR body. No new mini-cluster or performance timing claim.

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.

--verdict overflows the stack on a ~ parameter of some datatypes: model_at's cycle check misses cycles through ∀-typed fields

2 participants