Repository navigation
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
Closed
costamatheus97 wants to merge 2 commits into
costamatheus97 wants to merge 2 commits into
Conversation
… 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.
Contributor
Collaborator
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_locreads it.blk_locreads the whole cell with a plain 64-bit load, whilerfc_bumpandterm_dropmove 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.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.
blk_locreads the cell atomically.__atomic_load_n).#if DEVICE, CUDA and Metal): the two halves, each through the file'sa32_load, recombined ashi << 8 | lo >> 24.rfc_viewalready 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.BLK_SHR 0, which is all 16bench/runtimeprograms) has this branch compiled out.Seg.moved.emit_jumpadds a param when the self-jump's argument for it is not the param itself (args[i] !== p).bind_popadds any local it re-binds throughterm_keep.spin_holdchecks each param of a looping spin (seg.spin) that is not inmovedand whose loc the body reads. It declaresLoc _bl_N = blk_loc(e.mem, p);beforeWL_SPINand uses that local for the reads.arr_op,arr_leafand thearray_atomic_*templates), and all three run before the spin's jumps are known.spin_holdtherefore 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
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 postedERR_RFCSinrfc_bump, so that run has failed anyway.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.&is&wpollinsideWL_SPIN.carb_book), so it has no fork or task that could hand the param elsewhere.blk_locof it is just its own loc bits, so hoisting it reads no memory.WL_AGAINasmusttail) isn't affected. Native spins always compile as aforloop.Endianness
The host path reads the whole word, so it has no endianness assumption. The device path takes
was the low half andw + 1as the high half, asrfc_viewandrfc_bump(which adds toa32_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
u64cells througha32_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.
Host read variants (histogram d22 b0 c1, 5 runs, ms):
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 1and--threads 16,--gpu off; 5 rounds; load 2.1 → 3.3)BLK_SHR 0, so the newblk_locbranch 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.blk_loc's dead branch, and the two binaries'.textsections are byte-identical. An isolated rerun (10–12 alternating runs each, load up to 10 from the runs themselves) gave:Verification
-O1 -g -fsanitize=thread,TSAN_OPTIONS='halt_on_error=0 exitcode=0',--gpu off):--threads 2, 3 runs each: main reports 1 race each run (blk_locagainstrfc_bump). Fix alone and this PR report none. All runs print4.--threads 2,4and16.11264.tests/reg/spin_array_hold(new) passes on check, interp, JS and C.swaptrades its two arrays each turn, so neither param is held and the reads stay per turn.tot.goholds its array, and so doesbump, which runs on a fork's shared handle (BLK_SHR 1) insidefan!.movedcheck removed, C prints1234/0instead of1030/204.gates/test.ts's rules on one machine, CPU lanes only,io_tcp_send_slow_peerexcluded): 1469 / 1473 on this branch against 1468 / 1472 onmain; the one extra test isspin_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) andio_process_runon interp and JS (its "inherited pipe" case).run_tests.sh(the package code unchanged, this compiler): 9 tests × check, JS, c1 and c16, plus the proof: 37 / 37.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.tsgoes 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
rfc_view's read,a32_atplus twoa32_loads in one expression. Metal'sa32_loadis a statement expression through a volatile local; CUDA's is a volatile 32-bit load.Loclocal before the spin'sfor (;;), and spins are already device code.fan!runs its leaves on the GPU. That is new coverage of the halves read there, and also where a Metal problem would show.