Repository navigation
Rename Timeout to AutoCancel - #207
Conversation
- 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
📝 WalkthroughWalkthroughRenames 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 decrementpending_errorswhen consuming an auto-cancel.When
setTimeout()fires, it increments bothauto_canceledandpending_errors(src/runtime/task.zig:237–238). ButconsumeAutoCancel()only decrementsauto_canceled, leavingpending_errorshanging. This breaks the pairing: latercheckCanceled()calls (which decrementpending_errors) will still see a nonzero count and incorrectly returnerror.Canceledeven though you've already handled the timeout.The fix should also assert that
pending_errors > 0when 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
📒 Files selected for processing (11)
src/io.zigsrc/runtime.zigsrc/runtime/autocancel.zigsrc/runtime/awaitable.zigsrc/runtime/task.zigsrc/signal.zigsrc/sync/Condition.zigsrc/sync/Futex.zigsrc/sync/Notify.zigsrc/sync/ResetEvent.zigsrc/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.zigsrc/sync/ResetEvent.zigsrc/sync/Futex.zigsrc/sync/Condition.zigsrc/signal.zigsrc/runtime/awaitable.zigsrc/io.zigsrc/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.zigsrc/sync/ResetEvent.zigsrc/sync/Futex.zigsrc/sync/Notify.zigsrc/sync/Condition.zigsrc/signal.zigsrc/runtime/task.zigsrc/runtime.zigsrc/runtime/awaitable.zigsrc/io.zigsrc/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.zigsrc/sync/ResetEvent.zigsrc/sync/Futex.zigsrc/sync/Notify.zigsrc/sync/Condition.zigsrc/signal.zigsrc/runtime/task.zigsrc/runtime.zigsrc/runtime/awaitable.zigsrc/io.zigsrc/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.zigsrc/sync/Futex.zigsrc/runtime/task.zigsrc/runtime.zigsrc/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.zigsrc/sync/Notify.zigsrc/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.zigsrc/sync/Condition.zigsrc/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.zigsrc/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.
Ifruntime.checkCanceled()consumes auto-cancel, timeouts may surface aserror.Canceledbeforetimer.check()runs. Either confirmcheckCanceledignores 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 toerror.Timeoutis 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_canceledfield inCanceledStatus. One minor observation: the function is still namedsetTimeoutwhile 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 toerror.Timeout, otherwise propagate the original error. This is clearer than the previousrt.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 toAutoCancel.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 withAutoCancel.init, set the timer, and in the catch path usetimer.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, thentimer.clear(), then cancel the I/O. This matters becausecheck()examines the timer's triggered state whichclear()resets. The explicitis_timeoutvariable 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 nullifiesself.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 thatAutoCancel.check(runtime, err)returnstrueonly for auto‑cancellederror.Canceledand not for user‑initiated cancellations, otherwise this path would surfaceerror.Timeoutincorrectly.
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.
|
@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 |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 2458 🏁 Script executed: Length of output: 9124 🏁 Script executed: Length of output: 8369 🏁 Script executed: Length of output: 3949
In 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 The correct behavior:
The 🧠 Learnings used |
|
@coderabbitai you seem to be misunderstanding how the CancelationStatus works |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 4785 🏁 Script executed: Length of output: 3805 🏁 Script executed: Length of output: 4849
The flow is:
So The
Could you clarify what specific aspect of 🧠 Learnings used |
- 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
There was a problem hiding this comment.
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. Ifset()is called withDuration.maxafter 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
📒 Files selected for processing (8)
src/runtime.zigsrc/runtime/autocancel.zigsrc/runtime/awaitable.zigsrc/runtime/blocking_task.zigsrc/runtime/task.zigsrc/sync/Condition.zigsrc/sync/Mutex.zigsrc/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.zigsrc/runtime/task.zigsrc/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.zigsrc/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.zigsrc/runtime/awaitable.zigsrc/runtime/autocancel.zigsrc/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.zigsrc/runtime/task.zigsrc/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.zigsrc/runtime/task.zigsrc/runtime/awaitable.zigsrc/runtime/autocancel.zigsrc/runtime.zigsrc/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.zigsrc/runtime/task.zigsrc/runtime/awaitable.zigsrc/runtime/autocancel.zigsrc/runtime.zigsrc/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.zigsrc/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.zigsrc/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
.userto align with the newCancelKindsemantics. 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
AutoCancelfrom the new module path.
128-128: LGTM!Method renamed from
checkCanceledtocheckCancelper the API rename.
178-180: LGTM!Timer initialization and lifecycle correctly updated to use
AutoCancel. Thedefer timer.clear(runtime)ensures cleanup regardless of exit path.
204-210: Solid error discrimination logic.The flow correctly prioritizes user cancellation over timeout:
checkCancel()surfaces any user-initiated cancellation firsttimer.check(runtime, err)then determines if this timer was the source- 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.triggeredis 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
checkCanceland now delegates toAwaitable.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 theresumeTaskcall if the task was already canceled. This avoids scheduling noise when cancel is called multiple times.Using
resumeTask(self, .maybe_remote)is correct sincecancel()can be called from any thread.src/runtime/awaitable.zig (5)
26-32: LGTM!Field renamed from
timeouttoauto_canceledto match the new naming convention. Theu8type allows tracking multiple auto-cancels, which is needed when multiple timers could theoretically fire.
34-36: LGTM!Clean enum to distinguish cancellation sources. Having
.userand.automakes the call sites self-documenting.
140-163: LGTM!
checkAutoCancelcorrectly 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!
checkCancelis the general "consume a pending error" method. It doesn't care about the source — just decrementspending_errorsif 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 == .autoanduser_canceledis already set,pending_errorsis incremented because the error will still be delivered at a cancellation point viacheckCancel(), just not through the timeout handler.auto_canceledremains 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 ofautocancel.zig, which confirms user cancellation has priority. No errors are orphaned;checkCancel()will consume thepending_errorsentry.src/runtime.zig (5)
33-33: LGTM!Import updated to bring in
AutoCancelinstead of the oldTimeouttype.
455-456: LGTM!Pre-yield cancellation check renamed to
checkCancel.
501-503: LGTM!Post-resume cancellation check renamed consistently.
535-537: LGTM!
Executor.checkCancelproperly renamed and delegates to the task's method.
1116-1119: LGTM!
Runtime.checkCancelis 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.
There was a problem hiding this comment.
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
📒 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.
Summary
zio.Timeouttozio.AutoCancelto free up theTimeoutname for a future tagged union type (matchingstd.Io.Timeout)Awaitable.consumeAutoCancel()Runtime.checkTimeout()withAutoCancel.check()returning boolCanceledStatus.timeouttoauto_canceledTest plan