Skip to content

A spin reads a shared Array's redirect once, atomically: blk_loc no longer races its count - #1084

Closed
costamatheus97 wants to merge 2 commits into
bendlang:mainfrom
costamatheus97:spin-redirect-once
Closed

costamatheus97 wants to merge 2 commits into
bendlang:mainfrom
costamatheus97:spin-redirect-once

Conversation

@costamatheus97

@costamatheus97 costamatheus97 commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #975.

Why

A fork's shared Array handle is a redirect: one heap cell holding the array's loc in bits 24..63 and a reference count in bits 0..23. Two things are wrong with how blk_loc reads it.

  • It's a data race (Shared Array redirect lookup races with atomic reference-count updates #975). blk_loc reads the whole cell with a plain 64-bit load, while rfc_bump and term_drop move the count with 32-bit atomics on the cell's low half. ThreadSanitizer reports it on the issue's repro. No Bend result was wrong: the loc bits never change while the reader holds its count. But in C the compiler is free to assume otherwise.
  • It's read on every access. A spin (a flat def's self-jumping loop) re-reads the cell on each Array.get/set/atomic of an array parameter, although the loc can't change during the loop. bend-parallel's counting sort spends most of its b=0 time on those reads.

What changes (bend2/comp.ts, +40 / −4; one new test)

