Repository navigation
Conversation
Add error.Cancelled propagation throughout the async runtime system: - Update Runtime.yield() to return Cancellable error - Add Cancellable to error sets for async operations in File, TCP, UDP - Update all sync primitives (Mutex, Condition, Barrier, ResetEvent, Semaphore, Queue, BroadcastChannel) to propagate cancellation - Convert Cancelled errors to standard I/O errors in StreamReader/Writer for compatibility with std.io interfaces - Add try keywords throughout test code for proper error handling All 77 tests passing.
Change Awaitable.state from tristate (pending/complete/cancelled) to binary (pending/complete) and add separate atomic cancelled flag. Key changes: - Add Awaitable.cancelled atomic bool flag for cancellation requests - Remove state=2 (cancelled) - state is now only 0 (pending) or 1 (complete) - Replace markCancelled() with requestCancellation() that sets the flag - In yield(), use CAS to consume the cancellation flag atomically - Cancellation is now transient: flag is consumed and error.Cancelled is returned, then operation can complete normally This design ensures cancellation is a temporary signal rather than a permanent state. When a task receives cancellation, it can clean up and complete (setting state=1) with its result. All 77 tests passing.
When Semaphore.wait() or timedWait() is cancelled, ensure permits are properly managed: 1. If cancelled before acquiring permit: return error.Cancelled cleanly 2. If cancelled after acquiring permit: release permit, signal waiting tasks, then return error.Cancelled When Semaphore.post() is cancelled while acquiring the mutex: - Retry until lock succeeds (must post the permit) - Track cancellation and return error.Cancelled after posting This prevents permit leaks when cancellation occurs. Implementation: - Track cancellation with was_cancelled flag - In wait/timedWait: continue to check if permit available after error - If permit was acquired, always release it before returning error - In post: retry lock on cancellation, post permit, then return error All 77 tests passing.
|
Caution Review failedThe pull request is closed. WalkthroughMake suspension points, I/O completions, and sync primitives cancellation-aware: add a public Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant Task as Caller (Task)
participant RT as Runtime
participant Driver as Driver / Kernel
rect rgba(235,250,235,0.6)
Note over Task,RT: Coroutine-backed I/O completion & cancellation
Task->>Driver: submit readBuf(..., result.coro = coro)
Driver->>RT: on completion -> Runtime.fromCoroutine(coro).markReady(...)
Task->>RT: try RT.waitForXevCompletion(completion)
alt cancelled
RT-->>Task: error Canceled
Task-->>Task: propagate (Cancelable || Error)!...
else completed
RT-->>Task: ok
Task-->>Task: return success or specific error
end
end
sequenceDiagram
autonumber
participant Caller as Caller (Task)
participant RT as Runtime
rect rgba(240,245,255,0.6)
Note over Caller,RT: Cancellation-aware suspension
Caller->>RT: try RT.yield(.waiting)
alt cancellation happened
RT-->>Caller: error Canceled
else resumed
RT-->>Caller: ok
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
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: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (8)
src/sync/Mutex.zig (1)
22-38: Cancelled lockers stay queued and end up owning the mutexIf the caller is cancelled while waiting,
runtime.yield(.waiting)now returnserror.Cancelledand we exitlockimmediately. But we already enqueuedtask.awaitable; nothing removes it. The nextunlockwill pop that same awaitable, transfer ownership to the cancelled coroutine, and mark it ready even though it has already unwound. From there the mutex is permanently “owned” by a task that will never callunlock, so subsequent lockers hang.Handle
error.Cancelledexplicitly: unlink the awaitable fromwait_queue(and leaveownerunchanged) before propagating the error. Otherwise cancellation turns into a latent deadlock.src/sync/Barrier.zig (1)
32-51: Barrier state is left inconsistent when wait is cancelled
self.currentis incremented before we enter the wait loop. Ifself.cond.waitreturnserror.Cancelled, we bubble it out immediately, leavingself.currentat the higher value and the waiter still linked to the condition queue. The barrier now believes the task is still participating, so no one ever reachesself.countagain – future callers will block forever.Catch
error.Cancelled, roll backself.current, detach the waiter from the condition queue, and then propagate the error. Without that, a cancelled participant bricks the barrier for everyone else.src/sync/ResetEvent.zig (2)
71-78: Cancellation must remove the waiter from the queueOn Line 75 we enqueue the awaitable, but if
runtime.yield(.waiting)(Line 77) returnserror.Cancelled, we immediately unwind with our awaitable still linked. A subsequentset()will pop that stale pointer and callmarkReady()on a task that may already have completed or been deinitialized, leading to use-after-free. Please ensure weremovethe awaitable when the wait exits with an error (e.g. anerrdeferright after thepush).Apply this diff:
self.wait_queue.push(&task.awaitable); + errdefer _ = self.wait_queue.remove(&task.awaitable); // Suspend until woken by set() try runtime.yield(.waiting);
103-128: Timed wait needs the same cancellation cleanup
timedWait(Lines 104-126) also enqueues the awaitable before yielding. A cancellation path returns without removing it, so the waiter stays in the list andset()/timeout callbacks can touch freed stack memory. Please mirror the fix fromwait()by removing the awaitable in the error path (anerrdeferalongside the existing one is fine).Example fix:
self.wait_queue.push(&task.awaitable); + errdefer _ = self.wait_queue.remove(&task.awaitable); const TimeoutContext = struct { wait_queue: *AwaitableList,src/sync/Condition.zig (2)
21-29: Cancelled wait loses the mutex and leaves a dangling waiterWhen Line 26’s
runtime.yield(.waiting)returnserror.Cancelled, control unwinds before Line 29 re-locks the mutex. The caller expects the mutex to be held on return; instead we exit with it unlocked and the surroundingdefer unlockwill double-unlock. Worse, the awaitable pushed on Line 21 never gets removed, so latersignal()/broadcast()will pop a stale pointer. Add anerrdeferright after thepushthat (1) removes the awaitable, and (2) re-locks the mutex (catching cancellation) so the caller regains ownership before the error propagates.Suggested shape:
self.wait_queue.push(&task.awaitable); + errdefer { + _ = self.wait_queue.remove(&task.awaitable); + mutex.lock(runtime) catch {}; + } // Atomically release mutex and wait mutex.unlock(runtime);
35-66: Timed wait needs to drop cancelled waiters as well
timedWaitalready reacquires the mutex viaerrdefer mutex.lock(...), but we still leave the awaitable in the queue on cancellation. Please extend the errdefer to remove the awaitable (similar towait()), so cancellation cannot leave dangling nodes for future broadcasts.One option:
self.wait_queue.push(&task.awaitable); const TimeoutContext = struct { wait_queue: *AwaitableList, awaitable: *Awaitable, }; + errdefer { + _ = self.wait_queue.remove(&task.awaitable); + mutex.lock(runtime) catch {}; + } - mutex.unlock(runtime); - errdefer mutex.lock(runtime) catch {}; + mutex.unlock(runtime);(Adjust ordering as needed to keep the existing unlock/relock semantics.)
src/tcp.zig (1)
96-103: Cancellation breaks outstanding xev operationsIf Line 96’s
yield(.waiting)returnserror.Cancelled, we exitaccept()while the xev accept is still in flight. The callback will later write intoresult_data(Lines 65-84), but that struct—and the embeddedWaiter—live on this stack frame, so we end up with a use-after-free once the coroutine unwinds. The same pattern exists inconnect,shutdown,writeBuf, andreadBuf. We need to either cancel the xev completion before returning, or keep the result storage alive until the callback fires (e.g. heap-allocate and tie its lifetime to the completion). Right now any cancellation of these APIs is memory corruption waiting to happen.src/file.zig (1)
289-292: Preserve cancellation instead of downgrading to ReadFailed.
xev.ReadErroralready exposeserror.Cancelled; funneling it through the genericelsebranch turns a cooperative cancel into an I/O failure, defeating the new(Cancellable || std.io.Reader.Error)surface. Returnerror.Cancelleddirectly so callers can distinguish the two cases.- const bytes_read = result_data.result catch |err| switch (err) { - error.EOF => return error.EndOfStream, - else => return error.ReadFailed, - }; + const bytes_read = result_data.result catch |err| switch (err) { + error.EOF => return error.EndOfStream, + error.Cancelled => return error.Cancelled, + else => return error.ReadFailed, + };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (13)
src/file.zig(9 hunks)src/io.zig(5 hunks)src/net.zig(2 hunks)src/runtime.zig(21 hunks)src/sync/Barrier.zig(8 hunks)src/sync/Condition.zig(8 hunks)src/sync/Mutex.zig(4 hunks)src/sync/ResetEvent.zig(8 hunks)src/sync/Semaphore.zig(5 hunks)src/sync/broadcast_channel.zig(18 hunks)src/sync/queue.zig(10 hunks)src/tcp.zig(13 hunks)src/udp.zig(3 hunks)
🔇 Additional comments (2)
src/net.zig (1)
132-132: Propagation of wait errors looks goodSwitching to
try ready_event.wait(rt)lets the client tasks surface cancellation instead of silently blocking, which aligns with the new cancellation-aware runtime.Also applies to: 190-190
src/io.zig (1)
34-37: Correctly bridging cancellation to std.ioMapping
error.Cancelledtoerror.ReadFailedkeeps thestd.io.Readercontract intact while still letting cancellation bubble up to callers.
- Refactor Condition.timedWait to use single defer block for mutex re-acquisition - Consolidates lock re-acquisition logic into one place (lines 65-72) - Properly prioritizes cancellation over timeout errors - Rename error.Cancelled to error.Canceled throughout codebase - Update error definition in runtime.zig - Update all sync primitives (Condition, Semaphore, ResetEvent, Barrier) - Update I/O error handling in io.zig and tcp.zig - Update examples to handle Canceled error All 77 tests pass.
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 (4)
src/sync/ResetEvent.zig (1)
197-202: Re-throw non-timeout errors in the test waiter.After expanding
timedWaitto returnerror.Canceled, this catch now hides cancellations silently. Please rethrow anything other than the expected timeout so the test doesn’t pass after a cancellation. For example:- event.timedWait(rt, 10_000_000) catch |err| { - if (err == error.Timeout) { - timeout_flag.* = true; - } - }; + event.timedWait(rt, 10_000_000) catch |err| { + if (err == error.Timeout) { + timeout_flag.* = true; + return; + } + return err; + };src/sync/Barrier.zig (1)
33-50: Restore the barrier count on cancellation.If a coroutine is cancelled after
self.current += 1but before the broadcast,self.currentstays permanently incremented and the barrier never opens again. Add anerrdefer self.current -= 1;immediately after incrementing so cancellation restores the count.const local_gen = self.generation; self.current += 1; + errdefer self.current -= 1;src/sync/Condition.zig (1)
20-79: Remove cancelled waiters and re-lock before returning.If
runtime.yield(.waiting)(orruntime.timedWaitForReadyWithCallback) returnserror.Canceled, we exit without re-locking the mutex and without removing our entry fromwait_queue. The mutex invariant is broken (caller expects the lock held when wait returns), and the stale queue node will later be popped bysignal/broadcast, causingRuntime.markReadyto panic because the coroutine is no longer in.waiting. We need to retrymutex.lockeven on cancellation, remove the awaitable fromwait_queue, and only then propagateerror.Canceled.src/runtime.zig (1)
530-538: Propagate cancellation instead of crashing blocking joins.
waitForComplete()now returnserror.Canceled, but the blocking-task join path still doescatch unreachable. If a coroutine waiting on a blocking task is cancelled, we’ll hit thatunreachableand abort. Please let cancellation bubble up (e.g. makeBlockingTask.join/resultreturnCancellable!Tandtrythe wait) so joiners aren’t forced to crash.
♻️ Duplicate comments (1)
src/runtime.zig (1)
1040-1042: Clean up cancelled waiters before returning.A cancelled call to
yield(.waiting)leavescurrent_task.awaitableintask.awaitable.waiting_list, so when the target task completesmarkReadywill panic because the coroutine isn’t actually waiting. We still need theerrdefer/remove fix that was called out earlier.
🧹 Nitpick comments (1)
src/io.zig (1)
169-174: Trim redundant cancellation branches.Both catch blocks return
error.WriteFailedregardless of the condition, so theif (err == error.Canceled)check no longer changes behavior. Dropping the conditional keeps the intent clear without altering semantics.Also applies to: 182-185
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
examples/mutex_demo.zig(2 hunks)examples/producer_consumer.zig(2 hunks)src/io.zig(5 hunks)src/runtime.zig(21 hunks)src/sync/Barrier.zig(8 hunks)src/sync/Condition.zig(8 hunks)src/sync/ResetEvent.zig(8 hunks)src/sync/Semaphore.zig(5 hunks)src/tcp.zig(13 hunks)
🔇 Additional comments (2)
examples/producer_consumer.zig (1)
12-15: Nice addition for graceful cancellation.Mapping
error.Canceledto an early return keeps both sides of the example from logging spurious noise once cancellation kicks in. 👍Also applies to: 30-33
examples/mutex_demo.zig (1)
9-43: Looks solid with cancellation propagation.Converting
incrementTask/spawns to!voidand usingtrykeeps the mutex unlocked even on cancellation, which is exactly what we want.
Address cancellation cleanup issues identified in code review: - Mutex.lock: Remove awaitable from wait queue on cancellation to prevent deadlock when unlock() tries to transfer ownership to cancelled waiter - Condition.wait/timedWait: Remove awaitable from queue and reacquire mutex (with retry) on cancellation to maintain invariant that mutex is held - ResetEvent.wait/timedWait: Remove awaitable from queue on cancellation to prevent use-after-free when set() wakes stale pointer - Barrier.wait: Rollback current count on cancellation to keep barrier state consistent All synchronization primitives now properly clean up on cancellation, preventing deadlocks, use-after-free, and inconsistent state.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/sync/Condition.zig (1)
16-38: Document the mutex reacquisition invariant.The implementation correctly maintains the invariant that
wait()returns with the mutex held, even on cancellation. However, the infinite retry loop on lines 29-32 warrants documentation:while (true) { mutex.lock(runtime) catch continue; break; }This loop ignores subsequent cancellation signals during mutex reacquisition, prioritizing the original cancellation error. While this design maintains a clear invariant (mutex always held on return), it has subtle implications:
- Subsequent cancellation signals are consumed/lost during reacquisition
- The loop retries indefinitely until the mutex is acquired
- In a cooperative scheduling environment, this should eventually succeed as other coroutines yield
Consider adding a comment explaining this design choice:
// Must reacquire mutex before returning to maintain the invariant that // wait() returns with mutex held (even on error). Subsequent cancellations // during reacquisition are ignored to prioritize the original error. while (true) { mutex.lock(runtime) catch continue; break; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/sync/Barrier.zig(8 hunks)src/sync/Condition.zig(8 hunks)src/sync/Mutex.zig(4 hunks)src/sync/ResetEvent.zig(10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/sync/Mutex.zig
🔇 Additional comments (6)
src/sync/Barrier.zig (2)
32-56: LGTM! Proper cancellation handling with resource cleanup.The cancellation implementation is correct:
- Line 33: Propagates cancellation from
mutex.lock()- Lines 48-52: Critical rollback logic that decrements
self.currenton cancellation, preventing the barrier from becoming permanently stuck- The rollback maintains barrier correctness: if a coroutine is cancelled after incrementing the counter, it must decrement before exiting
The error propagation preserves the barrier's synchronization guarantees.
69-79: Test updates are consistent with cancellation semantics.The test worker function properly returns
!voidand usestryon thewait()call, correctly propagating any cancellation errors through the test harness.src/sync/ResetEvent.zig (2)
63-86: LGTM! Proper cleanup on cancellation.The cancellation handling correctly prevents resource leaks:
- Line 74: Adds awaitable to wait queue
- Lines 77-81: On cancellation, removes the awaitable from the queue before propagating the error
- This ensures cancelled waiters don't remain in the queue indefinitely
The cleanup is essential for correctness of the ResetEvent primitive.
91-138: LGTM! Correct distinction between timeout and cancellation.The implementation properly handles both timeout and cancellation scenarios:
- Line 128: The callback handles timeout by attempting to remove from the queue
- Lines 131-137: The catch block distinguishes between timeout (already handled by callback) and cancellation (requires explicit removal on line 134)
- This prevents double-removal and ensures proper cleanup in both cases
The error handling logic is sound.
src/sync/Condition.zig (2)
40-105: LGTM! Complex but correct cancellation priority logic.The
timedWait()implementation correctly handles multiple error conditions with proper priority:
Lines 72-90: Handle errors from
timedWaitForReadyWithCallback
- Timeout: Handled by callback removal (line 69)
- Cancellation: Explicit removal from queue (line 75)
- Reacquires mutex before returning (lines 78-84)
Lines 92-104: Success path also reacquires mutex
- Tracks if cancellation occurred during reacquisition (line 95)
Lines 86-88, 102-104: Cancellation has priority over timeout
The
was_cancelledtracking ensures that cancellation during mutex reacquisition takes precedence over the original operation outcome. This is a sensible priority ordering.
114-119: LGTM! Straightforward broadcast implementation.The
broadcast()function correctly wakes all waiters by iterating through the wait queue and marking each task as ready. The implementation mirrors the existingsignal()function but processes all waiters instead of just one.
Address additional cancellation issues from code review: - file.zig writeBuf: Explicitly bubble error.Canceled instead of masking it as WriteFailed, allowing callers to observe cooperative cancellation per the (Cancellable || std.io.Writer.Error) contract - runtime.zig wait: Remove awaitable from waiting_list on cancellation to prevent use-after-free when target task completes and tries to wake a cancelled waiter that may have already been freed Both fixes ensure proper cleanup and error propagation when operations are cancelled.
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/file.zig (1)
289-292: Fix the error return type.Line 291 returns
error.WriteFailedin a read operation. This should beerror.ReadFailed.Apply this diff:
const bytes_read = result_data.result catch |err| switch (err) { error.EOF => return error.EndOfStream, - else => return error.WriteFailed, + else => return error.ReadFailed, };
🧹 Nitpick comments (1)
src/file.zig (1)
289-292: Consider explicitly handlingerror.Canceledfor consistency.
writeBuf(lines 335-338) explicitly checks forerror.Canceledin its error handling, butreadBufuses a catch-allelsebranch. For symmetry and clarity, consider adding an expliciterror.Canceled => return error.Canceledbranch here as well, matching the pattern inwriteBuf.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/file.zig(9 hunks)src/runtime.zig(21 hunks)
🔇 Additional comments (11)
src/file.zig (2)
73-73: LGTM: Cancellation propagation is correct.The updated
trycorrectly propagates cancellation fromyield().
247-247: LGTM: Signatures correctly widened for cancellation.The
Cancellableunion in the return types properly signals that these operations can be cancelled.Also applies to: 299-299
src/runtime.zig (9)
52-55: LGTM: Clean cancellation error set.The
Cancellableerror set witherror.Canceledprovides a clear cancellation signal throughout the runtime.
145-146: LGTM: Atomic cancellation flag.The atomic boolean flag enables lock-free, transient cancellation requests that can be consumed exactly once via CAS.
841-878: LGTM: CAS-based one-time cancellation consumption.The
cmpxchgStrong(true, false, ...)pattern before yielding (lines 847-850) and after resuming (lines 875-877) ensures exactly-once delivery of cancellation. The check before yielding catches immediate cancellation, while the check after resuming handles cancellation that occurred while suspended.
152-186: LGTM: Proper wait queue cleanup on cancellation.When
yield(.waiting)returnserror.Canceled(line 171), the code removes the awaitable from the wait list (line 173) before propagating the error. This prevents the dangling-waiter panic that could occur ifmarkCompletelater tried to wake an already-running coroutine.
193-247: LGTM: Timed wait handles both timeout and cancellation.The error handling at lines 230-236 properly distinguishes
error.Timeoutfromerror.Canceled, removing the awaitable from the wait list only on cancellation. This maintains correct cleanup semantics for both exit paths.
1030-1046: LGTM: Wait queue cleanup mirrors the waitForComplete pattern.As noted in the past review comment (now marked addressed), the
errdefer-style cleanup at lines 1041-1044 removes the awaitable from the wait queue ifyieldreturns an error, preventing orphaned queue entries.
360-374: LGTM: Type introspection helpers.The
getErrorSet()andgetPayload()helper functions cleanly extract the error set and payload types from error unions using@typeInfo, enabling generic handling of both plain and error-union return types.Also applies to: 441-455, 579-593
530-540: Blocking tasks intentionally ignore cancellation.
BlockingTask.join()usescatch unreachable(line 537) because blocking tasks execute on the thread pool and cannot be cooperatively interrupted. This is by design and documented in comments (lines 536 and 570). The assumption is thatrequestCancellation()will never be called on a blocking task's awaitable.Also applies to: 567-573
1254-1255: LGTM: Test code updated for cancellation propagation.All test yields now use
try, correctly propagating potential cancellation errors through the test logic.Also applies to: 1298-1300, 1319-1322
Implement waitForXevCompletion() helper to safely handle cancellation of xev I/O operations. When a coroutine is cancelled during I/O: - Request cancellation of the xev operation (on io_uring backend) - Wait for the operation to complete before returning - Prevents use-after-free bugs where xev callbacks access freed stack Apply cancellation handling to all file operations: read(), write(), pread(), pwrite(), readBuf(), writeBuf(), and close().
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
src/file.zig (2)
32-54: Document backend cancellation limitations more prominently.The current implementation only attempts to cancel xev operations on io_uring backends. For other backends (e.g., kqueue, IOCP), the operation cannot be interrupted and must complete before
error.Canceledis returned. Consider adding a more prominent note about this limitation in the function's doc comment so callers understand the cancellation semantics vary by platform.Apply this diff to enhance the documentation:
/// Wait for an xev completion to finish, handling cancellation properly. /// When a coroutine is cancelled while waiting for an I/O operation, /// we need to cancel the operation (if the backend supports it) and /// wait for it to complete before returning error.Canceled. +/// +/// Note: Actual operation cancellation is only supported on io_uring backends. +/// On other backends (kqueue, IOCP), the operation will run to completion, +/// but error.Canceled will still be returned if cancellation was requested. /// This prevents use-after-free bugs where the xev callback accesses /// freed stack memory.
392-394: Simplify single-branch error switch.The switch statement with only an
elsebranch can be simplified to a direct catch for better readability.Apply this diff:
- const bytes_written = result_data.result catch |err| switch (err) { - else => return error.WriteFailed, - }; + const bytes_written = result_data.result catch return error.WriteFailed;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/file.zig(11 hunks)
🔇 Additional comments (4)
src/file.zig (4)
304-351: LGTM! Cancellation properly propagated through readBuf.The signature correctly includes
Cancellablein the error union,waitForXevCompletionproperly propagates cancellation viatry, and the error mapping from xev to std.io errors is appropriate.
89-89: Good practice: marking waiter variables as const.Changing
var waitertoconst waiteracross all I/O operations correctly reflects that these variables are not reassigned, improving code clarity and preventing accidental mutation.Also applies to: 138-138, 211-211, 257-257, 305-305, 357-357, 400-400
130-130: LGTM! Consistent cancellation-aware I/O pattern.All I/O operations (
read,write,pread,pwrite,close) consistently usewaitForXevCompletioninstead of direct yields, properly integrating cancellation support while maintaining existing semantics.Also applies to: 179-179, 251-251, 297-297, 436-436
17-21: Use the canonical error nameCanceled(one 'l') as defined in src/runtime.zig; update PR description accordingly.Likely an incorrect or invalid review comment.
- Move waitForXevCompletion helper from file.zig to Runtime - Helper function now waits for xev operations to complete before returning error.Canceled - For io_uring backend, requests cancellation via loop.cancel() - For other backends, simply waits for completion - Apply to all TCP operations: accept, connect, readBuf, writeBuf, shutdown - Apply to all UDP operations: read, write - Leave close operations with catch unreachable as intended - All 77 tests passing
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/file.zig (1)
342-382: Inconsistent close cancellation handling across I/O types.File's
close()usestry self.runtime.waitForXevCompletion(&completion)at line 379, which can propagateerror.Canceled. However, TCP and UDP close operations useyield(.waiting) catch unreachableto panic on cancellation.This inconsistency creates unpredictable behavior:
- File close can be cancelled
- TCP/UDP close panics if cancelled
Standardize the behavior. Either:
- All close operations should propagate cancellation (change tcp/udp to match file)
- All close operations should panic on cancellation (change file to match tcp/udp with
catch unreachable)Apply this diff if option 2 is preferred:
- try self.runtime.waitForXevCompletion(&completion); + waiter.runtime.yield(.waiting) catch unreachable; // close should never be cancelledsrc/runtime.zig (1)
1234-1387: Add missing cancellation tests
The runtime needs explicit coverage for cancellation paths. Please add tests that:
- call
requestCancellationon an awaitable and assert it propagates- verify I/O operations return
error.Canceledwhen cancelled- ensure CAS-based cancellation is consumed exactly once
- confirm no waiter leaks or hanging tasks after cancellation
🧹 Nitpick comments (1)
src/file.zig (1)
335-337: Consider explicit error handling in writeBuf.The switch statement only contains an
elsecase, which is unusual. While this works for opaque xev error sets, being explicit about handled errors improves maintainability.If xev.WriteError contains known errors, consider handling them explicitly:
const bytes_written = result_data.result catch |err| switch (err) { + // Add explicit cases for known xev write errors if applicable else => return error.WriteFailed, };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/file.zig(11 hunks)src/runtime.zig(22 hunks)src/tcp.zig(16 hunks)src/udp.zig(5 hunks)
🔇 Additional comments (11)
src/udp.zig (2)
30-30: LGTM: Proper cancellation handling added.The migration to
waitForXevCompletioncorrectly addresses the use-after-scope concern raised in the previous review. The new implementation ensures that:
- Stack-allocated
result_dataremains valid until the xev callback completes- The waiter is properly cleaned up before returning cancellation errors
- For io_uring, cancellation is requested but completion is still awaited
Also applies to: 76-76, 86-86, 130-130
172-172: Verify close cancellation behavior is documented.Close operations panic on cancellation via
catch unreachable, asserting that close should always complete. This is a strong design choice that should be documented, especially since file.zig's close behaves differently (see file.zig review).Consider adding a comment explaining why close operations must complete and under what conditions the cancellation flag should never be set during close.
src/tcp.zig (2)
62-62: LGTM: Consistent cancellation-aware I/O pattern.The accept, connect, and shutdown operations properly use
waitForXevCompletionto handle cancellation. The const waiter refactor is a good cleanup.Also applies to: 96-96, 164-164, 201-201, 271-271, 307-307
314-349: LGTM: Clean separation of cancellation and I/O errors.The error handling correctly distinguishes between:
- Cancellation errors from
waitForXevCompletion(propagated viatry)- I/O errors from
result_data.result(converted to std.io errors)This maintains compatibility with std.io interfaces while supporting cancellation.
Also applies to: 353-399
src/file.zig (2)
32-32: LGTM: Proper cancellation-aware I/O operations.The read, write, pread, and pwrite operations correctly use
waitForXevCompletionwith const waiter initialization.Also applies to: 73-73, 81-81, 122-122, 154-154, 194-194, 200-200, 240-240
247-295: LGTM: Cancellation support in low-level I/O primitives.The
readBufandwriteBufmethods properly includeCancellablein their error sets and usewaitForXevCompletionto handle cancellation during I/O waits.Also applies to: 299-340
src/runtime.zig (5)
52-55: LGTM: Well-designed cancellation infrastructure.The new
Cancellableerror set and atomiccancelledflag provide a clean foundation for cancellation. TherequestCancellationmethod completes the API.Also applies to: 145-146, 264-268
841-878: LGTM: Exactly-once cancellation consumption via CAS.The double-check pattern ensures the cancellation flag is consumed exactly once:
- Before yielding (lines 847-850)
- After resuming (lines 875-877)
The use of
cmpxchgStrongguarantees atomic compare-and-swap semantics, preventing race conditions.
152-186: LGTM: Proper cleanup on cancellation in wait operations.The errdefer-style cleanup (line 173 in
waitForComplete, lines 232-236 intimedWaitForComplete) correctly removes the awaitable from the wait queue when yield returns a cancellation error. This addresses the critical issue from the previous review about leaked waiters.Also applies to: 193-247
1177-1231: LGTM: Safe cancellation for I/O operations.The
waitForXevCompletionmethod is the key to safe cancellation:
- Waits for xev completion to reach
.deadstate (line 1192)- On cancellation, requests xev cancellation for io_uring (lines 1199-1219)
- Continues waiting for the operation to complete (line 1222)
- Only returns cancellation error after completion (lines 1228-1230)
This prevents use-after-scope bugs by ensuring stack-allocated data remains valid until the xev callback completes.
340-378: LGTM: Type-safe error propagation helpers.The
getErrorSet()andgetPayload()helper methods cleanly extract error and payload types from error unions, enabling proper type inference for cancellation-aware APIs.Also applies to: 429-455, 567-593
Rename Cancellable to Cancelable and change all instances of "cancelled" to "canceled" throughout the codebase for consistency. Changes: - Error set type: Cancellable -> Cancelable - Variable names: cancelled -> canceled (e.g., was_cancelled -> was_canceled) - Comments: all instances updated to US spelling All tests pass with the new spelling.
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/file.zig (1)
287-294: Propagate cancellation explicitly in readBuf.Similar to the issue flagged in writeBuf (previous review comment),
readBufdeclaresCancelablein its return type but the error mapping at lines 289-292 doesn't explicitly handleerror.Canceled. It falls through to the else clause and returnserror.ReadFailed, hiding cooperative cancellation from callers.Apply this diff to propagate cancellation explicitly:
const bytes_read = result_data.result catch |err| switch (err) { error.EOF => return error.EndOfStream, + error.Canceled => return error.Canceled, else => return error.ReadFailed, };
♻️ Duplicate comments (1)
src/file.zig (1)
333-340: Cancellation still not propagated in writeBuf.The previous review comment (marked as addressed in commit 7c55f4b) flagged that
error.Canceledshould be explicitly propagated rather than mapped toerror.WriteFailed. However, the current code still only has anelseclause that maps all errors toWriteFailed, hiding cancellation.Apply this diff to propagate cancellation explicitly:
- const bytes_written = result_data.result catch |err| switch (err) { - else => return error.WriteFailed, - }; + const bytes_written = result_data.result catch |err| switch (err) { + error.Canceled => return error.Canceled, + else => return error.WriteFailed, + };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
examples/producer_consumer.zig(2 hunks)src/file.zig(11 hunks)src/runtime.zig(22 hunks)src/sync/Condition.zig(8 hunks)src/sync/Mutex.zig(4 hunks)src/sync/ResetEvent.zig(10 hunks)src/sync/Semaphore.zig(5 hunks)src/sync/queue.zig(10 hunks)src/tcp.zig(16 hunks)src/udp.zig(5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- examples/producer_consumer.zig
🔇 Additional comments (16)
src/sync/Condition.zig (4)
16-38: LGTM! Proper cancellation handling with mutex invariants.The cancellation flow correctly ensures the mutex is always reacquired before returning, maintaining the function's contract. The retry loop (lines 29-32) that ignores further cancellations during mutex reacquisition is appropriate—the caller expects the mutex to be locked on return regardless of cancellation state.
40-105: LGTM! Cancellation priority and mutex invariants maintained.The implementation correctly prioritizes cancellation over timeout (lines 86-88, 102-104) and ensures the mutex is always reacquired before returning. The dual retry loops handle both error and success paths, maintaining the contract that the mutex is locked on return.
114-119: LGTM! Standard broadcast implementation.The broadcast function properly wakes all waiting tasks, aligning with standard condition variable semantics.
132-239: LGTM! Tests updated for cancellation-aware APIs.Test functions properly updated to propagate errors via try, aligning with the new cancellable function signatures.
src/sync/Semaphore.zig (3)
19-51: LGTM! Correct permit handling under cancellation.The cancellation logic correctly handles the race between cancellation and permit availability:
- If cancelled while waiting and a permit becomes available, the permit is acquired then immediately released (lines 42-46)
- If cancelled while waiting and no permit is available, the error is returned directly (lines 47-50)
This ensures no permit is consumed when a wait is cancelled, maintaining semaphore semantics.
56-99: LGTM! Timeout prioritized correctly over cancellation.The implementation properly prioritizes timeout errors (lines 66-68, 72-74) while still handling cancellation with proper permit rollback (lines 89-94), maintaining semaphore invariants.
103-122: LGTM! Post operation completes despite cancellation.The retry loop (lines 107-113) ensures the permit is always posted even under cancellation, then returns
error.Canceledto inform the caller. This is correct behavior—the side effect completes but the cancellation state is still communicated.src/runtime.zig (8)
52-55: LGTM! Clean cancellation infrastructure.The
Cancelableerror set and atomiccanceledflag provide a thread-safe foundation for cooperative cancellation across coroutines and blocking tasks.Also applies to: 145-146
152-186: LGTM! Proper cancellation handling in waitForComplete.The coroutine path correctly handles cancellation by removing from the wait queue before returning (lines 172-175). The double-check pattern (lines 163-168) prevents lost wakeups. The thread path doesn't need cancellation handling as threads aren't cooperatively cancellable in this design.
193-247: LGTM! Proper timeout and cancellation handling.The implementation correctly handles both timeout and cancellation:
- Timeout path: callback removes from wait queue (lines 226-228)
- Cancellation path: explicit removal before returning error (lines 232-234)
This prevents leaving cancelled waiters in the queue while avoiding double-removal on timeout.
264-268: LGTM! Simple and correct cancellation request.The atomic store with release semantics ensures the cancellation request is visible to the target coroutine's next yield point.
340-378: LGTM! Consistent cancellation propagation across task types.The API changes properly propagate
Cancelablethrough the type system:
- Async tasks (Task, Future) propagate cancellation via
waitForComplete()- Blocking tasks explicitly mark cancellation as
unreachable(line 537)—correct since thread pool tasks don't support cooperative cancellation- JoinHandle dispatches appropriately for each task kind
The
getErrorSet()andgetPayload()helpers cleanly handle both error unions and plain types.Also applies to: 429-455, 530-544, 567-594
841-878: LGTM! Robust cooperative cancellation in yield.The dual cancellation checks are essential:
- Before suspending (lines 845-850): catches cancellation requested before yield
- After resuming (lines 874-877): catches cancellation requested while suspended
The atomic compare-exchange correctly consumes the cancellation flag, ensuring exactly-once semantics.
1030-1046: LGTM! Wait properly handles cancellation.The cancellation handling correctly removes the waiter from the queue on error (lines 1042-1044), preventing stale wait list entries.
1177-1231: LGTM! Critical use-after-free prevention for cancelled I/O.The while-loop pattern (lines 1192-1225) is essential for safety:
- On cancellation, requests backend cancellation if supported (io_uring, lines 1199-1219)
- Continues waiting until
completion.state() == .dead- Only then returns
error.CanceledThis ensures the xev callback completes before the stack frame is destroyed, preventing use-after-free bugs. The design correctly prioritizes cancellation semantics over I/O results—if a task is cancelled, the I/O outcome is discarded.
src/file.zig (1)
31-78: Ignore cancellation signature concern. High-level I/O methods use!usize(i.e.anyerror!usize), which already includeserror.Canceled. Explicit inclusion ofCancelableis only required in the buffered APIs (readBuf/writeBuf) to matchReader.Error/Writer.Error. No changes needed.Likely an incorrect or invalid review comment.
Implements beginShield/endShield pattern to protect cleanup operations from cancellation. This allows operations like close() to complete even when the task is canceled, while preserving the cancellation flag for future yield() calls. Key changes: - Add shield_count field to AnyTask to track nested shield blocks - Update yield() to skip cancellation checks when shielded - Add beginShield() and endShield() methods to Runtime - Update all close() methods (File, TCP, UDP) to use shields - Change File.close() return type from !void to void for consistency
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/tcp.zig (1)
106-147: Close operation correctly shielded from cancellation.The
beginShield()/endShield()pattern ensures that even if the task was canceled before callingclose(), the cleanup will complete. Thecatch unreachableis safe because the shield preventsyieldfrom returningerror.Canceled.However, for consistency with the rest of the codebase, consider using
self.runtime.waitForXevCompletion(&completion) catch unreachable;instead ofwaiter.runtime.yield(.waiting) catch unreachable;at line 147. This would:
- Be more consistent with other I/O operations
- Properly handle io_uring cancellation if needed
- Still be safe with the shield in place
Apply this diff if you want to improve consistency:
- waiter.runtime.yield(.waiting) catch unreachable; + self.runtime.waitForXevCompletion(&completion) catch unreachable;Also applies to: 409-450
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/file.zig(16 hunks)src/fs.zig(2 hunks)src/runtime.zig(23 hunks)src/tcp.zig(18 hunks)src/udp.zig(5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/udp.zig
🔇 Additional comments (25)
src/fs.zig (1)
194-194: LGTM! Close operations are now non-throwing.The removal of
tryis correct sinceclose()now returnsvoidand is shielded from cancellation (as implemented in src/file.zig lines 342-388). This aligns with the broader pattern of making close operations non-cancellable to ensure cleanup completes.Also applies to: 204-204
src/tcp.zig (4)
62-62: LGTM! Proper cancellation handling for accept operation.Using
waitForXevCompletioncorrectly handles both normal completion and cancellation, with proper I/O cleanup if the backend supports it.Also applies to: 96-96
169-169: LGTM! Cancellation-aware I/O operations.The
waitForXevCompletioncalls correctly propagate cancellation while ensuring proper cleanup of I/O operations.Also applies to: 206-206, 276-276, 312-312
319-319: LGTM! Return types correctly widened to include cancellation.The signatures properly include
error{Canceled}in the error union, allowing callers to observe cooperative cancellation.Also applies to: 358-358
481-481: LGTM! Tests updated to propagate cancellation.Using
tryforwait()calls is correct since the signature now includesCancelablein its error set.Also applies to: 520-520, 568-568, 616-616, 714-714, 778-778
src/file.zig (6)
6-6: LGTM! Cancelable error set imported.Properly imports the cancellation infrastructure from runtime.zig.
32-32: LGTM! Cancellation-aware I/O completions.All I/O operations correctly use
waitForXevCompletionto handle both normal completion and cancellation with proper cleanup.Also applies to: 248-248,287-287,300-300,333-333
Also applies to: 73-73, 81-81, 122-122, 154-154, 194-194, 200-200, 240-240
247-247: LGTM! Return types correctly include cancellation.The
readBufandwriteBufsignatures properly widen the error set to includeCancelable, allowing callers to observe cooperative cancellation.Also applies to: 299-299
335-337: LGTM! Error handling correctly separates cancellation from I/O errors.Cancellation is handled earlier by
waitForXevCompletion(line 333), which returnserror.Canceledif the operation was canceled. The error handling here correctly maps xev I/O errors toerror.WriteFailedfor std.io compatibility. Based on past reviews, this addresses the concern about bubbling cancellation through.Similar pattern in readBuf at lines 289-291.
342-388: LGTM! Close operation properly shielded and non-throwing.The implementation correctly:
- Returns
voidto make close non-throwing- Uses
beginShield()/endShield()to ensure cleanup completes even if canceled- Uses
waitForXevCompletionfor proper I/O cleanup- Ignores close errors per Zig standard library pattern
The
catch unreachableat line 384 is safe because the shield preventswaitForXevCompletionfrom returningerror.Canceled.
434-434: LGTM! Close calls correctly non-throwing.The removal of
tryis correct sinceclose()now returnsvoid.Also applies to: 440-440, 467-467, 511-511, 546-546, 563-563
src/runtime.zig (14)
52-55: LGTM! Cancelable error set introduced.Establishes the foundation for cooperative cancellation across the runtime.
145-146: LGTM! Atomic cancellation flag added.Using
std.atomic.Value(bool)with proper memory ordering (release/acquire) ensures thread-safe cancellation requests.
152-186: LGTM! Cancellation-aware wait with proper cleanup.The implementation correctly:
- Fast-path checks before suspending (avoids unnecessary work)
- Double-checks after enqueuing (avoids lost wakeups)
- Removes from wait queue if
yieldreturnserror.Canceled(prevents stale queue entries)- Thread path correctly loops on futex
The errdefer-like pattern at lines 171-175 ensures proper rollback on cancellation, addressing past review concerns.
193-247: LGTM! Timed wait correctly handles both timeout and cancellation.The implementation properly:
- Fast-path checks to avoid timer overhead
- Removes from wait queue on both timeout and cancellation (lines 232-236)
- Returns appropriate errors for each case
- Thread path uses futex timedWait
264-268: LGTM! Cancellation request API.Simple and clear API for requesting cancellation with proper memory ordering (release).
279-279: LGTM! Shield count added for critical sections.Enables non-cancellable regions like cleanup operations while keeping the cancellation flag for later.
341-341: LGTM! Task API updated for cancellation propagation.The
join()andresult()methods correctly return(Cancelable || Self.getErrorSet())!Self.getPayload(), and the helper methods properly extract error sets and payloads from return types.Also applies to: 430-430,442-456,568-568,576-576,580-594
Also applies to: 377-377, 361-375
531-538: LGTM! Blocking tasks correctly ignore cancellation.Using
catch unreachableis correct here because blocking tasks run on thread pool threads, which don't participate in cooperative cancellation. The comment clearly documents this behavior.
842-883: LGTM! Yield correctly implements cancellation checking with shield support.The implementation properly:
- Checks and consumes cancellation flag before yielding (lines 846-853)
- Respects shield_count to allow critical sections
- Uses compare-and-exchange for thread-safe flag consumption
- Re-checks after resuming (lines 877-882) to catch cancellation during suspension
- Correct memory ordering (acquire) ensures visibility
885-905: LGTM! Shield mechanism correctly implemented.The
beginShield()/endShield()pair provides a clean way to protect critical sections (like cleanup) from cancellation. The assertion inendShield()catches mismatched pairs.
1057-1073: LGTM! Wait correctly handles cancellation with cleanup.The implementation properly removes the task from the wait queue if
yieldreturnserror.Canceled(lines 1068-1072), preventing stale queue entries that would cause panics.
1104-1104: LGTM! Timed wait methods correctly return cancellation errors.Both
timedWaitForReadyWithCallbackandtimedWaitForReadyproperly includeerror.Canceledin their error sets and propagate it fromyield.Also applies to: 1189-1189
1212-1258: LGTM! waitForXevCompletion correctly handles cancellation with I/O cleanup.The implementation properly:
- Waits for completion to reach
.deadstate- On cancellation, requests io_uring cancellation if supported (lines 1226-1246)
- Continues waiting for completion even after cancellation (prevents use-after-free)
- Returns
error.Canceledafter completion if canceled- For non-io_uring backends, gracefully waits without cancellation support
This is a sophisticated and correct approach to async I/O cancellation.
1337-1339: LGTM! Tests updated to propagate cancellation.Using
tryforyieldandwaitcalls is correct since these operations now returnCancelable!void.Also applies to: 1402-1406
Also applies to: 1381-1406
The Waiter struct was an unnecessary abstraction that packaged a runtime pointer and coroutine pointer together. Since Runtime.fromCoroutine() can derive the runtime from any coroutine, we can simplify by storing only *Coroutine in I/O callbacks and calling Runtime.fromCoroutine(coro).markReady(coro) directly. Changes: - Remove Waiter type and Runtime.getWaiter() method - Update all I/O operations (file, TCP, UDP) to store *Coroutine directly - Callbacks now use Runtime.fromCoroutine() to get the runtime instance - markReadyFromXevCallback updated to take ?*Coroutine instead of ?*Waiter This removes one layer of indirection without losing any functionality.
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 (3)
src/runtime.zig (3)
1286-1307: Add missing try for error propagation.Lines 1301-1302:
future.wait()now returnserror{Canceled}!i32, so the call must usetryto propagate or handle the error. Withouttry, this will be a compile error (assigning an error union where a value is expected).Apply this diff:
// Set value future.set(42); // Get value (should return immediately since already set) - const result = future.wait(); + const result = try future.wait(); try testing.expectEqual(@as(i32, 42), result);
1309-1347: Add missing try in multiple locations.Lines 1326 and 1341 are missing
tryfor error propagation:
- Line 1326:
return future.wait();should bereturn try future.wait();- Line 1341:
const result = getter_handle.join();should beconst result = try getter_handle.join();Both
Future.wait()andJoinHandle.join()now return error unions that includeerror.Canceled.Apply this diff:
fn getterTask(future: *Future(i32)) !i32 { // This will block until setter sets the value - return future.wait(); + return try future.wait(); } fn asyncTask(rt: *Runtime) !void { ... - const result = getter_handle.join(); + const result = try getter_handle.join(); try testing.expectEqual(@as(i32, 123), result);
1349-1396: Add missing try for future.wait().Line 1356:
const result = future.wait();should beconst result = try future.wait();for the same reason as above.Apply this diff:
fn waiterTask(future: *Future(i32), expected: i32) !void { - const result = future.wait(); + const result = try future.wait(); try testing.expectEqual(expected, result); }
🧹 Nitpick comments (2)
src/tcp.zig (2)
320-356: Consider using the Cancelable type alias for consistency.The return type uses
error{Canceled}directly, while file.zig imports and uses theCancelabletype alias from runtime.zig. Both are functionally equivalent, but using the alias would improve consistency across the codebase.Apply this change for consistency:
- pub fn writeBuf(self: *const TcpStream, buffer: xev.WriteBuffer) (error{Canceled} || std.io.Writer.Error)!usize { + pub fn writeBuf(self: *const TcpStream, buffer: xev.WriteBuffer) (Cancelable || std.io.Writer.Error)!usize {And add the import at the top:
+const Cancelable = @import("runtime.zig").Cancelable;
360-406: Apply the same type alias change to readBuf.For consistency with the writeBuf suggestion above and with file.zig.
- pub fn readBuf(self: *const TcpStream, buffer: *xev.ReadBuffer) (error{Canceled} || std.io.Reader.Error)!usize { + pub fn readBuf(self: *const TcpStream, buffer: *xev.ReadBuffer) (Cancelable || std.io.Reader.Error)!usize {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/file.zig(21 hunks)src/runtime.zig(24 hunks)src/tcp.zig(24 hunks)src/udp.zig(9 hunks)
🔇 Additional comments (12)
src/udp.zig (3)
30-84: LGTM! Cancellation-aware read operation.The read operation correctly uses
waitForXevCompletionwithtryto propagate cancellation. The coroutine-based result storage prevents use-after-free bugs that were flagged in past reviews. The callback marks readiness viaRuntime.fromCoroutine, which is the correct pattern for cancellable I/O.
86-134: LGTM! Cancellation-aware write operation.The write operation follows the same correct pattern as read: coroutine-based result storage and cancellation propagation via
waitForXevCompletion. This addresses the use-after-scope concern from previous reviews.
136-182: LGTM! Close operation correctly shielded from cancellation.The close implementation properly addresses the critical issue flagged in past reviews about panicking under cancellation. By using
beginShield()/endShield(), the operation cannot be interrupted, and thecatch unreachablesafely asserts this invariant. This ensures cleanup always completes even when the task is cancelled.src/tcp.zig (2)
106-152: LGTM! Listener close properly shielded.The shielded close implementation correctly addresses the critical issue from past reviews where cancellation could cause panics during cleanup. The shield ensures the io_uring completion is observed before the function returns.
410-456: LGTM! Stream close properly shielded.The stream close follows the same correct shielding pattern as the listener close, ensuring cleanup completes even under cancellation.
src/file.zig (3)
248-296: LGTM! readBuf correctly propagates cancellation.The cancellation flows through
waitForXevCompletionon Line 288, and xev errors are properly mapped to std.io-compatible errors. The use of theCancelabletype alias is consistent and clear.
300-342: LGTM! writeBuf correctly propagates cancellation.Cancellation is propagated via the
tryon Line 335. The past review concern about observing cancellation explicitly is addressed: the cancellation comes fromwaitForXevCompletion, not fromresult_data.result, so the error handling at Lines 337-339 correctly maps only xev errors (not cancellation) to WriteFailed.
344-390: LGTM! Close operation correctly shielded and non-cancellable.The shield mechanism ensures close always completes, and the signature change from
!voidtovoidcorrectly reflects that close is now non-cancellable from the caller's perspective. Thecatch unreachablesafely asserts the shield invariant.src/runtime.zig (4)
42-45: LGTM! Clean cancellation error definition.The Cancelable error set provides a clear, unified type for cancellation across the runtime. This is well-designed.
135-259: LGTM! Atomic cancellation flag with proper synchronization.The atomic cancelled flag with memory ordering (.release for stores, .acquire for CAS) ensures proper happens-before relationships. The waitForComplete implementation correctly handles cancellation during suspension with proper queue cleanup on Line 163. The double-check pattern prevents lost wakeups.
832-895: LGTM! Comprehensive yield cancellation handling with shields.The yield implementation correctly checks and consumes the cancellation flag before yielding (Lines 836-843) and after resuming (Lines 867-872). The shield mechanism (Lines 875-895) provides safe opt-out for critical sections like close operations. The dual-check pattern ensures cancellation is caught at suspension points.
1186-1240: LGTM! waitForXevCompletion prevents use-after-free.This helper correctly addresses the critical use-after-scope issue from past reviews. By looping until the completion is .dead (Line 1201), it ensures the xev callback has fired and finished accessing stack-allocated result data before returning error.Canceled. The io_uring cancellation request (Lines 1208-1227) is a nice optimization but the safety comes from waiting for completion.
Replace catch unreachable with cancellation shield in Queue.close to prevent process abort if cancellation occurs during cleanup. This matches the pattern used in TcpListener, TcpStream, UdpSocket, and File close operations.
When a waiting task is cancelled after being popped from the wait queue but before waking up, it already owns the lock. Previously we would just remove it from the queue (which fails) and return the error, leaking the lock ownership and causing a deadlock. Now we check if remove() failed (meaning we already inherited the lock) and if so, properly unlock to transfer ownership to the next waiter or release the lock entirely.
Replace direct usage of error{Canceled} with the Cancelable type alias
across the codebase for better consistency and maintainability.
Changes:
- tcp.zig: Import and use Cancelable in writeBuf and readBuf functions
- sync/Barrier.zig: Import and use Cancelable in wait function
- runtime.zig: Use Cancelable in waitForXevCompletion function
All instances now follow the same pattern as file.zig, which already
uses the Cancelable type alias.
When waitForXevCompletion successfully waits for an I/O operation to complete after requesting cancellation via loop.cancel(), the xev backend may return error.Canceled in result_data.result. This backend error should be treated as a generic I/O failure, not a coroutine cancellation. If the coroutine was canceled, waitForXevCompletion would have already returned error.Canceled before we examine result_data.result. Updated files: - src/tcp.zig: accept(), connect(), shutdown(), writeBuf(), readBuf() - src/udp.zig: read(), write() - src/file.zig: read(), write(), pread(), pwrite(), readBuf(), writeBuf()
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/tcp.zig (1)
267-279: Include Cancelable in readVec/writeVec signatures to avoid error narrowing.readVec/writeVec call the cancellable readBuf/writeBuf but return only std.io.* errors. This either drops cancellation or won’t compile once used. Align their signatures.
- pub fn readVec(self: *const TcpStream, iovecs: [][]u8) std.io.Reader.Error!usize { + pub fn readVec(self: *const TcpStream, iovecs: [][]u8) (Cancelable || std.io.Reader.Error)!usize { @@ - pub fn writeVec(self: *const TcpStream, iovecs: []const []const u8) std.io.Writer.Error!usize { + pub fn writeVec(self: *const TcpStream, iovecs: []const []const u8) (Cancelable || std.io.Writer.Error)!usize {If you prefer to keep the non‑cancelable API, explicitly catch error.Canceled here and translate it to a std.io‑compatible error (and document the policy).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/file.zig(21 hunks)src/tcp.zig(23 hunks)src/udp.zig(8 hunks)
⏰ 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 (3)
src/udp.zig (1)
142-146: Close shielding looks good.beginShield/endShield + waitForXevCompletion ensures close completes and ignores task cancellation. Matches the intended safety guarantees.
Also applies to: 183-185
src/tcp.zig (1)
110-116: Close shielding is correct and consistent.beginShield/endShield with waitForXevCompletion ensures listener/stream close completes even under cancellation.
Also applies to: 151-153, 421-424, 461-463
src/file.zig (1)
354-360: Close shielding looks correct.beginShield/endShield with waitForXevCompletion ensures close completes regardless of task cancellation. Ignoring close result matches std pattern.
Also applies to: 395-400
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
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 (2)
src/runtime.zig (2)
1147-1168: Cancel the timer and invalidate its context when cancellation firesIf
yield(.waiting)returnserror.Canceled, we unwind immediately while the timer is still armed withctxpointing into this stack frame. The callback sees a matching generation and then dereferences freed memory — a latent use-after-return. Please invalidate the generation and cancel the timer before propagating the error.- try self.yield(.waiting); + self.yield(.waiting) catch |err| { + // Invalidate pending callbacks before unwinding so they ignore this stack frame. + task.timer_generation +%= 1; + timer.cancel( + &self.loop, + &task.timer_c, + &task.timer_cancel_c, + void, + null, + noopTimerCancelCallback, + ) catch {}; + return err; + };
521-536: Propagate cancellation from blocking joins instead of panickingWhen a coroutine waiting on a blocking task is canceled,
waitForComplete()now returnserror.Canceled. Catching that withunreachablecrashes the runtime, which defeats the new cancellation support. Make the blocking join/result APIs cancellation-aware and bubble the error up, matching the rest of the runtime.- fn join(self: *Self) T { + fn join(self: *Self) (Cancelable || Self.getErrorSet())!Self.getPayload() { if (self.future_result.get()) |res| { return res; } - // Wait for blocking task to complete (works from both coroutines and threads) - // Blocking tasks should never be canceled - self.any_blocking_task.awaitable.waitForComplete() catch unreachable; + try self.any_blocking_task.awaitable.waitForComplete(); return self.future_result.get() orelse unreachable; } - fn result(self: *Self) T { + fn result(self: *Self) (Cancelable || Self.getErrorSet())!Self.getPayload() { return self.join(); }
🧹 Nitpick comments (5)
src/tcp.zig (2)
330-366: Map OS-level error.Canceled consistently.For consistency with
accept,connect, andshutdown(which explicitly map error.Canceled to error.Unexpected), and per the learning that OS-level error.Canceled represents an unexpected system event, explicitly handle it inwriteBuf:Based on learnings.
Apply this diff:
- return result_data.result catch return error.WriteFailed; + return result_data.result catch |err| switch (err) { + error.Canceled => return error.Unexpected, + else => return error.WriteFailed, + };
370-416: Map OS-level error.Canceled consistently.Similarly,
readBufshould explicitly handle OS-level error.Canceled:Based on learnings.
Apply this diff:
const n = result_data.result catch |err| switch (err) { + error.Canceled => return error.Unexpected, error.EOF => return error.EndOfStream, else => return error.ReadFailed, };src/file.zig (2)
260-308: Map OS-level error.Canceled consistently.For consistency with
read,write,pread, andpwrite(which explicitly map error.Canceled to error.Unexpected at lines 76-79, 128-131, 203-206, 252-255),readBufshould also explicitly handle it:Based on learnings.
Apply this diff:
const bytes_read = result_data.result catch |err| switch (err) { + error.Canceled => return error.Unexpected, error.EOF => return error.EndOfStream, else => return error.ReadFailed, };
312-352: Map OS-level error.Canceled consistently.Similarly,
writeBufshould explicitly map OS-level error.Canceled to error.Unexpected:Based on learnings.
Apply this diff:
- const bytes_written = result_data.result catch return error.WriteFailed; + const bytes_written = result_data.result catch |err| switch (err) { + error.Canceled => return error.Unexpected, + else => return error.WriteFailed, + };src/sync/Semaphore.zig (1)
103-122: Consider making post() non-cancelable for defer patterns.The retry loop ensures the permit is posted even under cancellation, but returning
Cancelable!voidcreates awkward usage in defer-based cleanup:defer sem.post(rt) catch {}; // Ignores error.Canceled // or defer sem.post(rt) catch unreachable; // Panics on cancellationConsider using a shield to make
post()fully non-cancelable for simpler defer usage:pub fn post(self: *Semaphore, rt: *Runtime) void { rt.beginShield(); defer rt.endShield(); self.mutex.lock(rt) catch unreachable; defer self.mutex.unlock(rt); self.permits += 1; self.cond.signal(rt); }This matches the shield pattern used for close operations in file.zig and tcp.zig.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (16)
examples/mutex_demo.zig(2 hunks)examples/producer_consumer.zig(2 hunks)src/file.zig(21 hunks)src/fs.zig(2 hunks)src/io.zig(5 hunks)src/net.zig(2 hunks)src/runtime.zig(24 hunks)src/sync/Barrier.zig(9 hunks)src/sync/Condition.zig(8 hunks)src/sync/Mutex.zig(4 hunks)src/sync/ResetEvent.zig(10 hunks)src/sync/Semaphore.zig(5 hunks)src/sync/broadcast_channel.zig(18 hunks)src/sync/queue.zig(10 hunks)src/tcp.zig(23 hunks)src/udp.zig(8 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-10-10T05:59:17.066Z
Learnt from: lalinsky
PR: lalinsky/zio#41
File: src/udp.zig:79-82
Timestamp: 2025-10-10T05:59:17.066Z
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:
examples/producer_consumer.zigsrc/udp.zigsrc/tcp.zigsrc/file.zig
🔇 Additional comments (3)
src/sync/Condition.zig (2)
16-38: LGTM! Robust cancellation handling in wait().The cancellation path properly removes the task from the wait queue and retries mutex acquisition, ensuring no lost wakeups or queue corruption. The retry loop correctly handles nested cancellation during mutex reacquisition.
40-105: LGTM! Correct cancellation priority in timedWait().The implementation correctly prioritizes cancellation over timeout (lines 86-89, 102-104) and ensures the mutex is always reacquired before returning, even if the reacquisition itself is canceled. The
was_canceledtracking across both the timed wait and the mutex reacquisition paths is sound.src/sync/Semaphore.zig (1)
19-51: LGTM! Correct permit handling during cancellation.The logic correctly handles the edge case where a permit becomes available just as the task is canceled: it acquires the permit (lines 36-39) to prevent races, then immediately releases it (lines 42-45) since the canceled task shouldn't consume it. This ensures no permits are lost during cancellation.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/sync/Barrier.zig (1)
75-285: Add test coverage for cancellation behavior.The test suite validates basic synchronization, leader detection, reusability, and ordering, but lacks coverage for the newly added cancellation paths. Consider adding a test that verifies:
- A cancelled waiter returns
error.Canceled- Other waiters receive
error.BrokenBarrierafter the broadcast- Subsequent
wait()calls on the broken barrier returnerror.BrokenBarrierThis would confirm the cancellation unwind logic functions correctly.
Would you like me to generate a test case for cancellation behavior?
src/sync/Semaphore.zig (1)
96-207: Add test coverage for cancellation behavior.The test suite covers basic wait/post, timeout, and multiple permits, but lacks coverage for the newly added cancellation paths. Consider adding tests that verify:
wait()returnserror.Canceledwhen cancelled and properly signals another waiter if permits are availabletimedWait()returnserror.Canceledvserror.Timeoutcorrectlypost()successfully posts the permit and returnserror.Canceledafter retrying on contentionWould you like me to generate test cases for cancellation behavior?
♻️ Duplicate comments (1)
src/sync/Barrier.zig (1)
57-63: Cancellation handling correctly addresses previous review concerns.The implementation now properly handles cancellation by:
- Rolling back the participant count (
self.current -= 1)- Marking the barrier as broken (
self.broken = true)- Broadcasting to wake all waiting coroutines (
self.cond.broadcast)- Propagating the cancellation error
This ensures that when one participant is cancelled, the remaining waiters are woken up and receive
error.BrokenBarrierrather than blocking indefinitely. The previous review's deadlock concern has been resolved.
🧹 Nitpick comments (4)
src/sync/Barrier.zig (1)
34-36: Document that cancellation permanently breaks the barrier.The documentation mentions that "The barrier can be reused for multiple synchronization cycles" (line 10), but cancellation makes the barrier permanently unusable due to the
brokenflag having no reset mechanism. Consider clarifying that after any cancellation, the barrier cannot be reused and all subsequentwait()calls will returnerror.BrokenBarrier.Apply this diff to clarify the documentation:
/// Returns error.BrokenBarrier if the barrier has been broken by a cancellation. -/// Returns error.Canceled if this coroutine is cancelled while waiting. +/// Returns error.Canceled if this coroutine is cancelled while waiting. +/// Note: Once broken by cancellation, the barrier becomes permanently unusable. pub fn wait(self: *Barrier, runtime: *Runtime) (Cancelable || error{BrokenBarrier})!bool {src/sync/Semaphore.zig (1)
75-94: Clarify the retry loop semantics inpost().The retry loop (lines 79-85) ensures the permit is always posted, even if the coroutine is cancelled while waiting for the mutex. The loop continues until
lock()succeeds, which happens immediately (without yielding) when the mutex becomes available.However, if the mutex is highly contended, a cancelled coroutine might retry many times before the mutex becomes available. Consider expanding the documentation to explain this behavior and the rationale that
post()commits to posting the permit regardless of cancellation to prevent permit leaks.Apply this diff to enhance the documentation:
/// Increment the permit count and wake one waiting coroutine. -/// Retries if canceled to ensure the permit is posted, then returns error.Canceled. +/// Retries if canceled to ensure the permit is posted, then returns error.Canceled. +/// The retry guarantees the permit is always posted to prevent leaks, even if the +/// coroutine is cancelled. The loop exits when the mutex becomes available, at which +/// point lock() succeeds immediately without yielding (and thus without cancellation). pub fn post(self: *Semaphore, rt: *Runtime) Cancelable!void {src/future_result.zig (2)
12-21: Concurrency/publish pattern looks correct; minor ordering simplification possibleState transitions and release/acquire pairing are correct. The release store on Line 21 is the necessary publish. The cmpxchg success ordering on Line 13 need not be .release; .monotonic (or .acquire if you prefer symmetry) is sufficient.
Minimal tweak:
- const prev = self.state.cmpxchgStrong(.not_set, .setting, .release, .monotonic); + const prev = self.state.cmpxchgStrong(.not_set, .setting, .monotonic, .monotonic);No behavior change; slightly reduces barriers on the fast path.
27-33: get() returns ?anyerror!T; provide a typed accessor to avoid leaking anyerror to callersCallers expecting (Cancellable || E)!T will need to down-cast from anyerror repeatedly. Add a typed accessor to keep error-set precision at the API edge (or implement get() as ?E!T per prior comment).
Example helper (sketch; implement with your preferred casting approach):
pub fn getAs(self: *const Self, comptime E: type) ?E!T { if (self.state.load(.acquire) != .set) return null; if (self.err) |e| { // cast e to E and return error // e.g., return @errSetCast(E, e); } return self.value; }This matches the PR’s typed cancellation story and reduces boilerplate at call sites. Based on PR objectives.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/future_result.zig(1 hunks)src/runtime.zig(31 hunks)src/sync/Barrier.zig(10 hunks)src/sync/Semaphore.zig(7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/runtime.zig
🔇 Additional comments (3)
src/sync/Barrier.zig (1)
37-72: LGTM! Cancellation propagation and rollback are well-structured.The
wait()implementation correctly:
- Propagates cancellation from
mutex.lock()(line 37)- Guards against entering a broken barrier (lines 41-43)
- Rolls back state on cancellation during wait (line 59)
- Ensures all participants are notified via broadcast (line 61)
- Prevents new participants from entering after breaking (lines 67-69)
The error handling flow maintains barrier invariants and prevents lost wakeups.
src/sync/Semaphore.zig (2)
24-30: Defensive signaling on cancellation prevents lost wakeups.The implementation correctly signals another waiter when cancelled while
permits > 0(lines 26-27, 59-60). This handles the race condition where:
- A permit becomes available
- A waiter is signaled
- The waiter is cancelled before waking
- Without defensive signaling, the permit would be lost
This ensures semaphore permits are never leaked due to cancellation timing.
Also applies to: 57-63
50-50: Timeout comparison fix is correct.Changing the comparison from
>to>=(line 50) ensures that whenelapsedexactly equalstimeout_ns, the timeout is properly detected. This is a subtle but correct precision improvement.
Changed post() from Cancelable!void to void by using beginShield/endShield instead of manually retrying on cancellation. This simplifies the API and makes it clear that post always succeeds.
…tate (#41) Add a new 'dead' state to track when a completion's callback has been invoked, separate from when the operation itself completes. Previously, the 'completed' state conflated two concepts: - The I/O operation finished (result available) - The callback was invoked (no longer active) This meant active count was decremented when the operation finished, not when the callback was actually called. Now the state flow is: - new → running → completed → dead where 'completed' = operation done, result ready and 'dead' = callback invoked, fully finished Changes: - Add State.dead to Completion.State enum - markCompleted() now transitions to 'completed' (not 'dead') - New finishCompletion() transitions to 'dead' and invokes callback - Active count decrements in finishCompletion (moved from markCompleted) - processCompletions() calls finishCompletion() for deferred callbacks - Cancel checks now test for both 'completed' and 'dead' states - io_uring backend skips completions in 'completed' or 'dead' state - All tests updated to expect 'dead' after loop.run(.until_done)
Summary
This PR adds comprehensive cancellation support to the zio async runtime, allowing tasks to be cancelled gracefully with proper resource cleanup and prevention of use-after-free bugs.
Key Changes
Core Cancellation Infrastructure (
runtime.zig)Cancellableerror set containingerror.Canceledcancelledflag toAwaitablefor cancellation requestsyield()to check and consume the cancellation flag before and after yieldingwaitForXevCompletion()helper that properly handles cancellation of I/O operations:loop.cancel()error.CanceledwaitForComplete(),timedWaitForComplete(),wait(), andtimedWaitForReady()to propagate cancellationTask System Updates
Task.join()andFuture.wait()now return(Cancellable || ErrorSet)!PayloadgetErrorSet()andgetPayload()to extract types from result error unionsJoinHandleupdated to propagate cancellation from async tasks (blocking tasks ignore cancellation)File I/O (
file.zig)read,write,pread,pwrite,readBuf,writeBuf,close) now usewaitForXevCompletion()waiterfromvartoconst(minor cleanup)Synchronization Primitives
All sync primitives now support cancellation with proper rollback:
wait()returnserror{Canceled}!bool, decrements count on cancellationwait()andtimedWait()propagate cancellationwait()returnserror{Canceled}!voidlock()returnserror{Canceled}!voidlockRead()andlockWrite()return cancellable errorsacquire()returnserror{Canceled}!voidwait()returnserror{Canceled}!voidpush()andpop()return cancellable errors with proper cleanupNetwork I/O (
net.zig,tcp.zig,udp.zig)waitForXevCompletion()for proper cancellation handlingtrywith cancellable operationsStream I/O (
io.zig)error.Canceledtoerror.ReadFailed/error.WriteFailedsincestd.io.Reader/Writerdon't support cancellation in their error setsExamples
incrementTaskto handle cancellable operationserror.Canceledhandling in producer/consumer loopsTechnical Details
Cancellation Flow
awaitable.requestCancellation()to set the atomic flagyield(), it checks the flag and returnserror.CanceledwaitForXevCompletion()requests cancellation and waits for completionSafety Guarantees
Testing
Summary by CodeRabbit
New Features
Refactor
Bug Fixes
Tests
Documentation