Skip to content

Add Signal.timedWait with timeout support - #75

Merged
lalinsky merged 2 commits into
mainfrom
feature/signal-timed-wait
Oct 24, 2025
Merged

lalinsky merged 2 commits into
mainfrom
feature/signal-timed-wait

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 24, 2025 •

Copy link
Copy Markdown
Owner

Summary

Implements timeout support for signal waiting by adding Signal.timedWait(), which allows waiting for OS signals with a timeout.

Changes

  • Added timedWaitForIo() in src/io/base.zig - Generic function for timed I/O operations with timeout support
  • Added Signal.timedWait() in src/signal.zig - Wait for signal with timeout parameter (nanoseconds)
  • Fixed xev io_uring backend - Added proper handling of ECANCELED error in .poll operation to prevent "unexpected errno: 125" warnings
  • Added comprehensive tests - Both timeout and success scenarios

Implementation Details

The implementation follows the same pattern as other sync primitives (ResetEvent.timedWait, Notify.timedWait):

  • Fast path: checks signal counter first for already-received signals
  • Uses timedWaitForReadyWithCallback from the runtime for timeout handling
  • Properly handles cancellation using the shield mechanism
  • Returns error{ Timeout, Canceled }

Test Results

All 125 tests pass, including the two new tests:

  • Signal: timedWait timeout - Verifies timeout behavior when no signal arrives
  • Signal: timedWait receives signal before timeout - Verifies successful signal reception

Fixes #73

Summary by CodeRabbit

  • New Features

    • I/O operations and signal waits now support timeouts, returning Timeout or Canceled when appropriate.
  • Bug Fixes

    • Improved handling of canceled I/O so cancellations are reported reliably.
  • Tests

    • Added tests covering signal timeout and successful signal-before-timeout scenarios.

Implements timeout support for signal waiting by adding:
- timedWaitForIo() in src/io/base.zig for timed I/O operations
- Signal.timedWait() in src/signal.zig with timeout parameter
- Comprehensive tests for both timeout and success cases
- Fix xev io_uring poll operation to handle ECANCELED properly

The implementation follows the same pattern as other sync primitives
(ResetEvent, Notify) and properly handles cancellation using the
shield mechanism.

Fixes #73
@coderabbitai

coderabbitai Bot commented Oct 24, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

A new public timedWaitForIo function is added to the I/O runtime layer to enable timeout-aware I/O operations. Signal.timedWait extends signal waiting with timeout support. The io_uring backend now explicitly maps CANCELED errno to error.Canceled, formalizing cancellation error handling.

Changes

Cohort / File(s) Summary
I/O timeout infrastructure
src/io/base.zig
Adds timedWaitForIo(rt, completion, timeout_ns) implementing timeout-aware I/O wait with a TimeoutContext, cancellation/timed-out flags, executor callback loop using timedWaitForReadyWithCallback, and shield use around cancellation and final checks.
Signal timed wait
src/signal.zig
Adds Signal.timedWait(self, rt, timeout_ns) that registers an async wait and uses timedWaitForIo to enforce timeouts; includes tests for timeout and successful pre-timeout signal delivery.
Backend cancellation handling
vendor/libxev/src/backend/io_uring.zig
Extends Completion.invoke poll error mapping to convert CANCELED errno into error.Canceled instead of treating it as an unexpected errno.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Signal
    participant Runtime as Runtime (I/O)
    participant Executor
    participant XEV as XEV (backend)

    User->>Signal: Signal.timedWait(rt, timeout_ns)
    Signal->>Signal: create WaitContext & completion
    Signal->>Runtime: timedWaitForIo(completion, timeout_ns)
    Runtime->>Executor: timedWaitForReadyWithCallback(completion, callback, timeout_ns)

    alt I/O ready before timeout
        XEV-->>Executor: completion ready
        Executor-->>Runtime: callback invoked (ready)
        Runtime->>Signal: resume task (success)
    else Timeout fires first
        Executor-->>Runtime: callback invoked (timeout)
        Runtime->>XEV: cancel I/O (once)
        Runtime->>Signal: resume task (error.Timeout)
    else External cancellation
        XEV-->>Executor: operation returns CANCELED
        Executor-->>Runtime: callback invoked (canceled)
        Runtime->>XEV: cancel I/O (once)
        Runtime->>Signal: resume task (error.Canceled)
    end

    Signal->>Signal: consume counter if needed
    Signal-->>User: return (void / Timeout / Canceled)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Pay special attention to:
    • src/io/base.zig: correctness of the timeout/cancellation state machine, single-cancel guarantee, and shield pairing.
    • src/signal.zig: correct interaction with completion, tests covering race conditions between signal delivery and timeout.
    • vendor/libxev/src/backend/io_uring.zig: ensure mapping CANCELED to error.Canceled matches upstream error semantics.

