Skip to content

Add BroadcastChannel synchronization primitive - #38

Merged
lalinsky merged 3 commits into
mainfrom
broadcast-channel
Oct 9, 2025
Merged

lalinsky merged 3 commits into
mainfrom
broadcast-channel

Conversation

@lalinsky

@lalinsky lalinsky commented Oct 9, 2025 •

Copy link
Copy Markdown
Owner

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

  • Non-blocking producers: send() never blocks, overwriting oldest values when the buffer is full
  • Dynamic subscription: Consumers can subscribe/unsubscribe at any time using an intrusive linked list (zero allocations)
  • Lag detection: Slow consumers automatically receive error.Lagged when they fall more than buffer.len behind, then skip to the oldest available message
  • Closeable: Channel can be closed to prevent new sends while allowing consumers to drain remaining messages
  • Ring buffer: Efficient fixed-capacity implementation with monotonic write position tracking

API

var buffer: [10]Message = undefined;
var channel = BroadcastChannel(Message).init(&buffer);

// Producer
try channel.send(runtime, message);
channel.close(runtime);

// Consumer
var consumer = BroadcastChannel(Message).Consumer{};
channel.subscribe(runtime, &consumer);
defer channel.unsubscribe(runtime, &consumer);

while (true) {
    const msg = channel.receive(runtime, &consumer) catch |err| switch (err) {
        error.Lagged => continue, // Skip and get next available
        error.Closed => break,
        else => return err,
    };
    // Process message
}

Testing

Comprehensive test coverage includes:

  • Basic send/receive operations
  • Multiple consumers receiving same messages
  • Lag detection and recovery
  • Non-blocking tryReceive()
  • New subscriber positioning
  • Unsubscribe isolation
  • Close semantics (drain, wake waiters, prevent new sends)

All tests pass.

Summary by CodeRabbit

  • New Features

    • Adds a broadcast channel for fan-out messaging with a fixed-capacity ring buffer.
    • Supports multiple subscribers with per-consumer read positions and a Consumer handle for subscription management.
    • Exposes subscribe/unsubscribe, blocking receive, non-blocking tryReceive, send, and close APIs; handles overwrite/lag semantics and is single-runtime only.
  • Tests

    • Adds comprehensive tests for multi-consumer delivery, lag behavior, subscription/unsubscription, new-subscriber semantics, close/drain behavior, wake-on-close, and non-blocking receive on closed channels.

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

coderabbitai Bot commented Oct 9, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a public generic BroadcastChannel(comptime T: type) in src/sync.zig implementing a fixed-capacity ring buffer, per-consumer read cursors, subscription management, blocking and non-blocking send/receive APIs, close semantics, Consumer/ConsumerList types, tests, and a single-Runtime (non-thread-safe) restriction.

Changes

Cohort / File(s) Summary
BroadcastChannel API and internals
src/sync.zig
Adds pub fn BroadcastChannel(comptime T: type) type with pub fn init(buffer: []T), pub fn subscribe, pub fn unsubscribe, pub fn receive, pub fn tryReceive, pub fn send, and pub fn close. Implements fixed-capacity ring buffer, per-consumer read_pos, nested pub const Consumer and const ConsumerList with append/remove, internal Mutex/Condition usage, wake/lag/closed error semantics, and extensive tests covering multi-consumer delivery, lag, tryReceive, subscribe/unsubscribe, close/drain, and wake-on-close.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Poem

I thump a beat to send the news,
each ear a cursor, bright and true.
I hop, I broadcast, queues align—
miss a hop and you'll lag behind.
When burrow closes, hush — goodnight, queue. 🐇📡

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly states the primary change by indicating that a BroadcastChannel synchronization primitive is being added, which matches the core functionality implemented in the pull request.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ 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

📜 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 173f533 and c3f6093.

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

1220-1227: Excellent design and documentation!

The BroadcastChannel implementation follows a clear and well-documented design. The non-blocking producer semantics with lag detection is a solid approach for scenarios where producers must not be blocked by slow consumers.


1228-1238: LGTM!

The struct fields are well-chosen. The monotonically increasing write_pos simplifies lag detection logic compared to using wrapping indices.


1248-1277: LGTM!

The intrusive doubly-linked list implementation is correct and handles all edge cases properly (first/last node updates).


1286-1303: LGTM!

The subscription management correctly positions new consumers at the current write position, ensuring they don't receive past messages (as documented and tested).


1305-1340: Excellent lag handling with proper recheck!

The lag detection logic is correct:

  • consumer.read_pos + self.buffer.len < self.write_pos detects when consumer has missed messages
  • Repositioning to self.write_pos - self.buffer.len places consumer at the oldest available message

Importantly, Line 1325 rechecks lag after waking from wait, handling the case where the consumer was lapped while waiting.


