Skip to content

Add Signal support to select() - #98

Merged
lalinsky merged 3 commits into
mainfrom
signal-select-support
Oct 30, 2025
Merged

lalinsky merged 3 commits into
mainfrom
signal-select-support

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

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

Changes

Core Implementation

  • Future protocol declarations: Added Result = void and WaitContext struct
  • asyncWait(): Implements fast path for already-received signals, registers xev async wait
  • waitCallback(): Simple callback that wakes parent wait node
  • asyncCancelWait(): Cancels xev operation if still active, prevents spurious wakes
  • getResult(): Consumes signal counter

Refactoring

  • Unified wait() and timedWait() to use the same WaitContext and waitCallback()
  • Removed duplicate local context structs and inline callbacks
  • Simplified to use parent_wait_node.wake() instead of direct task resumption
  • Removed unused imports (AnyTask, resumeTask)

Bug Fixes

  • Fixed select.zig default_value_ptr field for Zig 0.15 compatibility

Tests

Added 3 comprehensive tests:

  • Signal: select on multiple signals - Wait on SIGUSR1 vs SIGUSR2
  • Signal: select with signal already received (fast path) - Pre-received signal returns immediately
  • Signal: select with signal and task - Mix signal with slow task

All 153 tests pass.

Example Usage

var sig1 = try Signal.init(.interrupt);  // SIGINT
defer sig1.deinit();
var sig2 = try Signal.init(.terminate);  // SIGTERM
defer sig2.deinit();

const result = try select(rt, .{
    .interrupt = &sig1,
    .terminate = &sig2,
});

switch (result) {
    .interrupt => std.debug.print("Received SIGINT\n", .{}),
    .terminate => std.debug.print("Received SIGTERM\n", .{}),
}

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

coderabbitai Bot commented Oct 30, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Switched per-wait-context struct fields in src/select.zig to use pointer-based default values. Reworked src/signal.zig to use a WaitNode/WaitContext future protocol: added Result/WaitContext types, asyncWait/asyncCancelWait/getResult, refactored wait/timedWait paths, and extended tests.

Changes

Cohort / File(s) Summary
WaitContextsType pointer initialization
src/select.zig
For fields whose FutureWaitContext(...) is non-void, struct field construction now uses default_value_ptr instead of default_value.
Signal Future protocol & WaitNode integration
src/signal.zig
Removed AnyTask/resumeTask usage; added nested Result and WaitContext types; implemented pub fn asyncWait, pub fn asyncCancelWait, pub fn getResult, and waitCallback; updated wait/timedWait to use WaitContext/parent_wait_node; added/adjusted tests for select-like semantics.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Inspect asyncWait/asyncCancelWait/getResult for race conditions and correct completion lifecycle.
  • Verify waitCallback uses parent_wait_node wake/cancellation logic safely across code paths.
  • Confirm default_value_ptr change matches memory/layout and initialization expectations for select/wait contexts.

Possibly related PRs

Poem

Wait nodes wake where tasks once lay,
Pointers stand ready to point the way,
Signals queue, contexts hold tight,
Callbacks nudge the parent to light,
A tiny runtime leap — code sleeps less tonight.

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 "Add Signal support to select()" directly captures the primary objective of this PR. The changeset implements the Future protocol for Signal, adding asyncWait(), asyncCancelWait(), and getResult() methods, which are the concrete mechanisms enabling Signal to work with select(). This title accurately reflects what a developer scanning the commit history would care about—that Signal can now be used in select() operations.
Description Check ✅ Passed The description is well-structured and directly related to the changes. It explains the Future protocol implementation (Result and WaitContext types), details each new public method and what it does (asyncWait fast-path logic, waitCallback for waking, asyncCancelWait for cleanup, getResult for consumption), covers refactoring of existing code (unified wait/timedWait paths, removed duplicate structures), mentions the select.zig compatibility fix, and provides concrete test coverage examples plus usage code. Every section maps to actual changes in the PR.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch signal-select-support

📜 Recent 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 44910ca and 68dcdd0.

📒 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 (8)
src/signal.zig (8)

7-7: LGTM - necessary import for Future protocol.

The WaitNode import is required for implementing the async wait pattern used by select().


230-235: LGTM - clean Future protocol implementation.

