Skip to content

Refactor BroadcastChannel to use sync primitives and add AsyncReceive support - #95

Merged
lalinsky merged 5 commits into
mainfrom
broadcast-channel-async-receive
Oct 28, 2025
Merged

lalinsky merged 5 commits into
mainfrom
broadcast-channel-async-receive

Conversation

@lalinsky

Copy link
Copy Markdown
Owner

Summary

This PR refactors BroadcastChannel to follow the same pattern as Channel, using synchronous primitives and direct wait queue management instead of async Mutex/Condition primitives. It also adds AsyncReceive support for use with select().

Changes

Phase 1: Refactor to use synchronous primitives

  • Replace async Mutex with std.Thread.Mutex
  • Replace Condition with SimpleWaitQueue(WaitNode) for direct wait management
  • Refactor receive() to use executor.yield() pattern with proper cancellation support
  • Remove Runtime parameter from subscribe(), unsubscribe(), tryReceive(), send(), close()
  • Update all existing tests to match new signatures

Phase 2: Add AsyncReceive support

  • Implement AsyncReceive(T) type that implements the future protocol
  • Add asyncReceive() method to BroadcastChannel
  • Properly handle broadcast channel semantics:
    • Consumer lag detection (error.Lagged)
    • Multiple independent consumers
    • Proper cancellation handling
    • Fast path for already-available messages and closed channels

Test Coverage

  • All existing tests updated and passing
  • Added 5 new tests for async functionality:
    • Basic async receive with blocking
    • Already-ready fast path
    • Closed channel handling
    • Lagged consumer detection
    • Multiple broadcast channels with select

All 146 tests pass.

Benefits

  • Consistent with Channel implementation pattern
  • More efficient (no async overhead for non-blocking operations)
  • Enables use of BroadcastChannel with select() for multiplexing
  • Better cancellation handling

… support

This commit refactors BroadcastChannel to follow the same pattern as Channel,
using synchronous primitives and direct wait queue management instead of async
Mutex/Condition primitives.

Changes:
- Replace async Mutex with std.Thread.Mutex
- Replace Condition with SimpleWaitQueue(WaitNode) for direct wait management
- Refactor receive() to use executor.yield() pattern with cancellation support
- Remove Runtime parameter from subscribe(), unsubscribe(), tryReceive(), send(), close()
- Implement AsyncReceive type for use with select()
- Add asyncReceive() method to BroadcastChannel
- Add comprehensive tests for async operations

The AsyncReceive implementation properly handles broadcast channel semantics:
- Consumer lag detection (error.Lagged)
- Multiple independent consumers
- Proper cancellation handling
- Fast path for already-available messages and closed channels

All existing tests updated and passing, plus 5 new tests for async functionality.
@coderabbitai

coderabbitai Bot commented Oct 28, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Replaces per-consumer Mutex/Condition with a wait-queue (SimpleWaitQueue/WaitNode), removes runtime parameters from several channel APIs (subscribe/unsubscribe/tryReceive/send/close), and adds a select-friendly AsyncReceive type with tests for asyncReceive/select, lag handling, and close behavior.

Changes

Cohort / File(s) Summary
BroadcastChannel Core
src/sync/broadcast_channel.zig
Rewrote synchronization from per-consumer Mutex/Condition to SimpleWaitQueue/WaitNode; updated waiter management and internal receive flow to use wait-queue semantics.
API Signature Changes
src/sync/broadcast_channel.zig
Removed runtime param from subscribe, unsubscribe, tryReceive, send, and close; receive retains runtime but internal sync was updated.
AsyncReceive / Select Integration
src/sync/broadcast_channel.zig
Added public AsyncReceive(T) and asyncReceive factory with init, asyncWait, asyncCancelWait, getResult, plus Result = error{ Closed, Lagged }!T for select compatibility.
Wait-queue & Select Surface
src/utils/wait_queue.zig, src/core/WaitNode.zig, src/select.zig
Channel now uses and exposes SimpleWaitQueue, WaitNode, and select integration points instead of per-channel Mutex/Condition.
Tests
test/sync/broadcast_channel.zig
Updated tests to new signatures; added coverage for asyncReceive/select flow, immediate-ready receives, lag detection, close semantics, and multi-channel selects.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Pay extra attention to:
    • Race between fast-path receive and queued waiters.
    • Correctness of AsyncReceive single-shot semantics and asyncCancelWait races.
    • send/close wake semantics to avoid lost wakeups and ensure correct multi-waiter behavior.
    • Tests validating cancellation, lag reporting, and cross-channel select.