Two commits. They review better apart, and the squash lands them together.

  1. blk_loc reads the cell atomically.
    • Host: one relaxed 64-bit atomic load (__atomic_load_n).
    • Device (#if DEVICE, CUDA and Metal): the two halves, each through the file's a32_load, recombined as hi << 8 | lo >> 24. rfc_view already reads the same cell this way on every lane. Metal has no general 64-bit atomic load, which is why the device can't take the host's path.
    • No acquire. The old read had none, and a fork's writes reach its join through the task counter, not through this cell.
    • A program whose Arrays are never shared (BLK_SHR 0, which is all 16 bench/runtime programs) has this branch compiled out.
  2. A spin reads a passed-back array's redirect once, before its loop.
    • What counts as "passed back as is": the emitter records which params it reassigns in a new Seg.moved.
      • emit_jump adds a param when the self-jump's argument for it is not the param itself (args[i] !== p).
      • bind_pop adds any local it re-binds through term_keep.
    • The hoist: after the body is emitted, spin_hold checks each param of a looping spin (seg.spin) that is not in moved and whose loc the body reads. It declares Loc _bl_N = blk_loc(e.mem, p); before WL_SPIN and uses that local for the reads.
    • Why the reads are rewritten by text. The reads come from three emitters (arr_op, arr_leaf and the array_atomic_* templates), and all three run before the spin's jumps are known. spin_hold therefore replaces that one exact spelling in the spin's own lines. The decision to hoist comes from the emitter's data, not from the text: there is no pattern-matching on assignments or &p.

Why the hoist is safe

  • The cell's loc bits never move. They are written once, in rfc_wrap. Afterwards only the count, in bits 0..23, changes, by 32-bit atomics. A count that would carry into bit 24 has already posted ERR_RFCS in rfc_bump, so that run has failed anyway.
  • The cell can't be freed or reused during the loop. The looping param holds a count, or its caller does for a borrowed param, and it passes the same handle back on every jump.
  • Nothing else changes the param inside a spin.
    • Array writes (array_set, swap, the atomics) happen in place and return the same handle. An Array is affine, so no copy-on-write produces a new one.
    • No emitter site takes a local's address. The only & is &wpoll inside WL_SPIN.
    • A spin is a flat def, and a flat def neither forks nor bangs (carb_book), so it has no fork or task that could hand the param elsewhere.
  • A handle that isn't a redirect costs nothing. blk_loc of it is just its own loc bits, so hoisting it reads no memory.
  • Where the hoist doesn't run. A spin compiled as a host segment's tail call (WL_AGAIN as musttail) isn't affected. Native spins always compile as a for loop.

Endianness

The host path reads the whole word, so it has no endianness assumption. The device path takes w as the low half and w + 1 as the high half, as rfc_view and rfc_bump (which adds to a32_at(r) as the count) already do. Every target Bend builds for is little-endian: x86-64 and arm64 hosts, NVIDIA GPUs and Apple GPUs.

Mixed-size access

On the host, a 64-bit atomic load overlaps the 32-bit atomic RMWs on its low half. ISO C11 doesn't define mixed-size atomics. The runtime already mixes sizes on these u64 cells through a32_at, though, and on x86-64 and arm64 an aligned 8-byte load is single-copy atomic. ThreadSanitizer treats both accesses as atomic and reports nothing. The plain read it replaces was an outright data race. I tried the device's two 32-bit halves on the host first (numbers below). It was race-free too, but 2–3x slower on histogram, because the compiler can't merge or hoist the atomic loads.

Measurements

The machine is an AMD Ryzen 7 5800XT (8 cores / 16 threads) under WSL2 (kernel 6.18), with AMD clang 22 (ROCm 7.2.1) at -O3. All runs are CPU-only (--gpu off): the machine's GPU is an AMD Radeon, which upstream has no lane for. It's a shared machine. I give the 1-minute load average with each table; the c16 runs themselves push it up. Builds were interleaved, with the order rotated each round, and every value is a median.

bend-parallel benches (sort, histogram, scan; ms per call; 5 rounds; load 0.6 → 4.4)

"fix" is commit 1 alone; "both" is this PR. The d=22 rows are single calls with 1 ms resolution.

case main fix both
sort d22 b0 c1 30 26 17
sort d22 b0 c16 30 25 18
sort d22 b6 c1 32 26 19
sort d22 b6 c16 10 9 8
sort d22 b12 c1 36 32 24
sort d22 b12 c16 18 18 14
sort d17 b0 c1 (8 calls) 0.75 0.63 0.38
sort d14 b0 c1 (64 calls) 0.109 0.078 0.031
hist d14 b12 c16 (64 calls) 4.16 4.94 4.08
hist d17 b12 c16 (8 calls) 4.38 5.25 4.25
hist d22 b0 c1 3 5 4
scan d22 b0 c1 3 4 2
  • The other scan and histogram rows are within 5% of main in both builds.
  • Checksums match across all builds and lanes.
  • The fix costs something on its own: the histogram rows above get slower. The hoist more than recovers it, and the PR lands as one squashed commit.
  • What's left: histogram at d=22 b=0 c1 is still about 1 ms over main (single-call rows). The reads are likely in spins that don't loop themselves and are called from another spin's loop, so the hoist doesn't reach them. The multi-call histogram rows at d=14 and d=17 are flat.

Host read variants (histogram d22 b0 c1, 5 runs, ms):

read ms
main (plain) 3–4
two 32-bit halves 9–11
one relaxed 64-bit load 4–6

With the hoist, sort d22 b0 c1 is 22–23 ms with halves and 17 ms with the 64-bit load.

bench/runtime (16 programs, --threads 1 and --threads 16, --gpu off; 5 rounds; load 2.1 → 3.3)

  • All 16 are BLK_SHR 0, so the new blk_loc branch is compiled out. The hoist fires only in bfs (2 spins), editdist (2) and terrain (3). The other 13 emit the same C as the fix alone.
  • 29 of 32 rows are within ±2% of main. raytrace c16 is −2.2% and tree-radix c16 −3.0%. All outputs are identical.
  • tree-bitonic c16 read +6% (2.152 → 2.275 s), which is noise. Its C under this PR differs from main only in blk_loc's dead branch, and the two binaries' .text sections are byte-identical. An isolated rerun (10–12 alternating runs each, load up to 10 from the runs themselves) gave:
    • main 2.168 s vs this PR 2.209 s (+1.9%);
    • then main 2.177 s, a byte copy of main 2.203 s, and this PR 2.137 s (−1.8%).

Verification

  • ThreadSanitizer (AMD clang 22, -O1 -g -fsanitize=thread, TSAN_OPTIONS='halt_on_error=0 exitcode=0', --gpu off):
    • Shared Array redirect lookup races with atomic reference-count updates #975's repro, verbatim, --threads 2, 3 runs each: main reports 1 race each run (blk_loc against rfc_bump). Fix alone and this PR report none. All runs print 4.
    • Larger variant: 1024 leaves, each a 40-turn atomic-add spin over the shared handle (hoisted), then one more add.
      • main reports 1, 2 and 3 races at --threads 2, 4 and 16.
      • Fix alone and this PR report none at all three.
      • Every run prints 11264.
  • tests/reg/spin_array_hold (new) passes on check, interp, JS and C.
    • swap trades its two arrays each turn, so neither param is held and the reads stay per turn.
    • tot.go holds its array, and so does bump, which runs on a fork's shared handle (BLK_SHR 1) inside fan!.
    • The test catches the bug. With the moved check removed, C prints 1234 / 0 instead of 1030 / 204.
    • The turn counts come from an array's size, so the compiler can't unroll the loops.
  • Local gate (gates/test.ts's rules on one machine, CPU lanes only, io_tcp_send_slow_peer excluded): 1469 / 1473 on this branch against 1468 / 1472 on main; the one extra test is spin_array_hold, which passes. The same 4 tests fail on both, for reasons outside this change: io_audio_only_{open,write,close} (this machine has no ALSA headers) and io_process_run on interp and JS (its "inherited pipe" case).
  • bend-parallel's run_tests.sh (the package code unchanged, this compiler): 9 tests × check, JS, c1 and c16, plus the proof: 37 / 37.
  • The structural rule makes the same decisions as a text rule. I also built an oracle with an earlier version of the hoist, which decided by string-matching the generated lines (p = rI;, rI = p;, &p). Over 336 programs (tests/reg, tests/run, tests/io, bench/runtime and bend-parallel), it generates byte-identical C to this PR's rule; 22 of those programs have at least one hoist.
  • bun gates/repo.ts: 46/46. comp.ts goes from 63,523 to 63,650 ttok (+127) with the fix and to 63,900 (+250) with the hoist, against a 64,000 cap.

Not run

  • CUDA and Metal were not compiled or run here (no NVIDIA or Apple GPU).
    • Neither lane gets a new construct: the device branch is rfc_view's read, a32_at plus two a32_loads in one expression. Metal's a32_load is a statement expression through a volatile local; CUDA's is a volatile 32-bit load.
    • The hoist adds one Loc local before the spin's for (;;), and spins are already device code.
    • On Metal, the new test's fan! runs its leaves on the GPU. That is new coverage of the halves read there, and also where a Metal problem would show.
  • The cluster, perf and GPU gates: not run.

… its count

A fork's shared Array handle is a redirect cell, its loc in bits 24..
and its count in bits 0..23. blk_loc read the cell with a plain 64-bit
load while rfc_bump and term_drop move the count with 32-bit atomics on
its low half: a C data race, which ThreadSanitizer reports on the bendlang#975
repro. The loc bits never change while the reader holds its count, so no
Bend result was wrong, but the compiler was free to assume otherwise.

The host now reads the cell with one relaxed 64-bit atomic load. A
device (CUDA, Metal) reads its two halves with relaxed 32-bit loads
(a32_load, as rfc_view does), since Metal has no general 64-bit atomic
load; on the host the halves cost 3x on a histogram whose reads the
compiler can no longer hoist. No acquire: the old read had none, and a
fork's writes reach its join through the task counter. A program that
never shares an Array (BLK_SHR 0) runs the same code. comp.ts +127 ttok.

Fixes bendlang#975.
A spin (a flat def's self-jumping loop) read blk_loc(e.mem, p) on every
access to an array param, a load of the redirect cell for a shared
handle. A param that each jump passes back as is (its tail argument is
p) and that is never kept (bind_pop's term_keep) holds its count through
the loop, and a redirect's loc bits are written only by rfc_wrap, so the
spin reads it once, before WL_SPIN, into a local. emit_jump and bind_pop
record the params they reassign (Seg.moved); spin_hold names the reads
of the rest. No emitter site takes a local's address, and a flat def
neither forks nor bangs, so nothing else changes p inside the loop. The
three emitters of the read (arr_op, arr_leaf, the atomics) run before
the jumps are known, so spin_hold replaces its exact spelling.

bend-parallel's counting sort of 2^22 keys at b=0 on one thread goes
from 30 to 17 ms. tests/reg/spin_array_hold: a spin that trades its two
arrays each turn holds neither; tot, and bump over a fork's shared
handle, hold theirs. comp.ts +250 ttok.
@VictorTaelin

Copy link
Copy Markdown
Contributor

Thank you! #975 is fixed in Bend 2.0.32 (573002f): every redirect read is two atomic halves (term_peek), which covers every reader and not only the spin. Closing as superseded.

@nicolas-abril

Copy link
Copy Markdown
Collaborator

Superseded by #1155: it takes #999's hoist as you suggested, reads the redirect with one relaxed 64-bit atomic on the CPU as you did (plainly on the device), and includes your tests/reg/spin_array_hold.bend. You're a co-author on the commit. Thank you!

nicolas-abril added a commit that referenced this pull request Sep 28, 2026
…c on the device, once per spin (#1155)

blk_loc reads a fork's redirect word through w64_load: one relaxed 64-bit
atomic on the host (the same load as a plain read) and a plain read on
Metal and CUDA, where rfc_view's atomic halves cost the shared-array path
4.5x; the target bits never change, so no read, torn or not, misses them.
A spin takes, beside each box word, the storage its caller resolved, and
a handle equal to the one it entered with reads that instead of the
redirect (#999). Tests: #997's race reproducer and #1084's
spin_array_hold. Fixes #975; supersedes #997, #999 and #1084.

Co-authored-by: uta080522 <[email protected]>
Co-authored-by: Matheus Costa <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Shared Array redirect lookup races with atomic reference-count updates

3 participants