Skip to content

Add cancellation support to async runtime - #41

Merged
lalinsky merged 24 commits into
mainfrom
cancel
Oct 10, 2025
Merged

lalinsky merged 24 commits into
mainfrom
cancel

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 9, 2025 •

Copy link
Copy Markdown
Owner

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)

  • Added Cancellable error set containing error.Canceled
  • Added atomic cancelled flag to Awaitable for cancellation requests
  • Updated yield() to check and consume the cancellation flag before and after yielding
  • Added waitForXevCompletion() helper that properly handles cancellation of I/O operations:
    • On io_uring backend, requests cancellation via loop.cancel()
    • Waits for operation to complete before returning error.Canceled
    • Prevents use-after-free bugs where callbacks access freed stack memory
  • Updated waitForComplete(), timedWaitForComplete(), wait(), and timedWaitForReady() to propagate cancellation

Task System Updates

  • Task.join() and Future.wait() now return (Cancellable || ErrorSet)!Payload
  • Added helper methods getErrorSet() and getPayload() to extract types from result error unions
  • JoinHandle updated to propagate cancellation from async tasks (blocking tasks ignore cancellation)
  • Proper cleanup: tasks remove themselves from wait queues when cancelled

File I/O (file.zig)

  • All file operations (read, write, pread, pwrite, readBuf, writeBuf, close) now use waitForXevCompletion()
  • Operations properly handle cancellation with cleanup
  • Changed waiter from var to const (minor cleanup)

Synchronization Primitives

All sync primitives now support cancellation with proper rollback:

  • Barrier: wait() returns error{Canceled}!bool, decrements count on cancellation
  • Condition: wait() and timedWait() propagate cancellation
  • Latch: wait() returns error{Canceled}!void
  • Mutex: lock() returns error{Canceled}!void
  • RwLock: lockRead() and lockWrite() return cancellable errors
  • Semaphore: acquire() returns error{Canceled}!void
  • ResetEvent: wait() returns error{Canceled}!void
  • Queue: push() and pop() return cancellable errors with proper cleanup

Network I/O (net.zig, tcp.zig, udp.zig)

  • All I/O operations use waitForXevCompletion() for proper cancellation handling
  • TCP accept, connect, read, write all cancellable
  • UDP send, receive operations cancellable
  • Tests updated to use try with cancellable operations

Stream I/O (io.zig)

  • Convert error.Canceled to error.ReadFailed/error.WriteFailed since std.io.Reader/Writer don't support cancellation in their error sets
  • Ensures compatibility with standard library interfaces

Examples

  • mutex_demo.zig: Updated incrementTask to handle cancellable operations
  • producer_consumer.zig: Added error.Canceled handling in producer/consumer loops

Technical Details

Cancellation Flow

  1. External code calls awaitable.requestCancellation() to set the atomic flag
  2. Next time the task calls yield(), it checks the flag and returns error.Canceled
  3. Error propagates up through the call stack
  4. Tasks automatically clean up (remove from wait queues, etc.)
  5. For I/O operations, waitForXevCompletion() requests cancellation and waits for completion

Safety Guarantees

  • No use-after-free: I/O operations always complete before stack memory is released
  • No resource leaks: Proper cleanup on cancellation paths
  • No lost wakeups: Cancellation checks happen at suspension points
  • Atomic operations ensure thread-safe cancellation requests

Testing

  • All existing tests pass with cancellation support
  • Examples demonstrate proper cancellation handling
  • Tests verify cancellation propagation through sync primitives

Summary by CodeRabbit

  • New Features

    • Global cancellation support (Cancelable); Condition.broadcast; close operations shielded from cancellation.
  • Refactor

    • Many public APIs (runtime, I/O, TCP/UDP, sync primitives) now return cancellation-aware results; coroutine-backed completion model; future/result now carries optional error.
  • Bug Fixes

    • More consistent cancellation-to-error mapping while preserving end-of-stream semantics.
  • Tests

    • Tests updated to propagate and exercise cancellable flows.
  • Documentation

    • Examples adjusted for fallible, cancellation-aware APIs.

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.
@coderabbitai

