Skip to content

Rename Timeout to AutoCancel - #207

Merged
lalinsky merged 3 commits into
mainfrom
rename-timeout-to-autocancel
Jan 16, 2026
Merged

lalinsky merged 3 commits into
mainfrom
rename-timeout-to-autocancel

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

  • Rename zio.Timeout to zio.AutoCancel to free up the Timeout name for a future tagged union type (matching std.Io.Timeout)
  • Move timeout consumption logic to Awaitable.consumeAutoCancel()
  • Replace Runtime.checkTimeout() with AutoCancel.check() returning bool
  • Rename CanceledStatus.timeout to auto_canceled

Test plan

  • All existing tests pass
  • Full build (examples and benchmarks) succeeds

- Rename zio.Timeout to zio.AutoCancel to free up the Timeout name
  for a future tagged union type (matching std.Io.Timeout)
- Move timeout consumption logic to Awaitable.consumeAutoCancel()
- Replace Runtime.checkTimeout() with AutoCancel.check() returning bool
- Rename CanceledStatus.timeout to auto_canceled
@coderabbitai

coderabbitai Bot commented Jan 16, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Renames Timeout → AutoCancel, introduces AutoCancel.check(rt, err), and shifts cancellation APIs from checkCanceled → checkCancel plus awaitable auto-cancel semantics across runtime, tasks, I/O, and synchronization timed-wait paths. Public exports updated accordingly.

Changes

Cohort / File(s) Summary
Core runtime & autocancel
src/runtime/autocancel.zig, src/runtime.zig, src/runtime/task.zig
Rename Timeout → AutoCancel; add AutoCancel.check(rt, err); remove Runtime.checkTimeout; rename checkCanceled → checkCancel on Runtime/Executor/Task; adjust cancel logic to use awaitable check APIs.
Awaitable cancel model
src/runtime/awaitable.zig
Replace timeout flag with auto_canceled; add CancelKind enum; change setCanceled to accept kind and return bool; add checkAutoCancel and checkCancel helpers.
I/O & signal timed-waits
src/io.zig, src/signal.zig
Swap Timeout import for AutoCancel; use AutoCancel.init; on cancellation errors call if (timer.check(rt, err)) return error.Timeout; else propagate original error.
Sync primitives (timed waits)
src/sync/Condition.zig, src/sync/Futex.zig, src/sync/Notify.zig, src/sync/ResetEvent.zig, src/sync/Mutex.zig, src/sync/Semaphore.zig
Replace Timeout → AutoCancel in timedWait flows; use timer.check(...) to map auto-cancel → error.Timeout; rename runtime cancellation checks to checkCancel; update doc comments.
Public exports & small call sites
src/zio.zig, src/runtime/blocking_task.zig, src/io.zig (export), tests/...
Export pub const AutoCancel instead of Timeout; callsites updated to awaitable.setCanceled(.user) and renamed check methods; tests adjusted to use AutoCancel.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

A timer shed its old name, AutoCancel now in play,
User cancels stand first in line, autos only sneak a way.
Checks consume the tiny flags, tasks wake when they must,
Code shifted, names aligned — in careful, minimal trust. 🚦

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the primary change: renaming Timeout to AutoCancel across the codebase.
Description check ✅ Passed The description covers the main objectives and directly relates to the changeset: renaming Timeout to AutoCancel, moving logic, replacing methods, and renaming fields.
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 rename-timeout-to-autocancel

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

Caution

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

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

26-149: consumeAutoCancel() must decrement pending_errors when consuming an auto-cancel.

When setTimeout() fires, it increments both auto_canceled and pending_errors (src/runtime/task.zig:237–238). But consumeAutoCancel() only decrements auto_canceled, leaving pending_errors hanging. This breaks the pairing: later checkCanceled() calls (which decrement pending_errors) will still see a nonzero count and incorrectly return error.Canceled even though you've already handled the timeout.

The fix should also assert that pending_errors > 0 when consuming:

