Skip to content

Add support for stackable per-task timeouts - #113

Merged
lalinsky merged 35 commits into
mainfrom
timeout
Nov 2, 2025
Merged

lalinsky merged 35 commits into
mainfrom
timeout

Conversation

@lalinsky

@lalinsky lalinsky commented Nov 1, 2025

Copy link
Copy Markdown
Owner

Summary

This PR implements a comprehensive timeout mechanism for the zio runtime, replacing the previous ad-hoc timer management approach with a clean, heap-based system.

Key Changes

Cancellation Status Refactoring

  • Replaced boolean canceled flag with CanceledStatus packed struct tracking:
    • user_canceled: Counter for user-initiated cancellations
    • timeout: Counter for timeout-triggered cancellations
    • pending_errors: Counter for pending cancellation errors to consume
  • Enables distinguishing between user cancellation and timeout expiration

New Timeout Infrastructure

  • Added src/core/timeout.zig with RAII-style Timeout type
  • Stack-allocated timeouts with defer pattern for cleanup
  • TimeoutHeap: Min-heap ordering timeouts by earliest deadline
  • Supports nested timeouts (earliest deadline always applies)
  • triggered field allows callers to distinguish timeout from user cancellation

Task-Level Timeout Management

  • Each AnyTask maintains a TimeoutHeap for active timeouts
  • Shared timer per task tracks earliest deadline
  • New methods:
    • checkTimeout(): Decrements timeout counter, returns error.Timeout if triggered
    • checkCanceled(): Decrements pending_errors counter, returns error.Canceled (respects shields)
    • updateTimer(), maybeUpdateTimer(): Manage shared timer based on heap state

Simplified I/O Operations

  • Cleaned up waitForIo() and timedWaitForIo() to use timeout infrastructure
  • cancelIo(): Properly shields, cancels, and waits for I/O completion
  • timedWaitForIo() uses Timeout objects with RAII pattern

Runtime/Executor Improvements

  • Removed complex timer packing/unpacking logic
  • sleep() reimplemented using Timeout infrastructure
  • yield() delegates to task.checkCanceled() for cleaner cancellation handling

Benefits

  • Multiple timeouts can be active simultaneously (nested scopes)
  • One shared timer per task efficiently tracks earliest deadline
  • Clear distinction between user cancellation and timeout expiration
  • RAII pattern ensures proper cleanup
  • Simpler, more maintainable code

Testing

Existing tests pass with the new implementation.

This properly sets the canceled flag when a timeout occurs,
allowing tasks to detect timeout cancellation. Also added
TODO comments for potential race conditions.
Simplifies timeout handling by using the new Timeout API:
- Uses task's shared timer heap instead of per-call timer
- Distinguishes timeout from explicit cancel via timeout.triggered
- Handles fairness: re-signals if we stole a wakeup from signal()
…e mutex reacquisition

- Round instead of truncate in Timeout.set to prevent sub-ms timeouts becoming 0ms
- Clear timeout in Condition.timedWait before mutex.lockUncancelable() to prevent spurious timeout during contended lock
- Add debug assertions that timeout.triggered is false on success paths
- Refactor Executor.sleep to use Timeout pattern instead of timedWaitForReady
- Fix timeout_count leak: decrement in timeoutCallback when setting active=false
- Clear timer userdata in timeoutCallback to prevent stale pointer comparisons
- Fixes hang when multiple sleeps are called sequentially on same task
- Change task from *AnyTask to ?*AnyTask (null means inactive)
- Remove redundant active boolean field
- Remove unnecessary timeout_count field (heap already tracks timeouts)
- Simplify init() from function to constant: Timeout.init
- Update all callers to use Timeout.init instead of Timeout.init(runtime)
- Replace timedWaitForReadyWithCallback with Timeout + yield
- Remove callback-based timeout handling
- Simplify error handling with timeout.triggered check
- Add debug assertion for success path
Replace simple boolean canceled flag with a packed struct (u32) that tracks:
- user_canceled (u8): counter for user-initiated cancellations
- timeout (u8): counter for timeout-triggered cancellations
- pending_errors (u16): number of error.Canceled to return in yield

This enables proper handling of concurrent cancellations from multiple
sources and allows distinguishing between timeout and user cancellation.

Key changes:
- Add CanceledStatus packed struct and CAS-based atomic operations
- Add AnyTask.checkTimeout() to check and consume timeout cancellations
- Add AnyTask.checkCanceled() to check and consume pending errors
- Add Runtime.checkTimeout() convenience wrapper
- Update all timeout handling code to use checkTimeout() instead of
  checking timeout.triggered directly
