Skip to content

perf(rt): a hungry drain splits the oldest fork a sequential task has open - #2255

Closed
nicolas-abril wants to merge 81 commits into
bendlang:mainfrom
nicolas-abril:opt/par-split
Closed

nicolas-abril wants to merge 81 commits into
bendlang:mainfrom
nicolas-abril:opt/par-split

Conversation

@nicolas-abril

Copy link
Copy Markdown
Collaborator

Stacked on #2253, which is stacked on opt/integration (1bae016): this PR's own commit is 6938a7d6. comp.ts +3,465 ttok over #2253 (87,877 to 91,342). Measured on one Mac (M4, 4 P + 6 E cores), GPU off, under the shared lock; other processes held at most 2.0 cores during the A/B below. The cluster gates have not been run.

What

A drain runs each of its tasks in sequence on the thread that claimed it, and a task never moves. When one task holds most of a drain's work (one corner of an unbalanced fork tree), it runs on one thread while the others wait for the next turn. This is lazy task creation for the drain:

  • A two-call fork run in sequence notes its first call's frame on the thread's fork list (only threads of a pool with more than one; the test is a bit of seq, a register, so one thread pays a test and a branch per fork and its first continuation).
  • Threads past their claims hunt. While more hunt than tasks wait, a note turns the thread's oldest unsplit frame into a task, at most once per 20 µs of a thread: the fork's s segment reads the second call's arguments off that frame (as its first continuation would) into a task whose answer goes to a future, in a slot of the thread's box, and writes the fork's w segment into the frame's id word.
  • Returning there, w takes the task back and runs it, or waits for the thread that took it, running others' tasks meanwhile; then it continues as the first continuation would.
  • A drain still ends when its claims do: a claim waits for every task split off it. A hunter that finds nothing for a while sleeps until a task is boxed or the drain ends.

Without the 20 µs limit, bend-runtime/tree-bitonic split 3.3 million small frames at 10 threads and took 2,682 ms against 1,292; with it, 1,315.

Effect

Wall ms, median of 5, #2253 and this PR interleaved:

program 1 thr #2253 1 thr this PR 10 thr #2253 10 thr this PR
unbalanced fork tree (micro, item i holds 1/(i+1)) 2979 2983 1031 358 0.35x
bfs 957 953 307 298 0.97
delaunay 2972 2961 854 830 0.97
msort 1188 1186 202 198 0.98
bfs-tree-entangled-fixed 945 903 427 426 1.00
mcss / nearest-nbrs / triangle-count / primes / 1000 rounds of 64 leaves 0.99 to 1.00
seam-carve 965 966 284 297 1.05
one array forked per element (micro) 74 85 1242 1323 1.07
fib with a fork at every level (micro) 42 54 8 12 1.39

The unbalanced micro now scales 8.3x on 10 threads (2.9x before). The parallel-ml programs these were found in (primes, primes-simple-bool) do not gain: they run the same instructions at 10 threads as at 1 but 2.7x the user time, memory traffic (lanes of different primes unmark the same lines of a 400 MB array), not the scheduler.

Cost. Fine-grained forks pay the note and its drop: the fib micro (a fork every ~38 instructions) +31% at one thread (+4.7% instructions; the rest is the drop test in the first continuation, measured by removing it by hand), +39% at 10. Over the 244 bend-benchmarks programs at one thread, instructions against #2253: geomean 1.0016 over the 215 outside the set apart (the harness-hoisted 28, rbtree-ck), within this machine's run-to-run noise of up to 2.7%; above it: osprey/fib (bend-par) +6.5%, polybench/atax +5.1%, osprey/pascal (bend-par) +4.3%, polybench/bicg +3.9%. At 10 threads, wall geomean 0.980 over 157 programs above 0.1 s (one run each).