Possibly related PRs

Poem

A node waits where mutex used to lie,
Queues hum soft and sendings fly.
AsyncReceive raises one small hand,
Selects decide and tests stand grand.
Close whispers "done" — the waiters land. 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The PR title "Refactor BroadcastChannel to use sync primitives and add AsyncReceive support" directly and accurately describes the main changes in the changeset. The raw summary confirms two major refactoring efforts: replacing async Mutex/Condition primitives with synchronous ones (std.Thread.Mutex and SimpleWaitQueue), and introducing AsyncReceive support for select integration. The title is specific, concise, and avoids vague terms—a developer scanning commit history would immediately understand the primary modifications to the BroadcastChannel implementation.
Description Check ✅ Passed The PR description is directly related to the changeset and provides concrete details about the refactoring. It clearly outlines Phase 1 changes (replacing async primitives, removing Runtime parameters from method signatures) and Phase 2 changes (implementing AsyncReceive), matches the raw summary accurately, and includes specific test coverage metrics (146 tests passing, 5 new async tests). The description avoids generic language and gives exact technical details about what changed and why, making it a solid companion to the actual code modifications.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch broadcast-channel-async-receive

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c5090dc and 7a4cff4.

📒 Files selected for processing (1)
  • src/sync/broadcast_channel.zig (18 hunks)
🔇 Additional comments (14)
src/sync/broadcast_channel.zig (14)

1-115: LGTM - Clean refactoring to sync primitives

The import changes and structural updates correctly replace async primitives with sync ones. The updated documentation examples accurately reflect the new API signatures without runtime parameters.


123-144: LGTM - Runtime parameter correctly removed

The signature changes align with PR objectives. The debug assertions at lines 127-128 and 139-141 provide good protection against common mistakes.


156-214: LGTM - Solid cancellation handling with wrapping arithmetic

The executor.yield() pattern with cancellation support is well-implemented. The wrapping arithmetic (lines 165, 174, 176) correctly handles position counter overflow. The cancellation logic at lines 193-210 properly handles the case where a sender has already removed the wait node, ensuring the message gets consumed by waking another consumer.


223-248: LGTM - Consistent wrapping arithmetic

The runtime parameter removal is correct. Wrapping arithmetic usage matches receive() for consistent overflow handling.


257-293: LGTM - Efficient direct wakeup pattern

The simplified signatures and direct wait queue manipulation are cleaner than the async approach. Wrapping arithmetic at line 266 maintains overflow safety.


295-316: LGTM - Clear documentation and straightforward factory

The documentation effectively explains the single-shot nature and provides a clear usage example. The factory method is simple and correct.


335-360: LGTM - Well-structured future protocol implementation

The AsyncReceive structure correctly implements the future protocol with proper VTable setup and initialization.


361-399: LGTM - Race condition correctly fixed

The parent_wait_node is properly captured and disarmed under the channel lock (lines 369-370) before unlocking and waking. This prevents the UAF race condition identified in past reviews. The wrapping arithmetic at line 373 correctly handles counter overflow.


403-439: LGTM - Fast paths and slow path correctly implemented

The asyncWait implementation correctly handles all cases:

  • Fast path detection (data available, lagged, or closed) with immediate result
  • Slow path with proper enqueueing for future wake
  • Consistent wrapping arithmetic throughout (lines 409, 413, 422)

Setting parent_wait_node at line 404 before locking is safe because waitNodeWake only runs if we enqueue (slow path).


