Skip to content

fix: attach server-opened data channels before didOpen returns - #1253

Closed
Moriquendi wants to merge 2 commits into
livekit:mainfrom
Moriquendi:fix/attach-server-data-channel-synchronously
Closed

Moriquendi wants to merge 2 commits into
livekit:mainfrom
Moriquendi:fix/attach-server-data-channel-synchronously

Conversation

@Moriquendi

Copy link
Copy Markdown

What this fixes

With two peer connections (singlePeerConnection: false), the first messages the server sends on a server-opened data channel can be dropped, with nothing logged.

Transport.peerConnection(_:didOpen:) hands the new channel to Room through MulticastDelegate.notify, which hops to a dispatch queue. Only after that hop does DataChannelDrain.setChannel set channel.delegate. WebRTC starts delivering the channel's messages as soon as didOpen returns, so a message that arrives before the hop runs goes to a nil delegate and is lost. Nothing reaches DataChannelPair, so no duplicate, decode or decrypt warning fires either.

The window is usually under a millisecond, but it grows whenever that queue is busy at join time. We measured 260 ms to 1 s on an iPad, and longer in production.

How it showed up

Our app talks to a LiveKit Agents worker. Right after join, the agent sends an RPC (mcp.initialize, v2 over lk.rpc_request) and a text-stream hello. In about 7% of production rooms the first RPC got no ack (RpcError('Connection timeout')) and only succeeded on the agent's retry, while the phone's own messages to the agent arrived fine. A text-stream message sent once in that window was never seen at all.

Repro and verification

We added logging of every reliable packet DataChannelPair receives (sender, sequence, kind) on an iPad (iPad14,3, iOS 27.2) on 2.19.0, connecting to LiveKit Cloud 1.13.11 with the default two peer connections. We ran 12 launches against a dev agent.

  • Before: in 5 of 11 runs with logs, the first agent packet the phone received was sequence 10, 11, 21 or 22, with no gaps after it. The agent's first 9–21 packets, including the first mcp.initialize request, never reached DataChannelPair. In those runs the server-opened _data_track / _lossy / _reliable channels reached Room 260 ms to 1 s apart. In clean runs they arrived in the same millisecond.
  • After this change: 11 of 11 runs received from sequence=1 with no gaps, and the first RPC was handled about 1 s after join in every run. In 5 of those runs the first agent packet arrived 0–2 ms after the channel opened, which is exactly the window that used to drop it.

The change

didOpen now notifies its delegates synchronously, through a new MulticastDelegate.notifySync, so the channel's delegate is in place before didOpen returns. Room.transport(_:didOpenDataChannel:) is safe to run on WebRTC's signaling thread:

  • It reads readyState, which is a BYPASS proxy call.
  • It takes StateSync locks.
  • It sets the channel's delegate.
  • It sends a displaced channel's release to parkChannelRelease.

None of these are blocking proxy calls back into WebRTC.

#1209 makes a single peer connection the default. In that mode the client creates its own data channels with their delegates already set, so this race no longer applies there. It still affects apps that opt out of single-PC, and servers that don't support it.

I haven't added a test. The race depends on when the server's first message lands relative to the delegate hop, and I don't see a way to control that deterministically with withRooms. I'm happy to add one if you can suggest a shape you'd accept.

🤖 Generated with Claude Code

With two peer connections, Transport.peerConnection(_:didOpen:) handed the
channel to Room through MulticastDelegate.notify, a dispatch-queue hop, so the
channel's delegate was set only after WebRTC had started delivering messages.
A message that arrived in that window went to a nil delegate and was lost.
Notify synchronously instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CLAassistant

CLAassistant commented Dec 2, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ pblazej
❌ Moriquendi
You have signed the CLA already but the status is still pending? Let us recheck it.

@devin-ai-integration devin-ai-integration 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.

🔍 Devin Review: 2 flags

Not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

The test holds the transport delegate queue in didUpdateState and requires that
didOpenDataChannel ran before peerConnection(_:didOpen:) returns.

Document the threading of MulticastDelegate.notifySync and of
TransportDelegate.transport(_:didOpenDataChannel:).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pblazej

pblazej commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Thanks for the clear report. We reproduced the loss on main against a local server with two peer connections and a busy delegate queue at join. This PR fixes it.

I pushed one commit on top of yours. It adds a regression test that needs no server (TransportDidOpenTests, which fails with notify and passes with notifySync). It also adds doc comments on notifySync and TransportDelegate.transport(_:didOpenDataChannel:) about the signaling thread and the queue order.

One correction to the description: the proxy skips readyState, but outside a data channel callback SctpDataChannel::state() blocks on the network thread. That adds latency but cannot deadlock.

pblazej added a commit to livekit/libwebrtc that referenced this pull request Dec 4, 2026
`RTCDataChannel` registers its native observer in its initializer, which
runs inside `peerConnection:didOpenDataChannel:`. The observer forwards
each message to the weak `delegate`, so a message that arrives before
the app sets the delegate is lost without a log. `SctpDataChannel`
already queues received data while no observer is registered, but the
early registration turns that queue off.

