Repository navigation
Add BroadcastChannel synchronization primitive - #38
Conversation
Implements a non-blocking broadcast channel similar to Tokio's broadcast channel: - Fixed capacity ring buffer with monotonic write position - Multiple consumers can subscribe/unsubscribe dynamically - Producers never block, overwriting oldest values when full - Slow consumers receive error.Lagged and skip to oldest available message - Intrusive linked list for zero-allocation consumer tracking - Channel can be closed, preventing new sends while allowing drain API: - init(buffer) - initialize with ring buffer - subscribe(runtime, consumer) - add consumer at current position - unsubscribe(runtime, consumer) - remove consumer - send(runtime, item) - broadcast to all (returns error.Closed if closed) - receive(runtime, consumer) - blocking receive with error.Lagged/Closed - tryReceive(runtime, consumer) - non-blocking receive - close(runtime) - close channel Includes comprehensive tests for basic send/receive, multiple consumers, lag detection, subscription management, and close semantics.
WalkthroughAdds a public generic BroadcastChannel(comptime T: type) in Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Producer
participant Runtime
participant BroadcastChannel
participant ConsumerA
participant ConsumerB
rect rgba(230,240,255,0.5)
note over BroadcastChannel: init(buffer)
Producer->>BroadcastChannel: init(buffer)
end
rect rgba(235,255,235,0.5)
note over BroadcastChannel,ConsumerA: subscribe
ConsumerA->>BroadcastChannel: subscribe(Runtime, ConsumerA)
ConsumerB->>BroadcastChannel: subscribe(Runtime, ConsumerB)
end
rect rgba(255,245,230,0.5)
note over Producer,BroadcastChannel: send (broadcast)
Producer->>BroadcastChannel: send(Runtime, item)
BroadcastChannel-->>ConsumerA: wake if waiting
BroadcastChannel-->>ConsumerB: wake if waiting
end
rect rgba(245,245,255,0.5)
note over ConsumerA,BroadcastChannel: receive / tryReceive
ConsumerA->>BroadcastChannel: receive(Runtime, ConsumerA)
BroadcastChannel-->>ConsumerA: item or (Lagged/Closed)
ConsumerB->>BroadcastChannel: tryReceive(Runtime, ConsumerB)
BroadcastChannel-->>ConsumerB: item or (WouldBlock/Lagged/Closed)
end
rect rgba(255,235,235,0.5)
note over BroadcastChannel,Consumers: close & drain
Producer->>BroadcastChannel: close(Runtime)
BroadcastChannel-->>ConsumerA: wake with Closed when drained
BroadcastChannel-->>ConsumerB: wake with Closed when drained
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~30 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🔇 Additional comments (9)
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: 0
🧹 Nitpick comments (1)
src/sync.zig (1)
1279-1303: LGTM! Subscription management correctly implemented.The init() function appropriately validates buffer capacity, and subscribe() correctly positions new consumers at the current write_pos so they only receive future messages. The unsubscribe() operation properly removes consumers from the linked list.
Note: The documentation states consumers "must remain valid while subscribed" (line 1241), which is critical since the channel holds pointers. Consider adding a runtime assertion in debug builds to detect use-after-unsubscribe if a Consumer's pointers are non-null, though this is not strictly necessary given the documented contract.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/sync.zig(1 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). (3)
- GitHub Check: test (windows-latest)
- GitHub Check: test (macos-latest)
- GitHub Check: test (ubuntu-latest)
🔇 Additional comments (7)
src/sync.zig (7)
1220-1238: LGTM! Clear documentation and well-structured type definition.The documentation clearly explains the channel's behavior (non-blocking sends, lag detection, overwrite semantics) and appropriately warns about single-Runtime usage. The struct fields are logically organized with the ring buffer, consumer management, and synchronization primitives.
1240-1277: LGTM! Correct doubly-linked list implementation.The Consumer type with intrusive linked list pointers enables zero-allocation subscription management as described in the PR objectives. The ConsumerList append() and remove() methods correctly maintain the first/last pointers and prev/next links.
1309-1340: LGTM! Correct lag detection and recovery logic.The receive() method correctly implements:
- Lag detection using
consumer.read_pos + self.buffer.len < self.write_posto determine if the consumer has fallen more than buffer.len behind- Recovery by advancing to the oldest available message (
self.write_pos - self.buffer.len)- Rechecking for lag after waking from the condition variable (lines 1324-1328), which is essential for correctness when multiple sends occur while waiting
- Proper closed-channel semantics allowing consumers to drain remaining messages
1342-1368: LGTM! Non-blocking receive correctly implemented.The tryReceive() method properly mirrors receive()'s lag detection and recovery logic while returning error.WouldBlock when no new items are available, providing the expected non-blocking semantics.
1373-1386: LGTM! Non-blocking send with correct broadcast semantics.The send() method correctly implements the non-blocking producer behavior:
- Never waits, potentially overwriting old values (as documented)
- Uses ring buffer modulo arithmetic for wrapping
- Broadcasts to wake all waiting consumers (appropriate for multiple consumers)
- Returns error.Closed after channel closure
1391-1399: LGTM! Clean close semantics.The close() method correctly sets the closed flag and broadcasts to wake all waiting consumers so they can observe the channel closure and either drain remaining messages or receive error.Closed.
1403-1791: LGTM! Comprehensive test coverage.The test suite thoroughly validates all behaviors described in the PR objectives:
- Basic send/receive with blocking and non-blocking variants
- Multiple consumers receiving the same messages
- Lag detection (correctly tests that consumer.read_pos advances to oldest available after falling behind)
- Subscription positioning (new subscribers start at current write_pos)
- Unsubscribe isolation
- Close semantics (prevents new sends, allows draining, wakes waiters)
The tests follow the established patterns from other sync primitives in this file and provide good confidence in the implementation's correctness.
|
@claude try to investigate why are the new tests hanging |
|
Claude finished @lalinsky's task —— View job Investigation: Test Hanging Issue ✅I investigated and fixed the hanging tests in the BroadcastChannel implementation. Todo List
Root Cause & FixProblem: Race condition in task spawning order caused tests to hang indefinitely. When a consumer subscribes to a BroadcastChannel, it starts at the current write position (src/sync.zig:1293), meaning it only receives messages sent after subscription. This is by design (line 1287: "won't receive past messages"). Two tests had race conditions where senders could run before receivers subscribed:
In both cases, receivers would subscribe after messages were already sent, causing them to wait forever for messages that would never arrive (from their perspective). Solution: Added Test ResultsAll BroadcastChannel tests now pass:
Full test suite: 70 of 70 tests passed ✅ Changes committed and pushed to branch |
The tests were hanging due to race conditions in task spawning order. When a consumer subscribes, it starts at the current write position, so it only receives messages sent after subscription. Two tests had senders that could run before receivers subscribed: - 'basic send and receive': no synchronization - 'consumers can drain after close': receiver explicitly yielded first Fixed by adding rt.yield() at the start of sender functions to ensure receivers subscribe before any messages are sent. Co-authored-by: Lukáš Lalinský <[email protected]>
|
@claude use ResetEvent for synchronization, not depending and hoping that yield will help |
|
Claude finished @lalinsky's task —— View job Refactoring Test Synchronization ✅Successfully replaced Todo List
Changes MadeRefactored 4 BroadcastChannel tests to use ResetEvent instead of
All synchronization now follows the established pattern from tcp.zig tests: waiters call Test Results✅ All 70 tests pass, including all 10 BroadcastChannel tests. CommitPushed to branch
|
…el tests Use ResetEvent for explicit synchronization instead of relying on yield timing. This makes the tests more robust and deterministic. Changes: - basic send and receive: sender waits for receiver to subscribe - multiple consumers: sender waits for all 3 consumers to subscribe - consumers can drain after close: sender waits for receiver to subscribe - waiting consumers wake on close: closer waits for waiter to be ready Co-authored-by: Lukáš Lalinský <[email protected]>
Summary
Implements a non-blocking broadcast channel similar to Tokio's
broadcast::channel, allowing multiple consumers to each receive all broadcast messages with automatic handling of slow consumers.Features
send()never blocks, overwriting oldest values when the buffer is fullerror.Laggedwhen they fall more thanbuffer.lenbehind, then skip to the oldest available messageAPI
Testing
Comprehensive test coverage includes:
tryReceive()All tests pass.
Summary by CodeRabbit
New Features
Tests