Repository navigation
feature/js-plains - #974
MattCozendey wants to merge 4 commits into
Conversation
8ff7eab to
c03b845
Compare
f1d114d to
b47bbd1
Compare
|
Since 2.0.17 (#860, 4033e90) import Base
def main() -> IO(Unit):
do IO<Unit>:
IO.print(Nat.show(Nat.min(Nat.mul(1000000000n, 1n), Nat.mul(1000000000n, 2n))))
|
b47bbd1 to
924362d
Compare
|
You were right, thanks. Since #860 made WSL, clang 18 -O3 and bun, medians of three, identical outputs; before is
The details are in the updated PR description, under section 3 and the new measurements table. |
There was a problem hiding this comment.
Thanks, this is a good change, and the measurements hold up here. We'd like to merge it once the one issue below is fixed and tests are added.
The intrinsics are correct. Every template matches its base.bend body, including F32's NaN and ±0 behaviour. On a cross-lane program covering NaN, ±0, the U32 extremes, every Bool combination, Bool.pick at String and Nat, and Nat near 10^12, this branch prints exactly what main prints on the interpreter, JS and C wherever main finishes. Where main overflows the stack, it prints the right values.
The issue: plain defs can recurse on the JS stack. The plain-def argument relies on "Bend has no mutual recursion and no forward calls". Since c64e021d, an @unsafe def can call a def written below it, and tests/run/unsafe_forward.bend has two that recurse into each other. Two defs that tail-call each other then both count as plain, so they call each other directly, one JS frame per hop. A tail call into a non-plain callee also became run_loop(call) in place of run_jump, which nests a frame per call and so also grows on a cycle.
import Base
@unsafe
def even(n: Nat) -> Bool:
match n:
case 0n:
True{}
case 1n+p:
odd(p)
@unsafe
def odd(n: Nat) -> Bool:
match n:
case 0n:
False{}
case 1n+p:
even(p)
def main() -> IO(Unit):
do IO<Unit>:
t : Nat <- IO.now()
IO.print(Bool.show(even(Nat.add(1000000n, Nat.mul(Nat.mod(t, 1n), 1n)))))
main prints True on every lane. On this branch the JS lane and bend file.bend stop with memory fault (machine stack overflow?); the C lane still prints True. It passes at 20,000 and fails at 100,000.
A fix we tested. A def is plain only if it is foreign, or every tail call in it reaches a plain def. A def that is still being evaluated counts as not plain, so any call cycle is not plain. Every non-plain callee keeps main's behaviour, and fl.def is no longer needed:
// A def is plain when its JS returns no $JMP: a foreign def, or one whose
// tail calls all reach plain defs. A tail self call, a tail closure and a
// def on its own call cycle (unsafe defs call forward) ride the
// trampoline, so a direct call never recurses through the machine stack.
function plain_of(c: Carb, k: Bend.Name): boolean {
const got = PLAINS.get(k);
if (got !== undefined) {
return got;
}
PLAINS.set(k, false);
const tld = def_body(c, k);
const out = tld?.$ === "Def" && (def_foreign(tld) || tld.h !== undefined
&& !term_any(c, tld.h as HTerm, (s, tail) => {
const ck = tail ? call_kind(c, s) : null;
return ck !== null && (ck.k === CLO_APPLY || !plain_of(c, ck.k));
}));
PLAINS.set(k, out);
return out;
} return v !== "" ? "(" + v + ") => " + call
: plain_of(fl, k) ? call
: tail ? "run_jump(" + js_sat(k) + ", [" + exprs.join(", ") + "])"
: "run_loop(" + call + ")";With it, the program above prints True on every lane and unsafe_forward still passes. The gains are kept on the JS lane (medians of three, bun, 10M steps):
| workload | main |
this branch | with the fix |
|---|---|---|---|
| chain of three small defs per step | 0.71 s | 0.30 s | 0.30 s |
U32 min/max, Bool.pick/and/not, Nat.min per step |
~41 s | 0.44 s | 0.44 s |
| a wrapper that tail-calls a self-recursive loop | 0.45 s | 0.37 s | 0.45 s |
The last row is the only cost: the in-place run_loop is what makes that shape faster, and it is the part that is unsafe on a cycle. Recovering it would take a real call-cycle analysis, which we don't think is worth it.
A smaller simplification. The six min/max entries are one pattern with a different comparison, so a helper can write them once:
// min and max as Base writes them, a Bool.pick over is_lt: a tie or a NaN
// answers min's second argument and max's first.
function sel_ops(pre: string, C: string): Record<string, Intr> {
return {
[pre + "min"]: { C: `(${C} ? $0 : $1)`, JS: "($0 < $1 ? $0 : $1)" },
[pre + "max"]: { C: `(${C} ? $1 : $0)`, JS: "($0 < $1 ? $1 : $0)" },
};
} ...sel_ops("u32_", "U32_BIN($0, <, $1)"),
...sel_ops("f32_", "f32_unbox($0) < f32_unbox($1)"),
...sel_ops("nat_", "$0 < $1"),For U32 this returns the original word, as Bool.pick in Base does, and it prints the same values on all three lanes.
Tests. The branch adds none. Please add:
tests/base/nat_min_max.bendfrom #1037, which we're closing in favour of this PR (Nat.min/max at 0, equal values, both orders and pairs near 2^40, through a template and a closure);- a cross-lane intrinsics test for F32 NaN and ±0, the U32 extremes and every
Boolcombination; - the mutual recursion above, so the JS lane keeps this depth.
Merged onto current main, the branch passes gates/repo.ts (46/46), and a local run of gates/test.ts gives 1439/1441, failing only the two display tests gfx_clicks and gfx_window. With the fix and the helper applied the result is the same. The cluster and GPU gates were not run.
A further suggestion, optional. The C lane compiles a def's self tail call as a loop (WL_AGAIN in its helper), but the JS lane emits return run_jump($f$, [...]) on every iteration. If js_def compiled a self tail call as a loop instead, a def could only return a $JMP through a closure in tail position or through a cycle of unsafe defs. plain_of would shrink to that check, nearly every def would be plain (loop defs included), and the per-iteration $JMP allocation behind your control row would go away. Hand-editing the emitted JS of a benchmark whose loop tail-calls a wrapper around a small self-recursive loop (3M steps) gave:
| emitted JS | time |
|---|---|
| as this branch emits it | ~0.43 s |
| the inner loop compiled as a loop | ~0.25 s |
| both loops compiled as loops | ~0.17 s |
One thing to watch: a loop must give each iteration fresh bindings for its parameters, or a lambda created in the body would see a later iteration's values.
Take this only if it pays for itself in size: the whole change should end up smaller than this branch's patch. Measured with ttok, as gates/repo.ts does, this branch adds 630 tokens to comp.ts (62215 to 62845), and the fix and helper above bring that to 522. If the loop emission plus the smaller plain_of fit under 630, it is worth doing here; otherwise, leave it for a follow-up.
Note: this review was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.
036e0b4 to
a79f452
Compare
|
Updated as requested! |
JS-only OPERATIONS entries for bool_and, bool_not, bool_pick, u32_min, u32_max, f32_min, f32_max, nat_min and nat_max: each mirrors its base.bend body exactly (pick c a b = c ? a : b; min = a < b ? a : b; max = a < b ? b : a, so F32's NaN answers follow is_lt, and Nat's Succ-peeling recursion becomes one BigInt compare). Before, each call cost a run_jump trampoline into the def and, for min/max, a second one into Bool.pick; now the ternary emits in place. The C lane is untouched: intr_of without js sees no JS-only entry, so fuse, spins and the borrow inference read the same book as before. Verified through WSL on the JS lane: a scratch program exercising every entry through variable and constant arguments prints the same value interpreted and emitted, and 14 tests (num_kit, nat_ops, list_ops, list_fold, list_kit, string_ops, text_ops, float_roundtrip, u32_divmod, rand, tuple_suite, bool_algebra, fold, readback_sugars) pass run and emitted-JS alike. The cluster gates did not run (no ssh from this machine). Co-Authored-By: Claude Fable 5 <[email protected]>
A def is plain when its emitted JS returns no $JMP: a self call or a closure applied in tail position rides the trampoline, so its callers must run_loop; everything else returns through the machine stack, whose depth the def DAG bounds, since defs never call forward. plain_of reads that off the body with term_any's tail flag (a closure body counts as tail, which only errs toward the trampoline). js_call then calls a plain callee directly, tail or not, so the JIT can inline it; a self tail call keeps run_jump, and a tail call to a trampolined callee absorbs its $JMPs with run_loop in place, one bounded frame. The C lane and the device read none of this. Verified through WSL on the JS lane: 73 tests across base, eval and io pass run and emitted-JS alike (three tests/run fails are the @unsafe stderr note the local runner merges into stdout; they fail identically on the parent commit), and a 10M-iteration loop over a three-def chain runs 1.14-1.42 s before, 0.45-0.54 s after, same output and RSS. The cluster gates did not run (no ssh from this machine). Co-Authored-By: Claude Fable 5 <[email protected]>
- Cycle-aware plain-def detection and safe tail calls. - Shared min/max selector helper. - Four regression tests covering both recursion forms, large Nats, NaN, signed zero, U32 extremes, and Bool combinations.
37690bb to
149bce0
Compare
|
@MattCozendey, following up on the review: we tried the loop suggestion and put the result in a draft, #1040. It contains your three commits unchanged, plus one commit on top:
On the JS lane it runs about 2 to 2.7 times faster than this branch on every benchmark we tried, and it adds 579 tokens to It's your PR, so tell us which way you'd like to go: pull the commit into this branch, or we continue on #1040 and close this one. Tests are still missing on both. The list from the review (#1037's Note: this comment was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself. |
|
Thanks, Nicolas. #1040 is the better base. It is smaller, and it reuses the I opened #1043. It contains #1040 unchanged, plus 2 commits:
JS lane, compared to #1040. The outputs are identical, and the memory use is the same:
The tests pass on the interpreter, JS and C. I did not run the cluster gates. If #1043 is good for you, it can replace both #974 and #1040. |
…d off the same Src walk as C's flat On top of bendlang#974. A def's tail self call is a loop (for (;;) with per-turn const bindings, so a closure keeps its turn's values), as the C lane's flat helpers loop with WL_AGAIN. carb_book's one walk records each def's tail callees in its Src beside deps; plain_of reads them with the same in-progress false guard as flat_of, so a def is plain when every def it tail-calls is: a closure has no source and a call cycle (unsafe defs call forward) is not plain. A plain callee is called directly, every other one keeps main's run_jump in tail position and run_loop elsewhere, so a 10^6-deep mutual tail recursion runs on the JS lane again. The PLAINS map, plain_of's own walk and js_call's foreign branch go; the min/max selectors are one sel_ops row per type and bool_and joins tpl_ops. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
From bendlang#974 (149bce0) and feature/js-cga: Nat/U32/F32/Bool selectors across lanes, unsafe tail cycles (plain and law), mutual tail jumps across arities, closures captured in a loop, and a tail call through a closure. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d off the same Src walk as C's flat On top of bendlang#974. A def's tail self call is a loop (for (;;) with per-turn const bindings, so a closure keeps its turn's values), as the C lane's flat helpers loop with WL_AGAIN. carb_book's one walk records each def's tail callees in its Src beside deps; plain_of reads them with the same in-progress false guard as flat_of, so a def is plain when every def it tail-calls is: a closure has no source and a call cycle (unsafe defs call forward) is not plain. A plain callee is called directly, every other one keeps main's run_jump in tail position and run_loop elsewhere, so a 10^6-deep mutual tail recursion runs on the JS lane again. The PLAINS map, plain_of's own walk and js_call's foreign branch go; the min/max selectors are one sel_ops row per type and bool_and joins tpl_ops. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
From bendlang#974 (149bce0) and feature/js-cga: Nat/U32/F32/Bool selectors across lanes, unsafe tail cycles (plain and law), mutual tail jumps across arities, closures captured in a loop, and a tail call through a closure. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d off the same Src walk as C's flat On top of bendlang#974. A def's tail self call is a loop (for (;;) with per-turn const bindings, so a closure keeps its turn's values), as the C lane's flat helpers loop with WL_AGAIN. carb_book's one walk records each def's tail callees in its Src beside deps; plain_of reads them with the same in-progress false guard as flat_of, so a def is plain when every def it tail-calls is: a closure has no source and a call cycle (unsafe defs call forward) is not plain. A plain callee is called directly, every other one keeps main's run_jump in tail position and run_loop elsewhere, so a 10^6-deep mutual tail recursion runs on the JS lane again. The PLAINS map, plain_of's own walk and js_call's foreign branch go; the min/max selectors are one sel_ops row per type and bool_and joins tpl_ops. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
From bendlang#974 (149bce0) and feature/js-cga: Nat/U32/F32/Bool selectors across lanes, unsafe tail cycles (plain and law), mutual tail jumps across arities, closures captured in a loop, and a tail call through a closure. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d off the same Src walk as C's flat On top of bendlang#974. A def's tail self call is a loop (for (;;) with per-turn const bindings, so a closure keeps its turn's values), as the C lane's flat helpers loop with WL_AGAIN. carb_book's one walk records each def's tail callees in its Src beside deps; plain_of reads them with the same in-progress false guard as flat_of, so a def is plain when every def it tail-calls is: a closure has no source and a call cycle (unsafe defs call forward) is not plain. A plain callee is called directly, every other one keeps main's run_jump in tail position and run_loop elsewhere, so a 10^6-deep mutual tail recursion runs on the JS lane again. The PLAINS map, plain_of's own walk and js_call's foreign branch go; the min/max selectors are one sel_ops row per type and bool_and joins tpl_ops. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
From bendlang#974 (149bce0) and feature/js-cga: Nat/U32/F32/Bool selectors across lanes, unsafe tail cycles (plain and law), mutual tail jumps across arities, closures captured in a loop, and a tail call through a closure. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ess, no new Src or File fields, and only Nat.min and Nat.max become intrinsics On top of bendlang#1043, which carries bendlang#1040 and bendlang#974. The same tail loops, with less machinery: - One Tarjan pass over each def's tail callees, self calls included (tail_loops), fills a JS-lane LOOPS map. Src and File are main's again: carb_book records no tails, and plain_of, Src's plain and loop and File's loop go. The loop being emitted is read off fl.seg.def, as C's emit_jump spots a self jump; a closure's segment has no def, so its tail calls never continue the loop. A self loop is the group of one, so js_def's second walk for it goes. - Every tail call into a def is a direct JS call. Tail cycles loop, so a direct tail call can reach its caller again only through a closure, whose run_tail still bounces on the trampoline: run_jump and the plainness fixpoint go. A non-tail call keeps run_loop. - Only nat_min and nat_max stay intrinsics, on both lanes: Base's are unary and recurse min(a, b) deep. The other selectors are cheap direct calls now, and their C side measured nothing (clang inlines them), so they go with tests/base/selector_intrinsics; tests/run/ unsafe_law_tail_cycle repeated unsafe_tail_cycle. JS lane under bun, bendlang#1043 -> this, ms: cycle3 175 -> 176, mutual2 282 -> 282, listacc 148 -> 149, wrapper 137 -> 140, fib 152 -> 157 (a non-tail call keeps run_loop), bounce 263 -> 118 (a tail call into a def that bounces a closure skips the trampoline); node shows the same. bench/runtime/hashmap 5303 -> 5296. Verified: every runnable test, demo and runtime bench through the JS lane under bun prints what bendlang#1043 prints (the removed tests aside); emitted C equals main's but for tests/base/nat_ops and num_kit (Nat.min and Nat.max), which pass; 10^6-step CPS, def/closure ping-pong, List.foldl and IO loops run; gates/repo.ts 46/46 (comp.ts 63446 ttok); tsc reports its 4 existing errors, none in comp.ts. The cluster gates did not run. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A def on a tail cycle, or tail-calling itself, is one JS loop: loop_of finds its cycle (Tarjan over tail callees, cached in LOOPS with the other per-book caches), and js_def emits `let $pc = <its case>; for (;;) switch ($pc)` with each turn's parameters bound afresh, so a closure keeps its own. A tail call into the loop being emitted (fl.seg.def names it, as in C) sets $i and $pc and continues. Every other tail call into a def is a direct JS call: tail cycles loop, so it can reach its caller again only through a closure, whose run_tail still bounces; run_jump goes. Nat.min and Nat.max become one tpl_ops row on both lanes (Base's are unary and recurse min(a, b) deep). Src and File are unchanged. JS lane under bun against the trampoline: a three-def tail cycle 841 -> 176 ms, two-def mutual recursion 895 -> 282, a closure bounce 265 -> 118, fib 316 -> 157. comp.ts +627 ttok. Tests: nat_min_max, js_group_args, js_loop_capture, js_tail_closure, unsafe_tail_cycle. Builds on #974 and #1043 by Mathews Fernando; supersedes #1040 and #1043. The cluster gates did not run. Co-authored-by: Mathews Fernando <[email protected]> Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The JS lane stops paying for calls: selector intrinsics + plain defs off the trampoline
Three changes to
bend2/comp.ts; the first two are invisible to the Cemitter, the device and the checker, and the third gives the C lane the same
templates (no base.bend, bend.ts or Lean surface is touched).
1. Selector intrinsics (b4ebc8b)
JS-only
OPERATIONSentries forbool_and,bool_not,bool_pick,u32_min,u32_max,f32_min,f32_max,nat_min,nat_max.Before,
U32.min(a, b)emitted a trampolined call into$U32$min$, whichtrampolined again into
$Bool$pick$— three frames and two$JMPallocations for one compare. Now the ternary emits in place.
Each template mirrors its base.bend body exactly:
pick c a b = c ? a : b,min = a < b ? a : b,max = a < b ? b : ais_lt, asBool.pickofF32.is_ltdoesNat.min/max's Succ-peeling recursion (O(min(a,b)) BigInt steps) becomesone BigInt compare
bool_pickstays JS-only because itsAis polymorphic; on native lanesno single word shape fits
2. Plain defs are called directly (8ff7eab)
A def is plain when its emitted JS can never return a
$JMP: no tailself-call and no closure applied in tail position. Every other return comes
back through the machine stack, whose depth the def call DAG bounds — Bend
has no mutual recursion and no forward calls.
js_callnow calls a plain callee directly (tail or not), so the JIT caninline it. A self tail call keeps
run_jump; a tail call into a trampolinedcallee absorbs its
$JMPs withrun_loopin place, costing one boundedframe.
plain_ofreads the property off the body withterm_any's tailflag; a closure body counts as tail, which only errs toward keeping the
trampoline.
3. The C lane gets the same templates (036e0b4)
As @jeromelaurens pointed out, since 2.0.17 (#860, 4033e90)
Nat.min/Nat.maxpeel successors in lockstep, and the C lane ran that recursion as written:
one continuation frame per successor, O(min(a, b)), so
Nat.min(10^9, 2*10^9)dies withbend: memory fault (machine stack overflow?). Clang can't recover the compare because the recursion goesthrough the runtime's work loop.
C templates now sit beside the JS ones for
nat_min,nat_max,u32_min,u32_max,f32_min,f32_max,bool_andandbool_not:nat_min/max:($0 < $1 ? $0 : $1), the same raw-word compare asnat_subandnat_is_ltu32_min/max: compare asU32.is_ltdoes ((u32)casts, likeU32_BIN) and return the operand normalized to 32 bitsf32_min/max: compare asF32.is_ltdoes (f32_unbox) and return theoriginal word, bit-identical to
Bool.pick, so NaN and ±0 behave as in Basebool_pickkeeps no C template: its untaken side may own a box to drop,and a wider
Aisn't one word, so the C lane keeps its matchOnly the Nat pair was a real cost;
U32/F32min/max are aBool.pickover
is_ltin base.bend, already O(1) on C, and their templates are forlane parity.
Measurements (WSL, bun, medians of three, identical outputs and RSS)
The control row is expected: a def that never calls anything gains nothing;
its costs (per-iteration
run_jumpallocation, BigInt Nat arithmetic) arefollow-up work, not this PR.
C and JS lanes after change 3 (WSL, clang 18 -O3 and bun, medians of three, identical outputs)
Before is
main; RSS is the median max RSS (/usr/bin/time).Nat.min(p, 100)+Nat.max(p, 50)per stepNat.min(p, 100)+Nat.max(p, 50)per stepBool.and/notper stepBool.and/notper stepNat.min(10^9, 2*10^9), one callNat.min(10^9, 2*10^9), one callThe C selector row is mostly process startup: clang already compiled the
Bool.pickmatch to the same compare. The report row ran once per side.Verification
variable arguments prints the same value interpreted and emitted.
tests/base,tests/evalandtests/iopass on boththe run path and the emitted-JS path.
tests/basetest agree across check, C and JS; five tests my localharness couldn't build fail the same way on
main.perf pins and the device lane still need the usual gate pass.
🤖 Generated with Claude Code