Repository navigation
Handle spurious wakeups in sync primitives and select - #232
Conversation
Test demonstrates that canceling a task while it's in a shielded sleep causes a spurious wakeup and assertion failure. The cancel() unconditionally wakes the task, but waitForIo doesn't handle spurious wakeups when shielded.
When a shielded task is canceled while waiting for I/O, it gets woken up but the cancel is ignored (due to shielding). This caused an assertion failure because the code assumed any wakeup meant completion. Fix by: 1. Tracking whether completion was already added to avoid re-adding 2. Checking completion after setting state to .preparing_to_wait to handle the race where completion happens while in .ready state 3. Looping on spurious wakeups instead of asserting
The Waiter abstraction now: - Tracks signaled state with atomic bool - Provides wait() that handles spurious wakeups internally by looping - Provides waitUncancelable() for waiting with shield (used after removal from queue) - Refreshes executor on each iteration (may change after cancel/reschedule) ResetEvent.wait() updated to: - Use waiter.wait() instead of manual yield - On cancel: if removed from queue by set(), wait for signal completion before destroying stack-allocated waiter (prevents use-after-free)
Moved Waiter from sync/common.zig to common.zig and updated it to: - Take *Runtime in init() and get current task automatically - Provide wait() and waitUncancelable() methods with spurious wakeup handling Updated all sync primitives to use the new Waiter pattern: - waitForIo: simplified using waiter.wait() instead of manual loop - Notify, Mutex, Condition, Signal: use waiter.wait() and waitUncancelable() - All now handle spurious wakeups (e.g., cancel while shielded) correctly - Cancel paths properly wait for signal completion before destroying waiter Deleted sync/common.zig as it's no longer needed.
Add timedWait() and callback() methods to Waiter, then migrate all sync primitives to use the simplified pattern: - ResetEvent: Use waiter.timedWait() instead of AutoCancel + yield - Notify: Same migration - Condition: Same migration - Futex: Implement wait() directly using Waiter.wait(), migrate timedWait, embed Waiter in FutexWaiter, use waiter.signal() in wake() The new pattern determines timeout vs signal winner by attempting to remove from the wait queue after waking, rather than checking timer state.
Replace manual task.state + executor.yield pattern with waiter.wait() in both channel implementations. The new pattern handles spurious wakeups internally and properly waits for signal completion on cancellation before destroying the stack-allocated waiter.
📝 WalkthroughWalkthroughAdds a runtime-bound public Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Add proper spurious wakeup handling to select(), selectAwaitables(), and waitInternal() following the same pattern as Waiter.wait(): 1. Set state to preparing_to_wait at the start of each loop iteration 2. Check completion condition after setting state (handles race) 3. Yield 4. Check completion condition again 5. If not complete, loop (spurious wakeup)
31f25a3 to
e7fe6d0
Compare
SelectWaiter now takes a *Waiter parent instead of *WaitNode, and signals the parent Waiter when winning. This allows select(), selectAwaitables(), and waitInternal() to use Waiter.wait() instead of duplicating the spurious wakeup handling loop.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/select.zig (1)
294-328: Verify the guarantees of asyncCancelWait against concurrent wake calls.The protocol documentation (select.zig lines 55-57) explicitly acknowledges a race where
wait_node.wake()can still be called afterasyncCancelWait()returns if a completion handler is in-flight. SinceSelectWaiter.waitNodeWake()uses@fieldParentPtrto access a stack-allocated struct, a late wake afterselect()returns would be a use-after-free. Confirm either: (1) OS/runtime synchronization prevents this race in practice, (2) the acknowledged race is actually prevented by protocol implementation details, or (3) this needs heap-allocated waiters or explicit draining to remain safe.
Change Waiter to use a signal counter instead of a boolean flag. This enables waiting for multiple signals, which is needed for safe cleanup in select() when multiple futures complete concurrently. - signal() now increments counter instead of setting to true - wait(expected, cancel_mode) waits for signaled >= expected - Removes waitUncancelable(), replaced by wait(n, .no_cancel) - timedWait() also takes expected parameter
Change asyncCancelWait to return bool indicating whether the wait_node was successfully removed (true) or already removed by completion with wake in-flight (false). In select cleanup, count expected signals and wait for all of them: - Start with registered_count (futures where asyncWait returned true) - Decrement for each successful cancel (won't signal) - Wait for remaining signals (winner + in-flight non-winners) This ensures all in-flight wakes complete before stack-allocated SelectWaiters go out of scope.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/select.zig (1)
435-452: Setwinnerbefore returning on the fast path to prevent deadlock.When
asyncWaitreturnsfalse(future already complete), you return immediately without settingwinner. The defer block then seeswinner == NO_WINNER, callsasyncCancelWait(returnsfalsesince never registered), and executeswaiter.wait(1, .no_cancel)which hangs forever waiting for a signal that never comes.Both
select()andselectAwaitables()handle this correctly by callingwinner.store()before their fast-path returns. Apply the same pattern here:Fix
if (!added) { + winner.store(0, .release); return .{ .value = fut.getResult() }; }
Add 'available' counter to track unreserved items. This fixes race conditions where new receivers could steal items from already-woken receivers via fast-path, violating FIFO ordering. Key changes: - Add 'available: usize' field tracking items available for fast-path - Sender: if receiver waiting, don't increment available (item reserved) - Receiver fast-path: check available > 0, decrement, take - Receiver with reservation (woken by sender): just take - Receiver without reservation (woken by close): check available > 0 - Cancel with reservation: transfer to another receiver or release - Add takeItem() helper for buffer operations Also updates AsyncReceive and AsyncSend to use the reservation system, deferring item consumption to getResult() so items aren't lost when losing a select race.
Mirror the item reservation system for senders to fix race conditions where new senders could steal slots from already-woken senders, and AsyncSend hitting unreachable when its slot was stolen. Key changes: - Rename 'available' to 'items_available' for clarity - Add 'slots_available' field tracking slots for sender fast-path - Add putItem() helper mirroring takeItem() - takeItem(): wake sender with reservation, or increment slots_available - send(): use slot reservations (same pattern as receive) - trySend(): check slots_available instead of count == buffer.len - AsyncSend: defer actual send to getResult() like AsyncReceive - AsyncSend.asyncCancelWait: handle reservation transfer
Inspired by Go's channel implementation, this replaces the reservation system with a cleaner approach: 1. CAS-based claiming: When a sender/receiver finds a waiting counterpart, it tries to CAS-claim via the SelectWaiter. If CAS fails (another select op won), try the next waiter. This handles select races at dequeue time. 2. Direct transfer: When sender finds waiting receiver, transfer item directly to receiver's result field (bypassing buffer). When receiver finds waiting sender, take from buffer and put sender's item in buffer. 3. Simplified Channel: Remove items_available/slots_available tracking. receive()/send() now just wrap asyncReceive()/asyncSend() + wait(). Key changes: - SelectWaiter: add tryClaim() and didWin() methods, make vtable public - AsyncReceive/AsyncSend: add tryClaim()/didWin() that check parent vtable - Channel: remove reservation tracking, use direct transfer - asyncCancelWait: use didWin() to detect orphaned nodes vs claimed ones
With direct transfer, unbuffered channels naturally work: - Sender finds waiting receiver: direct transfer - Receiver finds waiting sender: direct transfer - No buffer needed for rendezvous Changes: - Remove assert(buffer.len > 0) from init() - Add direct transfer from waiting sender in AsyncReceive.asyncWait - Add direct transfer from waiting sender in tryReceive - Add comprehensive tests for unbuffered channels
Instead of going through wait() and SelectWaiter, receive/send now use a plain Waiter. The tryClaim() check already handles the non-SelectWaiter case by returning true (always claimable), so CAS overhead is avoided. Also removes all parent_wait_node clearing - it was unnecessary since the struct goes out of scope after getResult() anyway, and the clearing created potential coordination bugs between wake and cancel paths.
Instead of having AsyncReceive/AsyncSend maintain their own channel_wait_node that forwards wake calls to the parent, we now push the parent's wait_node directly to the channel queues and use userdata to store a pointer back to the operation struct. Changes: - SelectWaiter.tryClaim/didWin are now static methods that take a WaitNode - AsyncReceive/AsyncSend no longer have channel_wait_node or parent_wait_node - Operations use wait_node.userdata to store pointer to self - Wake calls go directly to Waiter/SelectWaiter without forwarding This reduces memory per operation (~40 bytes) and simplifies the code path.
Move mutable state from AsyncReceive/AsyncSend into WaitContext, enabling
futures to be passed by value to select().
Changes:
- AsyncReceive.WaitContext holds result, AsyncSend.WaitContext holds self_ptr and succeeded flag
- asyncWait/asyncCancelWait/getResult now take *const Self
- getResult takes WaitContext parameter for futures that have it
- select() updated to pass context to getResult
- Futures with WaitContext can now be passed by value: select(rt, .{ .recv = ch.asyncReceive() })
This separates the operation descriptor (immutable) from per-wait state (in WaitContext),
giving clearer ownership semantics.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/select.zig (1)
456-458: Initialize WaitContext fields before asyncWait in the slow path.Context is declared
undefinedwithout applying struct field defaults. In the slow path (whenasyncWaitreturns true), the context fields are not initialized byasyncWait, but later read bygetResult. For closed-channel scenarios where the channel closes before the wait completes,getResultwill read uninitialized fields. Initialize with field defaults:Proposed fix
var context: WaitCtx = undefined; const has_context = comptime (WaitCtx != void); + if (has_context) context = .{};
🤖 Fix all issues with AI agents
In `@src/select.zig`:
- Around line 300-306: The per-wait Contexts object is left uninitialized which
causes UB when Channel futures (Reader.getResult / Sender.getResult) read
optional fields; replace the undefined declaration with an initialized instance
of the WaitContexts type (use the type returned by WaitContextsType(S) and call
its initializer before any waits) so e.g. construct ContextsType via its init
routine (the same runtime/rt used for Waiter.init(rt)) and use that initialized
variable `contexts` for all subsequent operations.
- Remove channel_wait_node and parent_wait_node from AsyncReceive
- Add WaitContext with result field, push parent wait_node directly
- Read from buffer in getResult (slow path) instead of custom wake logic
- Fix uninitialized WaitContext bug: properly initialize contexts with .{}
- WaitContextsType now provides default_value_ptr for each field
This enables value-based select: select(rt, .{ .recv = ch.asyncReceive(consumer) })
Summary
Waiterabstraction withwait()andtimedWait()methodsCommits
Key changes
Waiter abstraction (
common.zig): Provideswait(),timedWait(), andsignal()methods that handle spurious wakeups internally with a loop patternSync primitives migrated to Waiter:
ResetEvent.waitandResetEvent.timedWaitNotify.waitandNotify.timedWaitCondition.waitandCondition.timedWaitFutex.waitandFutex.timedWaitChannel.sendandChannel.receiveBroadcastChannel.receiveSelect cleanup fix:
asyncCancelWaitnow returnsboolindicating if wait_node was removed (true) or wake is in-flight (false)Future protocol change
asyncCancelWaitreturn type changed fromvoidtobool:true: Successfully removed from queue, no wake will happenfalse: Already removed by completion, wake is in-flight or already happenedTest plan
./check.sh --fullpasses