441-466: LGTM - Cancellation race correctly handled

The defensive check at lines 448-451 properly addresses the past review concern about assertion failures. The logic correctly handles two scenarios:

  1. Still in queue: remove and done (no message available)
  2. Already removed by sender: wake another consumer (message available but we're cancelled)

The parent_wait_node clearing under lock prevents late wakes after cancellation.


468-473: LGTM - Simple result accessor

Straightforward implementation. The forced unwrap (.?) is safe given the documented usage constraints.


476-876: LGTM - Existing tests properly updated

All existing tests have been correctly updated to use the new signatures. The pattern of marking unused runtime parameters (e.g., line 625, 739, 861) keeps the code clean.


878-1069: LGTM - Comprehensive async test coverage

The new tests thoroughly cover:

  • Blocking receive with late sender (lines 878-917)
  • Fast path when data is already available (lines 919-948)
  • Error cases: closed channel (lines 950-978) and lagged consumer (lines 980-1014)
  • Multi-channel select scenarios (lines 1016-1069)

This provides solid confidence in the AsyncReceive implementation.


1071-1146: LGTM - Excellent overflow coverage

This test is particularly valuable as it verifies that the wrapping arithmetic correctly handles counter overflow in all scenarios:

  • Normal send/receive operations across the wrap boundary (lines 1096-1125)
  • Lag detection with wrapped counters (lines 1128-1140)

This provides confidence that long-running channels won't encounter arithmetic bugs.


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

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

123-129: Guard against double-subscribe/unsubscribe misuse with debug asserts

Easy win: catch list corruption early. Add assertions under the lock.

Apply this diff:

 pub fn subscribe(self: *Self, consumer: *Consumer) void {
   self.mutex.lock();
   defer self.mutex.unlock();
+  // Prevent double-subscribe of the same Consumer in debug builds.
+  std.debug.assert(consumer.prev == null and consumer.next == null);

   consumer.read_pos = self.write_pos;
   self.consumers.append(consumer);
 }

 pub fn unsubscribe(self: *Self, consumer: *Consumer) void {
   self.mutex.lock();
   defer self.mutex.unlock();
+  // Unsubscribing only makes sense if the consumer is currently linked.
+  std.debug.assert(consumer.prev != null or consumer.next != null or self.consumers.first == consumer);

   self.consumers.remove(consumer);
 }

Also applies to: 131-137


184-201: Cancel path mirrors asyncCancelWait — good; one nit

Logic wakes a replacement waiter only when remove() failed (already dequeued). That avoids stranding a message. Good. Consider adding a short comment explaining why we only wake another when not found to prevent over-wake when no message was published.


61-61: Counter width/overflow: consider u64 for positions

write_pos/read_pos are usize. On 32-bit or extremely long runs, wrap would break lag detection and indexing. Consider u64 for positions and cast at modulo sites, or use wrapping-diff helpers.

Also applies to: 74-77, 218-223, 232-235, 253-255

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9244233 and e2b5f78.

📒 Files selected for processing (1)
  • src/sync/broadcast_channel.zig (18 hunks)
🔇 Additional comments (4)
src/sync/broadcast_channel.zig (4)

256-263: Wake outside the lock — correct choice

Taking the waiters list under the lock and waking after unlock avoids lock inversion and thundering herd under contention. Nicely done.

Also applies to: 274-281


29-47: Docs example: confirm while/else pattern compiles with error unions

The listener sample uses while (ch.receive(...)) |value| { } else |err| { }. Zig typically uses this pattern with optionals; for error unions it’s usually a loop + switch. Please verify or tweak the snippet to a guaranteed-compiling variant.


214-236: tryReceive fast paths/read-modify under lock look solid

Lagged advancement, Closed vs WouldBlock split, and single-item read all occur under the mutex. Matches receive() semantics. Good.


847-1038: Select integration tests hit the key paths

You covered: blocking, already-ready, closed, lagged, and multi-channel select. Once parent disarming is fixed, these tests should also protect against regressions. Consider adding one test for canceling a losing arm (two recv ops where only one channel sends), to exercise asyncCancelWait disarm.

Comment thread src/sync/broadcast_channel.zig Resolved
Comment thread src/sync/broadcast_channel.zig Resolved
Fixed two race conditions with parent_wait_node access:

1. waitNodeWake: Read and clear parent_wait_node while holding the mutex
   before performing the receive operation. Previously, the parent pointer
   was accessed after releasing the mutex, which could lead to use-after-free
   if cancellation freed the parent concurrently, or spurious wakes if the
   parent was reused.

2. asyncCancelWait: Verify and clear parent_wait_node under lock before
   removing from the wait queue. This prevents a concurrent waitNodeWake
   from observing a stale parent pointer and waking it after cancellation.

Both fixes ensure the parent pointer is safely disarmed under the lock,
then the mutex is released before calling wake() to avoid holding the
lock during callbacks.

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

157-162: Minor note: Theoretical integer overflow in lag detection.

The lag check consumer.read_pos + self.buffer.len < self.write_pos could theoretically wrap on 32-bit systems after 2^32 sends, causing false positives. Not a practical concern for most use cases, but worth noting for safety-critical applications with extremely long-running channels.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e2b5f78 and 2dff26e.

📒 Files selected for processing (1)
  • src/sync/broadcast_channel.zig (18 hunks)
🔇 Additional comments (5)
src/sync/broadcast_channel.zig (5)

355-358: Critical issue from past review is now fixed.

The parent_wait_node is now correctly read and cleared while holding the channel mutex, preventing the race condition where cancellation could free/reuse the parent before wake(). The fix matches the suggested pattern from the previous review.


427-429: Critical issue from past review is now fixed.

The cancellation path now properly disarms parent_wait_node under lock with a debug assertion to verify correctness. This prevents late wakes of canceled select arms.


149-205: Solid refactoring of receive() with proper cancellation handling.

The yield pattern is implemented correctly: prepare state, enqueue, unlock, yield with allow_cancel, then handle cancellation by removing from queue (or waking next consumer if already removed). This matches the pattern used in asyncCancelWait and maintains broadcast semantics.


323-452: AsyncReceive implementation is clean and correct.

The future protocol is implemented properly:

  • Fast paths (lagged, ready message, closed) return false immediately with result set
  • Slow path enqueues and returns true
  • Cancellation properly removes from queue and wakes next consumer
  • The single-shot design is documented and enforced through usage patterns

The disarming of parent_wait_node under lock in both waitNodeWake and asyncCancelWait prevents all the race conditions flagged in previous reviews.


856-1047: Test coverage is comprehensive.

The five new tests cover all the important cases: blocking receive with select, fast path (already ready), closed channel handling, lagged consumer detection, and multi-channel select. The tests validate both the happy path and error conditions.

Added assertions in subscribe() and unsubscribe() to catch list corruption
early:

- subscribe(): Assert that the consumer is not already in the list (both
  prev and next are null). This catches double-subscribe bugs.

- unsubscribe(): Assert that the consumer is actually in the list (has
  prev/next links or is first/last). This catches double-unsubscribe or
  unsubscribe-without-subscribe bugs.

These assertions help catch misuse during development before it can corrupt
the intrusive linked list structure.

@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

🧹 Nitpick comments (1)
src/sync/broadcast_channel.zig (1)

395-428: asyncWait implementation is functionally correct.

The fast path checks (lagged, data available, closed) properly return false with result set, while the slow path enqueues and returns true. Setting parent_wait_node at line 396 before acquiring the lock is safe since we don't enter the queue until line 425, but it leaves parent_wait_node set on fast path returns. This is harmless given the single-shot usage guarantee, though clearing it on fast path exits would be slightly cleaner.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2dff26e and 796083e.

📒 Files selected for processing (1)
  • src/sync/broadcast_channel.zig (18 hunks)
🔇 Additional comments (10)
src/sync/broadcast_channel.zig (10)

8-57: Documentation accurately reflects the refactored API.

The example code correctly shows the new signatures - subscribe/unsubscribe without runtime parameters, while receive still requires runtime for blocking operations. The mixed usage pattern is clear and accurate.


123-144: Signature changes and mutex usage look correct.

The removal of the Runtime parameter and direct use of std.Thread.Mutex is consistent with the stated goal. The debug assertions provide good protection against misuse (double-subscribe, unsubscribe of non-subscribed consumer).


156-212: Refactored receive() with proper cancellation support.

The executor.yield pattern with explicit cancellation handling is well-implemented. The logic correctly handles the case where we're removed from the queue by a sender during cancellation (lines 195-203), ensuring another consumer gets the message. The loop structure properly rechecks conditions after yielding.


221-288: API changes and wait queue integration look correct.

The removal of Runtime parameters and direct use of wait_queue.popAll() for waking waiters is properly implemented. Waking happens outside the lock (lines 267-269, 285-287), which avoids potential deadlocks or long lock hold times.


290-311: Factory method and documentation are clear.

The asyncReceive() factory and its documentation properly explain the single-shot nature of AsyncReceive operations and provide a good usage example.


330-354: AsyncReceive type structure is sound.

The type properly implements the WaitNode protocol with appropriate fields for tracking the channel, consumer, and parent wait node. The optional parent_wait_node field correctly reflects that it's only set during active wait operations.


356-391: Past review concern properly addressed.

The parent_wait_node is now read and cleared under lock (lines 364-365) before performing the receive operation and unlocking. This correctly prevents the race where cancellation could free or reuse the parent wait node. The wake happens after releasing the lock, avoiding lock-held callbacks.


453-457: getResult() implementation is correct.

Simply unwrapping the result that was set by asyncWait's fast path or waitNodeWake's wake path.


461-861: Existing tests properly updated for new API signatures.

All test code correctly reflects the signature changes - subscribe, unsubscribe, send, and close no longer take runtime parameters. The test logic remains sound and validates the refactored implementation.


863-1054: Comprehensive test coverage for async receive functionality.

The five new tests validate all critical aspects of asyncReceive with select:

  • Blocking wait and wake (lines 863-902)
  • Fast path for already-available data (lines 904-933)
  • Closed channel error propagation (lines 935-963)
  • Lagged consumer detection (lines 965-999)
  • Multi-channel select arbitration (lines 1001-1054)

This covers both happy paths and error conditions, ensuring the select integration is robust.

Comment thread src/sync/broadcast_channel.zig Resolved
Changed all position counter arithmetic to use wrapping operators to
correctly handle overflow on 32-bit systems and long-running channels:

- Changed comparisons to use wrapping subtraction: `write_pos -% read_pos`
  gives the unread message count, which works correctly across overflow
- Changed increments to use wrapping addition: `pos +%= 1`
- Replaced direct comparisons like `read_pos < write_pos` with distance
  checks like `unread > 0`
- Replaced lag detection `read_pos + buffer.len < write_pos` with
  `unread > buffer.len`

Added comprehensive overflow test that simulates counter wrap-around by
setting positions near usize max, then verifies:
- Normal receive operations work across overflow boundary
- Lag detection works correctly with wrapped counters
- Messages are correctly retrieved after overflow

This ensures correct behavior even when counters wrap around. On 32-bit
systems with usize counters, overflow occurs after ~4.3B messages, which
can happen in under 2 hours at 1M msg/sec. With wrapping arithmetic, the
implementation remains correct indefinitely.
Changed asyncCancelWait to defensively check parent_wait_node instead of
unconditionally asserting. The previous assertion could fail if waitNodeWake
cleared parent_wait_node before asyncCancelWait acquired the mutex.

New logic:
- If parent_wait_node is null: waitNodeWake already cleared it (race we're
  defending against), proceed without error
- If parent_wait_node equals wait_node: normal case, clear it
- If parent_wait_node is something else: assert fails (programming error -
  wrong wait_node passed to asyncCancelWait)

This properly handles the race while still catching misuse.
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