coderabbitai Bot commented Oct 9, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

Make suspension points, I/O completions, and sync primitives cancellation-aware: add a public Cancelable error, switch waiter-based per-call sync to coroutine-backed completions (Coroutine + waitForXevCompletion), add shielding for close, and update runtime, I/O, sync primitives, examples, and tests to propagate cancellation.

Changes

Cohort / File(s) Summary
Runtime & core
src/runtime.zig
Introduce Cancelable error; add cancellation flag to Awaitable and requestCancellation; make yield/wait/timed-waits cancellation-aware; add waitForXevCompletion, beginShield/endShield; update Task/Future/JoinHandle/BlockingTask APIs to surface cancelable unions and add helpers.
File & generic I/O
src/file.zig, src/io.zig
Replace waiter-based per-call sync with coroutine-based flow and waitForXevCompletion; readBuf/writeBuf now return cancelable unions; map Canceled to std.io Reader/Writer errors at the API boundary; shield close and ignore cancellation during close.
Networking (TCP/UDP) & tests
src/tcp.zig, src/udp.zig, src/net.zig
Replace Waiter usage with coroutine handles in result payloads; callbacks mark readiness via Runtime.fromCoroutine(...).markReady(...); readBuf/writeBuf return cancelable unions; close guarded with shields; test fixes (try ready_event.wait).
Sync primitives
src/sync/{Mutex,Condition,Semaphore,Barrier,ResetEvent}.zig
Make lock/wait/timedWait/post/broadcast/barrier wait APIs cancellation-aware (Cancelable!void, error{Timeout, Canceled}!void, or `(Cancelable
Sync utilities & channels
src/sync/queue.zig, src/sync/broadcast_channel.zig
Make mutex operations fallible (try on lock); change isEmpty/isFull → !bool; subscribe/unsubscribe/close → !void; propagate lock/wait errors and update callers/tests.
Future / Awaitable result
src/future_result.zig
Replace single result field with value + err; set now accepts anyerror!T and stores either value or error; get returns ?anyerror!T.
Coroutines / I/O wait bridging
src/* (I/O & xev completion sites)
Centralize coroutine-backed completion handling: store coro handles in result payloads, use Runtime.fromCoroutine(...).markReady(...) in callbacks, and await via waitForXevCompletion.
Examples & tests
examples/*, src/* tests
Convert many tasks/examples/tests to fallible (!void), add try/catch for cancellation flows, remove try around shielded close where appropriate, and adjust ready/wait test calls.

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
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

I hop where coroutines quietly yield,
I tuck a try into each waiting field.
If cancellation whispers through the queue,
I unhook waiters neatly, then hop anew.
A rabbit's patch: small hops, code shining through. 🐇

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title “Add cancellation support to async runtime” accurately and concisely summarizes the primary change in this pull request, which is the introduction of cancellation semantics across the async runtime, I/O, and synchronization primitives. It clearly conveys the scope of the work without unnecessary detail or vagueness. A teammate glancing at the history will immediately understand the core update.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d27816 and 99b29ee.

📒 Files selected for processing (1)
  • src/sync/Semaphore.zig (7 hunks)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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 mutex

If the caller is cancelled while waiting, runtime.yield(.waiting) now returns error.Cancelled and we exit lock immediately. But we already enqueued task.awaitable; nothing removes it. The next unlock will 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 call unlock, so subsequent lockers hang.

Handle error.Cancelled explicitly: unlink the awaitable from wait_queue (and leave owner unchanged) 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.current is incremented before we enter the wait loop. If self.cond.wait returns error.Cancelled, we bubble it out immediately, leaving self.current at 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 reaches self.count again – future callers will block forever.

Catch error.Cancelled, roll back self.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 queue

On Line 75 we enqueue the awaitable, but if runtime.yield(.waiting) (Line 77) returns error.Cancelled, we immediately unwind with our awaitable still linked. A subsequent set() will pop that stale pointer and call markReady() on a task that may already have completed or been deinitialized, leading to use-after-free. Please ensure we remove the awaitable when the wait exits with an error (e.g. an errdefer right after the push).

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 and set()/timeout callbacks can touch freed stack memory. Please mirror the fix from wait() by removing the awaitable in the error path (an errdefer alongside 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 waiter

When Line 26’s runtime.yield(.waiting) returns error.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 surrounding defer unlock will double-unlock. Worse, the awaitable pushed on Line 21 never gets removed, so later signal()/broadcast() will pop a stale pointer. Add an errdefer right after the push that (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

timedWait already reacquires the mutex via errdefer mutex.lock(...), but we still leave the awaitable in the queue on cancellation. Please extend the errdefer to remove the awaitable (similar to wait()), 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 operations

If Line 96’s yield(.waiting) returns error.Cancelled, we exit accept() while the xev accept is still in flight. The callback will later write into result_data (Lines 65-84), but that struct—and the embedded Waiter—live on this stack frame, so we end up with a use-after-free once the coroutine unwinds. The same pattern exists in connect, shutdown, writeBuf, and readBuf. 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.ReadError already exposes error.Cancelled; funneling it through the generic else branch turns a cooperative cancel into an I/O failure, defeating the new (Cancellable || std.io.Reader.Error) surface. Return error.Cancelled directly 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a29087 and 6c716cf.

📒 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 good

Switching 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.io

Mapping error.Cancelled to error.ReadFailed keeps the std.io.Reader contract intact while still letting cancellation bubble up to callers.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

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

⚠️ Outside diff range comments (4)
src/sync/ResetEvent.zig (1)

197-202: Re-throw non-timeout errors in the test waiter.

After expanding timedWait to return error.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 += 1 but before the broadcast, self.current stays permanently incremented and the barrier never opens again. Add an errdefer 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) (or runtime.timedWaitForReadyWithCallback) returns error.Canceled, we exit without re-locking the mutex and without removing our entry from wait_queue. The mutex invariant is broken (caller expects the lock held when wait returns), and the stale queue node will later be popped by signal/broadcast, causing Runtime.markReady to panic because the coroutine is no longer in .waiting. We need to retry mutex.lock even on cancellation, remove the awaitable from wait_queue, and only then propagate error.Canceled.

src/runtime.zig (1)

530-538: Propagate cancellation instead of crashing blocking joins.

waitForComplete() now returns error.Canceled, but the blocking-task join path still does catch unreachable. If a coroutine waiting on a blocking task is cancelled, we’ll hit that unreachable and abort. Please let cancellation bubble up (e.g. make BlockingTask.join/result return Cancellable!T and try the 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) leaves current_task.awaitable in task.awaitable.waiting_list, so when the target task completes markReady will panic because the coroutine isn’t actually waiting. We still need the errdefer/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.WriteFailed regardless of the condition, so the if (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

📥 Commits

Reviewing files that changed from the base of the PR and between 6c716cf and 08dc2fd.

📒 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.Canceled to 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 !void and using try keeps 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/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:

  1. Subsequent cancellation signals are consumed/lost during reacquisition
  2. The loop retries indefinitely until the mutex is acquired
  3. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 08dc2fd and e852f99.

📒 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.current on 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 !void and uses try on the wait() 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:

  1. 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)
  2. Lines 92-104: Success path also reacquires mutex

    • Tracks if cancellation occurred during reacquisition (line 95)
  3. Lines 86-88, 102-104: Cancellation has priority over timeout

The was_cancelled tracking 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 existing signal() 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

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

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

289-292: Fix the error return type.

Line 291 returns error.WriteFailed in a read operation. This should be error.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 handling error.Canceled for consistency.

writeBuf (lines 335-338) explicitly checks for error.Canceled in its error handling, but readBuf uses a catch-all else branch. For symmetry and clarity, consider adding an explicit error.Canceled => return error.Canceled branch here as well, matching the pattern in writeBuf.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e852f99 and 7c55f4b.

📒 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 try correctly propagates cancellation from yield().


247-247: LGTM: Signatures correctly widened for cancellation.

The Cancellable union 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 Cancellable error set with error.Canceled provides 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) returns error.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 if markComplete later 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.Timeout from error.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 if yield returns an error, preventing orphaned queue entries.


360-374: LGTM: Type introspection helpers.

The getErrorSet() and getPayload() 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() uses catch 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 that requestCancellation() 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().

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (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.Canceled is 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 else branch 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c55f4b and 0e29b0d.

📒 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 Cancellable in the error union, waitForXevCompletion properly propagates cancellation via try, and the error mapping from xev to std.io errors is appropriate.


89-89: Good practice: marking waiter variables as const.

Changing var waiter to const waiter across 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 use waitForXevCompletion instead 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 name Canceled (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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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() uses try self.runtime.waitForXevCompletion(&completion) at line 379, which can propagate error.Canceled. However, TCP and UDP close operations use yield(.waiting) catch unreachable to panic on cancellation.

This inconsistency creates unpredictable behavior:

  • File close can be cancelled
  • TCP/UDP close panics if cancelled

Standardize the behavior. Either:

  1. All close operations should propagate cancellation (change tcp/udp to match file)
  2. 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 cancelled
src/runtime.zig (1)

1234-1387: Add missing cancellation tests
The runtime needs explicit coverage for cancellation paths. Please add tests that:

  • call requestCancellation on an awaitable and assert it propagates
  • verify I/O operations return error.Canceled when 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 else case, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0e29b0d and 74a87cc.

📒 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 waitForXevCompletion correctly addresses the use-after-scope concern raised in the previous review. The new implementation ensures that:

  1. Stack-allocated result_data remains valid until the xev callback completes
  2. The waiter is properly cleaned up before returning cancellation errors
  3. 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 waitForXevCompletion to 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 via try)
  • 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 waitForXevCompletion with 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 readBuf and writeBuf methods properly include Cancellable in their error sets and use waitForXevCompletion to handle cancellation during I/O waits.

Also applies to: 299-340

src/runtime.zig (5)

52-55: LGTM: Well-designed cancellation infrastructure.

The new Cancellable error set and atomic cancelled flag provide a clean foundation for cancellation. The requestCancellation method 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:

  1. Before yielding (lines 847-850)
  2. After resuming (lines 875-877)

The use of cmpxchgStrong guarantees 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 in timedWaitForComplete) 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 waitForXevCompletion method is the key to safe cancellation:

  1. Waits for xev completion to reach .dead state (line 1192)
  2. On cancellation, requests xev cancellation for io_uring (lines 1199-1219)
  3. Continues waiting for the operation to complete (line 1222)
  4. 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() and getPayload() 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

Comment thread src/tcp.zig Resolved
@lalinsky lalinsky changed the title WIP: Add cancellation support to async runtime Add cancellation support to async runtime Oct 9, 2025
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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), readBuf declares Cancelable in its return type but the error mapping at lines 289-292 doesn't explicitly handle error.Canceled. It falls through to the else clause and returns error.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.Canceled should be explicitly propagated rather than mapped to error.WriteFailed. However, the current code still only has an else clause that maps all errors to WriteFailed, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 74a87cc and 9b3c30a.

📒 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.Canceled to 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 Cancelable error set and atomic canceled flag 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 Cancelable through 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() and getPayload() 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:

  1. Before suspending (lines 845-850): catches cancellation requested before yield
  2. 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:

  1. On cancellation, requests backend cancellation if supported (io_uring, lines 1199-1219)
  2. Continues waiting until completion.state() == .dead
  3. Only then returns error.Canceled

This 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 includes error.Canceled. Explicit inclusion of Cancelable is only required in the buffered APIs (readBuf/writeBuf) to match Reader.Error/Writer.Error. No changes needed.

Likely an incorrect or invalid review comment.

Comment thread src/sync/Mutex.zig Resolved
Comment thread src/sync/queue.zig Resolved
Comment thread src/tcp.zig Resolved
Comment thread src/tcp.zig Resolved
Comment thread src/udp.zig Resolved
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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/tcp.zig (1)

106-147: Close operation correctly shielded from cancellation.

The beginShield()/endShield() pattern ensures that even if the task was canceled before calling close(), the cleanup will complete. The catch unreachable is safe because the shield prevents yield from returning error.Canceled.

However, for consistency with the rest of the codebase, consider using self.runtime.waitForXevCompletion(&completion) catch unreachable; instead of waiter.runtime.yield(.waiting) catch unreachable; at line 147. This would:

  1. Be more consistent with other I/O operations
  2. Properly handle io_uring cancellation if needed
  3. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9b3c30a and 3b2ed8d.

📒 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 try is correct since close() now returns void and 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 waitForXevCompletion correctly 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 waitForXevCompletion calls 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 try for wait() calls is correct since the signature now includes Cancelable in 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 waitForXevCompletion to 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 readBuf and writeBuf signatures properly widen the error set to include Cancelable, 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 returns error.Canceled if the operation was canceled. The error handling here correctly maps xev I/O errors to error.WriteFailed for 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:

  1. Returns void to make close non-throwing
  2. Uses beginShield()/endShield() to ensure cleanup completes even if canceled
  3. Uses waitForXevCompletion for proper I/O cleanup
  4. Ignores close errors per Zig standard library pattern

The catch unreachable at line 384 is safe because the shield prevents waitForXevCompletion from returning error.Canceled.


434-434: LGTM! Close calls correctly non-throwing.

The removal of try is correct since close() now returns void.

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:

  1. Fast-path checks before suspending (avoids unnecessary work)
  2. Double-checks after enqueuing (avoids lost wakeups)
  3. Removes from wait queue if yield returns error.Canceled (prevents stale queue entries)
  4. 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:

  1. Fast-path checks to avoid timer overhead
  2. Removes from wait queue on both timeout and cancellation (lines 232-236)
  3. Returns appropriate errors for each case
  4. 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() and result() 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 unreachable is 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:

  1. Checks and consumes cancellation flag before yielding (lines 846-853)
  2. Respects shield_count to allow critical sections
  3. Uses compare-and-exchange for thread-safe flag consumption
  4. Re-checks after resuming (lines 877-882) to catch cancellation during suspension
  5. 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 in endShield() catches mismatched pairs.


1057-1073: LGTM! Wait correctly handles cancellation with cleanup.

The implementation properly removes the task from the wait queue if yield returns error.Canceled (lines 1068-1072), preventing stale queue entries that would cause panics.


1104-1104: LGTM! Timed wait methods correctly return cancellation errors.

Both timedWaitForReadyWithCallback and timedWaitForReady properly include error.Canceled in their error sets and propagate it from yield.

Also applies to: 1189-1189


1212-1258: LGTM! waitForXevCompletion correctly handles cancellation with I/O cleanup.

The implementation properly:

  1. Waits for completion to reach .dead state
  2. On cancellation, requests io_uring cancellation if supported (lines 1226-1246)
  3. Continues waiting for completion even after cancellation (prevents use-after-free)
  4. Returns error.Canceled after completion if canceled
  5. 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 try for yield and wait calls is correct since these operations now return Cancelable!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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

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

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

1286-1307: Add missing try for error propagation.

Lines 1301-1302: future.wait() now returns error{Canceled}!i32, so the call must use try to propagate or handle the error. Without try, 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 try for error propagation:

  • Line 1326: return future.wait(); should be return try future.wait();
  • Line 1341: const result = getter_handle.join(); should be const result = try getter_handle.join();

Both Future.wait() and JoinHandle.join() now return error unions that include error.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 be const 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 the Cancelable type 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3b2ed8d and f56120c.

📒 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 waitForXevCompletion with try to propagate cancellation. The coroutine-based result storage prevents use-after-free bugs that were flagged in past reviews. The callback marks readiness via Runtime.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 the catch unreachable safely 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 waitForXevCompletion on Line 288, and xev errors are properly mapped to std.io-compatible errors. The use of the Cancelable type alias is consistent and clear.


300-342: LGTM! writeBuf correctly propagates cancellation.

Cancellation is propagated via the try on Line 335. The past review concern about observing cancellation explicitly is addressed: the cancellation comes from waitForXevCompletion, not from result_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 !void to void correctly reflects that close is now non-cancellable from the caller's perspective. The catch unreachable safely 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()

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 062a7f0 and dc0cc55.

📒 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

Comment thread src/file.zig Resolved
Comment thread src/tcp.zig Resolved
Comment thread src/udp.zig Resolved
@lalinsky

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Oct 10, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

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

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

1147-1168: Cancel the timer and invalidate its context when cancellation fires

If yield(.waiting) returns error.Canceled, we unwind immediately while the timer is still armed with ctx pointing 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 panicking

When a coroutine waiting on a blocking task is canceled, waitForComplete() now returns error.Canceled. Catching that with unreachable crashes 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, and shutdown (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 in writeBuf:

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, readBuf should 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, and pwrite (which explicitly map error.Canceled to error.Unexpected at lines 76-79, 128-131, 203-206, 252-255), readBuf should 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, writeBuf should 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!void creates awkward usage in defer-based cleanup:

defer sem.post(rt) catch {}; // Ignores error.Canceled
// or
defer sem.post(rt) catch unreachable; // Panics on cancellation

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4a29087 and dc0cc55.

📒 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.zig
  • src/udp.zig
  • src/tcp.zig
  • src/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_canceled tracking 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.

Comment thread src/runtime.zig Resolved
Comment thread src/sync/Barrier.zig Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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.BrokenBarrier after the broadcast
  • Subsequent wait() calls on the broken barrier return error.BrokenBarrier

This 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() returns error.Canceled when cancelled and properly signals another waiter if permits are available
  • timedWait() returns error.Canceled vs error.Timeout correctly
  • post() successfully posts the permit and returns error.Canceled after retrying on contention

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

  1. Rolling back the participant count (self.current -= 1)
  2. Marking the barrier as broken (self.broken = true)
  3. Broadcasting to wake all waiting coroutines (self.cond.broadcast)
  4. Propagating the cancellation error

This ensures that when one participant is cancelled, the remaining waiters are woken up and receive error.BrokenBarrier rather 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 broken flag having no reset mechanism. Consider clarifying that after any cancellation, the barrier cannot be reused and all subsequent wait() calls will return error.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 in post().

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 possible

State 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 callers

Callers 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

📥 Commits

Reviewing files that changed from the base of the PR and between dc0cc55 and 6d27816.

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

  1. A permit becomes available
  2. A waiter is signaled
  3. The waiter is cancelled before waking
  4. 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 when elapsed exactly equals timeout_ns, the timeout is properly detected. This is a subtle but correct precision improvement.

Comment thread src/future_result.zig Resolved
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.
@lalinsky
lalinsky merged commit f98480e into main Oct 10, 2025
@lalinsky
lalinsky deleted the cancel branch October 10, 2025 07:30
@coderabbitai coderabbitai Bot mentioned this pull request Nov 16, 2025
2 tasks
lalinsky added a commit that referenced this pull request Jan 6, 2026
…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)
@coderabbitai coderabbitai Bot mentioned this pull request Jan 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant