Skip to content

Use atomic ring snapshots in row_grow - #2111

Draft
oxura wants to merge 2 commits into
bendlang:mainfrom
oxura:fix/2104-atomic-ring-snapshots-20261110
Draft

oxura wants to merge 2 commits into
bendlang:mainfrom
oxura:fix/2104-atomic-ring-snapshots-20261110

Conversation

@oxura

@oxura oxura commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Closes #2104.

row_grow now uses the existing relaxed a32_load helper for its ring-cursor snapshots. The production peer-writer race is on put: ring_push advances it while another row samples it. Existing slot publication and round-handoff ordering stay unchanged.

I found no peer get writer in the host scheduler paths checked here: grow bands and drain residues are disjoint, monk_step advances the owned cursor, and ring_rewind runs after the pool round joins. The get load stays atomic for consistent sampling. The harness deliberately advances get from its writer thread, so its second TSan report is counter stress, not evidence of a scheduler peer consuming the same row.

Locally on Linux, the portable harness below passes 8,192 real row_grow calls at each of strides 1 and 128 with no TSan reports; counters, slot data and published lap are checked. It includes Bend’s complete emitted C, not copied runtime functions. bun gates/repo.ts: 56/56. The compiler file is unchanged by this review follow-up (65,983 / 66,000 tokens).

YidaWeng’s updated independent macOS run applied a4974d57 to main d18110b6 on M2 Pro / macOS 27.2 / Apple clang 21, using the posted C11 recipe unchanged. Three unpatched runs each reported the real put race and the artificial get counter stress and exited 134; all three patched runs passed the assertions with no reports and exited 0. This is reviewer-reported evidence, not my own macOS run. Windows, GPU execution and mini-cluster gates remain unqualified; the PR stays draft.

Native reproduction

Save this as row-grow-race.c, then emit the runtime and compile it:

printf 'import Base
def main() -> U32:
  0
' > ring-input.bend
bun bend2/main.ts ring-input.bend -o runtime.c
clang -std=c11 -O1 -g -fsanitize=thread -fno-omit-frame-pointer -pthread '-DRUNTIME_SOURCE="runtime.c"' row-grow-race.c -lm -ldl -o row-grow-race
TSAN_OPTIONS=exitcode=66 ./row-grow-race

On unpatched 335f239a, the original Linux stress run reported the plain counter reads; the patched portable recipe exits 0 locally. With this C11 recipe, YidaWeng reports exit 134 for unpatched and 0 for patched on Apple silicon; TSAN_OPTIONS=exitcode=66 does not override the unpatched abort. The earlier barrier replacement was not evidence about this harness’s exit status. Check the reports and assertions alongside the exit code. The C11 release/acquire start flag avoids macOS’s missing pthread_barrier_*.

#define main bend_generated_main
#include RUNTIME_SOURCE
#undef main
#include <assert.h>
#include <stdatomic.h>

#define ITERATIONS 8192u

struct Run {
  u64* heap;
  _Atomic u32 start;
};

static void* publish(void* argument) {
  struct Run* run = argument;
  while (atomic_load_explicit(&run->start, memory_order_acquire) == 0) {}
  for (u32 i = 0; i < ITERATIONS; ++i) {
    ring_push(run->heap, 0, 0);
    a32_store_rel(ring_get(run->heap, 0),
      a32_load(ring_put(run->heap, 0)) - 1);
  }
  return NULL;
}

static void check_snapshots(u32 stride) {
  size_t bytes = (RING_OFF + (RING_LEN + 2) * LANES + CUBE_T) * sizeof(u64);
  struct Run run = { .heap = pool_mmap(bytes) };
  a32_store(a32_at(run.heap, H_ROOT_DONE), 0);
  a32_store(a32_at(run.heap, H_ERROR_CODE), 0);
  for (u32 i = 0; i < CUBE_T; ++i) {
    a32_store(ring_get(run.heap, i * stride), 0);
    a32_store(ring_put(run.heap, i * stride), 0);
  }
  ring_push(run.heap, 0, 0);
  ring_push(run.heap, stride, 0);
  pthread_t writer;
  assert(pthread_create(&writer, NULL, publish, &run) == 0);
  Term stack[STAK_LEN];
  Env environment = { run.heap, ALC[0] };
  atomic_store_explicit(&run.start, 1, memory_order_release);
  for (u32 i = 0; i < ITERATIONS; ++i) {
    assert(row_grow(environment, stack, 0, stride, 1, 0) == 0);
  }
  assert(pthread_join(writer, NULL) == 0);
  assert(a32_load(ring_put(run.heap, 0)) == ITERATIONS + 1);
  assert(a32_load(ring_get(run.heap, 0)) == ITERATIONS);
  assert(a32_load(a32_at(run.heap, H_ERROR_CODE)) == 0);
  u32* slot = (u32*)ring_slot(run.heap, 0, ITERATIONS);
  assert((a32_load_acq(slot + 1) >> 31) == ring_lap(ITERATIONS));
  assert(a32_load(slot) == 0);
  assert(munmap(run.heap, bytes) == 0);
  printf("stride=%u: %u real row_grow snapshots; ring counters and published lap preserved\n",
    stride, ITERATIONS);
}

int main(void) {
  check_snapshots(1);
  check_snapshots(CUBE_G);
  return 0;
}

AI-assisted.

@YidaWeng YidaWeng left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — the fix is right, and I re-ran your harness on the platform you couldn't.

Independent run: macOS arm64

