From 950d4c0373d19d905eb89a521ff3d4c1e9910dea Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 10 Nov 2026 13:00:24 -0300 Subject: ring: a stale head is not a full ring emit compared a head loaded earlier with a tail read later: when other producers reserved and the consumer consumed in between, the tail was past it and the subtraction underflowed. A panic in safe builds (the ring's own thread test aborted twice in 200 runs; a debug agent in a threaded target would die the same way), a spurious wait otherwise. Saturating: not full, and the exchange that follows fails and reloads. Co-Authored-By: Claude Fable 5.2 --- src/trace/Ring.zig | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'src/trace') diff --git a/src/trace/Ring.zig b/src/trace/Ring.zig index 0bde33a..93b6314 100644 --- a/src/trace/Ring.zig +++ b/src/trace/Ring.zig @@ -126,8 +126,11 @@ pub fn emit(r: *Ring, ev: Event, payload: []const u8) void { } var at = h.head.load(.monotonic); while (true) { - if (at + need - r.seen_tail.load(.monotonic) > h.capacity) r.seen_tail.store(h.tail.load(.acquire), .monotonic); - if (at + need - r.seen_tail.load(.monotonic) > h.capacity) { + // A tail past `at` means `at` is stale (others reserved, and were + // consumed, since it was loaded): not full, and the exchange below + // fails and loads the head again. Hence the saturating subtractions. + if (at + need -| r.seen_tail.load(.monotonic) > h.capacity) r.seen_tail.store(h.tail.load(.acquire), .monotonic); + if (at + need -| r.seen_tail.load(.monotonic) > h.capacity) { if (h.lossy.load(.monotonic) != 0) { _ = h.dropped.fetchAdd(1, .monotonic); return; @@ -136,7 +139,7 @@ pub fn emit(r: *Ring, ev: Event, payload: []const u8) void { // between the check and the wait. const seq = h.space_seq.load(.acquire); _ = h.space_waiters.fetchAdd(1, .seq_cst); - if (at + need - h.tail.load(.seq_cst) > h.capacity) futexWait(&h.space_seq, seq, std.time.ns_per_ms); + if (at + need -| h.tail.load(.seq_cst) > h.capacity) futexWait(&h.space_seq, seq, std.time.ns_per_ms); _ = h.space_waiters.fetchSub(1, .monotonic); at = h.head.load(.monotonic); continue; -- cgit v1.3