Required fix
if (status.auto_canceled > 0) {
+   std.debug.assert(status.pending_errors > 0);
    status.auto_canceled -= 1;
+   status.pending_errors -= 1;
    const new: u32 = `@bitCast`(status);
    if (self.canceled_status.cmpxchgWeak(current, new, .acq_rel, .acquire)) |prev| {
        current = prev;
        continue;
    }
    return true;
}
📜 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 4cce02c and 1e47151.

📒 Files selected for processing (11)
  • src/io.zig
  • src/runtime.zig
  • src/runtime/autocancel.zig
  • src/runtime/awaitable.zig
  • src/runtime/task.zig
  • src/signal.zig
  • src/sync/Condition.zig
  • src/sync/Futex.zig
  • src/sync/Notify.zig
  • src/sync/ResetEvent.zig
  • src/zio.zig
🧰 Additional context used
🧠 Learnings (9)
📚 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/zio.zig
  • src/sync/ResetEvent.zig
  • src/sync/Futex.zig
  • src/sync/Condition.zig
  • src/signal.zig
  • src/runtime/awaitable.zig
  • src/io.zig
  • src/runtime/autocancel.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.

Applied to files:

  • src/zio.zig
  • src/sync/ResetEvent.zig
  • src/sync/Futex.zig
  • src/sync/Notify.zig
  • src/sync/Condition.zig
  • src/signal.zig
  • src/runtime/task.zig
  • src/runtime.zig
  • src/runtime/awaitable.zig
  • src/io.zig
  • src/runtime/autocancel.zig
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.

Applied to files:

  • src/zio.zig
  • src/sync/ResetEvent.zig
  • src/sync/Futex.zig
  • src/sync/Notify.zig
  • src/sync/Condition.zig
  • src/signal.zig
  • src/runtime/task.zig
  • src/runtime.zig
  • src/runtime/awaitable.zig
  • src/io.zig
  • src/runtime/autocancel.zig
📚 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/sync/ResetEvent.zig
  • src/sync/Futex.zig
  • src/runtime/task.zig
  • src/runtime.zig
  • src/io.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/ResetEvent.zig
  • src/sync/Notify.zig
  • src/sync/Condition.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/Futex.zig
  • src/sync/Condition.zig
  • src/runtime.zig
📚 Learning: 2025-10-21T10:07:03.593Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 62
File: src/utils/queue.zig:109-126
Timestamp: 2025-10-21T10:07:03.593Z
Learning: In src/utils/queue.zig WorkStealingQueue implementation, the owner thread can safely use `.raw` to read its own `tail` atomic value since the owner is always a single thread and only it modifies tail. No ordering is needed when reading your own writes within the same thread.

Applied to files:

  • src/sync/Condition.zig
📚 Learning: 2026-01-07T13:15:48.677Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 179
File: src/os/windows.zig:424-424
Timestamp: 2026-01-07T13:15:48.677Z
Learning: In `src/os/windows.zig`, WSABUF must be re-exported from `std.os.windows.ws2_32.WSABUF` rather than defined locally because it needs to satisfy `std.Io.Reader` compatibility requirements.

Applied to files:

  • src/signal.zig
  • src/io.zig
📚 Learning: 2026-01-10T20:01:19.727Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 192
File: src/runtime/blocking_task.zig:82-85
Timestamp: 2026-01-10T20:01:19.727Z
Learning: Blocking tasks submitted via Runtime.spawnBlocking() are not currently cancelable in zio. No code calls thread_pool.cancel() on blocking tasks. Cancellation support (including ensuring completion callbacks fire for canceled work) is tracked as a future enhancement.

Applied to files:

  • src/runtime.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 (21)
src/runtime/autocancel.zig (2)

13-68: AutoCancel API rename + check flow look consistent.
No issues spotted in the core timer setup and check semantics.


71-288: Callback rename + test updates look good.
The test coverage for nested and priority cases is solid.

src/sync/Condition.zig (2)

63-63: AutoCancel import swap is fine.


178-210: Verify timeout mapping order vs cancellation check.
If runtime.checkCanceled() consumes auto-cancel, timeouts may surface as error.Canceled before timer.check() runs. Either confirm checkCanceled ignores auto-cancel or reorder the checks.

