Skip to content

A shared array resolves its redirect once: a spin takes each box word's storage - #999

Closed
nicolas-abril wants to merge 1 commit into
mainfrom
shared-array-storage
Closed

nicolas-abril wants to merge 1 commit into
mainfrom
shared-array-storage

Conversation

@nicolas-abril

Copy link
Copy Markdown
Collaborator

Draft: this needs a decision on bend2/comp.ts's ttok cap before it can land (see Size below).

What this changes

With any Array shared, BLK_SHR is on and a handle is a redirect: blk_loc reads the handle's cell to find the storage. Clang cannot hoist that load out of a loop, because array cells are written through u32a, which is may_alias, so a cell store may be the redirect word. It does already merge the reads within one iteration, and it unswitches the rfc test when a handle is unshared at runtime, so what is left is one load per handle per iteration.

A spin now takes, beside each box word, the storage its caller resolved (q), and keeps the handle it was entered with (h):

INLINE Term spin_7(Env e, THR Term* o, ..., Term r2, Loc q2, Term r3, Loc q3) {
  Term h2 = r2;
  Term h3 = r3;
  ...
      at_0 = a == h2 ? q2 : a == h3 ? q3 : blk_loc(e.mem, a);

Once the spins are inlined, a handle a loop carries is visibly the same value as its h, so clang folds the test and the loop reads the redirect once instead of per access. A handle that matches none reads it as before, so a loop that swaps its arrays, or hands over one it built itself, stays correct. Segments that are not spins are untouched.

Three details each paid for themselves in a measurement:

  • A handle that is the spin's own word is tested against that word alone. editdist's DP rows swap every row, so the tests run for real; against every word they cost 2.3%.
  • The word keeps the handle it came with, rather than the back edge resolving the current one. Recomputing per iteration cost editdist 2.7% and bfs 4.9%, on loops that gain nothing.
  • With no Array shared the words take nothing. blk_loc is then a mask with no load, and the extra values only cost registers: 2.3% on editdist, 0.9% on bfs.

Measurements

Apple M4, one thread unless noted, cc -std=c11 -O3.

A scaled tests/run/stencil3d.bend (2^21 cells, 128 leaves, 160 passes: the GPGPU pattern, forked handles to one block, 7 gets and 1 set per cell):

lane before after
SEQ 530 ms 445 ms
PAR, 10 threads 119 ms 101 ms
Metal 7.18 s 1.31 s

The kernel loop keeps its 7 cell reads and no redirect load. I have no account of the Metal factor beyond the loads being global memory there.

Programs that share one array and run their hot loops over unshared ones: editdist 2.139 → 2.139 s, bfs 4.00 → 3.93 s.

Every bench in bench/runtime emits the C it emitted before, byte for byte, so the suite is unchanged by construction.

Tests

  • Every test under tests/ built and run on the C lane locally: 617 pass, the same set as main, and the same 9 tests/io and tests/run/nat_overflow failures on both.
  • The six tests whose programs share an Array (array_fork, array_fork_unshare, stencil3d, array_atomic_fadd, brw_audit2_array_field, brw_audit2_array_match) pass on Metal.
  • The cluster gates have not been run.

Size

comp.ts 64941 → 65174 ttok, over the 65000 cap in gates/repo.ts, so bun gates/repo.ts fails at 45/46. main sits 59 ttok under the cap. Every piece of the change was removed in turn and each one cost time, so the choice is to raise the cap by ~200 or to find that much elsewhere in the file.

One sharp edge

q is trusted when a handle is bitwise equal to h. A redirect's storage is written only by rfc_wrap, when the redirect is made, so it never moves while a handle holds it. The exception would be a spin that drops the last reference to its entry handle and then shares a new array whose redirect reuses that freed cell with the same bits. Safe Bend never copies an Array, so this needs @unsafe and a fork-free def.

🤖 Generated with Claude Code

…'s storage

With any Array shared (BLK_SHR), a handle is a redirect and every access
loads its cell to find the storage. Clang cannot hoist that load out of a
loop: array cells are written through u32a, which may_alias, so a cell store
may be the redirect word. A spin now takes, beside each box word, the storage
its caller resolved (q), and keeps the handle it came with (h); an access
through a handle equal to one reads its q, and clang folds the test wherever
the handle is visibly carried, so a loop reads the redirect once instead of
per access. A handle that matches none, or a segment that is not a spin,
reads it as before.

The scaled stencil3d (2^21 cells, 128 leaves, 160 passes) runs 530 -> 445 ms
on one thread, 119 -> 101 ms on ten, and 7.18 -> 1.31 s on Metal, on an M4.
A handle that is a spin's own word is tested against that word alone: the DP
rows of editdist, which swap every row, cost 2.3% otherwise. With no Array
shared the words take nothing, so every bench in bench/runtime emits the C it
emitted before, byte for byte.

comp.ts 64941 -> 65174 ttok, over its 65000 cap.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@ghost ghost mentioned this pull request Sep 23, 2026
@costamatheus97

Copy link
Copy Markdown
Contributor

I only found this draft after opening #1084, which overlaps it. Sorry for the noise. #1084 has two parts, and only the first is new relative to this PR:

  1. The Shared Array redirect lookup races with atomic reference-count updates #975 race. blk_loc reads the whole redirect cell with a plain 64-bit load while rfc_bump/term_drop move the count with 32-bit atomics on its low half. TSan reports it on Shared Array redirect lookup races with atomic reference-count updates #975's repro (1 race per run on main; 1/2/2 on a larger variant at 2/4/16 threads). A spin reads a shared Array's redirect once, atomically: blk_loc no longer races its count #1084's first commit makes the read atomic: one relaxed 64-bit load on the host, and rfc_view's two a32_load halves on the device. It isn't covered here, as far as I can tell.
  2. The hoist. It's the same goal as this PR, done at compile time: the emitter records the params a spin reassigns (Seg.moved) and reads the rest once before the loop. It covers less than this PR, since there's nothing for Metal or across calls, and your stencil3d Metal number is a much bigger win.

A data point that matters for whichever version lands: on its own, the atomic read makes unforked histogram (bend-parallel, 2^20–2^22 keys, b=0) 38–50% slower on this machine (Ryzen 5800XT, WSL2, 2.0.29). A hoist wins most of it back; with #1084's it ends at +14–18%, and sort 2^22 b=0 c1 goes 30 → 17 ms. So the race fix and a hoist probably want to land together.

I'm happy to fold the atomic read into this PR, or rebase it onto this branch as a separate commit, and drop #1084's hoist in favour of yours. Tell me which you prefer. I can also run bend-parallel's sort/histogram/scan drivers against this branch on x86, and there's a regression test in #1084 you're welcome to take: tests/reg/spin_array_hold.bend. It covers a spin that trades its two arrays each turn, plus holds over a fork's shared handle in fan!, and it prints the wrong answer if a swapped handle is ever held.

@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

Superseded by #1155, which carries this hoist ported onto current main, together with the race fix.

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]>
@nicolas-abril
nicolas-abril deleted the shared-array-storage branch October 1, 2026 13:48
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