Repository navigation
Add support for Channel send/receive in select() - #92
Conversation
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
|
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 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)
WalkthroughEnforces 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (3 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 |
There was a problem hiding this comment.
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 assumesfuture.cancel()exists. Guard it.In the cancel-and-continue path you unconditionally call
fut.cancel(). Many futures (e.g.,AsyncReceive/AsyncSend) don’t exposecancel(), which will fail to compile if users callwaitUntilComplete(&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 samechannel.mutex. Here,defer self.mutex.unlock()keeps the lock held while you callnode.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 lockschannel.mutex. Waking underdeferkeeps 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
📒 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) == .pointeris 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
?Resultis 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().
- 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
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 (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.CanceledAlso 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 holdingself.mutex(because ofdefer 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
ChannelClosedis 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
📒 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
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.
There was a problem hiding this comment.
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
ChannelClosedwhen 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
📒 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 (viaacquireMutationLock()at the start andreleaseMutationLock()before returning), as dopush(),remove(), andpopOrTransition(). All queue mutations are protected by this internal lock, regardless of whether the caller holds the channel's mutex. The pattern inclose()of releasing the channel lock, then callingpop()(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.
Fixes #91