Skip to content

Add support for Channel send/receive in select() - #92

Merged
lalinsky merged 6 commits into
mainfrom
refactor-channel-waitqueue
Oct 28, 2025
Merged

lalinsky merged 6 commits into
mainfrom
refactor-channel-waitqueue

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 28, 2025 •

Copy link
Copy Markdown
Owner

Fixes #91

Replace async Mutex + Condition with std.Thread.Mutex + WaitQueue
for direct wait queue management. This lays the foundation for
implementing Sender/Receiver types that can participate in select().

Changes:
- Replace Mutex with std.Thread.Mutex (synchronous)
- Replace Condition variables with separate receiver_queue and sender_queue
- Manual wait node management in send() and receive()
- Proper lost-wakeup prevention via atomic state transitions
- Cancellation support: tasks remove themselves from queues on cancel
- Update isEmpty() and isFull() to be synchronous (no rt parameter)
- Update close() to manually wake all waiters from both queues
- Update trySend() and tryReceive() signatures (no rt parameter)

All tests pass (9/9 Channel tests, 129/129 total).
Implement single-shot AsyncSend and AsyncReceive types that enable
Channel operations to participate in select(). Both types implement
the Future protocol and can be used with select() to multiplex on
multiple channel operations.

Key design:
- Single-shot futures: each represents one send/receive operation
- AsyncReceive: non-blocking channel receive for select()
- AsyncSend: non-blocking channel send for select()
- Custom wake vtable performs operation atomically then wakes parent
- Fast path: completes immediately if channel ready
- Slow path: enqueues to channel's wait queue

API:
- channel.asyncReceive() -> AsyncReceive(T)
- channel.asyncSend(item) -> AsyncSend(T)

Usage:
  var recv = channel.asyncReceive();
  var send = channel.asyncSend(42);
  const result = try select(rt, .{ .recv = &recv, .send = &send });

Tests added:
- AsyncReceive with select (basic, ready, closed)
- AsyncSend with select (basic, ready, closed)
- Mixed send/receive select
- Multiple receivers select

All 137 tests pass (7 new select tests).
All futures passed to select() and wait() must now be pointers.
This provides better API consistency and prevents accidental copies.

Changes:
- Update FutureType() to enforce pointer types with compile error
- Update all tests to use pointer syntax (&future)
- Update documentation and examples to reflect pointer requirement
@coderabbitai

coderabbitai Bot commented Oct 28, 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 4 minutes and 28 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 5c3209b and f600985.

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

Walkthrough

Enforces pointer-based futures for select/wait and refactors Channel to a wait-queue model with select-friendly AsyncReceive/AsyncSend types; tests and docs updated to pass future/task pointers and to use the new channel select integration.

Changes

Cohort / File(s) Summary
Future pointer enforcement
src/select.zig
FutureType now requires a pointer input and returns the pointed-to type; FutureResult derives via FutureType. All select/wait call sites and docs updated to pass futures by pointer (e.g., &h1).
Select call-site updates in sync tests
src/sync/Notify.zig, src/sync/ResetEvent.zig
Tests changed to pass task/future pointers (&task, &...) into select instead of values; no exported signatures modified.
Channel synchronization redesign & select integration
src/sync/channel.zig
Replaced Condition-based signaling with std.Thread.Mutex + WaitQueue(WaitNode) for receivers/senders. Added asyncReceive() / asyncSend(item) returning new AsyncReceive(T) / AsyncSend(T) types (init/asyncWait/asyncCancelWait/getResult). Reworked receive/tryReceive/send/trySend/close to use wait-queues, explicit locking, wake/cancel semantics, and select cooperation.
Changelog / docs
CHANGELOG.md
Documented new Channel.asyncReceive/asyncSend APIs and breaking change: select()/wait() now require futures passed as pointers. Noted removal of some Runtime params from isEmpty/isFull/tryReceive/trySend/close.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Areas needing careful review:
    • src/select.zig: pointer indirection enforcement and FutureResult derivation.
    • src/sync/channel.zig: lock/unlock correctness, wait-queue enqueue/dequeue, wake/cancel callbacks, and race conditions between senders/receivers.
    • Tests/docs: ensure all call sites use pointer semantics consistently.