Checks

  • All 244 programs print expected.txt at 1 and 10 threads.
  • Native lane, 1,100 tests: no status differs from integration (952 pass, 25 FAIL, 123 that do not emit).
  • Memory check (-DBEND_POISON, live words) at 1 and 8 threads on the 117 tests that fork and the new tests: 0 live words but io/heap_large_reuse (65,536, as on integration).
  • Metal: the 53 ! tests built with bend -o, run with --gpu on, print the same as on integration; the notes are empty on the device.
  • New tests in tests/run/: lazy_split_deep (a fork chain 20,000 frames deep beside a filler tree, both sides), lazy_split_unbal (item 0 holds half the work), lazy_split_results (second calls returning a tree, a list and a pair), lazy_split_shared (one array forked to every leaf). Right at 1, 2, 4 and 10 threads, 3 runs each.
  • Wrong versions: splitting the newest frame (whose frame is not written yet), not waiting for a split task, reading the wrong answer word, a steal without its compare-and-swap: each gives wrong answers in the new tests. Not dropping notes exhausts memory (killed by the 4 GB cap). Never taking a task back, no 20 µs limit, and hunters that never hunt only change the speed.

🤖 Generated with Claude Code

nicolas-abril and others added 30 commits November 12, 2026 17:02
… a borrowed part of its argument

An Array.get of a boxed element reads the slot in place when its
consumer only lends the element; a write, a free or a hand-on of the
array while the element is live makes the read copy, as before. An
Array.set that stores the value read from the same slot moves it. A def
whose every result is a part of one borrowed parameter answers a
borrowed box.

hashmap: 2.41 s to 1.17 s on one thread. comp.ts is 68,402 ttok.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…y without the index masks

An Array index wraps, so every access masks it by the block's size, and
the mask keeps clang from reading and writing a loop's cells side by
side. A spin is now emitted twice when the index of an access to a
fixed array has a bound that can be computed before the loop: the copy
without the masks runs when every bound is under its array's size, the
copy as before otherwise. The bound is an interval over the operators
of U32 and Nat, a Nat countdown, a U32 counter and the conversions.

histogram: 1.572 s to 1.280 s on one thread. comp.ts is 69,018 ttok.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…t walks

A list of words (a String, a List<U32>, a chain of keys) was dropped
through term_drop's general path: each node joined the cur chain, its
fields were stepped one at a time, and it was freed on the way out. Such
a node now goes at once: when every field but the last is trivial, the
node is freed and the walk goes on with the last field. Order of frees
is unchanged, and a shared cell met on the way goes through the count
test at the top of the loop as before.

hashmap, one thread, GPU off: 18.50G instructions to 16.71G on main;
on top of bendlang#2135, 8.09G to 6.22G. tests/rfc/drop_list.bend spells the
shapes around the new path.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… loop that runs to the array's last cell

bendlang#2137 emits a spin a second time without the index masks when each
index has a bound fixed for the loop. Two shapes kept their masks:

- An access in a helper def the loop calls. The analysis and the
  mask-free copy now emit a helper's body in place of the call (a flat
  def that takes an Array and does not call itself, 32 a loop at most),
  so its accesses get the loop's checks. An array in a record or a pair
  is followed word by word, and a helper's result is the array it took
  only when every arm answers it.
- A loop over n cells from i: its counter was bounded by i0 + n0, one
  past the last index read, so a loop over a whole array failed its
  check. Under an arm that took k successors off the countdown the
  bound is i0 + c * (n0 - k).

An operator with an unbounded operand gives no bound, so a check that
cannot hold asks for no copy, and a spin's size class is read off its
masked copy alone, as on main.

Instructions retired, one thread, against bendlang#2137: editdist 49.74G to
36.88G, histogram 32.94G to 30.80G, terrain 43.83G to 41.15G; the
other benches the same. comp.ts is 70,103 ttok.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…nlined into the loop

clang inlines a static function with one caller whatever its size, but
one with several callers only under its size threshold, so a large
helper called from a hot loop and from elsewhere stays a call per
iteration. emit_spin now marks such a call with a statement attribute
(HOT, [[clang::always_inline]] on the host with clang 17+, nothing on
the device): the caller is in a tail-call loop, the callee is flat,
does not loop, has more than one call site and is over HOT_SIZE (1024)
terms with its flat callees included.

gameoflife, one thread: 172.4G to 145.7G instructions retired. The other
16 benches compile to the same object code.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… them has one target

