Skip to content

Fix interaction between timeouts and cancelation of spawned tasks - #181

Merged
lalinsky merged 2 commits into
mainfrom
timeout-cancelations-fix
Jan 8, 2026
Merged

lalinsky merged 2 commits into
mainfrom
timeout-cancelations-fix

Conversation

@lalinsky

@lalinsky lalinsky commented Jan 8, 2026

Copy link
Copy Markdown
Owner

No description provided.

@coderabbitai

coderabbitai Bot commented Jan 8, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Refactors timer handling and cancellation semantics: checkTimers now returns a TimerCheckResult { next_timeout_ms: ?u64, fired: bool }; select's wait path resets per-wait state after cancellation; adds a test that a spawned task is canceled via Timeout/join.

Changes

Cohort / File(s) Summary
Timer checking and event loop
src/ev/loop.zig
checkTimers signature changed from ?u64 to TimerCheckResult (fields: next_timeout_ms: ?u64, fired: bool). Tick path now uses fired to decide blocking and timeout math.
Task wait/cancellation state
src/select.zig
In waitInternal, after calling fut.cancel() the task's per-wait state is swapped to .preparing_to_wait with an assert that previous state was .ready, ensuring correct state for the next yield.
Timeout behavior tests
src/runtime/timeout.zig
New test "Timeout: cancels spawned task via join" added to confirm a spawned blocker task is canceled when a Timeout fires and that join yields the timeout error.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

Timers whisper when to wake, then tell if one has fired,
A canceled wait resets its state—no lost wakeups required.
A test now checks the timeout’s bite,
Async order kept polite. 🎯⏰

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description check ❓ Inconclusive No description was provided by the author, making it impossible to assess whether it relates to the changeset. Add a brief description explaining the timeout-cancellation bug being fixed and how the three-file solution addresses it.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title directly matches the changeset: fixes the interaction between timeouts and task cancellation across three files (loop.zig, timeout.zig, select.zig).
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch timeout-cancelations-fix

📜 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 eba7141 and 16dcb29.

📒 Files selected for processing (1)
  • src/runtime/timeout.zig
🧰 Additional context used
📓 Path-based instructions (1)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

Use zig env to get the path to the Zig standard library when checking standard library

Files:

  • src/runtime/timeout.zig
🧠 Learnings (4)
📚 Learning: 2025-11-04T10:29:56.949Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 118
File: src/core/task.zig:33-115
Timestamp: 2025-11-04T10:29:56.949Z
Learning: In zio's task implementation (src/core/task.zig), the Closure struct intentionally caps result_len and context_len at 4096 bytes (using u12 fields) and alignment at 16 bytes (using u4 padding fields). This is a deliberate design decision to avoid bloating task structures. Users needing larger result or context storage should heap-allocate and pass pointers instead. These limits are more generous than std lib's fixed storage (64 bytes for results, 1024 bytes for args).
<!-- [add_learning]
The task storage limits in zio (4 KiB for result/context, 16-byte alignment) are intentional design constraints to prevent task bloat, not correctness issues. The maintainer's position is that larger data should be heap-allocated.

Applied to files:

  • src/runtime/timeout.zig
📚 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/runtime/timeout.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/runtime/timeout.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/timeout.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). (2)
  • GitHub Check: test (windows-latest)
  • GitHub Check: test (macos-latest)
🔇 Additional comments (1)
src/runtime/timeout.zig (1)

260-293: Test looks solid.

The test correctly validates the timeout-join-cancel interaction:

  1. Spawns a long-running task
  2. Sets a short timeout
  3. Joins (which blocks waiting for the task)
  4. Expects the join to be interrupted by the timeout
  5. Properly cleans up via defer handle.cancel(rt) - this is key since the blocker is still running when join times out

The error handling pattern matches the other tests in this file. The defer ordering is correct: cancel runs before timeout.clear, ensuring the spawned task is properly terminated.


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

🤖 Fix all issues with AI agents
In @src/runtime/timeout.zig:
- Around line 260-293: The test "Timeout: cancels spawned task via join" is
calling Timeout.set with a raw 10 which is interpreted as 10 nanoseconds; change
the call to pass 10 milliseconds by multiplying 10 by the
nanoseconds-per-millisecond constant (use std.time.ns_per_ms) so that
Timeout.set(rt, ...) receives the timeout in nanoseconds as expected; update the
call to Timeout.set in the Test.main to use 10 * std.time.ns_per_ms (i.e.,
convert ms to ns) to avoid flakiness.
📜 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 abc32e3 and eba7141.

📒 Files selected for processing (3)
  • src/ev/loop.zig
  • src/runtime/timeout.zig
  • src/select.zig
🧰 Additional context used
📓 Path-based instructions (1)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

Use zig env to get the path to the Zig standard library when checking standard library

Files:

  • src/select.zig
  • src/runtime/timeout.zig
  • src/ev/loop.zig
🧠 Learnings (4)
📚 Learning: 2025-10-23T16:17:53.575Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 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
📚 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/select.zig
📚 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/select.zig
  • src/runtime/timeout.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/timeout.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). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: test (windows-latest)
🔇 Additional comments (4)
src/select.zig (1)

462-465: LGTM! Correct state reset for cancellation retry.

The state swap from .ready to .preparing_to_wait is necessary because fut.cancel() wakes the task (setting state to .ready), but the next yield iteration expects .preparing_to_wait for its CAS to succeed. The assertion verifies this state transition.

src/ev/loop.zig (3)

499-502: Clean refactoring - struct encapsulates timer check results.

The TimerCheckResult struct groups the timeout value with a flag indicating whether timers fired, making the return value more expressive than a bare optional.


504-516: Improved timer handling - tracks fired state correctly.

The refactored checkTimers now returns both the next timeout and whether any timers fired during this check. The fired flag is properly set when timers are completed (line 514) and preserved across the loop, allowing callers to differentiate between "no timers" and "timers just fired."


635-642: Better responsiveness - avoids blocking after timer fires.

Using timer_result.fired in the timeout calculation (line 640) prevents the loop from blocking immediately after processing timers. This ensures that any work triggered by timer callbacks gets a chance to run without an unnecessary wait cycle.

Comment thread src/runtime/timeout.zig Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 3 files

@lalinsky
lalinsky merged commit 9ba190b into main Jan 8, 2026
@lalinsky
lalinsky deleted the timeout-cancelations-fix branch January 8, 2026 09:59
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