Repository navigation
ty_holds opens a datatype once with DUMMY for its value arguments (#1513) - #1542
Conversation
ty_holds marked a datatype seen by name, so a later instance of the same
family (Chain<Num{}> after Chain<Fun{}>, or mutually nested A/B) was never
looked into, and a closure it held never reached the device. It now keys
seen by the instance, and stops 1000 datatypes deep.
Fixes #1513. Supersedes #1522.
Co-authored-by: oxura <[email protected]>
Type arguments are walked on their own, so keying them too let a nested datatype (Grow<P<A, A>>) open 2^d instances. Tests: a nested datatype compiles at once; a chain with a growing index stops at the cap.
…s may hold a closure (#1513) Back to main's walk: each datatype is opened once, keyed by name. When ty_clo meets it again with different arguments it answers yes, so the GPU reach set takes the closures in. No per-instance walk, no depth cap. Co-authored-by: oxura <[email protected]>
…ooked into apart (#1513)
nicolas-abril
left a comment
There was a problem hiding this comment.
This fixes #1513, but the repeat check also says "may hold a closure" for common value-indexed families that hold none, which turns on wide and pulls every host closure into the device build. Nothing breaks, but it costs size and build time. Details inline.
One more point, outside the diff: ty_value (line 904) and lay_of's re-entry check (line 951) still call ty_holds with the name-keyed skip that caused #1513. In a kind like Duo{a: K<X>, b: K<Y>} where only K<Y> computes to Type, the second K is skipped, ty_value says "value", and that argument gets keyed by syntax instead of walked as a type argument. That breaks the assumption the new comment rests on, that type arguments are "looked into apart".
) Its fields then cover every index it is met with, so a later instance with another index needs no second walk, and plain index recursion (Expr<-t>, Vec<A,-n>) still holds no closure. The value/type split of the parameters is memoized per datatype (FL.vals). Co-authored-by: oxura <[email protected]>
…1513) lay_of's re-entry walk seeks one datatype, so a field stuck on DUMMY read as no re-entry: Nest<n> hiding Nest<1n+n> behind a family in a nested datatype was laid flat and lay_of overflowed the stack.
main's ty_holds now takes p as a datatype name too (#1438); a name predicate keeps the first-met arguments, as lay_of's re-entry check did. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
DUMMY is a Var, so every predicate took it as a hit and lay_at laid a
concrete Box<Num{}> open. Only wide needs an answer for every index;
lay_at, ty_value and lay_of keep the arguments first met, as on main.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
ReviewI found four problems. Line numbers refer to the PR head. Items 1–3 were reproduced by compiling small programs; 2 and 3 also happen on main 60ca80a, so this PR doesn't cause them, but it leaves them in place.
Item 1 is a regression and should be fixed before merging. 4 is the fix I'd suggest for 1–3 together. 🤖 Generated with Claude Code |
# Conflicts: # bend2/comp.ts
seen keys a datatype by its name and its normalized value arguments, so each instance's fields are looked into; a type argument already walked is skipped, and a walk 1000 calls deep or an index past 4096 characters answers that it holds. This drops the DUMMY opening and the any flag: Vec and Word keep main's answer, and lay_of and lay_holds no longer miss a second instance's re-entry (family_cyclic_two). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…56 (#1513) Normalizing an index expanded a big Nat into a Succ chain and overflowed term_lower, and a growing index ran into the cap, whose true boxed closed types and made wide true. The key is now the value arguments as written; past 256 instances of a family the walk opens it once more with DUMMY for them, and a walk 4000 calls deep holds. FL.vals is seeded before it is computed, so a kind that meets its own family again does not loop. family_cyclic_nested passed on main, so it goes; kind_reenter is new. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
FL.vals is seeded inside its memo, the depth cap joins the return, and the comment is shorter; behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…es (#1513) FL.tys flags type arguments, so its seed reads a family met again while its kinds are worked out as value-indexed, as its own answer will say (kind_reenter's d: D was a type argument). 64 instances per walk before the DUMMY opening, and a walk 5000 entries long instead of 4000 calls deep, keep growing families as cheap as main. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
@nicolas-abril thanks, this follows your item 4: |
…1513) Past 64 instances a family is opened with DUMMY, so a field computed from its index stays stuck; lay_of and lay_holds looking for a datatype by name read that as "absent" and could lay a recursive type flat until the stack overflowed. Once a walk widens, a stuck type counts as found. The depth cap is back (4000 calls), so a large flat type is not boxed for its field count. The FL.tys memo and kind_reenter go: the kind re-entry loop is main's, not #1513's, and comp.ts needs the tokens. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
Three repros against the PR head (59d3049), checked against main (042e797) with bun on macOS. Each one compiles to C with 1. A type-function argument uses up the widened key
|
Bx wrappers per link |
ty_value(B) |
main -o .c |
PR -o .c |
|---|---|---|---|
| 12 | true | stack overflow | builds |
| 70 | false (cap hit) | stack overflow | stack overflow |
To confirm the cause, I temporarily logged ty_value(B). With 70 wrappers the walk over B reaches d > 3999 and reports "holds", so ty_value returns false. b is then treated as a type argument, Hold<Fa{}, n> and Hold<Tr{}, n> share the key Hold<,n>, the second instance is skipped, and #1513's overflow is back.
The cap makes ty_holds report "holds" when it gives up, and ty_value negates that result. Here, giving up should count as a value argument.
3. A re-entry behind a call stuck on the family's own index (on main too)
import Base
def Cell(n: Nat) -> Data:
match n:
case 0n:
Nest<1n>
case 1n+p:
Nest<(2n + p : Nat)>
type Hold<-n: Nat> is Data:
Hold{value: Cell(n)}
type Nest<-n: Nat> is Data:
End{}
More{next: Hold<n>}
def read(t: Nest<0n>) -> U32:
match t:
case End{}:
7
case More{next}:
0
def main() -> U32:
read(End{})
#|7
The C build overflows the stack on both main and the PR. lay_of's generic walk sees Cell(n) stuck on Nest's own parameter. That isn't DUMMY, and nothing has widened, so the stuck type doesn't count as found. Nest<0n> is then laid flat and recurses through Nest<1n>, Nest<2n>, and so on. The PR doesn't cause this, but its list of known approximations doesn't mention it.
🤖 Generated with Claude Code
…#1513) Drops the DUMMY widening, the stuck-type rule and the depth cap that answered "holds": past 8 calls deep or 64 keys a walk falls back to main's once-per-name rule, so the bound never flips ty_value or turns a plain family wide. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
@nicolas-abril thanks. I've replaced the widening with a smaller rule.
The emitted C of every test, demo and bench is identical to main except 🤖 Generated with Claude Code |
… walked once with it unknown (#1513) Drops the 8-deep / 64-key bound: past it the walk fell back to main's name rule and missed later instances, so a big enough type still failed. A field stuck on the unknown index counts as holding, the safe side, and keys of bounded length keep the walk finite. New tests: wrapped (two instances under ten type arguments) and far (a closure at index 12 of a growing chain); both fail on main. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
nicolas-abril
left a comment
There was a problem hiding this comment.
🤖 Written by an AI agent for @nicolas-abril.
I looked into the slowdowns listed under "Known approximations" (Vec(5000n), the branching index). Two changes bring them back to about main's speed. The emitted C is byte-identical to this PR's head everywhere I checked. Both are in the two suggestions below. They also need one line in file_new, which is outside this PR's diff, so it can't be a suggestion: after holds: new Map<string, Lay>(), add
hold: new Map<string, boolean>(),compile_book, median of 5 runs |
main | this PR | + path fix | + cache |
|---|---|---|---|---|
Vec(5000n) (counting down, under a bang) |
34 ms | 776 ms | 62 ms | 57 ms |
32-way branching index (G<-n> with 32 fields G<(k+1n + n : Nat)>) |
6 ms | 78–148 ms | 80 ms | 13 ms |
Chromi examples/eco/main.bend |
8.00 s | 8.04 s | – | 8.01 s |
1. The path costs O(depth) at every step. The profile of Vec(5000n) puts almost all of ty_holds's time in on.some(...) and [...on, [t.k, xs]]. Each step scans and copies the whole path, so a 5000-deep walk is quadratic. The suggestion keeps, per family on the path, the shortest key of each value argument, and restores it on the way out. "Some ancestor's key is shorter" is the same test as "longer than the shortest", so re gives the same answers, and a step now costs O(arguments).
2. Walks repeat across calls. On the branching index, lay_at runs ty_holds from 37 roots that share subtrees. Together they open 1,098 instances, only 74 of them distinct (Eco: 7,171 opened, 1,373 distinct). The suggestion keeps each instance's answer in FL.hold, keyed by the predicate, the instance key and the path state on. The path state is part of the key because re depends on it. Not every answer is safe to keep:
- A
trueis always kept. - A
falseis kept only when the instance's fields met (inseen) nothing but instances opened under it. Its walk then never depended on anything outside it, so a fresh walk from it would answer the same.seennow numbers instances in opening order, andlowcarries the earliest one met back up. - An instance whose walk was cut short by an ancestor or an earlier sibling is not cached, because its
falsemay be provisional.
A predicate is keyed by String(p): the TypeScript text of the lambda in comp.ts, such as (t) => ty_tag(t, "Var App"). Nothing from the user's program goes into it. That's sound only while every predicate captures nothing, which holds for all three call sites today, and the comment says so. Named predicate functions would be sturdier but cost about 55 tokens, and with them comp.ts is over its cap.
Checks (on top of 1f5df71, macOS M-series):
- Emitted C: I compiled every
.bendundertests/,demos/andbench/in one process with this PR's head and with the suggestions. All 867 programs that compile give byte-identical C. The other 925 are tests meant to fail, and they fail with the same errors. - This PR's tests: all 10 pass as Metal binaries.
- Earlier repros: the two
Boxinstances behind a 64-key field and behind 7 wrappers still print 42. - repo: 54/54.
comp.tsis 65,996 ttok (cap 66,000). - Not run:
gates/test.tson the minis, CUDA, Linux.
🤖 Generated with Claude Code
…cache From @nicolas-abril's review: the path keeps each family's shortest value keys (O(arguments) per step instead of scanning and copying the path), and an instance's answer is kept in FL.hold when it holds or met only instances opened under it. Vec(5000n) and the branching index build at about main's speed. Co-authored-by: nicolas-abril <[email protected]> Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…on-tail recursion under ! no longer faults at 1023 frames (bendlang#1393, bendlang#1394) Today on main (de26a91, after bendlang#1809 reverted bendlang#1439), emit_fork emits WL_ROOM(N) before pushing each sequential continuation frame, and WL_ROOM(N) posts ERR_DEEP and returns 0 on DEVICE once a lane's 2048-word stack fills, faulting at 1023 frames of List.append (bendlang#1393) or on an unbalanced fork tree (bendlang#1394). bendlang#1439 (40402b4) replaced WL_ROOM(N) with WL_ROOM(N, D) calling a 4-argument lane_spill(e, sp, N, D) at every sequential call site while the caller segment's local variables were still live, followed by a second branch if (!(sp = ...)) { err_post(e.mem, ERR_DEEP); return 0; }, and added a separate unspill block in WL_CASE(FID_EXIT). That grew the device CFG at every WL_ROOM site (27 device sites in symreg, 8 in merkle) and slowed bend -o's --gpu-build step by 17% on symreg and merkle (bendlang#1809). This change moves the stack-room check to emit_jump, after the sequential frame push and after r0..rn are loaded (where all caller segment local variables are dead and the entire continuation frame is already on the stack below sp), and makes WL_ROOM(F) on DEVICE jump to one cold sp_spill: label at the bottom of switch (fid) in work_loop: - emit_fork removes WL_ROOM(fr.length) before STK(j) = w and passes push = true to emit_jump(sc, cargs, c.k!, !fork && c.b, true). No other emit_jump caller passes push = true, so tail jumps and self-tail loops without a frame push emit no WL_ROOM. - emit_jump with push = true emits WL_ROOM(seg_ref(sc, fid)) right after r0..rn are assigned, before WL_JMP or WL_AGAIN. Self-recursive calls in emit_fork still set sc.seg.spin = true and take WL_AGAIN on the normal path when the stack is not full. - Because WL_ROOM runs after STK(j) = w; WL_PUSHN(fr.length) and after r0..rn are loaded, all caller segment locals are dead and the caller's complete continuation frame sits below sp. In bendlang#1439, WL_ROOM ran before WL_PUSHN, so spilling at a second fork call (such as walk in tests/compile/bang_lane_spill.bend) split the earlier call's stack words from the new frame's words across the exit frame unless lane_spill took D and copied D words back above the exit frame. Emitting WL_ROOM after WL_PUSHN places the exit frame above the complete continuation frame, so lane_spill(e, sp) needs neither N nor D. - On !DEVICE, WL_ROOM(F) expands to nothing (host SEQ-CPU and PAR-CPU machine code is byte-for-byte identical). - On DEVICE, WL_ROOM(F) checks if (sp >= e.mem + STAT_OFF - 247 * CUBE) { fid = (F); goto sp_spill; }. Because comp.ts caps each continuation segment's parameter count at WIDE (247), a single frame push adds at most WIDE + 1 (248) words, so STAK_LEN - WIDE (1801 words) is a static watermark: starting below 1801 words, pushing a frame reaches at most 2048 words (STAK_LEN), and every word below sp belongs to a complete pushed frame. - At the bottom of switch (fid) in work_loop on DEVICE, inside default: after return 0;, sp_spill: sp = lane_spill(e, sp); calls FAR DEV Term* lane_spill(Env e, DEV Term* sp) at a single call site where only e, sp, fid, and r0..rn are live, then exits switch (fid) to loop back to WL_SPIN -> switch (fid) without placing a label before switch (fid). - In WL_CASE(FID_EXIT), unspilling shares the existing WL_ARGS + heap_free + WL_TAKE block with continuation dispatch under cont != TERM_HOLE && ((DEVICE && wf == FID_EXIT) || fid_resw(wf)), ending with if (DEVICE && wf == FID_EXIT) { WL_RETN(n); }. comp.ts goes from 66,000 to 66,268 ttok (+268 ttok, vs +283 in bendlang#1439; main is at the 66,000 cap after bendlang#1809 kept bendlang#1439's token cuts and bendlang#1542 used the 283 tokens).
Fixes #1513. Supersedes #1522 (its test is kept as
gpu_reach_closure_instances).The bug
ty_holdsopens each datatype once per walk, keyed by name, with the arguments it first meets. ForDuo{plain: Box<Num{}>, callable: Box<Fun{}>},Box<Num{}>is opened (its field isU32) andBox<Fun{}>is skipped, so the bang's closure check says "no closure" and the GPU build fails with "a function the device does not hold". The same skip makeslay_oflay a family flat and overflow when it re-enters through a second instance, and makeslay_holdspick a spine by argument order (@nicolas-abril's review).The fix
seenkeys a datatype by its name and theterm_keyof its value arguments, so each instance's fields are looked into, for every caller (wide,lay_at,lay_of,lay_holds,ty_value).A family can reach infinitely many instances (
Ch<n>with a fieldCh<1n + n>). When an instance re-enters its own family on the walk's path with a value argument whose key grew, the walk opens it once with its value arguments unknown (DUMMY), keyed by name. A field stuck on the unknown index (Pick(n)) is not an ADT, so thewideandlay_atpredicates count it as holding: the safe side. An index that does not grow (Vec(2n)counting down) stays concrete, so the C is the same as main's.The path keeps, per family, the shortest key of each value argument, so a step costs O(arguments), and an instance's answer is cached per file in
FL.holdwhen it holds or met only instances opened under it (@nicolas-abril's suggestions). A predicate is keyed by its text, which is sound while no predicate captures a variable (true for all three call sites).There is no constant: along a path, the concrete instances of a family have keys no longer than the first one's, so they are finitely many, and the unknown instance is opened once. The previous version's 8-deep / 64-key bound fell back to main's rule past it, so a big enough type still missed the closure; the two new tests show it.
Known approximations:
ty_valuehas no safe side (either wrong answer can hurt). In it, a field stuck on the unknown index also counts as holding, so a kind whose family grows its own index with an index-computed field reads as a type, not a value. No test or repro reaches this.lay_of's re-entry check reads the constructors' fields with the family's parameters free, so a re-entry behind a call stuck on the family's own index still overflows, as on main (@nicolas-abril's third repro of 10-21). Instances that differ only in a type-function argument still collapse, and a kind that re-enters its own family still loops, both as on main.comp.ts: 66,000 tokens (main 65,612, cap 66,000).Checks (merged with main 5ce1e07)
chain,instances,mutualandfamily_cyclic_two, which fail on main.wrapped(twoBoxinstances under ten type arguments) andfar(a closure only at index 12 of a growing chain). Both fail on main and on this PR's previous head with "a function the device does not hold".deep,grow,nestedandwrapcheck that the walk ends.Vec(5000n)builds in 0.14 s (0.9 s before the path and cache changes) and a 32-way branching index in 0.2 s.Vec(2n)bang emits the same C as main.Nestbuilds.More's spine row is{2,0,1}in both argument orders.Chwith 12, 70 and 300 wrappers builds and prints 9; main overflows.L<(k => Gr<k>)>lambda emits the same C as main.Not run: CUDA, Linux, Windows (GPU checked on Metal only).
Please squash-merge.
🤖 Generated with Claude Code