Repository navigation
Optimize select() winner identification with atomic tracking - #97
Conversation
Replace runtime iteration over signaled flags with direct winner index lookup. Changes: - SelectWaiter now tracks shared atomic winner index and own index - First future to complete claims winner slot via cmpxchg - Remove per-waiter signaled flags and wake counter - Add NO_WINNER sentinel constant for unclaimed state Benefits: - Direct winner index lookup (no runtime conditionals per waiter) - Race-free atomic winner claiming - Only first winner wakes parent (no spurious wakeups) - Simpler code with fewer atomic operations per waiter All tests pass (150/150).
|
Warning Rate limit exceeded@lalinsky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 35 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (1)
WalkthroughReplaced the ready-counter/signaled design in selection with a single atomic winner slot. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
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 comprehensive documentation for the Future protocol methods: - asyncWait(): Return value semantics, guarantees, thread-safety - asyncCancelWait(): Behavior for both in-queue and race conditions - getResult(): When it can be called, what it returns Clarifies the behavioral contract for implementing custom futures that work with select(), without exposing implementation details like memory ordering.
|
@coderabbitai what do you think about this change? |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 29211 @lalinsky This is a solid optimization. Here's my analysis: What I like:
Minor observations:
Bottom line: This is good work. The atomic winner tracking is simpler, faster, and easier to reason about than counting wakeups and checking flags. The memory orderings are correct, edge cases are handled, and tests confirm it. Ship it. |
Extend the Future protocol to support optional per-wait mutable state through an optional WaitContext type. This enables futures that need per-wait state (like Signal with xev.Completion) while remaining backward compatible with existing futures. Changes: - Document WaitContext in Future protocol (void or struct) - Add FutureWaitContext() helper to extract context type - Add WaitContextsType() to build context struct for select() - Update select() to allocate context struct on stack - Update wait()/waitInternal() to handle contexts - Conditionally pass context to asyncWait/asyncCancelWait - Existing futures default to void context (no changes needed) Benefits: - Enables select() on Signal and other xev-based operations - Backward compatible (existing futures work unchanged) - Context allocated on caller's stack (no heap allocation) - Foundation for multi-shot futures All tests pass (150/150).
Previously, select() would call asyncCancelWait() on all futures except the winner, even if asyncWait() was never called on some futures. This could happen when hitting the fast path - if a future was already complete, we'd return early but still try to cancel all futures in the defer block. Now we track how many futures we've actually registered with and only cancel those we've called asyncWait() on.
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 (2)
src/sync/channel.zig (2)
379-412: Stop spurious wakes: clear parent_wait_node under lock (AsyncReceive).Race: if select() cancels this waiter after it’s dequeued (was_in_queue == false), waitNodeWake can still call parent.wake(), causing a second wake of the parent after a different winner was chosen.
Mirror the BroadcastChannel pattern: read-and-clear parent_wait_node under the channel lock in waitNodeWake; in asyncCancelWait, clear it under lock when removing, asserting the passed wait_node matches.
Suggested fix:
@@ - // Perform the receive operation under lock - self.channel.mutex.lock(); + // Perform the receive operation under lock + self.channel.mutex.lock(); + // Prevent double wake after cancel: capture and clear parent under lock + const parent = self.parent_wait_node; + self.parent_wait_node = null; @@ - self.channel.mutex.unlock(); - - self.result = item; - if (sender_node) |node| { - node.wake(); - } + self.channel.mutex.unlock(); + self.result = item; + if (sender_node) |node| node.wake(); @@ - self.channel.mutex.unlock(); - self.result = error.ChannelClosed; + self.channel.mutex.unlock(); + self.result = error.ChannelClosed; @@ - // Wake the parent (SelectWaiter or task wait node) - if (self.parent_wait_node) |parent| { - parent.wake(); - } + // Wake the parent (SelectWaiter or task wait node) + if (parent) |p| p.wake(); @@ - pub fn asyncCancelWait(self: *Self, _: *Runtime, wait_node: *WaitNode) void { - _ = wait_node; + pub fn asyncCancelWait(self: *Self, _: *Runtime, wait_node: *WaitNode) void { self.channel.mutex.lock(); const was_in_queue = self.channel.receiver_queue.remove(&self.channel_wait_node); if (!was_in_queue) { @@ self.channel.mutex.unlock(); if (next_receiver) |node| { node.wake(); } } else { - self.channel.mutex.unlock(); + // Clear parent under lock to prevent a later wake + if (self.parent_wait_node) |parent| { + std.debug.assert(parent == wait_node); + self.parent_wait_node = null; + } + self.channel.mutex.unlock(); } }Also applies to: 452-468
516-549: Apply the same parent clearing in AsyncSend to avoid double wake.Same race exists in send path. Capture-and-clear parent under lock in waitNodeWake; clear under lock in asyncCancelWait.
@@ - // Perform the send operation under lock - self.channel.mutex.lock(); + // Perform the send operation under lock + self.channel.mutex.lock(); + // Prevent double wake after cancel: capture and clear parent under lock + const parent = self.parent_wait_node; + self.parent_wait_node = null; @@ - self.channel.mutex.unlock(); - - self.result = {}; - if (receiver_node) |node| { - node.wake(); - } + self.channel.mutex.unlock(); + self.result = {}; + if (receiver_node) |node| node.wake(); @@ - // Wake the parent (SelectWaiter or task wait node) - if (self.parent_wait_node) |parent| { - parent.wake(); - } + // Wake the parent (SelectWaiter or task wait node) + if (parent) |p| p.wake(); @@ - pub fn asyncCancelWait(self: *Self, _: *Runtime, wait_node: *WaitNode) void { - _ = wait_node; + pub fn asyncCancelWait(self: *Self, _: *Runtime, wait_node: *WaitNode) void { self.channel.mutex.lock(); const was_in_queue = self.channel.sender_queue.remove(&self.channel_wait_node); if (!was_in_queue) { @@ self.channel.mutex.unlock(); if (next_sender) |node| { node.wake(); } } else { - self.channel.mutex.unlock(); + // Clear parent under lock to prevent a later wake + if (self.parent_wait_node) |parent| { + std.debug.assert(parent == wait_node); + self.parent_wait_node = null; + } + self.channel.mutex.unlock(); } }Also applies to: 589-605
🧹 Nitpick comments (2)
src/sync/broadcast_channel.zig (1)
361-399: Good: parent_wait_node captured/cleared under lock avoids double wake.This neatly prevents spurious parent wakes after cancel and matches the select winner model. Please mirror this in Channel AsyncReceive/AsyncSend.
Also applies to: 441-466
src/select.zig (1)
142-167: Minor compile-time refactor: avoid repeated slice concatenation in WaitContextsType.Building slices with ++ in a loop can be slow at comptime. Prefer a two-pass count + fixed array:
fn WaitContextsType(comptime futures_type: type) type { - const fields = @typeInfo(futures_type).@"struct".fields; - var context_fields: []const std.builtin.Type.StructField = &.{}; - inline for (fields) |field| { - const WaitCtx = FutureWaitContext(field.type); - if (WaitCtx != void) { - const ctx_field = std.builtin.Type.StructField{ - .name = field.name, - .type = WaitCtx, - .default_value = null, - .is_comptime = false, - .alignment = @alignOf(WaitCtx), - }; - context_fields = context_fields ++ &[_]std.builtin.Type.StructField{ctx_field}; - } - } - return @Type(.{ .@"struct" = .{ .layout = .auto, .fields = context_fields, .decls = &.{}, .is_tuple = false } }); + const fields = @typeInfo(futures_type).@"struct".fields; + comptime var n: usize = 0; + inline for (fields) |field| { + if (FutureWaitContext(field.type) != void) n += 1; + } + var context_fields: [n]std.builtin.Type.StructField = undefined; + comptime var j: usize = 0; + inline for (fields) |field| { + const WaitCtx = FutureWaitContext(field.type); + if (WaitCtx != void) { + context_fields[j] = .{ + .name = field.name, + .type = WaitCtx, + .default_value = null, + .is_comptime = false, + .alignment = @alignOf(WaitCtx), + }; + j += 1; + } + } + return @Type(.{ .@"struct" = .{ .layout = .auto, .fields = &context_fields, .decls = &.{}, .is_tuple = false } }); }
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
src/core/awaitable.zig(1 hunks)src/runtime.zig(1 hunks)src/select.zig(7 hunks)src/sync/Notify.zig(1 hunks)src/sync/ResetEvent.zig(1 hunks)src/sync/broadcast_channel.zig(2 hunks)src/sync/channel.zig(4 hunks)src/sync/future.zig(2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
PR: lalinsky/zio#47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.
Applied to files:
src/sync/future.zigsrc/core/awaitable.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: test (windows-latest)
🔇 Additional comments (16)
src/sync/channel.zig (2)
416-449: Signature change: extra Runtime parameter is fine and future‑proof.Matches the project-wide API shift; no behavior change.
553-586: Signature change on AsyncSend: looks good.Consistent with other awaitables; no logic changes introduced.
src/sync/Notify.zig (2)
223-227: Notify.asyncWait signature change: OK.Matches the unified Future protocol; logic intact.
230-240: Notify.asyncCancelWait signature change: OK.No behavior change; consistent with broader API.
src/sync/future.zig (2)
65-73: Future.asyncWait: signature addition looks good.Fast-path and pushUnless(done) semantics preserved.
77-79: Future.asyncCancelWait: signature addition looks good.No behavior change.
src/sync/broadcast_channel.zig (1)
403-439: Signature additions (asyncWait/asyncCancelWait) are consistent.Runtime arg threaded through without behavior change.
src/runtime.zig (1)
261-269: JoinHandle asyncWait/asyncCancelWait: OK.API matches the new protocol; delegation unchanged.
src/sync/ResetEvent.zig (2)
247-251: ResetEvent.asyncWait: signature change is fine.Keeps pushUnless(is_set) invariant.
255-257: ResetEvent.asyncCancelWait: signature change is fine.No behavior change.
src/select.zig (5)
9-11: NO_WINNER sentinel: fine.Using maxInt(usize) as sentinel is reasonable; indexes remain < NO_WINNER.
226-260: Winner claiming via CAS: correct memory ordering.acq_rel on success paired with acquire loads of winner ensures the task sees the winner’s prior writes.
If you want extra safety, add an assertion guarding bounds:
+comptime { std.debug.assert(@sizeOf(usize) >= @sizeOf(usize)); } // placeholder to anchor
304-349: select(): O(1) winner path and cleanup look solid.
- Early fast-path stores winner with .release then returns.
- Defer cancels only registered losers; acquire load reads the winner safely.
Also applies to: 355-365
390-457: waitInternal(): single-future path is correct and cancel-safe.Deferring cancel only after the fast-path return guard avoids canceling an unregistered waiter; assert(winner==0) is appropriate.
37-97: Future protocol docs: clear and useful.The WaitContext addition and guarantees read well.
src/core/awaitable.zig (1)
151-154: Runtime parameter rollout is complete across the codebase.All asyncWait and asyncCancelWait call sites (src/select.zig) pass the new Runtime argument, and wrapper implementations properly delegate without it. No lingering old-style calls found.
Clear parent_wait_node under lock in waitNodeWake and asyncCancelWait to prevent race where select() cancellation could occur after a waiter is dequeued but before parent.wake() is called. This mirrors the BroadcastChannel pattern and ensures only the winning operation can wake the parent.
Replace runtime iteration over signaled flags with direct winner index lookup.
Changes:
Benefits:
All tests pass (150/150).