Apple M2 Pro / macOS 27.2 / Apple clang 21.0.0, current main (f0ddfe7b). One portability change was needed: macOS has no pthread_barrier_*, so I replaced the barrier with an _Atomic u32 start flag (release by the main thread, acquire spin in the writer). Everything else is your harness as posted.

  • Unpatched: TSan reports two distinct races, one per read, both in the emitted runtime.c row_grow — the put0[i] = *ring_put(...) snapshot and the *ring_get(...) comparison (lines 1775 and 1776 of the generated C here). The harness's own assertions still pass.
  • Patched: no reports in three consecutive runs, 8,192 real row_grow calls at each of strides 1 and 128, with the final put/get counters, slot data and published lap assertions passing.

One macOS note for the recipe: this run exits 134 (abort) even with TSAN_OPTIONS=exitcode=66, so the exit code isn't the signal on Apple silicon — the two reports are.

That covers the macOS entry in your qualification list. I did not run Windows, the GPU lanes or the mini-cluster.

The change

Correct, and at the right strength. These counters are only sampled; the ordering that matters comes from the slot publication (a32_store_rel(lo + 1) / a32_load_acq) and the round handoff, so relaxed is what is wanted, and ring_push already reads get through a32_load. I also checked the two plain get reads you left alone — the drain loop at 4760 and monk_step's *get at 4452. Both read the calling row's own word, and pool_turn joins rounds before returning, so they don't need to change. Scoping the PR to row_grow is right.

One question on the second report

Can a thread other than the row's owner advance that row's get? I traced the paths I could find — row_grow always consumes base + i * stride; the drain branch consumes its own band (row + r % step, stepping by step inside row .. row + CUBE_T); the only other row_grow caller is cube_run, before the pool starts; and rounds are joined through pool_done — and I could not find one. If that holds, the second TSan report comes from the harness's writer advancing get itself, and the get half of the patch is defense-in-depth rather than a fix for a peer writer in the scheduler. I'd keep it either way (it is free and makes the snapshot atomic by construction); I'd just like the PR body to say which of the two reads has a real peer. If you know a path I missed, ignore this.

CHANGELOG

Is ## Unreleased the new convention? The history I see writes notes in the release commit (Bend 2.0.40), and the one recent non-release CHANGELOG edit (#1933) appended to the then-current release section. Happy to leave it if this has been agreed with Taelin; I just don't want to guess.

Size

65,974 → 65,980 ttok on current main (+6); your 65,983 on 335f239a is consistent. bun gates/repo.ts is 56/56 here.

Nothing blocking from me. With a mini-cluster run I would call it ready.

@oxura

oxura commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Yep, I found no peer get writer either. The body now calls out put as the production race and get as artificial counter stress; the atomic get read stays defensive.

a4974d57 removes the unagreed Unreleased section. The recipe now uses a C11 start flag, passes Linux/TSan at both strides, and notes Apple’s 134 exit. I credited your macOS run separately; mini, Windows and GPU stay unqualified, so the PR stays draft.

@oxura

oxura commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Can someone with access run the required mini gates on a4974d5? The documented cluster alias is unavailable here, and I also cannot access bendlang/bend-lang.com for the installer gate. I am keeping this draft rather than treating the local Linux checks as equivalent.

@YidaWeng

Copy link
Copy Markdown
Contributor

Re-ran the updated recipe, verbatim as posted, at the current head on macOS. It works there, and the exit code is usable after all.

macOS arm64, a4974d57 applied to main (d18110b6)

Apple M2 Pro / macOS 27.2 / Apple clang 21.0.0. No changes to the harness — row-grow-race.c copied from the PR body, built with your compile line.

build runs reports exit
unpatched 3 2 each 134
patched 3 0 0

Both strides pass the counter, slot and lap assertions in every run.

The two unpatched reports land exactly where you said they would:

  • write in ring_push (runtime.c:1138, the put advance) vs read at row_grow runtime.c:1775 — the real peer producer;
  • the harness's own a32_store_rel(ring_get(...)) (harness line 19) vs read at row_grow runtime.c:1776 — counter stress only.

So the split in the body is right, and on the emitted C as of d18110b6 those are still lines 1775 and 1776.

One correction to the note about Apple: the 134 in my earlier run came from my pthread_barrier_* replacement, not from the platform. With your C11 start flag the patched build exits 0 consistently, so on this harness the exit code is a fine signal — nonzero means reports, zero means clean. TSAN_OPTIONS=exitcode=66 still has no effect on Apple silicon (the unpatched run aborts with 134 despite it), but nothing needs it.

Size on the current head

main moved to d18110b6 (#2108), which took comp.ts from 65,974 to 65,938 ttok. With this patch it is 65,944, so +6 and 56 tokens under the 66,000 cap.

CHANGELOG

Resolved as far as I'm concerned. v2.0.40 was published 2026-11-06, and #1933 (b0df1666, 2026-10-29) appended a fix note to the already-released 2.0.39 section the same way, so adding to 2.0.40 is the established pattern and not an unreleased-section guess. (It will not show on the published 2.0.40 release page, but neither did #1933's.)

Mini gates

I don't have cluster access either, so I can't run them — the macOS harness, the size check and my review are all I can add. Staying draft until someone runs the mini gates is the right call. Windows, GPU lanes and the mini-cluster remain unqualified by me.

@oxura

oxura commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for rerunning the unchanged C11 recipe. I corrected the Apple note and linked your new d18110b + a4974d5 result separately from my Linux run: patched exits 0, unpatched aborts with 134 despite exitcode=66. Mini/GPU/Windows remain unqualified, so this stays draft.

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.

row_grow reads ring put/get with plain loads while other threads update put atomically (C11 data race)

2 participants