- Update Executor.yield() to use new checkCanceled() method

All operations use optimized CAS loops that leverage returned previous
values to avoid unnecessary atomic loads on retry.
Simplifies the API by making checkCanceled() automatically respect
cancellation shields. This prevents accidentally consuming cancellation
errors while shielded and makes the code more maintainable.

The shield_count check is now internal to checkCanceled(), so callers
in yield() only need to check cancel_mode without also checking
shield_count.
@coderabbitai

coderabbitai Bot commented Nov 1, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Replaces a boolean cancel flag with a packed atomic CanceledStatus and CAS-based updates; adds per-task Timeout/TimeoutHeap and task timer wiring; rewrites wait/cancel flows across I/O, sync primitives, runtime, and task migration to use timeout-aware semantics and propagate updated timer resets through libxev backends.

Changes

Cohort / File(s) Summary
Core cancel/status
src/core/awaitable.zig
Added pub const CanceledStatus (packed u32). Replaced canceled: std.atomic.Value(bool) with canceled_status: std.atomic.Value(u32). cancel() now CAS-loops: load, decode, set user_canceled, increment pending_errors, cmpxchgWeak retry, then wake waiters.
Timeout primitives
src/core/timeout.zig
New public Timeout struct (task, intrusive heap field, deadline_ms, triggered), init, set() and clear(); timeoutLess comparator; exported TimeoutHeap intrusive heap; includes tests.
Task timer integration
src/core/task.zig
Added AnyTask.timeouts: TimeoutHeap, shield_count, pin_count, timer_c, timer_cancel_c. New methods: getNextTimeout, cancelTimer, setTimer, updateTimer, maybeUpdateTimer, checkTimeout, checkCanceled. Added top-level timeoutCallback, noopTimerCancelCallback. canMigrate() now checks awaitable.canceled_status.
Blocking-task check
src/core/blocking_task.zig
threadPoolCallback now tests awaitable.canceled_status.load(...) != 0 instead of boolean canceled before running the user function.
I/O wait & cancel flow
src/io/base.zig
Added pub fn cancelIo(rt, completion). waitForIo() -> Cancelable!void. timedWaitForIo() -> `(Timeoutable
Runtime & executor
src/runtime.zig
Added pub fn checkTimeout(runtime, timeout, err) delegating to current task. Removed timedWaitForComplete() and several timer helpers. yield()/sleep() updated to call task-level checkCanceled/checkTimeout.
Sync primitives
src/sync/Condition.zig, src/sync/Notify.zig, src/sync/ResetEvent.zig
Replaced callback-based timeout contexts with inline Timeout instances; switched to executor.yield() + runtime.checkTimeout() to distinguish timeout vs cancel. Notify.timedWait signature changed to `(Timeoutable
Signal docs
src/signal.zig
Doc: Signal.wait() now states error.Canceled includes timeout expiry.
Public exports
src/zio.zig
Re-exported pub const Timeout from core/timeout.zig.
Select import
src/select.zig
Added Timeoutable import from common.zig.
Vendor: expose heap
vendor/libxev/src/main.zig
Added pub const heap = @import("heap.zig"); with doc comment exposing intrusive pairing heap.
Backend timer reset / cancel propagation
vendor/libxev/src/backend/...
vendor/libxev/src/backend/epoll.zig, .../kqueue.zig, .../iocp.zig, .../wasi_poll.zig
In timer_reset .adding branch compute absolute next once and assign to c.op.timer.next. If a cancellation is active, store that next into c.op.timer.reset so the cancel path can re-arm/re-queue the timer; cancel handlers re-add timers when reset present. Minor userdata/callback order fixes in adding state.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Extra attention:
    • Correctness and atomic ordering of the CAS loop in Awaitable.cancel() (packing/unpacking, pending_errors wrap/limits).
    • Race conditions between timeoutCallback, timer cancel flow, heap remove/re-add, and Timeout.triggered lifecycle.
    • All sites migrated from boolean canceled to canceled_status—verify semantic intent preserved.
    • I/O and sync primitive yield/wakeup transitions: mutex reacquire, waiter removal on cancel, and proper propagation of Timeout vs Cancelable.
    • Backend changes that preserve timer invariants when cancellation is in-flight (reset vs next handling).

Possibly related PRs

Poem

A packed status flips with a careful shove,
Timers stack up, waiting deadlines to shove.
CAS clicks, pending errors climb and wake,
Tasks yield, timeouts fire, and waits unmake.
Small fixes, steady—scheduler stays in love. ⚙️

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 support for stackable per-task timeouts" directly captures the primary objective of this changeset. The raw_summary and pr_objectives confirm that the core contribution is introducing a heap-based timeout system with nested timeout support, replacing previous ad-hoc timer management. The title is concise, specific enough that someone scanning commit history understands the main feature being added, and accurately reflects the substantial infrastructure changes across multiple files. It avoids vague phrasing and clearly highlights the stackable/nested nature of the new timeout mechanism.
Description Check ✅ Passed The description provides meaningful context directly tied to the changeset. It covers the CanceledStatus refactoring, the new Timeout infrastructure with RAII-style semantics, task-level timeout management methods, I/O operation simplifications, and runtime/executor improvements. Each section corresponds to actual changes documented in the raw_summary (e.g., src/core/timeout.zig additions, CanceledStatus changes in awaitable.zig, updates to src/core/task.zig). The description goes beyond generic statements by explaining concrete mechanisms: min-heap ordering, nested timeout support, counter-based cancellation tracking, and defer-based cleanup patterns. It's not vague or generic—it accurately reflects what was changed and why.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch timeout

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

Caution

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

⚠️ Outside diff range comments (1)
src/core/awaitable.zig (1)

24-90: Guard cancellation counters against overflow.

CanceledStatus stores user_canceled/timeout in u8 and pending_errors in u16, yet cancel() just increments them. After 255 user cancels (or 255 timeouts, 65 535 total pending errors) the add will trap in Debug/ReleaseSafe and silently wrap in fast builds, causing us to lose track of queued errors. Long‑running tasks that retry on timeout can absolutely hit those limits. Please widen the counters and the backing atomic so the bookkeeping can’t roll over.

-pub const CanceledStatus = packed struct(u32) {
-    user_canceled: u8 = 0,
-    timeout: u8 = 0,
-    pending_errors: u16 = 0,
-};
+pub const CanceledStatus = packed struct(u64) {
+    user_canceled: u16 = 0,
+    timeout: u16 = 0,
+    pending_errors: u32 = 0,
+};
…
-    canceled_status: std.atomic.Value(u32) = std.atomic.Value(u32).init(0),
+    canceled_status: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
…
-            const new: u32 = @bitCast(status);
+            const new: u64 = @bitCast(status);
📜 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 3acb9f5 and 8d9d703.

📒 Files selected for processing (12)
  • src/core/awaitable.zig (3 hunks)
  • src/core/blocking_task.zig (1 hunks)
  • src/core/task.zig (4 hunks)
  • src/core/timeout.zig (1 hunks)
  • src/io/base.zig (1 hunks)
  • src/runtime.zig (6 hunks)
  • src/signal.zig (1 hunks)
  • src/sync/Condition.zig (2 hunks)
  • src/sync/Notify.zig (3 hunks)
  • src/sync/ResetEvent.zig (3 hunks)
  • src/zio.zig (1 hunks)
  • vendor/libxev/src/main.zig (1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 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/core/awaitable.zig
  • src/core/blocking_task.zig
  • src/io/base.zig
  • src/signal.zig
📚 Learning: 2025-10-15T19:38:44.659Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 47
File: src/sync/Mutex.zig:237-237
Timestamp: 2025-10-15T19:38:44.659Z
Learning: In the `unlock` method of `src/sync/Mutex.zig`, the `runtime` parameter is intentionally retained (marked with `_ = runtime;`) for API consistency and future-proofing, even though it's not currently used in the implementation.

Applied to files:

  • src/sync/Condition.zig
  • src/runtime.zig
📚 Learning: 2025-10-21T10:00:56.962Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 62
File: src/utils/queue.zig:141-147
Timestamp: 2025-10-21T10:00:56.962Z
Learning: In work-stealing queues implemented in src/utils/queue.zig, stealers only modify the victim's head position, never the tail. The tail is exclusively owned by the owner thread, so no atomic acquire operations are needed when the owner reads its own tail.

Applied to files:

  • src/sync/Condition.zig
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 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.

Applied to files:

  • src/core/blocking_task.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.

Applied to files:

  • src/core/blocking_task.zig
  • src/core/task.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)

Comment thread src/core/timeout.zig Resolved
Comment thread src/runtime.zig Resolved
…ock usage

Changes checkTimeout signature to take the caught error as a parameter,
making it explicit that this function should be called from a catch block.
The function now returns either error.Timeout (if the timeout triggered)
or the original error.Canceled (if user canceled).

This improves the API by:
- Making the usage pattern more explicit (must be in catch block)
- Clearly showing the error transformation (Canceled -> Timeout)
- Reducing the chance of incorrect usage

Special handling in sleep() where timeout is the expected success case -
it catches error.Timeout and returns void (success), while propagating
error.Canceled.
Once user_canceled > 0, the task is "condemned" and must quit. This commit
implements priority-based cancellation handling:

In timeoutCallback:
- If user_canceled > 0: Only increment pending_errors (task already condemned)
- Otherwise: Increment both timeout and pending_errors, set triggered=true
- This ensures timeout information is discarded once user cancels

In checkTimeout:
- Always check user_canceled first - if > 0, return error.Canceled
- Only check timeout if no user cancellation exists
- user_canceled is never decremented (permanent condemnation marker)
- timeout counter is decremented when consumed

This design ensures:
- User cancellation is non-recoverable and has absolute priority
- Multiple cancel() calls stack as multiple error.Canceled
- Timeout cancellation is recoverable via checkTimeout
- Once user cancels, subsequent timeouts don't set triggered flag
- Clean semantics: condemned tasks always return error.Canceled
Since user_canceled is never decremented and only checked for > 0,
it can be simplified to a bool flag. The "condemned" state is binary -
either the user has requested cancellation or they haven't.

Multiple cancel() calls still stack properly via the pending_errors
counter, which gets decremented by checkCanceled().

Changes:
- CanceledStatus.user_canceled: u8 -> bool (with u7 padding)
- cancel(): Set flag instead of increment
- timeoutCallback: Check bool instead of > 0
- checkTimeout: Check bool instead of > 0

This simplification makes the semantics clearer: user_canceled is a
permanent condemnation flag, not a counter.
@lalinsky lalinsky changed the title Implement timeout infrastructure with heap-based deadline management Add support for stackable per-task timeouts Nov 1, 2025
Adds 6 new tests covering key timeout scenarios:
- Timeout fires and returns error.Timeout
- Nested timeouts - earliest deadline fires first
- Timeout cleared before firing doesn't trigger
- User cancellation has priority over timeout
- Multiple timeouts with different deadlines (heap ordering)
- Set, clear, and re-set timeout lifecycle

All tests verify correct behavior of the priority-based cancellation
system where user_canceled takes precedence over timeout.

159 of 159 tests passing.

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

📜 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 8d9d703 and e50d855.

📒 Files selected for processing (8)
  • src/core/awaitable.zig (3 hunks)
  • src/core/task.zig (4 hunks)
  • src/io/base.zig (1 hunks)
  • src/runtime.zig (6 hunks)
  • src/select.zig (1 hunks)
  • src/sync/Condition.zig (2 hunks)
  • src/sync/Notify.zig (3 hunks)
  • src/sync/ResetEvent.zig (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/sync/Condition.zig
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 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/io/base.zig
  • src/runtime.zig
  • src/core/awaitable.zig
📚 Learning: 2025-10-03T11:09:46.846Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 18
File: src/net.zig:18-25
Timestamp: 2025-10-03T11:09:46.846Z
Learning: In zio's `Runtime.BlockingTask`, calling `deinit()` on a blocking task only frees the task wrapper (TaskData) itself, not the result returned by the blocking function. The result remains valid and owned by the caller, who is responsible for its cleanup. This is the intended design for async blocking tasks.

Applied to files:

  • src/runtime.zig
  • src/core/task.zig
📚 Learning: 2025-10-16T14:33:19.718Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 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.

Applied to files:

  • src/runtime.zig
🔇 Additional comments (13)
src/runtime.zig (5)

521-524: LGTM - Pre-yield cancellation check.

The change correctly uses the new checkCanceled() API to consume one pending error before yielding, which aligns with the new counter-based cancellation model.


559-562: LGTM - Post-resume cancellation check.

Correctly checks for cancellation after resuming, ensuring cancellations that occurred during suspension are detected.


586-592: LGTM - Updated cancellation semantics.

Documentation correctly describes the new behavior of consuming one pending error, and the implementation properly delegates to the task-level method.


622-639: LGTM - Clean timeout-based sleep implementation.

The RAII-style Timeout with defer cleanup is elegant. The catch block correctly distinguishes between timeout expiration (returns successfully) and user cancellation (propagates error), with proper unreachable markers indicating the expected flow.


1172-1182: LGTM - Well-designed public timeout check API.

The documentation clearly explains the usage pattern (call in catch blocks), and the implementation correctly delegates to the task-level logic with appropriate no-op behavior when not in a coroutine.

src/core/task.zig (8)

30-40: LGTM - Well-structured per-task timeout state.

The fields support the new timeout infrastructure with a clear separation of concerns: heap storage (timeouts), timer state (timer_c, timer_cancel_c), and behavioral controls (shield_count, pin_count).


80-85: LGTM - Correct migration check with new cancellation status.

The change correctly checks the packed CanceledStatus (any non-zero value prevents migration), maintaining the same safety guarantee with the new counter-based model.


87-103: LGTM - Correct timeout queue management.

The method properly handles expired timeouts and calculates delays for the next valid timeout. The unreachable marker is correct since all paths through the loop return a value.


105-165: LGTM - Solid timer lifecycle management.

The timer methods handle edge cases correctly (dead timer, null userdata) and the defensive clearing of userdata before cancellation prevents spurious callbacks. The maybeUpdateTimer optimization (only resetting when the timeout pointer changes) is a nice touch.


167-201: LGTM - Correct timeout priority logic.

The implementation correctly enforces user cancellation priority (always returns error.Canceled if user_canceled is set) and only returns error.Timeout when the timeout actually triggered and hasn't been consumed yet. The documentation clearly notes that pending_errors is consumed separately by checkCanceled(), which is the correct design.


203-230: LGTM - Clean cancellation check with shield support.

The implementation correctly respects cancellation shields and uses a CAS loop to atomically consume one pending error. The early return when no errors are pending avoids unnecessary spinning.


320-382: LGTM - Careful timeout cancellation logic.

The callback correctly handles the distinction between user-initiated and timeout-initiated cancellations using the mark_as_triggered flag. The CAS loop ensures mark_as_triggered reflects the state that was actually committed, and even in race scenarios, checkTimeout correctly prioritizes user cancellation by checking user_canceled first.


384-396: LGTM - Standard noop callback.

Consistent with the existing noopTimerCancelCallback pattern in the codebase (e.g., runtime.zig line 92).

Comment thread src/io/base.zig Resolved
Comment thread src/select.zig
const builtin = @import("builtin");
const Runtime = @import("runtime.zig").Runtime;
const Cancelable = @import("common.zig").Cancelable;
const Timeoutable = @import("common.zig").Timeoutable;

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.

⚠️ Potential issue | 🔴 Critical

Fix unused Timeoutable import

const Timeoutable = @import("common.zig").Timeoutable; isn’t referenced anywhere in this file, so Zig will stop with an unused-declaration error. Drop the import or wire it into the code before merging.

-const Timeoutable = @import("common.zig").Timeoutable;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const Timeoutable = @import("common.zig").Timeoutable;
🤖 Prompt for AI Agents
In src/select.zig around line 8, the declaration "const Timeoutable =
@import(\"common.zig\").Timeoutable;" is unused and causes an unused-declaration
error; fix by either removing that import line entirely if Timeoutable is not
needed, or wire it into the file by using Timeoutable in the relevant function
signature/variable/type where timeouts are handled so the symbol is referenced
(choose the removal if there is no intended timeout-related API to implement).

@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

♻️ Duplicate comments (1)
src/core/timeout.zig (1)

43-43: Sub-millisecond rounding (previously discussed)

This rounding converts timeouts < 0.5ms to zero milliseconds, which sets the deadline to now() and triggers at the next yield point. Based on the previous discussion, this millisecond-granularity behavior appears intentional, but it means microsecond-precision timeouts aren't supported.

🧹 Nitpick comments (2)
src/core/timeout.zig (2)

31-31: Add a comment explaining when this is valid

The unreachable here will crash if set() is called outside of a task context. This is probably the intended behavior (timeouts must be associated with tasks), but a brief comment explaining this precondition would help future readers understand the requirement.

+    // Must be called from within a task context
     const task = self.task orelse rt.getCurrentTask() orelse unreachable;

43-44: Potential overflow in @intcast is unlikely but unchecked

Casting the u64 result to i64 could overflow for extremely large timeout_ns values (tens of thousands of years worth of milliseconds). In practice this won't happen, but you could add a debug assert or use @intCast with explicit overflow handling if you want to be defensive.

Example with assert:

     const timeout_ms: i64 = @intCast((timeout_ns + std.time.ns_per_ms / 2) / std.time.ns_per_ms);
+    std.debug.assert(timeout_ms >= 0); // Verify no overflow occurred
📜 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 e50d855 and 5568db9.

📒 Files selected for processing (1)
  • src/core/timeout.zig (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 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/core/timeout.zig
🔇 Additional comments (7)
src/core/timeout.zig (7)

1-4: LGTM - clean imports

The imports are minimal and cover what's needed for the timeout infrastructure.


6-18: LGTM - well-documented struct

The doc comment clearly explains the nesting behavior, RAII pattern, and how triggered distinguishes timeout-induced cancellation from explicit cancellation. The field types are appropriate for the timeout heap infrastructure.


20-28: LGTM - correct cleanup

The method properly handles the inactive case (early return), removes from the heap, updates the shared timer, and clears the task reference to allow reuse. The debug assert provides a reasonable safety check.


30-47: LGTM - set() logic is sound

The method correctly handles both first-set and re-set cases. Line 31 ensures that when self.task is non-null, task equals self.task, so the remove operation at line 39 operates on the right heap. The triggered reset (line 42), deadline computation (line 44), heap insertion (line 45), and timer update (line 46) all follow the correct sequence.


50-53: LGTM - correct min-heap comparator

Orders by earliest deadline first, which is exactly what's needed for the timeout heap.


56-56: LGTM

Clean type alias for the intrusive heap. The void context and timeoutLess comparator are correct.


61-274: LGTM - comprehensive test coverage

The test suite covers the essential scenarios: basic set/clear, timeout firing, nested timeouts with priority, clearing before expiration, user cancellation priority over timeout (key design requirement), multiple concurrent timeouts, and re-use patterns. All tests correctly use the RAII defer pattern for cleanup and properly verify both error values and the triggered field state.

When timer_reset() is called while a cancellation is in-flight and the
timer is in .adding state, the reset wasn't being properly handled in
backends that use process_cancellations (iocp, kqueue).

The issue:
- Timer in .adding state when timer_reset() is called
- Cancel is already in-flight (c_cancel.state() == .active)
- timer_reset() modifies next/userdata/callback but doesn't set reset field
- When process_cancellations runs, it marks timer .dead without checking reset
- Timer never gets rearmed with new deadline

The fix:
- In timer_reset() .adding branch: set reset field when cancel is active
- In process_cancellations() .adding case (iocp/kqueue): check reset and re-add timer
- epoll/wasi_poll already handle this correctly in stop_completion()

This was causing timeout tests to hang on Windows/macOS.
Call checkTimeout before clearing timeout state to preserve the triggered
flag, ensuring real timeouts return error.Timeout instead of error.Canceled

@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/io/base.zig (1)

75-81: Remove redundant explicit timeout.clear().

Good fix on the classification order (line 77 calls checkTimeout before clear, preserving the timeout triggered flag). However, line 78's explicit timeout.clear(rt) is redundant—the defer on line 60 already handles cleanup and will run immediately after return. Calling clear twice violates the RAII pattern and adds confusion.

Apply this diff to rely on the defer:

     executor.yield(.preparing_to_wait, .waiting, .allow_cancel) catch |err| {
         // Classify the error before clearing timeout state
         const classified_err = rt.checkTimeout(&timeout, err);
-        timeout.clear(rt);
         cancelIo(rt, completion);
         return classified_err;
     };

The defer ensures cleanup happens before the caller regains control, and cancelIo doesn't require the timeout to be cleared first (it's shielded anyway).

📜 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 763f21c and a0f7b1b.

📒 Files selected for processing (1)
  • src/io/base.zig (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: lalinsky
Repo: lalinsky/zio PR: 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.
📚 Learning: 2025-10-10T05:59:17.087Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 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/io/base.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 (2)
src/io/base.zig (2)

15-28: LGTM! Clear cancellation flow.

The shield properly prevents user cancellations during the two-phase cancel+wait sequence. The unreachable on line 27 is justified since the shield guarantees no cancellation errors.


30-52: Solid state machine implementation.

The preparing_to_wait optimization avoids suspension when IO completes during the transition window. The atomic CAS in yield (line 46) handles the race correctly, and the assertion on line 51 is safe since it only runs after successful yield (completion callback has disarmed).

@lalinsky
lalinsky merged commit 1dce8a9 into main Nov 2, 2025
@lalinsky
lalinsky deleted the timeout branch November 2, 2025 05:08
This was referenced Jan 15, 2026
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