Skip to content

Optimize select() winner identification with atomic tracking - #97

Merged
lalinsky merged 6 commits into
mainfrom
select-winner-optimization
Oct 29, 2025
Merged

lalinsky merged 6 commits into
mainfrom
select-winner-optimization

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

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).

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

coderabbitai Bot commented Oct 29, 2025 •

Copy link
Copy Markdown
Contributor

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between ab7161d and 73d4356.

📒 Files selected for processing (1)
  • src/sync/channel.zig (6 hunks)

Walkthrough

Replaced the ready-counter/signaled design in selection with a single atomic winner slot. SelectWaiter now points at a shared winner and an index; selection is claimed via CAS and results are returned by indexing the winner value. Several public asyncWait signatures gained an unused *: *Runtime parameter.

Changes

Cohort / File(s) Summary
Select core & API
src/select.zig
Added internal NO_WINNER sentinel. Rewrote select(), waitInternal(), and related logic to use winner: std.atomic.Value(usize) and per-wait index instead of a ready counter / signaled flag. Added FutureWaitContext, hasWaitContext, WaitContextsType, and WaitResult helpers and expanded Future protocol docs.
SelectWaiter struct & wake logic
src/select.zig
SelectWaiter fields changed: removed wake_counter/signaled, added winner: *std.atomic.Value(usize) and index: usize. init() signature updated. waitNodeWake() now CASes NO_WINNER → index and only wakes the parent on successful claim.
Awaitable / JoinHandle API surface
src/core/awaitable.zig, src/runtime.zig
Public methods asyncWait and asyncCancelWait on awaitable wrappers / JoinHandle now accept an extra unused _: *Runtime parameter; internal delegation preserved.
Sync primitives: Future/Notify/Events/Channels
src/sync/future.zig, src/sync/Notify.zig, src/sync/ResetEvent.zig, src/sync/broadcast_channel.zig, src/sync/channel.zig
Multiple asyncWait / asyncCancelWait signatures updated to accept an additional unused _: *Runtime parameter. Internal logic and queue operations remain unchanged; call sites must supply the runtime argument.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Verify CAS correctness, ordering, and use of the NO_WINNER sentinel in waitNodeWake() and all paths that set/read winner.
  • Confirm immediate-completion fast-paths write winner before returning and that deferred cleanup cancels non-winners reliably.
  • Ensure all updated asyncWait / asyncCancelWait signatures are consistently propagated to callers and that unused Runtime param is intentionally ignoring runtime state.
  • Review new Future wait-context helper types for correct typing with void vs non-void contexts.

Possibly related PRs

Poem

One CAS to claim the silent throne,
A shared slot marked with an index-tone.
Non-winners fold, the winner sings,
Results fetched quick — no extra strings.
Tiny change, clearer winning rings. 🎲

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Optimize select() winner identification with atomic tracking" accurately captures the core change in the pull request. The changeset fundamentally replaces the previous ready-counter and per-waiter signaled flag mechanism with an atomic winner-index model, enabling direct O(1) lookup instead of runtime iteration. The title is specific, concise, and directly reflects the main optimization goal without unnecessary noise or vague language.
Description Check ✅ Passed The description is directly related to the changeset and accurately describes the primary modifications. It correctly identifies the shift from iterating over signaled flags to using a shared atomic winner index, explains the cmpxchg mechanism for race-free claiming, and notes the removal of wake_counter and signaled flags. The stated benefits align with the actual changes in the select.zig file and related updates across the codebase.

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

Copy link
Copy Markdown
Owner Author

@coderabbitai what do you think about this change?

@coderabbitai

coderabbitai Bot commented Oct 29, 2025

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the select.zig file to understand the implementation
cat src/select.zig

Length of output: 29211


@lalinsky This is a solid optimization. Here's my analysis:

What I like:

  1. Correctness via atomic CAS: Using cmpxchgStrong(NO_WINNER, self.index, .acq_rel, .acquire) gives you race-free winner claiming. Multiple futures can complete simultaneously, but only one successfully transitions from NO_WINNER to their index. Clean.

  2. O(1) winner lookup: The old approach presumably iterated through signaled flags to find the winner. Now you load the winner index and directly return the corresponding result. No conditionals, no iteration.

  3. Spurious wakeup elimination: Only the winning waiter calls self.parent.wake(). Losers bail out silently after the failed CAS.

  4. Cleaner defer cleanup: The if (winner_index != i) check naturally skips canceling the winner. No extra bookkeeping needed.

  5. Memory ordering looks right: acq_rel on CAS success synchronizes the winner claim across threads, acquire on failure ensures you see the winner that beat you.

Minor observations:

  • The NO_WINNER = maxInt(usize) sentinel is fine, though you're limiting yourself to maxInt(usize) - 1 concurrent futures in a select. Not a practical concern.

  • In the fast path (line ~243), you store the winner and return immediately. This short-circuits the defer cleanup, which is correct since no waiters were added to queues yet.

  • Single-future waitInternal now uses the same winner mechanism with index 0. Consistent pattern, though slightly more overhead than a simple bool. The uniformity is probably worth it.

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.

@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 (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

📥 Commits

Reviewing files that changed from the base of the PR and between cdd66d1 and ab7161d.

📒 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.zig
  • src/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.
@lalinsky
lalinsky merged commit 093f0bc into main Oct 29, 2025
@lalinsky
lalinsky deleted the select-winner-optimization branch October 29, 2025 12:32
@coderabbitai coderabbitai Bot mentioned this pull request Dec 11, 2025
2 tasks done
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