The LiveKit Swift SDK hit this with two peer connections. The server
opens the subscriber channels, and the SDK set the delegate after a
dispatch hop. When that queue was busy at join, the first messages from
the other participant never arrived (livekit/client-sdk-swift#1253).

## Change

The wrapper registers the native observer when the first non-nil
delegate is set, after it stores the delegate. The native channel then
delivers its queued messages in order, each to the delegate that is set
when the signaling thread delivers it. Registration happens once. The
delegate store and the decision to register happen under one lock, and
`RegisterObserver` runs outside it. A nil delegate set later keeps the
observer registered. `dealloc` unregisters only if the wrapper
registered.

This is how the Android wrapper works. Its `DataChannel` registers no
native observer until the app calls `registerObserver`
([DataChannel.java](https://github.com/livekit/libwebrtc/blob/7c1a802ab4e0d74f28ee997678346b3e753ef42a/sdk/android/api/org/webrtc/DataChannel.java#L113-L127),
[data_channel.cc](https://github.com/livekit/libwebrtc/blob/7c1a802ab4e0d74f28ee997678346b3e753ef42a/sdk/android/src/jni/pc/data_channel.cc#L106-L121)).
The LiveKit Android SDK attaches after a thread hop
([SubscriberTransportObserver.kt](https://github.com/livekit/client-sdk-android/blob/dfe51a69a3a08db8bf056bcd010f35778a0d3a6c/livekit-android-sdk/src/main/java/io/livekit/android/room/SubscriberTransportObserver.kt#L75-L79),
[RTCEngine.kt](https://github.com/livekit/client-sdk-android/blob/dfe51a69a3a08db8bf056bcd010f35778a0d3a6c/livekit-android-sdk/src/main/java/io/livekit/android/room/RTCEngine.kt#L431-L440))
and loses nothing.

## Differences from Android

- Registration happens in the `delegate` setter. The first non-nil
assignment blocks on the network thread, and on the signaling thread
when the caller is not on it. Android's `registerObserver` blocks in the
same way. The header says not to make that assignment on the network
thread, or while holding a lock that a signaling-thread task needs.
- A nil delegate after registration drops messages, as before. On
Android, a new `registerObserver` unregisters the old observer first
([DataChannel.java](https://github.com/livekit/libwebrtc/blob/7c1a802ab4e0d74f28ee997678346b3e753ef42a/sdk/android/api/org/webrtc/DataChannel.java#L114-L120)),
so messages in between wait in the native queue.
- The wrapper could do the same: unregister when the delegate is set to
nil, and register again for the next delegate. It does not, because
`UnregisterObserver` also blocks on the network and signaling threads.
Apps usually set the delegate to nil during teardown, so that assignment
would start to block teardown.
- The delegate stays weak. Android keeps its observer alive through a
JNI global reference
([data_channel.cc](https://github.com/livekit/libwebrtc/blob/7c1a802ab4e0d74f28ee997678346b3e753ef42a/sdk/android/src/jni/pc/data_channel.cc#L48)).
If the delegate is deallocated, later messages are dropped.
- A channel whose delegate is never set now queues messages up to 16
MiB, then closes with `RESOURCE_EXHAUSTED`. Before, the wrapper dropped
them. An Android channel without an observer does the same.

## Deadlocks

`RegisterObserver` bypasses the proxy and blocks
([sctp_data_channel.cc](https://github.com/livekit/libwebrtc/blob/7c1a802ab4e0d74f28ee997678346b3e753ef42a/pc/sctp_data_channel.cc#L330-L377)).
Off the signaling thread, it waits for the signaling thread to set up
the observer adapter. Off the network thread, it waits for the network
thread to store the observer and deliver the queued data. Before this
change, `init` made the same call, inside
`peerConnection:didOpenDataChannel:` or
`dataChannelForLabel:configuration:`. The change moves the call to the
thread that sets the delegate, and adds no new kind of wait.

The first non-nil assignment can deadlock in three cases:

- The wrapper lock. A second setter can run on the signaling thread, for
example inside `peerConnection:didOpenDataChannel:`. If the first setter
held `@synchronized(self)` while `RegisterObserver` waited for the
signaling thread, each would wait for the other. The setter releases the
lock before it calls `RegisterObserver`.
`testDelegateSetDuringRegistrationReceivesQueuedMessages` and
`testNilSetDuringRegistrationDropsQueuedMessages` hold the registration
open and set the delegate from a second thread. With the call moved
inside the lock, both tests time out after 30 s.
- The network thread. WebRTC does not let the network thread block on
the signaling thread, so the assignment must not run there. The header
says so.
- A lock that the caller holds. If a task on the signaling or network
thread needs that lock, the caller and the task wait for each other. The
header says so.

Delivery does not block. The network thread posts each queued message to
the signaling thread
([sctp_data_channel.cc](https://github.com/livekit/libwebrtc/blob/7c1a802ab4e0d74f28ee997678346b3e753ef42a/pc/sctp_data_channel.cc#L209-L218)),
and the wrapper calls the delegate there. On the signaling thread, the
signaling step runs inline and only the network step blocks. WebRTC
allows that direction, so it cannot form a cycle. `dealloc` calls
`UnregisterObserver`, which blocks in the same way as before, and now
skips it if the wrapper never registered.

The LiveKit Swift SDK sets the delegate after a hop from
`peerConnection:didOpenDataChannel:` to its own serial queue, with no
lock held. Neither the signaling thread nor the network thread waits on
that queue, so the blocking setter cannot form a cycle. While the setter
waits, later callbacks from the same peer connection wait behind it on
that queue. In the Swift repro, the hop was delayed by 1 s, the setter
took 0.10 to 0.17 ms, and 200 of 200 messages arrived in 5 of 5 runs.
292 data channel, data stream and RPC tests also passed with no hang.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@pblazej

pblazej commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Turns out it may be fixed directly in the WebRTC layer, so closing in favor of #1254

Let's keep an eye on this one! 👀

@pblazej pblazej closed this Dec 4, 2026
@pblazej

pblazej commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Also, enabling single PC by default may mitigate this.

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.

3 participants