Skip to content

Handle spurious wakeups in sync primitives and select - #232

Merged
lalinsky merged 19 commits into
mainfrom
fix-shielded-cancel
Jan 23, 2026
Merged

lalinsky merged 19 commits into
mainfrom
fix-shielded-cancel

Conversation

@lalinsky

@lalinsky lalinsky commented Jan 22, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Add proper spurious wakeup handling to all sync primitives and select
  • Introduce Waiter abstraction with wait() and timedWait() methods
  • Fix select cleanup to properly wait for in-flight wakes before returning

Commits

  • Add failing test for shielded sleep cancellation
  • Handle spurious wakeups in waitForIo
  • Add spurious wakeup handling to Waiter and ResetEvent
  • Move Waiter to common.zig and update all sync primitives to use it
  • Add Waiter.timedWait and migrate sync primitives to use it
  • Migrate BroadcastChannel and Channel to use Waiter.wait
  • Handle spurious wakeups in select
  • Simplify SelectWaiter by using Waiter for wait loops
  • Refactor Waiter.signaled from bool to u32 counter
  • Fix select cleanup to wait for in-flight wakes

Key changes

  1. Waiter abstraction (common.zig): Provides wait(), timedWait(), and signal() methods that handle spurious wakeups internally with a loop pattern

  2. Sync primitives migrated to Waiter:

    • ResetEvent.wait and ResetEvent.timedWait
    • Notify.wait and Notify.timedWait
    • Condition.wait and Condition.timedWait
    • Futex.wait and Futex.timedWait
    • Channel.send and Channel.receive
    • BroadcastChannel.receive
  3. Select cleanup fix:

    • asyncCancelWait now returns bool indicating if wait_node was removed (true) or wake is in-flight (false)
    • Select cleanup counts expected signals and waits for all of them before returning
    • Prevents use-after-free of stack-allocated SelectWaiters

Future protocol change

asyncCancelWait return type changed from void to bool:

  • true: Successfully removed from queue, no wake will happen
  • false: Already removed by completion, wake is in-flight or already happened

Test plan

  • All existing tests pass (309 tests)
  • ./check.sh --full passes

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.
@coderabbitai

coderabbitai Bot commented Jan 22, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds a runtime-bound public Waiter in src/common.zig, removes the old task-bound helper in src/sync/common.zig, and rewires waits across I/O, select, and sync primitives to use Waiter.signal()/wait()/timedWait(). Many asyncCancelWait implementations now return a boolean indicating queue removal.

Changes

Cohort / File(s) Summary
Core Waiter & I/O
src/common.zig
Add public Waiter (fields, vtable, init(runtime), signal(), wait(), timedWait(), callback()); refactor waitForIo() / timedWaitForIo() to use the runtime-backed waiter and handle spurious wakeups.
Removed task-bound helper
src/sync/common.zig
Delete old task-bound Waiter helper and its vtable; callers migrated to runtime-backed Waiter.
Select / waiter orchestration
src/select.zig
SelectWaiter.parent now *Waiter; adds tryClaim/didWin; uses shared Waiter.signal()/wait(); select and selectAwaitables rewritten to the new waiter flow; future pointer/value handling adjusted.
Channel & broadcast
src/sync/channel.zig, src/sync/broadcast_channel.zig
Introduce per-operation WaitContext for AsyncSend/AsyncReceive; asyncWait/asyncCancelWait accept ctx and return bool; direct transfer/unbuffered rendezvous and select integration updated to use SelectWaiter + shared Waiter.
Sync primitives
src/sync/Mutex.zig, src/sync/Condition.zig, src/sync/Notify.zig, src/sync/ResetEvent.zig
Replace executor/task-bound yields with stack Waiter.init(runtime) + waiter.wait()/timedWait(); cancellation attempts remove waiter from queues (return bool) or wait uncancelably on races; timed waits use Waiter.timedWait.
Futex
src/sync/Futex.zig
Replace per-task waiter with waiter: Waiter; timedWait() return type adjusted to `(Timeoutable
Signal / I/O coordination
src/signal.zig
Use stack Waiter.init(runtime) for waits; replace executor.yield with waiter.wait()/timedWait(); asyncCancelWait now returns bool indicating removal.
Runtime / Awaitable / JoinHandle
src/runtime/awaitable.zig, src/runtime.zig
asyncCancelWait on Awaitable and JoinHandle now return bool (removal result); JoinHandle.asyncCancelWait signature updated; added test for shielded sleep non-cancelability.
Misc imports & call-sites
src/select.zig, src/signal.zig, src/sync/*, src/runtime/*
Import path adjustments for Waiter/WaitNode and Timeoutable; call-sites updated to new waiter API, timed-wait semantics, and boolean cancellation returns.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

A waiter perched upon the stack,
Counts signals, never lets one slack.
Timed sleeps, spurious taps, and boolean calls,
Queues whisper, select answers, nobody falls.
One small struct keeps wake-ups on track. ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly describes the main change: adding spurious wakeup handling across sync primitives and select, which is the core objective.
Description check ✅ Passed The description is well-structured and clearly related to the changeset, detailing the Waiter abstraction, affected primitives, and the select cleanup fix.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-shielded-cancel

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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)
@lalinsky
lalinsky force-pushed the fix-shielded-cancel branch from 31f25a3 to e7fe6d0 Compare January 22, 2026 23:40
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.

@coderabbitai coderabbitai Bot 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.

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 after asyncCancelWait() returns if a completion handler is in-flight. Since SelectWaiter.waitNodeWake() uses @fieldParentPtr to access a stack-allocated struct, a late wake after select() 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.

@coderabbitai coderabbitai Bot 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.

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: Set winner before returning on the fast path to prevent deadlock.

When asyncWait returns false (future already complete), you return immediately without setting winner. The defer block then sees winner == NO_WINNER, calls asyncCancelWait (returns false since never registered), and executes waiter.wait(1, .no_cancel) which hangs forever waiting for a signal that never comes.

Both select() and selectAwaitables() handle this correctly by calling winner.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.

@coderabbitai coderabbitai Bot 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.

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 undefined without applying struct field defaults. In the slow path (when asyncWait returns true), the context fields are not initialized by asyncWait, but later read by getResult. For closed-channel scenarios where the channel closes before the wait completes, getResult will 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.

Comment thread src/select.zig Resolved
- 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) })
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.

1 participant