1342-1368: LGTM!

The non-blocking tryReceive correctly implements the same lag detection semantics and returns appropriate errors for each state.


1370-1386: LGTM!

The send function correctly implements non-blocking semantics, always succeeding (unless closed) and overwriting old values when full. Using broadcast() ensures all waiting consumers are woken.


1388-1400: LGTM!

The close function implements proper shutdown semantics: prevents new sends, allows consumers to drain remaining messages, and wakes all waiting consumers.


1403-1805: Excellent test coverage with proper synchronization!

The 10 tests comprehensively validate all aspects of the BroadcastChannel:

  • Basic operations (send/receive, tryReceive)
  • Broadcast semantics (multiple consumers)
  • Lag detection and recovery
  • Subscription lifecycle
  • Close semantics (prevent sends, allow drain, wake waiters)

The use of ResetEvent for synchronization (Lines 1411, 1415, 1424, 1455, 1460, 1472, 1693, 1697, 1707, 1742, 1748, 1762) is excellent and addresses the PR comments about avoiding yield-based timing. This ensures tests are deterministic and won't hang.

Test 1447-1503 is particularly well-designed, using an atomic counter to coordinate 3 consumers before the sender starts.

Based on comments.


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

📥 Commits

Reviewing files that changed from the base of the PR and between 53c70e1 and deade93.

📒 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_pos to 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.

@lalinsky

lalinsky commented Oct 9, 2025

Copy link
Copy Markdown
Owner Author

@claude try to investigate why are the new tests hanging

@claude

claude Bot commented Oct 9, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Investigation: Test Hanging Issue ✅

I investigated and fixed the hanging tests in the BroadcastChannel implementation.

Todo List

  • Read the BroadcastChannel implementation in src/sync.zig
  • Analyze the code for potential deadlock issues
  • Identify the root cause
  • Fix the issue
  • Run tests to verify the fix
  • Commit and push changes

Root Cause & Fix

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

  1. "basic send and receive" (line 1403): No synchronization between sender and receiver
  2. "consumers can drain after close" (line 1675): Receiver explicitly called rt.yield() expecting sender to run first, but then subscribed after all messages were sent

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 rt.yield() at the start of sender functions to ensure receivers subscribe before any messages are sent.

Test Results

All BroadcastChannel tests now pass:

  • ✅ basic send and receive (0.64ms)
  • ✅ multiple consumers receive same messages (1.14ms)
  • ✅ lagged consumer (0.40ms)
  • ✅ tryReceive (0.41ms)
  • ✅ new subscriber doesn't receive old messages (0.40ms)
  • ✅ unsubscribe doesn't affect other consumers (0.41ms)
  • ✅ close prevents new sends (0.40ms)
  • ✅ consumers can drain after close (0.63ms)
  • ✅ waiting consumers wake on close (0.62ms)
  • ✅ tryReceive returns Closed when channel closed and empty (0.42ms)

Full test suite: 70 of 70 tests passed ✅

Changes committed and pushed to branch broadcast-channel.


Job Run • Branch: broadcast-channel

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]>
@lalinsky

lalinsky commented Oct 9, 2025

Copy link
Copy Markdown
Owner Author

@claude use ResetEvent for synchronization, not depending and hoping that yield will help

@claude

claude Bot commented Oct 9, 2025 •

Copy link
Copy Markdown

Claude finished @lalinsky's task —— View job


Refactoring Test Synchronization ✅

Successfully replaced rt.yield() synchronization with ResetEvent for more reliable test coordination.

Todo List

  • Read current BroadcastChannel implementation
  • Find ResetEvent usage examples in codebase
  • Identify tests using yield for synchronization
  • Refactor tests to use ResetEvent
  • Run tests to verify changes
  • Commit and push changes

Changes Made

Refactored 4 BroadcastChannel tests to use ResetEvent instead of rt.yield():

  1. "basic send and receive" (line 1403): Uses ResetEvent for sender to wait for receiver subscription
  2. "multiple consumers receive same messages" (line 1447): Uses ResetEvent + atomic counter to wait for all 3 consumers to subscribe
  3. "consumers can drain after close" (line 1678): Uses ResetEvent for sender to wait for receiver subscription
  4. "waiting consumers wake on close" (line 1734): Uses ResetEvent for closer to wait for waiter to be ready

All synchronization now follows the established pattern from tcp.zig tests: waiters call wait(), signalers call set(). This makes the tests more robust and deterministic by using explicit synchronization primitives rather than relying on yield timing.

Test Results

✅ All 70 tests pass, including all 10 BroadcastChannel tests.

Commit

Pushed to branch broadcast-channel:

  • Commit: c3f6093 - "Replace yield-based synchronization with ResetEvent in BroadcastChannel tests"

Job Run • Branch: broadcast-channel

…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]>
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