Repository navigation
Refactor BroadcastChannel to use sync primitives and add AsyncReceive support - #95
Conversation
… 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.
WalkthroughReplaces 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🔇 Additional comments (14)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
src/sync/broadcast_channel.zig (3)
123-129: Guard against double-subscribe/unsubscribe misuse with debug assertsEasy 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 nitLogic 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 positionswrite_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
📒 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 choiceTaking 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 unionsThe 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 solidLagged 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 pathsYou 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.
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.
There was a problem hiding this comment.
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_poscould 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
📒 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.
There was a problem hiding this comment.
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
📒 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.
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.
Summary
This PR refactors
BroadcastChannelto follow the same pattern asChannel, using synchronous primitives and direct wait queue management instead of async Mutex/Condition primitives. It also addsAsyncReceivesupport for use withselect().Changes
Phase 1: Refactor to use synchronous primitives
Mutexwithstd.Thread.MutexConditionwithSimpleWaitQueue(WaitNode)for direct wait managementreceive()to useexecutor.yield()pattern with proper cancellation supportRuntimeparameter fromsubscribe(),unsubscribe(),tryReceive(),send(),close()Phase 2: Add AsyncReceive support
AsyncReceive(T)type that implements the future protocolasyncReceive()method toBroadcastChannelerror.Lagged)Test Coverage
All 146 tests pass.
Benefits
Channelimplementation patternBroadcastChannelwithselect()for multiplexing