A non-tail call pushes a frame that ends in its continuation's id, and
the callee returns by jumping through the segment table on that id.
When two arms of a def continue the same way after their calls, each
arm had its own copy of the continuation, so the return had two
targets and which one depended on the arm that made the call, a
subtree ago. Continuation segments whose text is the same but for the
names of their locals are now emitted once (to a fixpoint, since
fusing two may make the ones that push them alike). A fused segment
is compiled for the device if any of its copies was.

queens: 22.3G to 20.1G cycles on one thread, same instructions.
comp.ts is 66,251 ttok.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…urns' calls side by side

A loop over a Nat that calls, each turn, a second countdown loop over
words (mandelbrot's 64-pixel chunk runs 51 steps a pixel) is a chain of
dependent steps: the core waits on each pixel's multiply before the next.
The host now enters the calls of the next sixteen turns at once and steps
them a round at a time, a loop over lanes that clang vectorises; each turn
then reads its result. The outer loop must leave only at zero and pass
the call words fixed for the loop but the predecessor; the inner loop
must take and answer words, leave only at zero and count the same in
every lane (else each lane runs alone). A count clang knows, or one
under eight, leaves the loop as it was.

mandelbrot: 19.76G to 11.50G cycles on one thread (1.72x); gameoflife:
31.81G to 22.18G (1.43x). comp.ts is 68,071 ttok.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…o bound stays none

A Nat that is fixed for a loop and matched in it (`case 1n+p`) gave p
the bound of the whole word, so `a[x - from_nat(p)]` could pass its
check one short and write past the array: ix_word's `same` branch
ignored the successors the match took off. The branch is bendlang#2137's; the
word-by-word roles of the commit before made it reachable. The
successors now come off the bounds of any role.

Three more, found reading every place a bound is carried:

- A countdown past 2^32 saturates to 2^32 - 1, which stands for no
  bound; taking a successor off it made it a bound again (also in
  bendlang#2137). It stays 2^32 - 1.
- The same under the countdown floor of the commit before: a counter's
  steps have no bound when the countdown's entry value has none.
- An operator was known by its name alone, so a file's own
  `U32.is_far` had the bound of a comparison (also in bendlang#2137). An
  operator is now Base's def of that name.

tests/run/array_index_carry.bend runs each shape in range and out of
it; bendlang#2137 prints two of its 29 lines wrong and the commit before four.
The benches' instruction counts are unchanged. comp.ts is 70,235 ttok.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ator is Base's def

Two bounds that let an index out of range into the copy without masks,
so it wrote outside the array where main wraps:

- A countdown past 2^32 saturates to 2^32 - 1, which stands for no
  bound; taking a successor off it made it a bound again. With
  n = 2^32 + 5 the index (n - 1) - 4294967290 is 10 and the bound said
  4. It stays 2^32 - 1.
- An operator was known by its name alone, so a file's own
  `U32.is_far` had a comparison's bound of [0, 1]. An operator is now
  Base's def of that name.

tests/run/array_index_bound.bend gets both shapes, in range and out of
it, with counts the compiler cannot see; the commit before prints two
of the five new lines wrong. bfs and terrain change only in the bound
temporaries (same instruction counts); the other 15 benches emit the
same C. comp.ts is 69,093 ttok.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… tests its sign

heap_free compared the lane's word count with KEEP_WORDS, a static the
host sets at start, so every free loaded it and compared twice (six
instructions on arm64). The count now starts at ALC_NONE, which is
-KEEP_WORDS on the host and 0 on the device, and the hand-off test is
the sign of the count after the add. heap_hand and heap_alloc_miss set
the count from ALC_NONE; corpus_setup gives every lane's row its start.
The chains, the generations and the order of every allocation are
unchanged.

tests/io/heap_large_reuse.c builds its private lane rows with the new
start. tests/run/heap_generations.bend frees several generations of
three classes on one lane and across forked lanes.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
emit_unfold took a call whose constant arguments decide its matches,
but only into a flat def: its residue is an expression. A call in
statement position (a tail call, or the one a let binds, where ANF puts
every call into a def that is not flat) now unfolds into such a def
too. Its residue is a statement, so ANF cuts the calls it makes and
they unfold where they stand.

There, and only there: a flat argument folds to its end; an op on
constants is its constant (a U32 or a Bool, by the op's JS, as a match
table's cells are); a def with no match of its own unfolds if its
body's tail call does, and a residue's tail call unfolds in place; an
argument that calls a def not flat is bound first, so no later one is
held across it, and is typed by the arguments before it.

A call with no constant argument is not tried. A residue that forks or
bangs is refused, and so is one that keeps a call leading back to the
def unfolded (the constants must carry a recursion to its end, or it
would only be peeled). A try that fails gives its fuel back, and a def
whose unfold ran out of fuel is not tried again in that unit.

lexer's gen walks a literal template: its frames, its returns and its
slot dispatch are gone from a line (53.41G to 39.78G instructions,
8.44G to 6.51G cycles). symreg's gen(5n, h) builds its candidate
without a frame. The other 15 benches emit the same C.

tests/run/unfold_statements.bend and tests/run/unfold_generic.bend.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Base spells them Pair.fst and Pair.snd of Nat.divmod. Nat.divmod was already
native, but the generic Pair.fst / Pair.snd then dropped the unused half, and
a drop of a word of unknown type is a test (term_sink) that clang cannot
remove when it cannot bound the word: a remainder computed for nothing, two
compares and a branch per division. Both names are now C operations, the two
halves of Nat.divmod's own text. The JS lane and the interpreter still run
Base's defs.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
nat_mul tested for overflow with a 64-bit division on every call
(a > NAT_IMM / b). When both operands are under 2^32 the 64-bit product is
exact, so nat_chk alone holds it to 2^48-1; the division is kept for an
operand of 2^32 or more, where the product can wrap.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A segment that reaches no fork tested seq before each frame it pushed and
before each call, and carried the task path it never takes: FID_ENTER and
FID_EXIT set seq for a fork-free task, and a forking segment hands a
fork-free callee to a task of its own. WL_SEQ(F) is seq, or on the host
true for a fork-free segment, so clang drops the test, the task path and
the frame the path's calls forced on every entry.

The one such segment that ran with seq clear is a closure body entered
through a Clo~apply that may fork; it now keeps its frames on the stack
above the task's frame, as a fork-free task does.

symreg -15.8% instructions, queens -6.3%, lexer -2.8% (one thread, M4).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… a loop

Nat.add(e, f(..)) or 1n+f(..) in tail position was a non-tail call: a frame
on the heap stack and an indirect return per step, where C carries the sum in
a register (String.length, List.length, any count or digit sum written the
plain way). Such a call no longer keeps its def from being flat: the def's
spin holds the sum in acc, adds the other operand at the call and jumps to
itself, and adds acc to whatever it answers. Nats only grow under add, so a
partial sum in either order is at most the whole one and both orders stop at
2^48-1 together. C lane only.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A non-tail call pushes a frame and jumps to its callee; when the callee's
match takes an arm that returns at once, the callee pops the frame's id
and jumps back through the segment table. In a tree recursion that is at
least half of the calls. The call now carries the callee's returning
arms: after the frame is pushed and the arguments are in the registers,
an arm that neither calls nor jumps runs in place and jumps straight to
the continuation the frame names. Any other arm falls through to the
call as before.

segs_base copies the arms from the callee's emitted entry segment, so
they run the code the callee would have run on the same registers. Only
for a callee that calls itself twice on one path, on the host, where the
frame is on the stack.

On top of the fork-free sequential path, one thread, M4: symreg -4.5%
instructions and 12.43G to 8.18G cycles (medians of a 16-position sweep;
its C twin runs 9.01G); fib(42) 2.74G to 2.03G cycles, tak 9.75G to 6.11G.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A def that calls itself may make, on every turn, a call that reads only
parameters each self call passes back as they are (binarytrees' go builds
and checks the same tree 1,200 times). def_fix, run at the end of
file_book on the checked terms, takes the largest such call that yields
words and runs a def that loops or is not flat: the arm that holds it
binds it at the head of its statement and goes on in k~fix, a copy of the
def that takes the value as a last parameter and reads it where the call
was. The def keeps its body, so a loop that never reaches that arm never
makes the call, and one that reaches it makes it there.

Not taken: a call under a lambda, in a partial application, in an unused
let or an erased argument, inside a call the emitter unfolds, with a bang
or a foreign def in it; a result that is a box; and, in an @unsafe def, a
call that reads a parameter holding an Array or anything but datatypes (a
write through one handle shows through the others).

binarytrees (koru osprey kernel), one thread: 1,639M instructions and
71.9 ms to 13.6M and 1.2 ms. Of 980 programs under bench/runtime, demos,
tests and the koru kernels, 6 emit different C: the two binarytrees ports
and four tests. comp.ts is 68,310 ttok (cap 66,000).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A def that answers a Nat or a U32 and whose every call to itself, past its
tail calls, is an operand of a tail add goes on in d~acc, a second def that
takes the sum so far as its first parameter. The other operands join the
sum, each call takes it in turn and answers it grown, and the last call is
a tail call, so one call under the add is a loop and two or more keep every
call but the last. The add may be spelled with nested adds, successors on
either side, or a call bound by a let that is used once. d calls d~acc
with 0.

This replaces the loop-local sum of the previous commit (acc_of and its
four emitter sites) with one rewrite on the checked terms in file_book, C
lane only. Left as they are: F32, a def in a tail cycle with another def, a
call behind !, a fork's calls, and a def with a call to itself anywhere
else.

tests/io/stack_fault_trap.bend xors the result of its self-call before the
adds, so the recursion it needs to fault the stack stays one.
tests/run/nat_sum_loop.bend asks for twenty thousand steps, which the JS
lanes hold.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
On the C lane a tail-call cycle across defs was never flat: each def was a segment, a call into it from an expression a frame and a return, and its callers were not flat either. A cycle is now flat when one of its defs is a head (every other def is named once in the cycle), no def of it calls another in an argument, and their other callees are flat. The head's spin holds each other def's body in place of its call, by the path a tail call to a def with one call site already takes, and a call back to the head is the spin's jump. A def that is no head gets a spin that calls the head's. Base's String.contains, String.starts_with, String.eq, U32.show, Nat.show, U32.read, Nat.read, U32.hex, String.trim_start and Map.diff are such cycles; the JS lane already ran them as one loop.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…s too

seg_base walks the callee's entry as blocks: a test below the entry chain is
copied with its returning arms when the lines before it only name words (the
callee runs them again when no arm answers). An arm that drops a subterm
stays in the callee: the call to term_drop gave the segment it was copied to
a C frame on every entry.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Where a call gets its callee's returning arms, the store of the
continuation's id moves below them: an arm that answers jumps to the
continuation with the frame as a return would leave it. Not in the callee's
own entry, where the call closes a loop that clang then vectorises (tak ran
5.7% more cycles), and a call that gets no arms is emitted as before.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…led in a loop is force-inlined

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…her in a cycle run as one loop

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ies its sum in a parameter

Conflict in bend2/comp.ts after loop_of: bendlang#2188 adds loop_head and bendlang#2175 adds
acc_def at the same place. Both kept, loop_head first.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
nicolas-abril and others added 23 commits November 22, 2026 12:23
, bendlang#2198, bendlang#2203, bendlang#2205 and others)

Conflicts:
- comp.ts, nat_mul: bendlang#2174's draft against bendlang#2205 on main (the same test
  without its two != 0); main's text taken.
- bendlang#2173 landed on main in another form (base.bend: Nat.div / Nat.mod drop
  the other half of Nat.divmod as a Nat) from the draft merged here
  (comp.ts OPERATIONS entries Nat.div / Nat.mod, native C). Both auto-merged
  and computed the same thing; the draft's comp.ts entries are removed so
  the branch carries bendlang#2173 as merged, and tests/run/nat_div_native.bend
  (add/add) is main's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…literal 0

No conflict. The new commit changes acc_def's answer for an arm that is 0;
a775631's @unsafe flag on d~acc is untouched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e answers at once runs the continuation in place

No conflict. The three new commits (1dea074, 1dca6d1, c9575eb) rewrite
segs_base's text of an answered call; segs_fuse (with f67950b's key) runs
on the segments, not on this text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… non-tail call that does not read it

Conflict in comp.ts, emit_body's choice of the next form (bendlang#2217 against
bendlang#2162): bendlang#2162 tries emit_deep on a statement's call before anf, bendlang#2217 tries
let_sink on a let first. They apply to disjoint heads (emit_deep only to a
call, let_sink only to a let), so both stay: let_sink first, then bendlang#2162's
emit_deep-or-anf as before. let_sink only reorders total U32 lets past a
frame-pushing call; acc_def (bendlang#2175), def_fix (bendlang#2180) and bendlang#2177's call-site
returns rewrite defs before emission and see the lets as written.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…the node, inline take and wrap, recursive drop, lent flat defs

With e34e9ce (the use-after-free fix for an erased field). Conflicts, all
in comp.ts:
- emit_args (three hunks; bendlang#2207 against bendlang#2135): bendlang#2135 added `inl` (an
  inlined callee roots its borrowed parameters) and `slot` (an Array slot
  passed as a variable is owned); bendlang#2207 added `lend` (a flat def that does
  not loop is lent a box its caller still uses) and makes an owned
  argument's words the ones val_own answers (term_keep of a lent word).
  Both kept: the parameters are (jump, fork, inl, lend); an owned argument
  takes val_own's words except when inlined, where bendlang#2135 leaves it to the
  callee's body, as before. lend[i] is only computed for an argument that
  is not borrowed, so it never meets a slot or a borrowed root.
- emit_spin (bendlang#2207 against bendlang#2149, bendlang#2152, bendlang#2154, bendlang#2135): the in-place
  helper (bendlang#2149's ix_inl) passes no lend array, since it has no lent copy;
  the out-of-line spin computes lend and calls its lent copy, and keeps
  bendlang#2152's HOT prefix, bendlang#2154's lanes (which refuse a def with a box
  parameter, so never meet a lent copy) and bendlang#2135's ret_root.
- emit_open / emit_native (bendlang#2207 against bendlang#2135 and bendlang#2149, bendlang#2154): bendlang#2135's
  def_vals now takes lend (a lent parameter's rent is "+", before the
  borrowed key); emit_native is (sc, k, to?, lend), its unit key and name
  carry the lent positions as bendlang#2207 has them, and every one of bendlang#2149's
  passes opens the lent copy the same way (74e27d5's clear stays first).
- the C macros after FAR: bendlang#2152's HOT and bendlang#2207's NEAR, both kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ion first, and a match whose arms all re-form its node is no match

Conflict in comp.ts, file_new's fields (bendlang#2211 against bendlang#2154): bendlang#2154's cnts
and bendlang#2211's cols and etas, all kept. Not a textual conflict but one all
the same: bendlang#2207 and bendlang#2211 both add path_use, the same function word for
word; the second copy is removed. With that the tree is the same as
opt/match-columns-stacked (bendlang#2211 on bendlang#2207, 3051c63) merged with bendlang#2207's
fix e34e9ce.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… fields share a word when that drops its size class

Conflict in comp.ts, node_fields' reads (bendlang#2218 against bendlang#2207): bendlang#2207
takes a node with ctr_take only when its constructor is hot (a static one
is read in place), bendlang#2218 reads each field from its packed word. Both kept:
the word a field lives in is bendlang#2218's (slot, shift, bits), read from the
take's buffer when hot and from the node otherwise, as bendlang#2207 decides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d word

Interaction of bendlang#2207 and bendlang#2218. bendlang#2207 splits an arm that opens with a
match on the node's first field, an enumeration, and tests that field
through the reference as `(u32)e.mem[term_peek(e.mem, t)]`, word 0 of the
node. bendlang#2218 packs a node's U32 and tag fields into shared words when that
drops the size class, so for a 5-field Node{color, l, key, val, r} word 0
is `key | color << 32 | val << 34`: the split read the key's low bits as
the colour and took the wrong arm. Checked rbtree-shaped programs printed
wrong numbers on C (both drafts alone, main, JS and the interpreter agree).

The read of a field's word is now one function, node_word (slot, shift
and mask from node_pack), used by node_fields and by the split; for a node
that is not packed the split's C is unchanged. Tests
tests/run/mix_pack_split.bend (unique trees) and mix_pack_split_shared.bend
(shared, so ctr_take) fail without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mix_sink_calls: bendlang#2217's U32 lets that sink below a non-tail call, in a
tree recursion whose returning arms run at the call (bendlang#2177), in sum loops
of two and three self calls and one whose arm answers 0 (bendlang#2175), next to a
fixed call (bendlang#2180), a let the call reads (stays), and a parallel call.
mix_reform_slots: trees in an Array's slots (bendlang#2135: read borrowed, taken
and written back) walked by a selector-first lookup and insert (bendlang#2211),
split by colour and re-formed (bendlang#2207), lent to a flat def, with the node's
U32, Bool and colour in one word (bendlang#2218), in @unsafe helper cycles.
Both print main's numbers on C at 1 and 8 threads and on JS.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The types inside d's body name its params by level; acc_def put acc in
front without moving them, so List.length~acc read its list as
List<acc, a> and its eta wrapper named every param x at level 0. Either
made facts_hot add "open", which makes every bound type hot: raytracer
sealed every field of its V3, Cam and Box nodes. The body is lowered and
raised before acc goes in, and the wrapper takes T's names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A chain of && reads to clang as a branch taken once in 2^n: the mask-free
copy's calls fell under its cold-call threshold (45) and stayed calls.
seam-carve-index's row loop called spin_dist twice per cell where the
masked copy inlined and vectorised it. The checks are now and-ed with &.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rray skips the node walk

On the host term_keep inlines rfc_wrap (a41ad59), so blk_fill's keep loop
widened every blk_copy's frame (two more saved registers on each
Array.clone); the loop is now blk_keeps, out of line on the host. term_sunk
sends a non-constructor straight to term_drop instead of through rfc_last
and term_fall (two calls per array sink). fannkuch-redux clones and sinks a
16-cell array per permutation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n words

The arms copied above a call wrote their answer to r0.., which the path
where no arm answers still jumps with: clang merged the two into a select
before every miss (pascal's binom_k1: three more instructions per call
that the base case does not answer). The answer now goes to wb_r words.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…opy is entered by one test of all its checks

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…its params by their new levels

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ation takes the callee's answer in its own words

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lock keeps its cells out of line, a dropped array skips the node walk

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s 16 steps

A loop that runs a few steps paid the checks' arithmetic on every entry,
and the copy made its spin too large for clang to inline into its callers
(fannkuch-redux's step, at cost 340-370 for 325). The countdown is now
tested first and the checks are computed under that test: fannkuch-redux
37.65G instructions against 37.00G on the base (40.20G before), cycles
level; seam-carve-index 24.62G against 26.23G, editdist, histogram,
terrain and bfs as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…opy is entered only when its countdown allows 16 steps

Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	bend2/comp.ts
7f9912b sent a non-constructor to term_drop before rfc_last, which put a
tag test in front of every constructor's sink: hashmap +1.6%
instructions. The tag is read after the count instead; an array still
skips term_fall. hashmap 15.02G against 14.98G before 7f9912b (15.25G
with it), fannkuch-redux 37.14G (base 36.88G in the same run).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ay takes rfc_last's count first

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d task's sequence

A drain task runs in sequence. When it returned through FID_EXIT into a heap
continuation, the direct path kept the sequence bit, so that continuation
and every continuation after it ran with their forks inline: the rest of
the program on one thread. monk_step already runs a continuation it is
handed in turns; FID_EXIT now does the same on the host.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… open

A drain runs each task in sequence, so a task that holds most of a drain's
work (one corner of an unbalanced fork tree) runs on one thread while the
others wait for the next turn. Now a two-call fork run in sequence notes its
first frame on the thread's fork list (a seq bit, so a thread without one
tests a register). While threads that ran out of claims hunt and fewer tasks
wait than hunt, a note turns the thread's oldest unsplit frame into a task:
the fork's s segment reads the second call's arguments off that frame, as
the first continuation would, into a task whose answer goes to a future in
a slot of the thread's box, and puts the fork's w segment in the frame's id
word. Returning there, w takes the task back and runs it, or waits for the
thread that took it, running others' tasks meanwhile. The oldest frame holds
the largest part left. A drain still ends when its claims do: a claim waits
for every task split off it. An idle hunter sleeps after a while, woken by
a boxed task or the drain's end.

The micro benchmark with an unbalanced fork tree (item i of 1024 holds a
share 1/(i + 1)) goes from 1053 to 385 ms at 10 threads (2.86x to 7.81x of
its 3010 ms on one thread).

Tests: tests/run/lazy_split_{deep,unbal,results,shared}.bend.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rbmr

rbmr commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

ThreadSanitizer reports a data race that this PR adds. It's between task_node's plain store of a new task's cont word and task_deliver's trailing a32_acq(c) on a future's delivery counter, at the same address. The race report is the same for #2255's head (6938a7d, Linux x86_64, clang 21.1.8): 6 runs out of 6 at --threads 16. Main and #2253 show nothing in 6 runs each. Every run prints the right value. The PR's own tests/run/lazy_split_unbal, lazy_split_shared and lazy_split_results hit it too.

import Base

def leaf(+i: U32) -> U32:
  (i * 3 + 1 : U32)

def prog(+n: Nat, +i: U32) -> U32:
  match n:
    case 0n:
      leaf(i)
    case 1n+p:
      a b = prog(p, (i + 1 : U32)) prog(p, (i + 2 : U32))
      (a * 3 + b : U32)

def main() -> U32:
  prog(16n, 1)
bend t.bend -o t.c
clang -std=c11 -O1 -g -fno-omit-frame-pointer -fsanitize=thread t.c -lpthread -lm -o t
TSAN_OPTIONS="halt_on_error=0" ./t +RTS --threads 16 -RTS
WARNING: ThreadSanitizer: data race
  Write of size 8 by thread T12:
    #0 task_node       t.c:1305   e.mem[loc + ar] = cont;
    #1 WL_FID_prog_s1  t.c:1758   task_node(e, FID_prog, _fk_0, 0, 0)
    #2 fk_call / fk_poll / fk_note / WL_FID_prog / work_loop / fk_help / fk_wait / WL_FID_prog_w4
  Previous atomic read of size 4 by thread T6:
    #0 a32_load_acq    t.c:512
    #1 task_deliver    t.c:1327   a32_acq(c);
    #2 WL_FID_EXIT     t.c:2022

I read it like this.

  1. fk_poll makes a future with arity 1. Its counter, task_tail(fut) + 1, is word 2 of a four-word block.
  2. The last delivery takes the counter to 0 with a32_sub_rel. The waiter's acquire load sees 0, and the waiter reads the result.
  3. The waiter frees the future on its own thread with WL_FKFREE.
  4. That same thread's next lazy split takes the block back from its free list. It's the s segment's task_node for a two-argument def, so it writes cont at word 2, the old counter.

Meanwhile the delivering thread may not have run its trailing a32_acq(c) yet. Nothing orders that load before the plain store into the reused block. When I patch the emitted C so WL_FKFREE does nothing, the report goes away (0 of 10 runs, against 8 of 10 with the free).

The loaded value is thrown away, so I don't expect wrong results, and 2,222 runs printed the right output. It is still a C11 data race, of the same kind as #2079 and #2104. One fix that would close it: task_deliver doesn't read the counter after its last decrement. Either it takes the acquire before the decrement, or it uses an acq_rel decrement and drops the trailing load. Another is for the thread that makes the last delivery to free the future.

@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

Moved to nicolas-abril#34, which keeps it saved off the main queue until it can be accepted.

nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 24, 2026
Three conflicts with bendlang#2227, all kept both ways: emit_fork's constructor hole
(a single call; no fork) beside the lazy two-call fork note; the Dst~put and
Fk~fut entries; the WL_DEST and WL_FK* macros.

Co-Authored-By: Claude Opus 5.5 <[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.

2 participants