Possibly related PRs

Poem

🐰
A rabbit waits where clocks entwine,
I/O and timeout mark the line,
If signals leap or timers chime,
I hop back in — on time, sublime!
✨

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 (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "Add Signal.timedWait with timeout support" directly and accurately describes the main objective of the changeset. The title clearly indicates that the primary change is adding a Signal.timedWait method with timeout functionality, which aligns perfectly with the core implementation in src/signal.zig. The title is concise, specific, and avoids vague terminology or noise.
Linked Issues Check ✅ Passed The PR fully satisfies the requirements from linked issue #73 (Implement Signal.timedWait). The implementation includes the Signal.timedWait(self: *Signal, rt: *Runtime, timeout_ns: u64) method that accepts a timeout parameter, returns the appropriate error types (Timeout, Canceled), and includes comprehensive tests validating both timeout and signal-received scenarios. The implementation also follows established patterns from other sync primitives (ResetEvent.timedWait, Notify.timedWait) as mentioned in the objectives.
Out of Scope Changes Check ✅ Passed All changes in the PR are directly aligned with the stated objective of implementing Signal.timedWait. The timedWaitForIo() helper in src/io/base.zig is a necessary supporting function for the timeout implementation, the Signal.timedWait() method in src/signal.zig is the core requirement, and the xev io_uring backend fix for ECANCELED handling is essential for proper cancellation/timeout behavior. No out-of-scope or unrelated changes have been introduced.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/signal-timed-wait

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3264522 and e923069.

📒 Files selected for processing (1)
  • src/io/base.zig (1 hunks)
🔇 Additional comments (4)
src/io/base.zig (4)

43-48: LGTM! Function signature and setup follow existing patterns.

The function signature correctly returns error{ Timeout, Canceled } and the two-flag approach with a single defer for shield cleanup is clean and efficient.


50-58: Clean context pattern for timeout callback.

The TimeoutContext struct appropriately bundles the completion pointer and canceled flag, enabling the timeout callback to make informed decisions about whether to actually timeout.


60-98: Shield lifecycle correctly prevents leak; nested conditions address past review.

The nested conditionals at lines 76-82 and 86-94 ensure that rt.beginShield() is called at most once (either on first timeout or first cancel, but not both), while the defer at line 48 correctly calls rt.endShield() exactly once. This properly addresses the shield leak concern from the previous review.

Note on nested shields: The code calls rt.beginShield() before invoking cancelIo(), which internally also uses beginShield()/endShield() (line 12-13). This creates nested shields. The same pattern exists in waitForIo (lines 28-29), suggesting the shield mechanism supports nesting via reference counting or similar. If you're uncertain, verify that the Runtime shield implementation is reentrant.


100-107: Error precedence correctly favors Timeout over Canceled.

When both flags are set, returning error.Timeout first (line 100-102) is appropriate because timeout represents the primary failure condition. The ordering is consistent with the catch block sequence (timeout at line 74, cancel at line 85).


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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a279428 and 3264522.

📒 Files selected for processing (3)
  • src/io/base.zig (1 hunks)
  • src/signal.zig (2 hunks)
  • vendor/libxev/src/backend/io_uring.zig (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 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:

  • vendor/libxev/src/backend/io_uring.zig
🔇 Additional comments (4)
src/signal.zig (3)

274-323: Signal.timedWait mirrors wait semantics correctly and integrates with timeout path.

Fast‑path counter check, Async wait wiring, and post‑success counter consumption look solid.


410-437: Test: timeout case is focused and deterministic.

Cleanly asserts Timeout without side effects. LGTM.


439-476: Test: signal-before-timeout happy path covered.

Covers end‑to‑end flow; timing margins are reasonable. LGTM.

vendor/libxev/src/backend/io_uring.zig (1)

772-777: I need broader context about how poll errors are used upstream. Let me search more comprehensively:

The web search confirms that ECANCELED is returned by io_uring when IO_POLL_CANCEL_FLAG is set, representing a legitimate system event. Now let me verify the specific UDP context from the retrieved learning:

Verified: ECANCELED → error.Canceled for poll is correct and aligns with other operations.

No code in the non-vendor codebase appears to special-case poll cancellations or depend on Unexpected being returned from poll operations. The mapping is consistent with accept/connect/send operations and correctly represents io_uring's OS-level poll cancellation semantics.

Comment thread src/io/base.zig Resolved
@lalinsky
lalinsky merged commit 084552d into main Oct 24, 2025
@lalinsky
lalinsky deleted the feature/signal-timed-wait branch October 24, 2025 22:45
@coderabbitai coderabbitai Bot mentioned this pull request Nov 12, 2025
2 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Jan 14, 2026
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.

Implement Signal.timedWait

1 participant