Skip to content

Add comprehensive documentation to sync primitives - #45

Merged
lalinsky merged 6 commits into
mainfrom
docs/sync-primitives
Oct 15, 2025
Merged

lalinsky merged 6 commits into
mainfrom
docs/sync-primitives

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 14, 2025 •

Copy link
Copy Markdown
Owner

Summary

This PR adds comprehensive documentation to all synchronization primitives in the src/sync/ directory.

Documentation added for:

  • Mutex - Async-aware mutual exclusion with cooperative locking
  • Condition - Condition variables for task coordination
  • Barrier - Synchronization barriers with leader election
  • ResetEvent - Manual-reset events for signaling
  • Semaphore - Counting semaphores for resource limiting
  • Channel - Bounded FIFO channels with backpressure
  • BroadcastChannel - Broadcast channels for pub/sub patterns

Changes:

  • Added module-level documentation explaining concepts, behavior, and usage patterns
  • Included practical examples showing task spawning and usage
  • Documented all public functions with clear descriptions of behavior and error conditions
  • Added notes on cancellation safety where applicable
  • Fixed BroadcastChannel.unsubscribe() to shield from cancellation

All tests pass.

Summary by CodeRabbit

  • New Features

    • Async Mutex, Condition, ResetEvent, Semaphore, and bounded FIFO Channel with cancellation, timeouts, close/backpressure semantics.
    • Runtime/Executor cancellation check API to detect consumed cancellations.
    • SharedPtr and RefCounter publicly available.
  • Refactor

    • Barrier reworked to task-based with generation/leader semantics and broken-state handling.
    • Broadcast unsubscribe now non-error and shielded; lag/closed semantics clarified.
  • Documentation

    • Expanded docs across synchronization primitives and RefCounter.
  • Tests

    • Added/updated tests for all changes.

Add detailed module-level and function-level documentation for all sync
primitives: Mutex, Condition, Barrier, ResetEvent, Semaphore, Channel,
and BroadcastChannel.

Each module now includes:
- Clear explanations of concepts and behavior
- Practical usage examples with task spawning
- Documentation for all public functions
- Error condition descriptions
- Notes on cancellation safety where applicable

Also fixes BroadcastChannel.unsubscribe() to shield from cancellation
and updates all test code accordingly.
@coderabbitai

coderabbitai Bot commented Oct 14, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

Walkthrough

Adds Executor.checkCanceled() and Runtime.checkCanceled(); expands sync exports (RefCounter, SharedPtr); implements or refactors many synchronization primitives (Mutex, Condition, ResetEvent, Semaphore, Barrier, Channel, broadcast_channel) with cancellation/timeouts; adds SharedPtr and ref-counter docs and tests.

Changes