Suggested ordering (if auto-cancel is consumed by checkCanceled)
-        try runtime.checkCanceled();
-
-        // Check if this auto-cancel triggered, otherwise it was user cancellation
-        if (timer.check(runtime, err)) return error.Timeout;
-        return err;
+        // Check if this auto-cancel triggered, otherwise it was user cancellation
+        if (timer.check(runtime, err)) return error.Timeout;
+        try runtime.checkCanceled();
+        return err;
src/zio.zig (1)

12-12: AutoCancel re-export looks good.

src/sync/Notify.zig (1)

57-187: AutoCancel integration in timedWait looks good.
The mapping from auto-cancel to error.Timeout is consistent with the new API.

src/runtime/task.zig (1)

234-239: LGTM - comments and field updated to auto-cancel terminology.

The logic is unchanged; only the naming reflects the new auto_canceled field in CanceledStatus. One minor observation: the function is still named setTimeout while it now conceptually handles "auto-cancel" state. If the internal API is meant to stay as-is for now, that's fine - just worth noting for future cleanup.

src/sync/ResetEvent.zig (2)

58-58: Import updated to AutoCancel - looks good.


192-205: Clean migration to the new AutoCancel API.

The pattern if (timer.check(runtime, err)) return error.Timeout; is straightforward - check if this specific timer caused the cancellation, map to error.Timeout, otherwise propagate the original error. This is clearer than the previous rt.checkTimeout() approach since the responsibility now sits with the timer instance itself.

src/runtime.zig (1)

33-33: Import path updated from Timeout to AutoCancel.

The removal of Runtime.checkTimeout() (not shown in diff but mentioned in summary) shifts the responsibility to AutoCancel.check(), which makes sense - the timer should know whether it triggered, not the runtime.

src/signal.zig (2)

13-13: Import updated to AutoCancel.


339-352: Consistent with the AutoCancel pattern used elsewhere.

Same pattern as ResetEvent.timedWait() - initialize with AutoCancel.init, set the timer, and in the catch path use timer.check(rt, err) to distinguish between timeout and user cancellation.

src/io.zig (3)

15-15: Import updated to AutoCancel.


160-160: Timer initialization updated to AutoCancel.init.


178-185: Good - capturing check result before clear.

The sequence here is deliberate: capture timer.check(rt, err) result first, then timer.clear(), then cancel the I/O. This matters because check() examines the timer's triggered state which clear() resets. The explicit is_timeout variable makes the intent clear.

The double clear() call (defer on line 161 plus explicit on line 183) is safe—clear() is idempotent. The first call nullifies self.loop, so the deferred call returns early without doing additional work.

src/sync/Futex.zig (6)

33-33: Import rename aligns with the new AutoCancel type.
No issues here.


113-116: AutoCancel timer setup looks consistent.
Set/clear flow is clean and matches the new API.


146-148: Confirm AutoCancel.check only maps auto-cancel to Timeout.
Please double‑check that AutoCancel.check(runtime, err) returns true only for auto‑cancelled error.Canceled and not for user‑initiated cancellations, otherwise this path would surface error.Timeout incorrectly.


233-235: Test update matches the rename.
Looks good.


302-304: Test update matches the rename.
Looks good.


346-348: Test update matches the rename.
Looks good.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@lalinsky

Copy link
Copy Markdown
Owner Author

@coderabbitai pending_errors should NOT actually be decreased here, the error was already delivered, that's why it has err as parameter, to make it obvious to the user to only call this after they received error.Canceled

@coderabbitai

coderabbitai Bot commented Jan 16, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find where pending_errors is decremented in the autocancel and awaitable files
echo "=== Searching for pending_errors in autocancel.zig ==="
rg -n -C5 'pending_errors' src/runtime/autocancel.zig

echo -e "\n=== Searching for pending_errors in awaitable.zig ==="
rg -n -C5 'pending_errors' src/runtime/awaitable.zig