Possibly related PRs

Poem

Pointers called with ampersands neat,
Wait-nodes queue where senders meet,
Mutex locks, a gentle wake,
Channels sing for select's sake,
Tests and docs give change a seat.

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning The PR includes changes to select.zig that enforce pointer-type requirements for all futures, a breaking change to the select() API that goes beyond what issue #91 explicitly requests. Issue #91 asks for Channel receiver/sender methods usable with select, not for fundamental changes to select's input requirements affecting all existing futures. The pointer enforcement is a broader architectural decision that impacts Notify.zig and ResetEvent.zig tests, representing scope beyond the linked issue's objective.
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 (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Add support for Channel send/receive in select()" directly describes the primary feature being added—Channel's integration with select() through new asyncReceive() and asyncSend() methods. It's clear and specific enough that someone scanning history understands what was added without needing to read further. The title doesn't mention implementation details like the pointer changes to select, but it accurately captures the main objective rather than being vague or misleading.
Linked Issues Check ✅ Passed The PR directly fulfills issue #91 by adding asyncReceive() and asyncSend() methods to Channel, returning AsyncReceive(T) and AsyncSend(T) structs designed for use with select(). These structs integrate with select's wait mechanism, enabling Channel operations to participate in select-based waits as requested. The implementation provides the core functionality required by the linked issue.
Description Check ✅ Passed The description "Fixes #91" is minimal but directly tied to the changeset. Issue #91 requests receiver and sender methods for Channel that work with select(), and the PR delivers exactly that through asyncReceive() and asyncSend() methods returning usable structs. The description relates to the changeset and passes the lenient criteria for this check.

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.

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/select.zig (1)

282-296: waitUntilComplete assumes future.cancel() exists. Guard it.

In the cancel-and-continue path you unconditionally call fut.cancel(). Many futures (e.g., AsyncReceive/AsyncSend) don’t expose cancel(), which will fail to compile if users call waitUntilComplete(&recv) or similar.

Add a compile-time guard and fallback.

[Suggest making this change now; it avoids avoidable breakage.]

-                        fut.cancel();
+                        if (comptime std.meta.hasMethod(@TypeOf(fut), "cancel")) {
+                            fut.cancel();
+                        } else {
+                            // No-op: cannot propagate cancellation to this future type.
+                            // We still keep shielding and continue waiting.
+                        }
src/sync/channel.zig (2)

142-163: Deadlock: calling node.wake() while holding channel.mutex in tryReceive.

AsyncSend.waitNodeWake() locks the same channel.mutex. Here, defer self.mutex.unlock() keeps the lock held while you call node.wake(), which will try to re-lock and deadlock.

Unlock before waking, mirroring the receive() fast path.

Apply:

-        self.mutex.lock();
-        defer self.mutex.unlock();
+        self.mutex.lock();

         if (self.count == 0) {
             if (self.closed) {
-                return error.ChannelClosed;
+                self.mutex.unlock();
+                return error.ChannelClosed;
             }
-            return error.ChannelEmpty;
+            self.mutex.unlock();
+            return error.ChannelEmpty;
         }

         const item = self.buffer[self.head];
         self.head = (self.head + 1) % self.buffer.len;
         self.count -= 1;

-        // Wake one sender if any
-        if (self.sender_queue.pop()) |node| {
-            node.wake();
-        }
-
-        return item;
+        // Pop a sender while still under lock, then unlock and wake
+        const sender_node = self.sender_queue.pop();
+        self.mutex.unlock();
+        if (sender_node) |node| {
+            node.wake();
+        }
+        return item;

222-242: Deadlock: calling node.wake() while holding channel.mutex in trySend.

Symmetric issue: AsyncReceive.waitNodeWake() also locks channel.mutex. Waking under defer keeps the lock held and can deadlock.

Unlock before waking.

Apply:

-        self.mutex.lock();
-        defer self.mutex.unlock();
+        self.mutex.lock();

         if (self.closed) {
-            return error.ChannelClosed;
+            self.mutex.unlock();
+            return error.ChannelClosed;
         }

         if (self.count == self.buffer.len) {
-            return error.ChannelFull;
+            self.mutex.unlock();
+            return error.ChannelFull;
         }

         self.buffer[self.tail] = item;
         self.tail = (self.tail + 1) % self.buffer.len;
         self.count += 1;

-        // Wake one receiver if any
-        if (self.receiver_queue.pop()) |node| {
-            node.wake();
-        }
+        // Pop a receiver while still under lock, then unlock and wake
+        const receiver_node = self.receiver_queue.pop();
+        self.mutex.unlock();
+        if (receiver_node) |node| {
+            node.wake();
+        }
🧹 Nitpick comments (1)
src/select.zig (1)

226-229: Clarify behavior with multiple ready futures.

You already pick the first in declaration order; the TODO can be removed or replaced with a short comment stating that policy to avoid second-guessing by readers.

📜 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 362ed03 and 82c1328.

📒 Files selected for processing (4)
  • src/select.zig (13 hunks)
  • src/sync/Notify.zig (1 hunks)
  • src/sync/ResetEvent.zig (1 hunks)
  • src/sync/channel.zig (16 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: lalinsky
PR: lalinsky/zio#70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.
📚 Learning: 2025-10-23T16:17:53.575Z
Learnt from: lalinsky
PR: lalinsky/zio#70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.

Applied to files:

  • src/select.zig
🔇 Additional comments (3)
src/select.zig (1)

40-48: Compile-time pointer-only futures check — good guard, clear message.

Enforcing pointer futures via @typeInfo(T) == .pointer is a clean fail-fast. Nice.

Please confirm docs and all call sites are updated (especially any external examples) to avoid breaking downstream users. If you want, I can draft a migration note.

src/sync/channel.zig (2)

310-436: AsyncReceive: Future protocol implementation is clean.

Fast paths, queueing, and parent wake semantics are straightforward. Result handling via ?Result is fine.


450-561: AsyncSend: symmetric to AsyncReceive, good.

Same notes apply; once the trySend wake-under-lock bug is fixed, this integrates well with select().

Comment thread src/sync/channel.zig Resolved
Comment thread src/sync/Notify.zig Resolved
Comment thread src/sync/ResetEvent.zig Resolved
- Update CHANGELOG.md with breaking API changes
- Enhance compile error message to suggest using '&' prefix
- Fix all Channel documentation examples to show pointer syntax
- Add prominent pointer requirement note to select() docstring

@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 (3)
src/select.zig (2)

34-39: waitUntilComplete requires cancel(); enforce or guard it.

Future protocol comment doesn’t mention cancel(), but waitUntilComplete calls fut.cancel() unconditionally. This will fail to compile for futures without cancel(). Either (a) require cancel() in the protocol, or (b) guard with a compile-time check and emit a clear error only in that code path.

Suggested change:

 // Future protocol:
 //   * needs to have const Result = T
 //   * needs to have asyncWait(*WaitNode) bool method (returns false if already complete)
 //   * needs to have asyncCancelWait(*WaitNode) void method
 //   * needs to have getResult() Result method
+//   * waitUntilComplete additionally requires a `cancel()` method on the future type

@@
-            while (true) {
+            while (true) {
                 executor.yield(.preparing_to_wait, .waiting, .allow_cancel) catch |err| switch (err) {
                     error.Canceled => {
                         if (shielded) unreachable;
                         rt.beginShield();
                         shielded = true;
-                        fut.cancel();
+                        if (std.meta.hasMethod(@TypeOf(fut), "cancel")) {
+                            fut.cancel();
+                        } else {
+                            @compileError("waitUntilComplete requires a future with cancel(); got " ++ @typeName(@TypeOf(fut)));
+                        }
                         continue;
                     },
                 };
                 break;
             }

Also applies to: 288-304


170-179: Fix examples: use free functions and handle errors.

These functions aren’t methods on Runtime and they return errors. Update examples:

-/// const result = rt.select(.{ .first = &h1, .second = &h2 });
+/// const result = try select(rt, .{ .first = &h1, .second = &h2 });
@@
-/// const result = try rt.wait(&future); // returns Cancelable!WaitResult(error{Foo}!i32)
+/// const result = try wait(rt, &future); // returns Cancelable!WaitResult(error{Foo}!i32)
@@
-/// const value = rt.waitUntilComplete(&future); // never returns error.Canceled
+/// const value = waitUntilComplete(rt, &future); // never returns error.Canceled

Also applies to: 330-334, 345-349

src/sync/channel.zig (1)

223-241: Wake-under-lock in trySend() — unlock before wake.

Same issue: node.wake() is invoked with the mutex held.

Apply:

-        self.mutex.lock();
-        defer self.mutex.unlock();
+        self.mutex.lock();

         if (self.closed) {
-            return error.ChannelClosed;
+            self.mutex.unlock();
+            return error.ChannelClosed;
         }

         if (self.count == self.buffer.len) {
-            return error.ChannelFull;
+            self.mutex.unlock();
+            return error.ChannelFull;
         }

         self.buffer[self.tail] = item;
         self.tail = (self.tail + 1) % self.buffer.len;
         self.count += 1;

-        // Wake one receiver if any
-        if (self.receiver_queue.pop()) |node| {
-            node.wake();
-        }
+        const receiver_node = self.receiver_queue.pop();
+        self.mutex.unlock();
+        if (receiver_node) |node| {
+            node.wake();
+        }
♻️ Duplicate comments (1)
src/sync/channel.zig (1)

143-161: Wake-under-lock in tryReceive() — unlock before wake.

node.wake() is called while holding self.mutex (because of defer self.mutex.unlock()). This risks lock-order issues and diverges from receive()/send() fast paths.

Apply:

-        self.mutex.lock();
-        defer self.mutex.unlock();
+        self.mutex.lock();

         if (self.count == 0) {
             if (self.closed) {
-                return error.ChannelClosed;
+                self.mutex.unlock();
+                return error.ChannelClosed;
             }
-            return error.ChannelEmpty;
+            self.mutex.unlock();
+            return error.ChannelEmpty;
         }

         const item = self.buffer[self.head];
         self.head = (self.head + 1) % self.buffer.len;
         self.count -= 1;

-        // Wake one sender if any
-        if (self.sender_queue.pop()) |node| {
-            node.wake();
-        }
-
-        return item;
+        const sender_node = self.sender_queue.pop();
+        self.mutex.unlock();
+        if (sender_node) |node| {
+            node.wake();
+        }
+        return item;
🧹 Nitpick comments (1)
src/sync/channel.zig (1)

350-383: “Shouldn’t happen” branches return ChannelClosed; verify semantics.

If a woken async op finds the channel not ready (e.g., race with another consumer/producer), returning ChannelClosed is misleading. Consider re-queuing or not waking the parent when no progress is possible, or documenting that wake implies readiness. At minimum, add tests to prove we never hit these branches spuriously.

I can draft a stress test that mixes tryReceive/receive with asyncReceive/select to verify no false ChannelClosed occurs. Want that?

Also applies to: 476-509

📜 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 82c1328 and beedb0a.

📒 Files selected for processing (3)
  • CHANGELOG.md (1 hunks)
  • src/select.zig (13 hunks)
  • src/sync/channel.zig (16 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
CHANGELOG.md

📄 CodeRabbit inference engine (CLAUDE.md)

Update CHANGELOG.md: change [Unreleased] to [X.Y.Z] with the current date

Files:

  • CHANGELOG.md
🧠 Learnings (1)
📚 Learning: 2025-10-23T16:17:53.575Z
Learnt from: lalinsky
PR: lalinsky/zio#70
File: src/select.zig:145-153
Timestamp: 2025-10-23T16:17:53.575Z
Learning: In src/select.zig, the select() function is designed to accept futures either as copyable wrappers (e.g., JoinHandle(T)) by value, or as pointers (e.g., &reset_event) for value-owned types. This is intentional, and users are expected to pass the appropriate form based on the future type.

Applied to files:

  • src/select.zig

Comment thread CHANGELOG.md Resolved
Changed tryReceive() and trySend() to pop wait nodes under lock but
wake them only after unlocking the mutex. This prevents potential
deadlocks and reduces lock contention.

The receive()/send() fast paths were already correct.

@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

🧹 Nitpick comments (2)
src/sync/channel.zig (2)

379-382: Defensive error handling masks potential bug.

The "shouldn't happen" case at lines 379-382 sets the result to ChannelClosed when woken but no item is available and the channel isn't closed. While this makes the code more defensive, it could mask a bug in the wakeup logic. Consider adding a debug assertion or log here:

 } else {
-    // Shouldn't happen - woken but nothing available
+    // Shouldn't happen - woken but nothing available
+    std.debug.assert(false); // or std.log.warn
     self.channel.mutex.unlock();
     self.result = error.ChannelClosed;
 }

This makes spurious wakeups more visible during development while still handling them gracefully in release builds.


505-508: Same defensive error handling issue as AsyncReceive.

Similar to AsyncReceive, this "shouldn't happen" case could mask bugs in the wakeup logic. Consider adding a debug assertion:

 } else {
-    // Shouldn't happen - woken but no space
+    // Shouldn't happen - woken but no space
+    std.debug.assert(false);
     self.channel.mutex.unlock();
     self.result = error.ChannelClosed;
 }
📜 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 beedb0a and 5c3209b.

📒 Files selected for processing (1)
  • src/sync/channel.zig (15 hunks)
🔇 Additional comments (4)
src/sync/channel.zig (4)

90-134: LGTM - receive() correctly implements unlock-before-wake.

The fast path properly pops the sender node under lock (line 110), releases the mutex (line 111), then wakes (line 113). The slow path and cancellation handling also look correct.


157-162: Wake-under-lock issue fixed.

The fix from previous review has been properly applied. The sender node is popped under lock (line 158), then the mutex is released (line 159), and only then is the node woken (line 161). This matches the unlock-before-wake pattern used throughout the codebase.


886-1169: Comprehensive test coverage for select integration.

The new tests thoroughly cover AsyncReceive and AsyncSend with select():

  • Basic blocking scenarios
  • Fast-path (already ready) cases
  • Closed channel handling
  • Multiple operations in select

The test structure is clear and covers the key integration points.


269-280: Remove the race condition comment—WaitQueue operations are internally synchronized.

The WaitQueue.pop() method acquires its own internal mutation lock (via acquireMutationLock() at the start and releaseMutationLock() before returning), as do push(), remove(), and popOrTransition(). All queue mutations are protected by this internal lock, regardless of whether the caller holds the channel's mutex. The pattern in close() of releasing the channel lock, then calling pop() (which acquires its own lock), then waking nodes is thread-safe—there's no race condition.

Likely an incorrect or invalid review comment.

In AsyncReceive and AsyncSend waitNodeWake(), the else branches should
never be reached as nodes are only woken when items/space are available
or the channel is closed. Use unreachable to make this explicit.
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.

Receiver and sender for channel

1 participant