Cohort / File(s) Summary
Runtime cancellation API
src/runtime.zig
Import path updated for RefCounter; added pub fn checkCanceled(self: *Executor) Cancelable!void and pub fn checkCanceled(self: *Runtime) Cancelable!void that consume the cancellation flag and return cancellation as appropriate.
Sync top-level exports & re-exports
src/sync.zig, src/zio.zig
Re-exports added: RefCounter and SharedPtr in src/sync.zig; src/zio.zig now re-exports RefCounter.
Shared pointer
src/sync/shared_ptr.zig
New SharedPtr(comptime T, comptime Context) implementation with init, clone, deinit, getRefCount; allocator-backed, uses RefCounter, optional Context.deinit on last release.
Ref counter docs
src/sync/ref_counter.zig
Documentation expanded for RefCounter API; no signature or behavioral changes.
Mutex
src/sync/Mutex.zig
New mutex implementation: init, tryLock, lock, lockNoCancel, unlock; waiter queue, owner tracking, and cancellation-aware acquisition/release.
Condition variable
src/sync/Condition.zig
New Condition with init, wait, timedWait, signal, broadcast; integrates with Mutex and handles cancellation and timeouts.
ResetEvent
src/sync/ResetEvent.zig
Manual-reset event: init, isSet, set, reset, wait, timedWait; wait queue, cancellation/timeout semantics, and idempotent set/reset behaviors.
Semaphore
src/sync/Semaphore.zig
Counting semaphore with wait, timedWait, post; cancellation-aware waiting, timeouts via timer, and signaling semantics.
Barrier
src/sync/Barrier.zig
Reworked Barrier struct (adds current, generation, broken); `wait(self: *Barrier, runtime: *Runtime) (Cancelable
Bounded FIFO Channel
src/sync/channel.zig
Ring-buffer Channel(comptime T) extended with head/tail/count, mutex, not_empty, not_full, closed; send/receive/trySend/tryReceive updated for blocking, cancellation, close (graceful/immediate) semantics.
Broadcast channel
src/sync/broadcast_channel.zig
unsubscribe signature changed from !void to void and is shielded from cancellation; added lag handling, overwrite policy, closed semantics, and adjusted wait/wakeup behavior.
Tests & docs
src/...
Tests and documentation updated or added across sync modules (Mutex, Condition, ResetEvent, Semaphore, Barrier, Channel, SharedPtr, ref counter, broadcast_channel) to reflect new semantics and behaviors.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Task as Task
  participant Exec as Executor
  Note over Task,Exec: Cancellation check after leaving a shielded section
  Task->>Exec: endShield()
  Task->>Exec: checkCanceled()
  Exec-->>Task: ok / error.Canceled
Loading
sequenceDiagram
  autonumber
  participant Task as Task
  participant M as Mutex
  participant RT as Runtime
  Note over Task,M: lock(rt) fast-path then suspend on contention
  Task->>M: tryLock()
  alt acquired
    M-->>Task: locked
  else busy
    Task->>RT: suspend (enqueue waiter)
    RT-->>M: waiter enqueued
    M-->>RT: unlock -> transfer ownership
    RT-->>Task: wake (lock acquired)
  end
  Task->>M: unlock()
  M-->>RT: transfer to next waiter or set unlocked
Loading
sequenceDiagram
  autonumber
  participant Producer as Producer
  participant Channel as Channel[T]
  participant Consumer as Consumer
  Producer->>Channel: send(item)
  alt buffer full
    Producer->>Channel: wait(not_full) [cancelable]
  end
  Consumer->>Channel: receive()
  alt buffer empty
    Consumer->>Channel: wait(not_empty) [cancelable]
  end
  Channel-->>Producer: ok / ChannelClosed
  Channel-->>Consumer: item / ChannelClosed (drained)
Loading
sequenceDiagram
  autonumber
  participant T1 as Task1
  participant TN as TaskN
  participant B as Barrier
  T1->>B: wait(rt)
  TN->>B: wait(rt)
  alt last arrives
    B-->>T1: wake (leader=true)
    B-->>TN: wake (leader=false)
    B->>B: generation++ (reset current)
  else cancellation/broken
    B->>B: broken = true
    B-->>T1: error BrokenBarrier / Canceled
    B-->>TN: error BrokenBarrier / Canceled
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60–90 minutes

Possibly related PRs

Poem

"I hop through code with tiny paws,
I count, I share, I mend the flaws.
Locks and waits and signals bright,
Barriers break or hold the night.
A rabbit cheers — refcounts snug and tight!" 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Title Check ⚠️ Warning The given title emphasizes documentation improvements but the changeset also includes extensive functional additions and API updates such as new cancellation APIs in runtime and full implementations of mutex, condition, barrier, reset event, semaphore, channel, broadcast channel, shared pointer, and ref counter enhancements. It therefore does not accurately summarize the primary content of the pull request. Reviewers scanning history would be misled into expecting a docs-only update. Revise the title to reflect both the implementation and documentation changes, for example “Implement async synchronization primitives with full documentation and cancellation-safe BroadcastChannel.unsubscribe fix.” This will give a clearer overview of the pull request’s scope.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
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 233821d and c4e5ebb.

📒 Files selected for processing (5)
  • src/runtime.zig (3 hunks)
  • src/sync/Condition.zig (5 hunks)
  • src/sync/Mutex.zig (3 hunks)
  • src/sync/ResetEvent.zig (4 hunks)
  • src/zio.zig (1 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.

Move src/ref_counter.zig to src/sync/ref_counter.zig and document it
following the same style as other sync primitives. Export it from both
sync.zig and zio.zig for public use.

RefCounter is a thread-safe atomic reference counter for shared ownership,
useful for shared memory management in server applications.

Update runtime.zig to import from the new location.

@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 (7)
src/sync/broadcast_channel.zig (2)

93-107: Removing a non-subscribed consumer corrupts the list

remove() assumes membership; calling unsubscribe() on an already-unsubscribed Consumer (or never-subscribed) will reset first/last incorrectly if prev/next are null. Guard membership.

Example approach:

  • Track membership on the Consumer (e.g., subscribed: bool) set in append(), cleared in remove(), and make unsubscribe() a no-op if not subscribed.
  • Alternatively, make remove() return bool and have unsubscribe() ignore false.
 pub const Consumer = struct {
     read_pos: usize = 0,
     prev: ?*Consumer = null,
     next: ?*Consumer = null,
+    subscribed: bool = false,
 };
@@
 fn append(self: *ConsumerList, consumer: *Consumer) void {
@@
     self.last = consumer;
+    consumer.subscribed = true;
 }
@@
-fn remove(self: *ConsumerList, consumer: *Consumer) void {
+fn remove(self: *ConsumerList, consumer: *Consumer) void {
+    if (!consumer.subscribed) return;
@@
     consumer.prev = null;
     consumer.next = null;
+    consumer.subscribed = false;
 }

And in unsubscribe():

- self.consumers.remove(consumer);
+ self.consumers.remove(consumer);

(no behavior change needed once remove() guards)


158-164: Avoid usize overflow in lag detection
Use subtraction to compute distance instead of adding two usize values:

- if (consumer.read_pos + self.buffer.len < self.write_pos) {
+ if (self.write_pos - consumer.read_pos > self.buffer.len) {

Apply the same change at lines 169–174, 199–204, and 205–212. Consider widening the counters (e.g., to u128) or resetting on wrap for very long-running channels.

src/sync/ResetEvent.zig (2)

114-135: Lost wake race in wait(): enqueue must be followed by a state re-check

Between cmpxchg to .waiting and yield, set() can swap to .is_set, pop an empty queue, and return before the waiter enqueues, causing the waiter to sleep forever. Re-check state after push and avoid yielding if already set.

Apply this fix:

@@ pub fn wait(self: *ResetEvent, runtime: *Runtime) Cancelable!void {
-    if (state == .waiting) {
+    if (state == .waiting) {
         const current = coroutines.getCurrent() orelse unreachable;
         const executor = Executor.fromCoroutine(current);
         const task = AnyTask.fromCoroutine(current);
         self.wait_queue.push(&task.awaitable);
 
+        // Avoid lost wake: if set() raced, do not sleep.
+        if (self.state.load(.acquire) == .is_set) {
+            // If remove fails, we were already signaled.
+            _ = self.wait_queue.remove(&task.awaitable);
+            return;
+        }
+
         // Suspend until woken by set()
         executor.yield(.waiting) catch |err| {
             // On cancellation, remove from queue
             _ = self.wait_queue.remove(&task.awaitable);
             return err;
         };
     }

149-198: Same lost wake in timedWait(): add post-enqueue state re-check

timedWait enqueues then waits; set() racing just before enqueue leads to a sleeper that never wakes. Re-check state and skip waiting if already set.

@@ pub fn timedWait(self: *ResetEvent, runtime: *Runtime, timeout_ns: u64) error{ Timeout, Canceled }!void {
     self.wait_queue.push(&task.awaitable);
 
+    // Avoid lost wake: if set() raced, do not wait.
+    if (self.state.load(.acquire) == .is_set) {
+        _ = self.wait_queue.remove(&task.awaitable);
+        return;
+    }
+
     const TimeoutContext = struct {
src/sync/Mutex.zig (1)

95-111: Wake the waiter via its own executor, not the current one

unlock() builds the executor from current instead of the woken task, unlike Condition/ResetEvent. This can misroute scheduling if executors are per-task. Align with others.

 pub fn unlock(self: *Mutex, runtime: *Runtime) void {
     _ = runtime;
     const current = coroutines.getCurrent() orelse unreachable;
-    const executor = Executor.fromCoroutine(current);
     std.debug.assert(self.owner.load(.monotonic) == current);
 
     // Check if there are waiters
     if (self.wait_queue.pop()) |awaitable| {
         const task = AnyTask.fromAwaitable(awaitable);
         // Transfer ownership directly to next waiter
         self.owner.store(&task.coro, .release);
-        // Wake them up (they already own the lock)
-        executor.markReady(&task.coro);
+        // Wake them up (they already own the lock)
+        const exec = Executor.fromCoroutine(&task.coro);
+        exec.markReady(&task.coro);
     } else {
         // No waiters, release the lock completely
         self.owner.store(null, .release);
     }
 }
src/sync/Condition.zig (1)

85-107: Guarantee mutex is held on return (success path bug)

Doc promises the mutex is held on return, even if cancellation occurs during reacquire. Current success path uses try mutex.lock(...), which can return error and exit without holding the mutex, violating the invariant and breaking callers (e.g., Semaphore.wait).

Apply this fix:

-    // Re-acquire mutex after waking
-    try mutex.lock(runtime);
+    // Re-acquire mutex after waking — retry until held, ignoring cancellation
+    while (true) {
+        mutex.lock(runtime) catch continue;
+        break;
+    }

This mirrors your timedWait reacquire loop.

src/sync/Barrier.zig (1)

51-58: Barrier type is missing its struct container (won’t compile).

Fields are declared at file scope and @This() is used outside a container. init/wait are also outside a struct. Wrap these in a pub const Barrier = struct { ... }; and use a proper Self alias.

Apply this diff:

@@
-const Mutex = @import("Mutex.zig");
-const Condition = @import("Condition.zig");
-mutex: Mutex = Mutex.init,
-cond: Condition = Condition.init,
-count: usize,
-current: usize = 0,
-generation: usize = 0,
-broken: bool = false,
-
-const Barrier = @This();
+const Mutex = @import("Mutex.zig");
+const Condition = @import("Condition.zig");
+
+pub const Barrier = struct {
+    mutex: Mutex = Mutex.init,
+    cond: Condition = Condition.init,
+    count: usize,
+    current: usize = 0,
+    generation: usize = 0,
+    broken: bool = false,
+
+    const Self = @This();
@@
-pub fn init(count: usize) Barrier {
+pub fn init(count: usize) Self {
     std.debug.assert(count > 0);
     return .{ .count = count };
 }
@@
-pub fn wait(self: *Barrier, runtime: *Runtime) (Cancelable || error{BrokenBarrier})!bool {
+pub fn wait(self: *Self, runtime: *Runtime) (Cancelable || error{BrokenBarrier})!bool {
@@
-    }
-}
+    }
+};

Also applies to: 60-66, 87-124

🧹 Nitpick comments (4)
src/sync/Mutex.zig (1)

59-61: Typo: error type spelling

Docs say error.Cancelled, code uses error.Canceled. Prefer consistent single-l spelling to match error type.

src/sync/Semaphore.zig (1)

62-79: Depends on Condition.wait reacquiring the mutex

Your correctness here relies on Condition.wait guaranteeing the mutex is held on return (success or error). With the current Condition.wait bug (success path uses try), unlock assertions may trip. After fixing Condition.wait, this looks good.

src/sync/channel.zig (2)

200-230: Immediate close drops buffered items without cleanup hooks.

If T owns resources (allocations/FDs), immediate = true discards items without cleanup. Consider adding a clearWith helper (or an overload of close that accepts a drop callback) to release resources for buffered items before zeroing the queue. Also mention this caveat in docs.


83-90: Make error sets explicit for API stability (optional).

To document/lock API, consider explicit error sets, e.g.:

  • receive: (Cancelable || error{ChannelClosed})!T
  • tryReceive: (Cancelable || error{ChannelEmpty, ChannelClosed})!T
  • send: (Cancelable || error{ChannelClosed})!void
  • trySend: (Cancelable || error{ChannelFull, ChannelClosed})!void

This clarifies behavior and avoids error-set widening across changes.

Also applies to: 115-122, 174-181

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1424f4b and 6c284b0.

📒 Files selected for processing (7)
  • src/sync/Barrier.zig (2 hunks)
  • src/sync/Condition.zig (5 hunks)
  • src/sync/Mutex.zig (3 hunks)
  • src/sync/ResetEvent.zig (4 hunks)
  • src/sync/Semaphore.zig (3 hunks)
  • src/sync/broadcast_channel.zig (15 hunks)
  • src/sync/channel.zig (6 hunks)
🔇 Additional comments (3)
src/sync/broadcast_channel.zig (1)

130-142: Unsubscribe shielding and non-throwing API LGTM

Shielding cleanup from cancellation is correct; void return simplifies call sites. Tests reflect this.

src/sync/Condition.zig (1)

121-188: Timed wait reacquire already robust — consistency note

timedWait correctly reacquires the mutex in a loop and prioritizes cancellation over timeout. Once wait() is fixed similarly, both APIs will align.

src/sync/channel.zig (1)

83-113: Core channel ops look correct.

FIFO ring buffer, signaling, and cancellation handling are solid.

Also applies to: 142-172

@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/sync/ResetEvent.zig (2)

114-138: Fix race: waiter can miss set() between state transition and queue push

If set() swaps to is_set after cmpxchg(.unset→.waiting) but before the waiter pushes to wait_queue, set() will pop no one; the waiter then enqueues and yields, potentially blocking until a future set. Re-check after enqueue and skip yielding if already set.

Apply this diff:

@@
-    // If we're now in waiting state, add to queue and block
-    if (state == .waiting) {
-        const current = coroutines.getCurrent() orelse unreachable;
-        const executor = Executor.fromCoroutine(current);
-        const task = AnyTask.fromCoroutine(current);
-        self.wait_queue.push(&task.awaitable);
-
-        // Suspend until woken by set()
-        executor.yield(.waiting) catch |err| {
-            // On cancellation, remove from queue
-            _ = self.wait_queue.remove(&task.awaitable);
-            return err;
-        };
-    }
-
-    // If state is is_set, we return immediately (event already set)
-    std.debug.assert(state == .is_set or state == .waiting);
+    // If we're now in waiting state, add to queue and block
+    if (state == .waiting) {
+        const current = coroutines.getCurrent() orelse unreachable;
+        const executor = Executor.fromCoroutine(current);
+        const task = AnyTask.fromCoroutine(current);
+        self.wait_queue.push(&task.awaitable);
+
+        // Re-check after enqueuing to avoid race with set()
+        if (self.state.load(.acquire) == .is_set) {
+            // Best-effort remove; if it fails, we were already signaled
+            _ = self.wait_queue.remove(&task.awaitable);
+            return;
+        }
+
+        // Suspend until woken by set()
+        executor.yield(.waiting) catch |err| {
+            // On cancellation, remove from queue
+            _ = self.wait_queue.remove(&task.awaitable);
+            return err;
+        };
+    }
+
+    // Event should be set here, or we yielded above
+    std.debug.assert(self.state.load(.acquire) == .is_set);

163-198: Apply the same enqueue-after-check race fix to timedWait

Re-check state after pushing; if already set, remove and return instead of arming the timer.

Apply this diff:

@@
-    self.wait_queue.push(&task.awaitable);
+    self.wait_queue.push(&task.awaitable);
+
+    // Re-check after enqueuing to avoid race with set()
+    if (self.state.load(.acquire) == .is_set) {
+        _ = self.wait_queue.remove(&task.awaitable);
+        return;
+    }
@@
     executor.timedWaitForReadyWithCallback(
src/sync/Condition.zig (1)

93-107: Fix invariant: always hold the mutex when wait() returns, even if cancellation happens during re‑acquire

Currently, after a successful wake, try mutex.lock(rt) can itself be canceled, causing wait() to return error.Canceled without holding the mutex, violating the documented invariant. Mirror the timedWait() approach: re‑acquire in a loop, record cancellation, and return error.Canceled only after the mutex is held.

-    // Re-acquire mutex after waking
-    try mutex.lock(runtime);
+    // Re-acquire mutex before returning; ignore cancellation while locking
+    var was_canceled = false;
+    while (true) {
+        mutex.lock(runtime) catch {
+            was_canceled = true;
+            continue;
+        };
+        break;
+    }
+    if (was_canceled) return error.Canceled;
🧹 Nitpick comments (10)
src/sync/ResetEvent.zig (1)

79-96: Optional: drop the early-return in set()

The pre-check can introduce a TOCTOU with a concurrent reset and isn't needed. Always swapping to is_set is idempotent and simpler.

Apply this diff:

-    // Quick check if already set to avoid unnecessary atomic operations
-    if (self.state.load(.monotonic) == .is_set) {
-        return;
-    }
-
-    // Atomically set to is_set and get the previous state
-    const prev_state = self.state.swap(.is_set, .release);
+    // Atomically set to is_set and get the previous state (idempotent)
+    const prev_state = self.state.swap(.is_set, .release);
src/sync/ref_counter.zig (2)

60-66: Constrain T to integer at compile time

Prevents accidental instantiation with non-integer types.

Apply this diff:

 pub fn RefCounter(comptime T: type) type {
-    return struct {
+    comptime {
+        if (@typeInfo(T) != .Int) {
+            @compileError("RefCounter expects an integer type parameter");
+        }
+    }
+    return struct {

79-81: Guard against overflow on incr()

Add a debug assertion to prevent wraparound.

Apply this diff:

         pub fn incr(self: *Self) void {
-            const prev_ref_count = self.refs.fetchAdd(1, .monotonic);
+            const prev_ref_count = self.refs.fetchAdd(1, .monotonic);
+            std.debug.assert(prev_ref_count < std.math.maxInt(T));
             std.debug.assert(prev_ref_count > 0);
         }
src/runtime.zig (1)

15-15: Prefer importing RefCounter via the public sync module re‑export

Avoid coupling to the internal file path; import through sync.zig for stability.

-const RefCounter = @import("sync/ref_counter.zig").RefCounter;
+const RefCounter = @import("sync.zig").RefCounter;
src/sync/broadcast_channel.zig (1)

130-142: Unsubscribe is now cancellation‑shielded (good). Guard against double unsubscribe to avoid list corruption

If unsubscribe is called twice for the same Consumer, remove() will corrupt the list. Add an idempotency/membership guard before removal.

 pub fn unsubscribe(self: *Self, runtime: *Runtime, consumer: *Consumer) void {
   // Shield unsubscribe operation from cancellation
   runtime.beginShield();
   defer runtime.endShield();

   self.mutex.lock(runtime) catch unreachable;
   defer self.mutex.unlock(runtime);

-  self.consumers.remove(consumer);
+  // Idempotency: skip if the consumer is not in the list
+  var cur = self.consumers.first;
+  var in_list = false;
+  while (cur) |c| {
+      if (c == consumer) { in_list = true; break; }
+      cur = c.next;
+  }
+  if (!in_list) return;
+  self.consumers.remove(consumer);
 }
src/sync/channel.zig (5)

69-75: Document cancellation on isEmpty().

Since lock(rt) can return error.Canceled, mention it in docs for clarity.

-        /// Checks if the channel is empty.
+        /// Checks if the channel is empty.
+        /// May return `error.Canceled` if the task is canceled while acquiring the lock.

76-82: Document cancellation on isFull().

Same rationale as isEmpty().

-        /// Checks if the channel is full.
+        /// Checks if the channel is full.
+        /// May return `error.Canceled` if the task is canceled while acquiring the lock.

200-231: Make close() idempotent and clarify immediate-drop behavior.

  • Optional: early-return if already closed to avoid surprising “second-call clears buffer” behavior.
  • Doc: note that buffered items are dropped without deinit on immediate close.
         pub fn close(self: *Self, rt: *Runtime, immediate: bool) void {
             // Shield close operation from cancellation
             rt.beginShield();
             defer rt.endShield();

             self.mutex.lock(rt) catch unreachable;
             defer self.mutex.unlock(rt);

-            self.closed = true;
+            if (self.closed) {
+                // Already closed; nothing to do (idempotent)
+                return;
+            }
+            self.closed = true;

             if (immediate) {
                 // Clear the buffer
                 self.head = 0;
                 self.tail = 0;
                 self.count = 0;
             }

Additionally, consider updating the doc above to:

-        /// If `immediate` is true, clears all buffered items immediately. This causes
-        /// receivers to get `error.ChannelClosed` right away instead of draining.
+        /// If `immediate` is true, clears all buffered items immediately (they are dropped
+        /// without running any user-defined deinit). This causes receivers to get
+        /// `error.ChannelClosed` right away instead of draining.

17-41: Example loop style: consider a catch/break pattern for portability.

Depending on Zig version, while (ch.receive(rt)) |value| ... else |err| ... may not compile. A safer pattern:

while (true) {
    const value = ch.receive(rt) catch |err| switch (err) {
        error.ChannelClosed => break,
        else => return err,
    };
    std.debug.print("Received: {}\n", .{value});
}

47-61: Optional API additions: len() and capacity().

Handy introspection without forcing callers to interpret emptiness/fullness.

Add alongside existing methods:

pub fn len(self: *Self, rt: *Runtime) !usize {
    try self.mutex.lock(rt);
    defer self.mutex.unlock(rt);
    return self.count;
}

pub fn capacity(self: *Self) usize {
    return self.buffer.len;
}

Also applies to: 115-122, 142-148, 174-181, 200-210

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1424f4b and 708a2dd.

📒 Files selected for processing (11)
  • src/runtime.zig (1 hunks)
  • src/sync.zig (2 hunks)
  • src/sync/Barrier.zig (2 hunks)
  • src/sync/Condition.zig (5 hunks)
  • src/sync/Mutex.zig (3 hunks)
  • src/sync/ResetEvent.zig (4 hunks)
  • src/sync/Semaphore.zig (3 hunks)
  • src/sync/broadcast_channel.zig (15 hunks)
  • src/sync/channel.zig (6 hunks)
  • src/sync/ref_counter.zig (3 hunks)
  • src/zio.zig (1 hunks)
🔇 Additional comments (12)
src/sync/Semaphore.zig (1)

61-79: Semaphore wait/timedWait/post look solid

Mutex-guarded state, correct loop predicate, cancellation handling, timeout math, and shielded post are all appropriate. Tests cover key paths.

Also applies to: 91-121, 128-138

src/sync/Barrier.zig (1)

87-124: Barrier wait/broken semantics are correct

Generation tracking, leader return, cancel → broken + broadcast behavior all look correct and race-free under the mutex.

src/sync.zig (1)

11-12: RefCounter re-export looks good

Public surface and test re-export are consistent with existing pattern.

Also applies to: 22-23

src/zio.zig (1)

33-33: LGTM: RefCounter re‑export

Consistent with the sync surface consolidation. No concerns.

src/sync/broadcast_channel.zig (1)

279-279: LGTM: defer unsubscribe after subscribe

Switching to a void, cancellation‑shielded unsubscribe pairs well with defer and simplifies call sites. Consistent across tests.

Also applies to: 323-323, 367-367, 409-409, 453-453, 556-556, 597-597, 642-642

src/sync/Condition.zig (1)

121-187: LGTM: timedWait cancellation/timeout semantics and re‑acquire loop

The timeout callback removal, cancellation priority, and re‑acquire loop are correct and robust.

src/sync/Mutex.zig (1)

61-111: LGTM: cooperative lock with cancellation and ownership transfer

  • Fast‑path tryLock + queue/yield slow‑path is sound.
  • On cancellation, removing from queue or dropping inherited lock via unlock() avoids stuck ownership.
  • unlock() transfers ownership before waking the waiter, matching the post‑wake assert.

No changes requested.

src/sync/channel.zig (5)

62-68: Init looks good.

Capacity > 0 asserted and buffer-based init is clear.


83-113: Receive path: state machine and wakeups look correct.

Loop on empty+!closed, recheck after wait, signal not_full on consume. Good.


115-141: tryReceive semantics LGTM.

Correct ChannelEmpty vs ChannelClosed distinction; signals not_full on success.


142-173: send() blocking semantics LGTM.

Closed checks before and after waits; not_empty signal on enqueue is correct.


174-199: trySend semantics LGTM.

Immediate errors for full/closed; not_empty signal on enqueue is correct.

Condition.wait() and timedWait() promised to always hold the mutex on
return, even during cancellation. The success path used try mutex.lock()
which could fail and exit without holding the mutex, violating this
invariant and breaking callers (e.g., Semaphore.wait using defer unlock).

Solution:
- Add Mutex.lockNoCancel() that uses shield to guarantee lock acquisition
- Add Runtime.checkCanceled() to detect cancellation after shielded ops
- Update Condition.wait/timedWait to use lockNoCancel + checkCanceled
- Simplify Semaphore.post, Channel.close, BroadcastChannel.unsubscribe

The new lockNoCancel() helper is cleaner than manual shield + catch
unreachable, and checkCanceled() allows flexible cancellation handling.

@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 (1)
src/sync/broadcast_channel.zig (1)

93-107: Fix unsafe ConsumerList.remove and guard subscribe/unsubscribe against misuse/double calls

remove() assumes membership. Calling unsubscribe() twice or with a non-member consumer corrupts the list (may null-out first/last). Guard membership and make unsubscribe idempotent.

Apply this diff:

@@
         const ConsumerList = struct {
             first: ?*Consumer = null,
             last: ?*Consumer = null,
@@
             fn remove(self: *ConsumerList, consumer: *Consumer) void {
+                // Defensive: only remove if currently linked
+                if (consumer.prev == null and consumer.next == null and self.first != consumer) {
+                    return; // not a member; no-op
+                }
                 if (consumer.prev) |prev| {
                     prev.next = consumer.next;
                 } else {
                     self.first = consumer.next;
                 }
                 if (consumer.next) |next| {
                     next.prev = consumer.prev;
                 } else {
                     self.last = consumer.prev;
                 }
                 consumer.prev = null;
                 consumer.next = null;
             }
+ 
+            fn contains(self: *ConsumerList, consumer: *Consumer) bool {
+                return consumer.prev != null or consumer.next != null or self.first == consumer;
+            }
         };
@@
-        pub fn subscribe(self: *Self, runtime: *Runtime, consumer: *Consumer) !void {
+        pub fn subscribe(self: *Self, runtime: *Runtime, consumer: *Consumer) !void {
             try self.mutex.lock(runtime);
             defer self.mutex.unlock(runtime);
 
+            // Prevent double-subscribe; idempotent no-op
+            if (self.consumers.contains(consumer)) return;
             consumer.read_pos = self.write_pos;
             self.consumers.append(consumer);
         }
@@
-        pub fn unsubscribe(self: *Self, runtime: *Runtime, consumer: *Consumer) void {
+        pub fn unsubscribe(self: *Self, runtime: *Runtime, consumer: *Consumer) void {
             self.mutex.lockNoCancel(runtime);
             defer self.mutex.unlock(runtime);
 
-            self.consumers.remove(consumer);
+            if (self.consumers.contains(consumer)) {
+                self.consumers.remove(consumer);
+            }
         }

Also applies to: 116-128, 133-138

🧹 Nitpick comments (3)
src/sync/broadcast_channel.zig (2)

154-160: Make lag detection overflow-safe

consumer.read_pos + buffer.len < write_pos risks usize overflow in debug and misclassification after long runs. Compute difference instead.

Apply this diff:

-            if (consumer.read_pos + self.buffer.len < self.write_pos) {
+            const behind = std.math.sub(usize, self.write_pos, consumer.read_pos) catch 0;
+            if (behind > self.buffer.len) {
                 // Skip to the oldest available message
                 consumer.read_pos = self.write_pos - self.buffer.len;
                 return error.Lagged;
             }
@@
-                if (consumer.read_pos + self.buffer.len < self.write_pos) {
+                const behind2 = std.math.sub(usize, self.write_pos, consumer.read_pos) catch 0;
+                if (behind2 > self.buffer.len) {
                     consumer.read_pos = self.write_pos - self.buffer.len;
                     return error.Lagged;
                 }

And in tryReceive:

-            if (consumer.read_pos + self.buffer.len < self.write_pos) {
+            const behind = std.math.sub(usize, self.write_pos, consumer.read_pos) catch 0;
+            if (behind > self.buffer.len) {
                 consumer.read_pos = self.write_pos - self.buffer.len;
                 return error.Lagged;
             }

Also applies to: 166-170, 195-199


242-250: Consider shielding close() to guarantee completion

Closing while cancelable can leave the channel open if cancellation happens mid-operation. Shield it like unsubscribe/post.

Apply this diff to make close robust without changing the signature:

-        pub fn close(self: *Self, runtime: *Runtime) !void {
-            try self.mutex.lock(runtime);
+        pub fn close(self: *Self, runtime: *Runtime) !void {
+            self.mutex.lockNoCancel(runtime);
             defer self.mutex.unlock(runtime);
 
             self.closed = true;
 
             // Wake all waiting consumers so they can see the channel is closed
             self.not_empty.broadcast(runtime);
         }
src/sync/Mutex.zig (1)

111-128: Use the target task’s executor when waking in unlock()

Currently derives executor from current coroutine; use the woken task’s executor for consistency (matches Condition.signal) and future multi-executor safety.

Apply this diff:

 pub fn unlock(self: *Mutex, runtime: *Runtime) void {
     _ = runtime;
     const current = coroutines.getCurrent() orelse unreachable;
-    const executor = Executor.fromCoroutine(current);
     std.debug.assert(self.owner.load(.monotonic) == current);
 
     // Check if there are waiters
     if (self.wait_queue.pop()) |awaitable| {
         const task = AnyTask.fromAwaitable(awaitable);
         // Transfer ownership directly to next waiter
         self.owner.store(&task.coro, .release);
         // Wake them up (they already own the lock)
-        executor.markReady(&task.coro);
+        const exec = Executor.fromCoroutine(&task.coro);
+        exec.markReady(&task.coro);
     } else {
         // No waiters, release the lock completely
         self.owner.store(null, .release);
     }
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 708a2dd and 0acd674.

📒 Files selected for processing (7)
  • src/runtime.zig (3 hunks)
  • src/sync.zig (2 hunks)
  • src/sync/Condition.zig (5 hunks)
  • src/sync/Mutex.zig (3 hunks)
  • src/sync/Semaphore.zig (3 hunks)
  • src/sync/broadcast_channel.zig (15 hunks)
  • src/sync/channel.zig (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/sync.zig
🔇 Additional comments (19)
src/runtime.zig (3)

15-15: Import path update looks correct

RefCounter re-import from sync/ref_counter.zig aligns with new exports. No issues.


960-971: Cancellation check API is sound and consumption semantics are clear

Atomically consuming the cancellation flag with acquire ordering is correct and matches yield() behavior. Good documentation and intended post-shield usage.


1437-1445: Runtime.checkCanceled passthrough is correct

No-op outside coroutine and proper delegation to Executor.checkCanceled. Good.

src/sync/broadcast_channel.zig (1)

1-50: Docs are thorough and clear

Great overview and example. Nice alignment with zio runtime semantics.

src/sync/Condition.zig (2)

84-105: wait(): cancellation and mutex reacquire semantics look correct

Queue before unlock, handle cancellation by dequeue+reacquire (no‑cancel), and propagate post‑lock cancellation via checkCanceled(). Solid.


119-166: timedWait(): correct priority to cancellation and invariant preservation

Timeout context + dequeue on timeout, reacquire with no‑cancel, and favor Canceled over Timeout. Looks good.

src/sync/Semaphore.zig (3)

61-79: wait(): correct cancellation handling and signaling

Loop + cond.wait with wake-on-permit race is good. Decrement and signal when permits remain is correct.


91-120: timedWait(): timeout and cancellation paths are correct

Local timeout calculation and proper signaling on cancel look good.


129-134: post(): cancellation-shielded critical section is appropriate

Ensures permits aren’t lost. Good alignment with Mutex.lockNoCancel.

src/sync/Mutex.zig (1)

97-101: lockNoCancel(): correct shielding pattern

beginShield/endShield around lock() is appropriate; post-acquire cancellation can be checked by callers via runtime.checkCanceled().

src/sync/channel.zig (9)

1-41: Excellent comprehensive documentation.

The module documentation clearly explains the channel's behavior, including backpressure, FIFO ordering, blocking semantics, and close/drain behavior. The example is practical and demonstrates proper usage.


47-60: LGTM! Well-structured ring buffer with proper synchronization.

The channel structure correctly implements a ring buffer with separate head/tail pointers and a count field to disambiguate full vs empty states. The use of a mutex with two condition variables (not_empty, not_full) follows the standard monitor pattern for producer-consumer synchronization.


62-81: LGTM! Proper initialization and state query methods.

The initialization includes a defensive assertion for non-zero capacity. The isEmpty and isFull methods correctly lock the mutex for atomic state queries, though callers should be aware that the results may become stale by the time they're used—this is inherent to any query method in a concurrent system.


83-113: LGTM! Correct receive implementation with proper drain semantics.

The receive logic correctly:

  • Blocks while empty and not closed, allowing graceful draining after close
  • Returns error.ChannelClosed only when both closed and empty
  • Updates the ring buffer head pointer with proper modulo arithmetic
  • Signals waiting senders via not_full
  • Handles cancellation correctly (defer ensures unlock)

115-140: LGTM! Correct non-blocking receive implementation.

The tryReceive method properly implements non-blocking semantics, returning appropriate errors (ChannelEmpty or ChannelClosed) when no item is available, and signaling not_full when an item is successfully retrieved.


142-172: LGTM! Correct send implementation with proper close handling.

The send logic correctly:

  • Checks if closed before attempting to send
  • Blocks while full with proper condition variable usage
  • Importantly re-checks the closed flag after waking (line 160-162), which is essential since the channel could be closed while the task is waiting
  • Updates the ring buffer tail pointer correctly
  • Signals waiting receivers via not_empty

174-198: LGTM! Correct non-blocking send implementation.

The trySend method properly implements non-blocking semantics with appropriate error codes for closed and full states, and correctly signals not_empty when an item is successfully sent.


200-226: LGTM! Correct close implementation with cancellation safety.

The close method is properly implemented:

  • Uses lockNoCancel (line 211) to shield from cancellation, ensuring the close operation completes reliably as documented
  • Supports both graceful (drain buffered items) and immediate (clear buffer) close semantics
  • Broadcasts to both condition variables to wake all waiting tasks, allowing them to observe the closed state

230-544: LGTM! Comprehensive test coverage.

The test suite thoroughly validates:

  • Basic send/receive operations
  • Non-blocking try operations and their error conditions
  • Blocking behavior when empty or full
  • Multiple concurrent producers and consumers
  • Both graceful and immediate close semantics
  • Sending on a closed channel
  • Ring buffer wrap-around behavior

The tests demonstrate proper usage patterns and verify correctness under various scenarios.

Comment thread src/sync/Condition.zig
Comment on lines +62 to 84
/// Creates a new condition variable.
pub const init: Condition = .{};

/// Atomically releases the mutex and waits for a signal.
///
/// This function must be called while holding the mutex. It will:
/// 1. Add the current task to the wait queue
/// 2. Release the mutex
/// 3. Suspend until signaled by `signal()` or `broadcast()`
/// 4. Reacquire the mutex before returning
///
/// This function should typically be called in a loop that checks the condition:
/// ```zig
/// try mutex.lock(rt);
/// defer mutex.unlock(rt);
/// while (!condition_is_true) {
/// try condition.wait(rt, &mutex);
/// }
/// ```
///
/// Returns `error.Cancelled` if the task is cancelled while waiting. The mutex
/// will still be held when returning with an error.
pub fn wait(self: *Condition, runtime: *Runtime, mutex: *Mutex) Cancelable!void {

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.

⚠️ Potential issue | 🟡 Minor

Doc typos: use “Canceled” consistently

Comments say error.Cancelled; the code uses error.Canceled. Please fix spelling to avoid confusion.

Also applies to: 107-119

🤖 Prompt for AI Agents
In src/sync/Condition.zig around lines 62-84 (and also apply the same change at
lines 107-119), the doc comment uses the British spelling `error.Cancelled` but
the code uses `error.Canceled`; update the comments to use `error.Canceled`
consistently (match the actual error identifier used in code) so all occurrences
in these comment blocks reflect the correct American spelling `Canceled`.

Resolved conflicts:
- Updated Mutex.tryLock() to use runtime parameter
- Kept checkCanceled() method in Executor and Runtime
- Fixed Runtime.checkCanceled() to use executor.current_coroutine
@lalinsky
lalinsky merged commit ee0e490 into main Oct 15, 2025
@lalinsky
lalinsky deleted the docs/sync-primitives branch October 15, 2025 08:22
This was referenced Oct 22, 2025
lalinsky added a commit that referenced this pull request Jan 6, 2026
* Handle Async notifications before submission

If an Async completion is notified before being submitted to the loop,
it now completes immediately upon submission instead of waiting for
another notify() call.

Changes:
- Make Async.loop optional to allow notify() before submission
- Add checkAndSetAsyncResult() helper to deduplicate pending check logic
- Check for pending state in loop.add() and complete immediately if set
- Clear loop reference when Async completes

* Refactor buffer API to store iovecs directly

Changes ReadBuf and WriteBuf to hold iovec arrays directly instead of
wrapping individual iovecs. This simplifies the API by:

- Removing intermediate buffer wrapper arrays
- Eliminating the toIovecs() conversion step
- Making storage management more explicit
- Reducing allocations and improving clarity

Breaking changes:
- ReadBuf.fromSlice() and WriteBuf.fromSlice() now require storage parameter
- ReadBuf.fromSlices() now returns ReadBuf instead of []ReadBuf
- Completion types now take ReadBuf/WriteBuf instead of slices
- Field names changed from plural (buffers) to singular (buffer)
@coderabbitai coderabbitai Bot mentioned this pull request Jan 14, 2026
2 tasks done
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