Skip to content

#624 Fix an ABA in the WAL commit buffer's back-pressure wait that wedged producers until their deadline - #646

Merged
nockawa merged 1 commit into
mainfrom
fix/wal-backpressure-aba
Aug 3, 2026
Merged

nockawa merged 1 commit into
mainfrom
fix/wal-backpressure-aba

Conversation

@nockawa

@nockawa nockawa commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #647

The first real catch from the macOS arm64 nightly (#624) — and it turned out not to be an arm64 problem at all.

The bug

A producer whose claim overflows the active WAL buffer parks in WalCommitBuffer.TryClaim until a swap gives it a fresh one. It waited on _activeBufferIndex:

while (_activeBufferIndex == bufferIndex) { ... _swapCompletedEvent.Wait(2); }

That index ping-pongs 0↔1. It is an ABA test on a single bit. A producer descheduled while two swaps complete finds the index back at the value it captured and goes on waiting for an edge that has already passed — twice.

Nothing recovers it. The only thing that advances the index is another producer overflowing the buffer, so once every live producer is parked that way the buffer sits drained and idle until each WaitContext deadline expires and throws WalBackPressureTimeoutException on a commit that had space available the whole time.

The frozen state from an instrumented run is the whole story:

swapState=SwapNormal  activeIdx=0  inflight=0
drainPos=58968  tail=58968        ← fully drained, 64 KiB buffer, nothing pending
prod=[0,151,303,3000,2879,0]      ← producer 3 finished; the other five wedged

Not arm64 — core count

It reproduces on x64/Windows under a 2-CPU affinity mask. The variable is core count, not architecture:

CPUs Result
1 passes (2 s) — strict serialisation always leaves another producer runnable to trigger the next swap
2 hangs — 20 s deadline burn
3 passes (91 ms) — a producer is rarely off-CPU across two whole swaps

The 16-core gate's hardware is precisely what hid this. The 3-core hosted macOS runner is what surfaced it.

The fix

Producers wait on _swapGeneration — a 64-bit monotonic counter incremented once per completed swap, sampled under the claim gate. The Dekker pair with SwapDraining guarantees no swap can complete between the sample and the park, so the sampled value is necessarily the generation the claim belongs to. PerformSwap increments it last — after the new index, the reset claim word and the folded LSN base — so observing a new generation implies observing everything it depends on.

A producer that backed out at the claim gate holding nothing no longer waits on a swap at all. It is owed none, and any generation it could sample is already racing the in-progress swap — the same missed-edge hazard through a different door. It waits only while _swapState == SwapDraining, then retries. Both arms of the predicate are edge-free by construction.

The loop's bounded _swapCompletedEvent.Wait(2ms) backstop did not rescue this and was never going to: a backstop caps a lost wake-up; a missed generation is not re-observable however often you re-check.

Also in here

  • The reporting bug. Both ThrowWalBackPressureTimeout call sites (WalCommitBuffer, WalWriter) passed ctx.Deadline.Remaining, which is TimeSpan.Zero by definition once ShouldStop is true — so the exception could only ever read timeout after 0ms. Deadline stores the expiry timestamp and not the start, so the waiter has to measure. Now Stopwatch.GetElapsedTime. This cost us the one number worth having every time the bug fired, and fixing it first is what made the rest of the investigation legible.
  • A correction. The WaitForData(5) added to this fixture's consumer in f4c7bef was credited with fixing these CI failures. It did not — it only narrowed the window. That comment is corrected rather than left to mislead the next reader.
  • WP-13 in claude/rules/durability.md (requires: WP-06), plus the same point in WAL-Design.md §4.5 where the ping-pong swap is introduced. check-rule-scopes.py passes. Docs pushed as Typhon-Claude@e4840ca.

Testing

BackPressureWait_ProducerLappedByTwoSwaps_IsNotStillWaiting drives two swaps deterministically and asserts the predicate directly, rather than trying to lose a scheduling race — reproducing the race needed a producer descheduled across two whole swaps, which never happens on a developer box.

Verified red against the old index compare (the producer is never released) and green against the fix.

Check Result
Pinned 2-CPU repro, the mask that hung was 5/8 failing → 10/10 then 6/6 green; 20 s → 45 ms
Full engine suite, Debug 4108 passed, 0 failed, 56 skipped
Full engine suite, Release 4108 passed, 0 failed, 56 skipped
check-rule-scopes.py all scope symbols resolve

🤖 Generated with Claude Code

https://claude.ai/code/session_01PDPx9FsFqDx3stceu2Rbv3

…dged producers until their deadline

A producer whose claim overflows the active buffer parks in WalCommitBuffer.TryClaim until a swap gives it a fresh one. It waited on `_activeBufferIndex`, which ping-pongs 0<->1 — an ABA test on a single bit. A producer descheduled while TWO swaps complete finds the index back at the value it captured and goes on waiting for an edge that has already passed twice. Nothing recovers it: the only thing that advances the index is another producer overflowing the buffer, so once every live producer is parked that way the buffer sits drained and idle (swapState=Normal, inflight=0, drainPos==tail, space available) until each WaitContext deadline expires and throws WalBackPressureTimeoutException on a commit that could have proceeded throughout.

Producers now wait on `_swapGeneration`, a 64-bit monotonic counter incremented once per completed swap, sampled under the claim gate — the Dekker pair with SwapDraining is what guarantees no swap can complete between the sample and the park, so the sampled value is necessarily the generation the claim belongs to. PerformSwap increments it LAST, after the new index, the reset claim word and the folded LSN base, so observing a new generation implies observing everything it depends on.

A producer that backed out at the claim gate holding nothing no longer waits on a swap at all — it is owed none, and any generation it could sample is already racing the in-progress swap. It waits only while `_swapState == SwapDraining`, then retries. Both arms of the predicate are edge-free by construction.

Found by the macOS arm64 nightly, and it is NOT arm64-specific: it reproduces on x64/Windows under a 2-CPU affinity mask. Core count is the variable, not architecture — 1 CPU passes (strict serialisation always leaves another producer runnable to trigger the next swap), 2 CPUs hang, 3 CPUs pass. The 16-core gate's hardware is exactly what hid it.

The loop's bounded `_swapCompletedEvent.Wait(2ms)` backstop did not rescue this and was never going to. A backstop caps a lost WAKE-UP; a missed generation is not re-observable however often the condition is re-checked.

Also fixes the reporting bug that cost us evidence every time this fired: both ThrowWalBackPressureTimeout call sites passed `ctx.Deadline.Remaining`, which is TimeSpan.Zero by definition once ShouldStop is true, so the exception could only ever read "timeout after 0ms". Deadline stores the expiry timestamp and not the start, so the waiter has to measure — now Stopwatch.GetElapsedTime over the wait.

The `WaitForData(5)` added to this fixture's consumer in f4c7bef was previously credited with fixing these CI failures. It did not; it only narrowed the window. That comment is corrected rather than left to mislead.

Test: BackPressureWait_ProducerLappedByTwoSwaps_IsNotStillWaiting drives two swaps deterministically and asserts the predicate directly, rather than trying to lose a scheduling race. Verified red against the old index compare (the producer is never released) and green against the fix.

Verification: pinned 2-CPU repro was 5/8 failing, now 10/10 and 6/6 green — 20s deadline burn down to 45ms. Full engine suite green in Debug and Release (4108 passed, 0 failed).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PDPx9FsFqDx3stceu2Rbv3
@nockawa
nockawa merged commit 3e7ca68 into main Aug 3, 2026
15 checks passed
@nockawa
nockawa deleted the fix/wal-backpressure-aba branch August 3, 2026 02:54
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.

WAL producers wedge until their back-pressure deadline — ABA on the commit buffer's ping-pong swap index

1 participant