echo -e "\n=== Looking at the check method in autocancel.zig ==="
ast-grep --pattern $'pub fn check($$$) $$$ {
  $$$
}'  src/runtime/autocancel.zig

Length of output: 2458


🏁 Script executed:

#!/bin/bash
# Read the full autocancel.zig file to see the check method
cat src/runtime/autocancel.zig

echo -e "\n\n=== Now let's look at consumeAutoCancel in awaitable.zig ==="
ast-grep --pattern $'pub fn consumeAutoCancel($$$) $$$ {
  $$$
}'  src/runtime/awaitable.zig

Length of output: 9124


🏁 Script executed:

#!/bin/bash
# Read the awaitable.zig file to see the consumeAutoCancel method
cat src/runtime/awaitable.zig

Length of output: 8369


🏁 Script executed:

#!/bin/bash
# Check task.zig for setTimeout and pending_errors handling
echo "=== Looking at setTimeout in task.zig ==="
rg -n -C10 'setTimeout' src/runtime/task.zig

echo -e "\n=== Looking for pending_errors in task.zig ==="
rg -n -C5 'pending_errors' src/runtime/task.zig

Length of output: 3949


@lalinsky You're absolutely right! I found the bug.

In src/runtime/task.zig, the setTimeout() method incorrectly increments pending_errors:

Line 232 (user_canceled branch):

status.pending_errors += 1;

Line 238 (auto-cancel branch):

status.pending_errors += 1;

