Skip to content

Disable arr_loc redirect caching in spins that may free RFC cells - #2289

Open
EpsilonPhoenix wants to merge 2 commits into
bendlang:mainfrom
EpsilonPhoenix:fix/spin-arr-loc-reuse
Open

EpsilonPhoenix wants to merge 2 commits into
bendlang:mainfrom
EpsilonPhoenix:fix/spin-arr-loc-reuse

Conversation

@EpsilonPhoenix

@EpsilonPhoenix EpsilonPhoenix commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

User-visible failure

When compiled to native C, programs that drop or split an RFC-wrapped Array inside a flat (spin_*) function and then allocate/wrap a new Array of the same size class can silently read the wrong array's elements (Array.get) and silently corrupt another live array's backing storage (Array.set).

This reproduces both in 100% pure, safe Bend (passing bend --verdict, via rfc_seal when BLK_SHR == 1) and in Array.fork + Array.join code.

Root cause

Commit ef66a7cc (#1155) caches the resolved data location q{i} for each box parameter r{i} of a spin_* function at entry (Term h{i} = r{i};) and rewrites blk_loc(e.mem, a) in arr_loc to:

a == h0 ? q0 : blk_loc(e.mem, a)

This assumes that any later Array handle a with the same 64-bit Term bits as h{i} still points to q{i}. When h{i} is an RFC-wrapped Array (term_rfc(h{i}) == true), that invariant breaks if the spin_* function (or a spin_* callee) frees r{i}:

  1. Dropping/splitting r{i} (term_sink, blk_free, blk_half, blk_node, or a freeing spin_* callee) returns its class-0 RFC redirect cell r to the lane's LIFO free list and its backing block old_loc to its size-class free list.
  2. Subsequent allocations place another array pad at old_loc, a new array b at new_loc, and wrap b in an RFC cell (rfc_seal or Array.fork), which pops the same class-0 cell r.
  3. The new handle b1 now has identical 64-bit Term bits to h0, yet points to new_loc != q0 (old_loc).
  4. arr_loc matches b1 == h0 and returns stale q0 (pad's backing storage), causing Array.get to read pad and Array.set to overwrite pad.

This also occurs across self-tail-loops (WL_AGAIN) when a spin_* drops its Array parameter and loops with a recycled RFC-wrapped handle (so merely restricting arr_loc to p === i is insufficient).

Minimal change

  • bend2/comp.ts (term_same, commit 1): remove the redundant hand-written recursion over Lam, App, Ctr, and Mat that duplicated Bend.term_lower, keeping the fast short-circuit on x === y || x.$ !== y.$ || (x.$ === "Ctr" && x.k !== y.k). Saves 156 tokens (65,989 -> 65,833) so the fix lands in the file's normal style with 87 tokens of headroom (65,913 / 66,000).
  • bend2/comp.ts (arr_q, arr_loc, emit_spin, emit_native, commit 2):
    • Track a "free" fact per spin_* in c_units()'s existing fixed-point loop whenever a spin_* takes at least one "box" parameter (seg.ks.includes("box")) and either emits an array-RFC-freeing helper (/term_sink|blk_(free|half|node)/) or calls another spin_* in seg.refs with fact("free", r).
    • Pass the spin's fid to arr_q(k, f) so spins with fact("free", f) omit Term h{i} = r{i}; / , u64 q${i} and always resolve blk_loc(e.mem, a) freshly (including when passing q into a non-freeing leaf spin_*).
    • Requiring seg.ks.includes("box") is sound (a spin with no boxed parameters cannot decrement a caller's RFC refcount) and preserves #1155 caching on hot non-freeing loops such as spin_array_hold and bench/runtime/histogram.
    • Generated C is byte-for-byte identical to main everywhere except the spins that lose their h/q cache.
  • tests/reg/spin_array_reuse.bend (100% safe Bend, passes --verdict): covers direct drop (term_sink), self-tail-loop (WL_AGAIN), transitive freeing spin_* callee + non-freeing leaf callee, ANode match (blk_half), and ALeaf match (blk_free), checking both Array.get reads and Array.set non-corruption of pad.
  • tests/reg/spin_array_fork_reuse.bend: covers the Array.fork + Array.join reuse path.

Before / after evidence

On tests/reg/spin_array_reuse.bend (main at 3d5bf43d):

  • Before fix (native C silently reads pad and overwrites pad on all 5 cases):
    2
    111333 333
    444333 333
    666666 666
    901903 903
    801803 803
    
  • After fix (--verdict: ALL PROOFS CHECK; Bun JS, Node JS, native C -O3 & -DBEND_POISON, --threads 1 & --threads 4 all match):
    2
    222333 111
    555333 444
    777777 666
    902903 901
    802803 801
    

On tests/reg/spin_array_fork_reuse.bend:

  • Before fix (native C): 111333 333
  • After fix (Bun JS, Node JS, native C -O3 & -DBEND_POISON, --threads 1 & --threads 4): 222333 111

Hot-loop caching & output preservation:

  • tests/reg/spin_array_hold.bend and bench/runtime/histogram/main.bend: emitted C only changes on the freeing spins; all hot non-freeing loops (spin_bump, spin_tot_go, spin_swap, spin_col_go, spin_grp_go, spin_cols_go, spin_count_go, spin_zero_go, spin_fill_go, spin_sum_go) are byte-for-byte identical to main.
  • bench/runtime/lexer/main.bend: emitted C and JS are byte-for-byte identical to main (and JS is byte-for-byte identical across all 36 bench/runtime/* + match/u32/f32/nat/char tests).

Validation & limits

  • Verified on Linux x86_64 (bun 1.3.12, node v24.14.1, clang 23.1.5, Lean v4.34.0):
    • bun gates/repo.ts: PASS: 56 / 56 (bend2/comp.ts: 65,913 / 66,000 ttok, -76 net from main).
    • tests/reg/spin_array_reuse.bend (--verdict, Bun, Node, C -O3 & -DBEND_POISON, --threads 1 & --threads 4), tests/reg/spin_array_fork_reuse.bend, tests/reg/spin_array_hold.bend, and all 20 runnable tests/run/*array*.bend tests on native C.
  • Not verified: macOS / Mac-mini cluster (gates/test.ts, gates/perf.ts), Metal, and CUDA device lanes.

@nicolas-abril

Copy link
Copy Markdown
Collaborator

The fix is right: both new tests reproduce on main, and histogram's time doesn't change. We can't merge it yet, though, because comp.ts doesn't have the tokens for it.

  • main is at 65,989 of the 66,000 cap now that Substitute call arguments into emit_unfold let type annotations #2288 is in, so there are 11 tokens of room.

  • Written in the file's usual style (one declaration per line, braced ifs), the fix needs about 66. The line merging and braceless ifs used here to get under the cap don't match the code style, so we don't want those. That includes the compaction commit I pushed here (7edd5cc).

  • I tried trimming in and around the fix:

    • Only term_sink, blk_free, blk_half and blk_node can free an array's RFC cell, so narrowing the regex to /term_sink|blk_(free|half|node)/ is more precise and saves 3 tokens.
    • Dropping the seg.ks.includes("box") guard saves 9, but histogram gets about 40% slower (1.36 s to 1.95 s): helper spins get marked and the mark spreads to the hot loops.
    • The check through callees (seg.refs) is needed for correctness.

    That still leaves it about 55 tokens over.

So this needs about 55 tokens of real simplification somewhere else in comp.ts before it can land, or a cap change, which only Taelin decides. I'm leaving it open until then.

@EpsilonPhoenix

Copy link
Copy Markdown
Contributor Author

Thanks for the clear review! Rebased cleanly onto main (3d5bf43d) in two commits, removing all declaration-merging / braceless-if compactions (including 7edd5cc8):

  1. fb7c88d6 (refactor(comp): delegate term_same to Bend.term_lower): drops the redundant hand-written recursion over Lam, App, Ctr, and Mat in term_same (already handled by Bend.term_lower), keeping the x === y || x.$ !== y.$ || (x.$ === "Ctr" && x.k !== y.k) fast path. Brings bend2/comp.ts from 65,989 to 65,833 ttok (-156 tokens) with byte-for-byte identical JS across all 36 bench/runtime/* + match/u32/f32/nat/char tests and byte-for-byte identical C (and slightly faster compile time) on bench/runtime/lexer/main.bend.
  2. a4c2aa45 (Disable arr_loc redirect caching in spins that may free RFC cells): writes the fix in the file's normal style (one declaration per line, braced ifs, unchanged emit_spin block structure) with your narrower /term_sink|blk_(free|half|node)/ regex. Emitted C on spin_array_hold and histogram now differs from main only on the freeing spins.

Final bend2/comp.ts count: 65,913 / 66,000 ttok (-76 vs main), bun gates/repo.ts passes (PASS: 56 / 56), and spin_array_reuse (--verdict, Bun, Node, C -O3 / -DBEND_POISON, --threads 1 / 4), spin_array_fork_reuse, spin_array_hold, and all 20 runnable tests/run/*array*.bend tests pass.

rbmr added a commit to rbmr/bend that referenced this pull request Nov 24, 2026
facts_hot never gets a null type, row_val never sees a Bool cell, js_def
never gets an intrinsic, and the JS lane never reads fuel. anf calls the
existing ty_all. The emitted C and JS are byte-identical on every test.
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