The type definitions are correct: Result = void matches Signal's behavior, and the WaitContext properly bundles the xev completion with an optional parent wait node for cancellation safety.


277-287: LGTM - good refactoring to share waitCallback.

The refactoring properly unifies wait() and timedWait() to use the same WaitContext and waitCallback, eliminating code duplication. The stack-allocated context is safe since both functions block until completion.

Also applies to: 321-331


341-366: LGTM - solid fast path optimization.

The fast path (line 346) correctly consumes the signal immediately if already received, avoiding unnecessary event loop registration. Note that getResult() will swap the counter again, but that's harmless (the second swap is a no-op).


368-383: LGTM - callback correctly handles parent_wait_node nullability.

The conditional wake on line 378 is essential since parent_wait_node can be cleared by asyncCancelWait() to prevent spurious wakes. Error handling with catch {} is appropriate for the callback context.


385-402: LGTM - cancellation safety properly handled.

The logic correctly distinguishes between:

  1. Still active (lines 395-397): Cancel the xev operation before signal delivered
  2. Already delivered (lines 399-400): Signal was received but this waiter didn't win the select() race - notify() ensures another waiter can consume it

The comment on line 399 (requested in PR) clearly explains why notify() is critical for preventing signal loss. This addresses the cancellation-safety concern mentioned in the PR objectives.


404-409: LGTM - correctly consumes signal counter.

For the fast path, this is a no-op (counter already consumed in asyncWait()). For the slow path, this properly consumes the counter after the signal was delivered. Consistent with the existing wait()/timedWait() behavior.


564-694: LGTM - comprehensive test coverage.

The three tests effectively cover:

  1. Multiple signals: Racing different signal types in select()
  2. Fast path: Signal already received before select() (tests the optimization in asyncWait())
  3. Mixed futures: Combining Signal with JoinHandle in select()

All tests are well-structured with proper cleanup and clear outcome verification.


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.

@lalinsky

Copy link
Copy Markdown
Owner Author

@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

claude Bot commented Oct 30, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Analysis

Found the cancellation safety issue! In Channel's asyncCancelWait, there's a pattern to handle this exact scenario:

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 asyncCancelWait() was missing this logic. When a signal triggers and calls waitCallback(), it might wake the parent wait node. However, if that signal loses the select race, asyncCancelWait() is called. The old code just:

  1. Nulled the parent_wait_node
  2. Cancelled the xev operation

But if the xev operation already completed and triggered waitCallback(), the signal has been received (counter incremented) but no one will process it. We needed to call event.notify() to potentially wake up another waiter.

Fix Implemented

Updated asyncCancelWait() (src/signal.zig:387-404) to check if the xev operation already completed. If it did (state != active), we call self.entry.event.notify() to wake another potential waiter since we won't be consuming this signal.

Changes:

  • Check if xev completion is still active before cancelling
  • If already completed, call event.notify() to wake another waiter
  • Follows the same cancellation safety pattern as Channel

Testing:

  • All 153 tests pass
  • Committed and pushed to branch: signal-select-support

--- | 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]>

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5acad21 and 44910ca.

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

@lalinsky

Copy link
Copy Markdown
Owner Author

@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

claude Bot commented Oct 30, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Adding inline comment to explain notify() call

Tasks

  • Read src/signal.zig to locate the code around line 399
  • Add inline comment explaining why notify() is needed
  • Run tests to verify nothing broke
  • Commit and push changes

Changes

Updated the comment at line 399 in src/signal.zig to use the suggested wording: "Signal was delivered but not consumed; wake another waiter to handle it."

The previous multi-line comment was replaced with the more concise version that clearly explains the purpose of the notify() call during cancellation.

Test Results

All 153 tests passed successfully.

Summary

Successfully addressed the review comment by improving the inline documentation for the notify() call in asyncCancelWait(). The new comment more clearly explains why we need to wake another waiter when a signal was delivered but not consumed during select() cancellation.

--- | 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]>
@lalinsky
lalinsky merged commit 226d299 into main Oct 30, 2025
@lalinsky
lalinsky deleted the signal-select-support branch October 30, 2025 08:29
@coderabbitai coderabbitai Bot mentioned this pull request Nov 12, 2025
2 tasks
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