Both of these are wrong. The error has already been delivered to the user (that's why they have the err parameter when calling check()). The pending_errors counter is meant for errors that need to be consumed later via checkCanceled(), not for errors that are already being handled.

The correct behavior:

  • Line 232: Remove the pending_errors increment entirely (if user_canceled is already set, we don't need to do anything extra)
  • Line 238: Only increment auto_canceled, NOT pending_errors

The err parameter in check() is indeed the signal that the error was already delivered, so incrementing pending_errors creates an extra phantom error that will never be properly consumed.


🧠 Learnings used
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.

@lalinsky

Copy link
Copy Markdown
Owner Author

@coderabbitai you seem to be misunderstanding how the CancelationStatus works

@coderabbitai

coderabbitai Bot commented Jan 16, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the CanceledStatus struct and pending_errors usage in awaitable.zig
echo "=== CanceledStatus struct definition and related methods in awaitable.zig ==="
ast-grep --pattern $'pub const CanceledStatus = struct {
  $$$
}'  src/runtime/awaitable.zig

echo -e "\n=== Full context around pending_errors in awaitable.zig ==="
rg -n -B5 -A15 'pending_errors' src/runtime/awaitable.zig

echo -e "\n=== consumeAutoCancel method ==="
rg -n -B2 -A25 'pub fn consumeAutoCancel' src/runtime/awaitable.zig

Length of output: 4785


🏁 Script executed:

#!/bin/bash
# Read the setTimeout and related logic in task.zig
echo "=== setTimeout implementation in task.zig ==="
rg -n -B5 -A20 'pub fn setTimeout' src/runtime/task.zig

echo -e "\n=== Any comments about pending_errors in task.zig ==="
rg -n -B3 -A3 'pending_errors' src/runtime/task.zig

Length of output: 3805


🏁 Script executed:

#!/bin/bash
# Read the check method in autocancel.zig
echo "=== check method implementation in autocancel.zig ==="
rg -n -B5 -A30 'pub fn check' src/runtime/autocancel.zig

echo -e "\n=== Full autocancel.zig to understand the flow ==="
cat src/runtime/autocancel.zig | head -100

Length of output: 4849


@lalinsky You're right, I apologize. Looking at the code more carefully:

The flow is:

  1. setTimeout() increments pending_errors → queues an error for future delivery
  2. A cancellation point (like waitForIo, checkCanceled) sees pending_errors > 0, decrements it, and returns error.Canceled to the user
  3. User receives error.Canceled in catch block and calls timer.check(rt, err)
  4. check() consumes from auto_canceled counter (not pending_errors, which was already decremented in step 2)

So pending_errors represents errors that will be delivered at future cancellation points. When setTimeout() increments it, it's queuing the error. By the time the user has err in their hand, pending_errors was already decremented during delivery.

The setTimeout() implementation is correct:

  • Line 232: user_canceled branch increments pending_errors to add another queued error
  • Line 238: auto-cancel branch increments both auto_canceled and pending_errors

Could you clarify what specific aspect of CanceledStatus I'm getting wrong? I want to understand the contract correctly.


🧠 Learnings used
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.

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.

Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:47.638Z
Learning: In src/stdio.zig, swapCancelProtectionImpl's return value is an opaque restoration token, not a reflection of actual shield state. The std.Io contract guarantees paired calls (old = swap(new); defer swap(old)), allowing the implementation to use increment/decrement logic (swap(.blocked) increments shield_count and returns .unblocked; swap(.unblocked) decrements and returns .blocked) without exposing internal state.

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.

- Add CancelKind enum to distinguish user vs auto cancellation
- Move setCanceled logic to Awaitable with kind parameter
- Remove setTimeout from AnyTask (now handled by setCanceled(.auto))
- Add checkCancel and checkAutoCancel methods to Awaitable
- Rename checkCanceled to checkCancel throughout codebase
- Only wake task on cancel if setCanceled returns true
- Use resumeTask directly instead of indirect wake() call

@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

Caution

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

⚠️ Outside diff range comments (1)
src/runtime/autocancel.zig (1)

37-59: Disable‑timeout path should clear prior state. If set() is called with Duration.max after a previous timer was armed, the early return leaves the old timer running and task/loop refs intact, which can trigger unexpected cancellation. Clear/reset state before returning.

🛠️ Proposed fix
-        // Skip setting timer if waiting forever
-        if (timeout.ns == Duration.max.ns) return;
+        // Skip setting timer if waiting forever
+        if (timeout.ns == Duration.max.ns) {
+            // Ensure any prior timer/state is cleared
+            self.clear(rt);
+            self.triggered = false;
+            self.task = null;
+            self.loop = null;
+            return;
+        }
📜 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 1e47151 and 9303d44.

📒 Files selected for processing (8)
  • src/runtime.zig
  • src/runtime/autocancel.zig
  • src/runtime/awaitable.zig
  • src/runtime/blocking_task.zig
  • src/runtime/task.zig
  • src/sync/Condition.zig
  • src/sync/Mutex.zig
  • src/sync/Semaphore.zig
✅ Files skipped from review due to trivial changes (2)
  • src/sync/Mutex.zig
  • src/sync/Semaphore.zig
🧰 Additional context used
🧠 Learnings (10)
📚 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/blocking_task.zig
  • src/runtime/task.zig
  • src/runtime.zig
📚 Learning: 2026-01-10T20:01:19.727Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 192
File: src/runtime/blocking_task.zig:82-85
Timestamp: 2026-01-10T20:01:19.727Z
Learning: Blocking tasks submitted via Runtime.spawnBlocking() are not currently cancelable in zio. No code calls thread_pool.cancel() on blocking tasks. Cancellation support (including ensuring completion callbacks fire for canceled work) is tracked as a future enhancement.

Applied to files:

  • src/runtime/blocking_task.zig
  • src/runtime.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/blocking_task.zig
  • src/runtime/awaitable.zig
  • src/runtime/autocancel.zig
  • src/runtime.zig
📚 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/blocking_task.zig
  • src/runtime/task.zig
  • src/runtime.zig
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.

Applied to files:

  • src/runtime/blocking_task.zig
  • src/runtime/task.zig
  • src/runtime/awaitable.zig
  • src/runtime/autocancel.zig
  • src/runtime.zig
  • src/sync/Condition.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.

Applied to files:

  • src/runtime/blocking_task.zig
  • src/runtime/task.zig
  • src/runtime/awaitable.zig
  • src/runtime/autocancel.zig
  • src/runtime.zig
  • 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/runtime/task.zig
  • src/runtime/awaitable.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.zig
  • src/sync/Condition.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-21T10:07:03.593Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 62
File: src/utils/queue.zig:109-126
Timestamp: 2025-10-21T10:07:03.593Z
Learning: In src/utils/queue.zig WorkStealingQueue implementation, the owner thread can safely use `.raw` to read its own `tail` atomic value since the owner is always a single thread and only it modifies tail. No ordering is needed when reading your own writes within the same thread.

Applied to files:

  • src/sync/Condition.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 (30)
src/runtime/blocking_task.zig (1)

46-50: LGTM!

The change correctly passes .user to align with the new CancelKind semantics. Discarding the return value is appropriate here since this is a fire-and-forget cancellation request. The actual thread pool cancellation remains a TODO, which is consistent with the existing behavior.

src/sync/Condition.zig (5)

63-63: LGTM!

Import updated to use AutoCancel from the new module path.


128-128: LGTM!

Method renamed from checkCanceled to checkCancel per the API rename.


178-180: LGTM!

Timer initialization and lifecycle correctly updated to use AutoCancel. The defer timer.clear(runtime) ensures cleanup regardless of exit path.


204-210: Solid error discrimination logic.

The flow correctly prioritizes user cancellation over timeout:

  1. checkCancel() surfaces any user-initiated cancellation first
  2. timer.check(runtime, err) then determines if this timer was the source
  3. Otherwise, falls through to return the original error

This handles the edge case where multiple auto-cancels might be pending.


217-221: LGTM!

The assertion on !timer.triggered is a good sanity check — if the timer fired but we didn't catch an error from yield or checkCancel, something's wrong with the cancellation propagation.

src/runtime/task.zig (2)

218-221: LGTM!

Renamed to checkCancel and now delegates to Awaitable.checkCancel() which handles the pending_errors decrement atomically.


224-228: Good refactor — conditional wakeup prevents redundant scheduling.

The previous code likely always woke the task. Now setCanceled(.user) returns whether cancellation actually triggered, so we skip the resumeTask call if the task was already canceled. This avoids scheduling noise when cancel is called multiple times.

Using resumeTask(self, .maybe_remote) is correct since cancel() can be called from any thread.

src/runtime/awaitable.zig (5)

26-32: LGTM!

Field renamed from timeout to auto_canceled to match the new naming convention. The u8 type allows tracking multiple auto-cancels, which is needed when multiple timers could theoretically fire.


34-36: LGTM!

Clean enum to distinguish cancellation sources. Having .user and .auto makes the call sites self-documenting.


140-163: LGTM!

checkAutoCancel correctly prioritizes user cancellation — if the user explicitly canceled, we don't want to consume an auto-cancel. The CAS loop handles concurrent access properly.


165-185: LGTM!

checkCancel is the general "consume a pending error" method. It doesn't care about the source — just decrements pending_errors if available. This is the right primitive for cancellation points that don't need to distinguish the source.


72-106: This behavior is intentional, not a bug.

When kind == .auto and user_canceled is already set, pending_errors is incremented because the error will still be delivered at a cancellation point via checkCancel(), just not through the timeout handler. auto_canceled remains unchanged because only unshadowed auto-cancels increment it—the counter distinguishes timeout-claimed errors from user-cancellation. The task is never resumed (line 87-90), so it encounters the error asynchronously rather than immediately. This is validated by the test case at lines 163-200 of autocancel.zig, which confirms user cancellation has priority. No errors are orphaned; checkCancel() will consume the pending_errors entry.

src/runtime.zig (5)

33-33: LGTM!

Import updated to bring in AutoCancel instead of the old Timeout type.


455-456: LGTM!

Pre-yield cancellation check renamed to checkCancel.


501-503: LGTM!

Post-resume cancellation check renamed consistently.


535-537: LGTM!

Executor.checkCancel properly renamed and delegates to the task's method.


1116-1119: LGTM!

Runtime.checkCancel is the public-facing convenience method, renamed consistently with the rest of the API.

src/runtime/autocancel.zig (12)

13-25: Rename + docs are consistent. The AutoCancel semantics are clear and match the new API.


27-35: clear() looks solid. Cancels the running timer and drops references as expected.


61-68: check() matches the new contract. Uses the trigger flag plus awaitable consumption; good.


71-90: Callback flow is correct. Clear refs, ignore canceled timers, and only wake on successful auto‑cancel.


96-104: Smoke test is fine. Basic init/set/clear coverage is useful.


106-123: Timeout firing test matches new check() behavior.


125-147: Nested auto‑cancels test is good coverage.


149-161: Clear‑before‑fire scenario looks good.


163-200: User‑cancel priority test is on point.


202-230: Multiple deadlines test is solid. Confirms only the earliest fires.


232-255: Set/clear/reset test matches expected reuse pattern.


257-287: Join‑cancellation test is good coverage for the public API path.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

When set() is called with Duration.max after a previous timer was armed,
the early return was leaving the old timer running. Now properly clears
any existing timer before returning.

@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/autocancel.zig`:
- Around line 109-126: Rename the test label and in-test comment to reflect the
actual error variant returned: change the test name string "AutoCancel: fires
and returns error.Timeout" to "AutoCancel: fires and returns error.Canceled" and
update any inline comment that references the expected error (e.g., the comment
on the rt.sleep catch and the trailing comment after the return) so they mention
error.Canceled instead of error.Timeout; verify the assertions around
AutoCancel.init/timeout.set and timeout.check(rt, err) remain unchanged
(symbols: AutoCancel, timeout.set, timeout.check, error.Canceled).
📜 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 9303d44 and 55c9005.

📒 Files selected for processing (1)
  • src/runtime/autocancel.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/runtime/autocancel.zig
📚 Learning: 2026-01-10T13:55:00.163Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/runtime/blocking_task.zig:117-146
Timestamp: 2026-01-10T13:55:00.163Z
Learning: In Zig files, do not reference libxev for async I/O. The project uses a custom event loop implementation under src/ev/ and a callback-based async I/O loop similar to libuv/libxev. Reviewers should ensure code relies on the src/ev event loop and that there are no libxev usage patterns; prefer the central event loop in src/ev/ for all asynchronous operations.

Applied to files:

  • src/runtime/autocancel.zig
📚 Learning: 2026-01-10T14:08:37.019Z
Learnt from: lalinsky
Repo: lalinsky/zio PR: 184
File: src/stdio.zig:117-129
Timestamp: 2026-01-10T14:08:37.019Z
Learning: In Zig files implementing swap-like semantics (e.g., old = swap(new); defer swap(old)), ensure the return value is an opaque restoration token rather than a direct reflection of internal state. Rely on the contract to perform increment/decrement logic internally (e.g., shield_count) and not expose internal state through the token. This makes behavior predictable, supports refactoring, and avoids leaking internal state across calls. Apply this pattern broadly to Zig code that uses a paired-swap or restoration-token mechanism.

Applied to files:

  • src/runtime/autocancel.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 (13)
src/runtime/autocancel.zig (13)

13-18: Docs match the new AutoCancel behavior.
Clear and consistent with the updated semantics.


27-35: clear() logic looks correct.
State reset + timer clear is in the right order.


37-62: set() handles Duration.max correctly now.
The disable path and re-arm path are clean.


64-71: check() semantics are clear and focused.
Triggered flag + awaitable consumption is the right split.


74-93: Callback behavior is solid.
Clearing task/loop before resuming avoids stale state.


99-107: Smoke test is fine.
Simple coverage for init/set/clear.


128-150: Nested timeout ordering test is good.
Covers the “earliest wins” behavior.


152-164: Clear-before-fire test is good.
Confirms no stray cancellation.


166-203: User-cancel priority test is solid.
Confirms the intended precedence.


205-233: Multiple deadlines test is good coverage.
Checks triggered flags and check() behavior.


235-258: Set/clear/re-set scenario is covered well.
Matches the expected lifecycle.


260-277: Duration.max disable test is great.
Directly verifies the fix in this PR.


279-309: Join-cancel path is covered nicely.
Good end-to-end signal for AutoCancel.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment thread src/runtime/autocancel.zig Resolved
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