Repository navigation
Add Signal support to select() - #98
Conversation
Implement the Future protocol for Signal to enable it to be used with select(). This allows waiting on multiple signals or mixing signals with other async operations like tasks and channels. Implementation details: - Add WaitContext with xev.Completion and parent_wait_node - Implement asyncWait() with fast path for already-received signals - Implement waitCallback() for xev completion notification - Implement asyncCancelWait() with completion state checking - Implement getResult() to consume signal counter - Unify wait()/timedWait() to use same WaitContext and callback - Fix select.zig default_value_ptr for Zig 0.15 compatibility Tests added: - Signal: select on multiple signals - Signal: select with signal already received (fast path) - Signal: select with signal and task All 153 tests pass.
WalkthroughSwitched per-wait-context struct fields in Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🧰 Additional context used🧠 Learnings (3)📓 Common learnings📚 Learning: 2025-10-23T16:17:53.575ZApplied to files:
📚 Learning: 2025-10-10T05:59:17.087ZApplied to files:
⏰ 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)
🔇 Additional comments (8)
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 |
|
@claude I think there is a cancelation safety issue, if we have signal triggering, but not winning the select race, we might need to call event.notify() to potentially wake up another one |
|
Claude finished @lalinsky's task —— View job AnalysisFound the cancellation safety issue! In Channel's const was_in_queue = self.channel.receiver_queue.remove(&self.channel_wait_node);
if (!was_in_queue) {
// We were already removed by a sender who will wake us.
// Since we're being cancelled and won't consume the item,
// wake another receiver to consume it instead.
const next_receiver = self.channel.receiver_queue.pop();
self.channel.mutex.unlock();
if (next_receiver) |node| {
node.wake();
}The Signal implementation in
But if the xev operation already completed and triggered Fix ImplementedUpdated Changes:
Testing:
--- | Branch |
When a signal triggers but loses the select() race, asyncCancelWait() is called to cancel the operation. If the xev completion already triggered (state != active), the signal was received but won't be consumed by this waiter. Call event.notify() to wake another potential waiter, following the same pattern used in Channel. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Lukáš Lalinský <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/signal.zig (1)
387-404: Cancellation-safety correctly addressed.The logic handles the tricky case where a signal arrives but loses the select race:
- Line 392: Clears parent_wait_node to prevent spurious wake of a dying parent
- Line 402: Calls notify() so another waiter can consume the signal that was delivered but not selected
The
catch {}on line 402 is acceptable—notify() failures should be exceptional, and the signal counter will still be consumed by the next waiter's fast path.Consider adding an inline comment at line 399 explaining why notify() is needed: "Signal was delivered but not consumed; wake another waiter to handle it."
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/signal.zig(5 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 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.
Learnt from: lalinsky
PR: lalinsky/zio#48
File: src/core/ConcurrentAwaitableList.zig:254-269
Timestamp: 2025-10-16T14:33:19.718Z
Learning: In the zio repository's `src/core/ConcurrentAwaitableList.zig` and `src/core/Awaitable.zig`, the `in_list` field should remain debug-only (conditional compilation with `builtin.mode == .Debug`). Double-removal detection in `ConcurrentAwaitableList.remove()` uses pointer-based checks (comparing `prev`/`next` against `head`/`tail`) rather than relying on a regular `in_list` field.
📚 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/signal.zig
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
PR: lalinsky/zio#41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.087Z
Learning: In UDP socket operations (src/udp.zig), error.Canceled from result_data.result represents OS/IO-level cancellation (e.g., io_uring), not user-requested cancellation. User cancellation is handled by waitForXevCompletion() via try. OS-level error.Canceled should be mapped to error.Unexpected as it represents an unexpected system event.
Applied to files:
src/signal.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 (10)
src/signal.zig (10)
7-7: LGTM - Import aligns with Future protocol.The switch from AnyTask to WaitNode is correct for the new async waiting mechanism.
230-235: LGTM - Future protocol correctly implemented.The Result and WaitContext types properly enable Signal to participate in select(). The optional parent_wait_node allows safe cancellation handling.
277-294: LGTM - Refactor unifies wait logic cleanly.The shared WaitContext and waitCallback eliminate duplication while maintaining the same semantics. Counter consumption after the wait is correct.
321-338: LGTM - Consistent refactoring.The timedWait() refactoring mirrors wait() and correctly integrates with the shared callback mechanism.
344-366: LGTM - Fast path optimization is solid.The counter swap on line 346 correctly handles the race between signal check and wait registration. Returning false for already-received signals avoids unnecessary event loop interaction.
368-383: LGTM - Callback correctly handles wake notification.The conditional check for parent_wait_node (line 378) enables clean cancellation handling. Ignoring the xev result is appropriate here since we want to wake the parent regardless.
408-411: LGTM - Correct result consumption.Simple counter consumption to acknowledge the signal. Works correctly with the fast path in asyncWait().
566-610: LGTM - Good coverage of multi-signal select.Test correctly verifies that select() identifies which of multiple signals arrived.
612-645: LGTM - Fast path coverage is essential.This test confirms that select() returns immediately when a signal has already been received, exercising the optimization at line 346.
647-696: LGTM - Demonstrates practical mixed-future usage.The test confirms Signal correctly interoperates with other future types via select(), and the timing (10ms vs 100ms) ensures deterministic test results.
|
@claude address the last review comment Consider adding an inline comment at line 399 explaining why notify() is needed: "Signal was delivered but not consumed; wake another waiter to handle it." |
|
Claude finished @lalinsky's task —— View job Adding inline comment to explain notify() callTasks
ChangesUpdated the comment at line 399 in The previous multi-line comment was replaced with the more concise version that clearly explains the purpose of the Test ResultsAll 153 tests passed successfully. SummarySuccessfully addressed the review comment by improving the inline documentation for the --- | Branch |
Clarified the comment to explain why notify() is called when a signal is delivered but not consumed during select() cancellation. Co-authored-by: Lukáš Lalinský <[email protected]>
Summary
Implements the Future protocol for
Signalto enable it to be used withselect(). This allows waiting on multiple signals or mixing signals with other async operations like tasks and channels.Changes
Core Implementation
Result = voidandWaitContextstructRefactoring
wait()andtimedWait()to use the sameWaitContextandwaitCallback()parent_wait_node.wake()instead of direct task resumptionAnyTask,resumeTask)Bug Fixes
select.zigdefault_value_ptrfield for Zig 0.15 compatibilityTests
Added 3 comprehensive tests:
Signal: select on multiple signals- Wait on SIGUSR1 vs SIGUSR2Signal: select with signal already received (fast path)- Pre-received signal returns immediatelySignal: select with signal and task- Mix signal with slow taskAll 153 tests pass.
Example Usage