Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/publisher-only-soft-reconnect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"client-sdk-android": patch
---

Let publishing participants complete a reconnect after publisher ICE recovers when the publisher is primary and the participant explicitly lacks subscribe permission.
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import livekit.org.webrtc.SessionDescription
* @param subscriberState connection state of [subscriber], as reported by its observer.
* @param subscriberPrimary the server's `subscriber_primary` flag from the join response.
* @param fastPublish the server's `fast_publish` flag from the join response.
* @param canSubscribe the local participant's current subscribe permission, or null before it is known.
*/
@Suppress("TooManyFunctions")
internal class DualPeerConnectionTransport(
Expand All @@ -51,6 +52,7 @@ internal class DualPeerConnectionTransport(
private val subscriberState: PeerConnectionStateObservable,
private val subscriberPrimary: Boolean,
private val fastPublish: Boolean,
private val canSubscribe: () -> Boolean? = { null },
) : Transport {
override val publisherConnectsOnDemand: Boolean
get() = subscriberPrimary
Expand Down Expand Up @@ -124,17 +126,21 @@ internal class DualPeerConnectionTransport(
if (includePublisher) {
launch { publisherState.waitUntilConnected() }
}
launch { subscriberState.waitUntilConnected() }
if (requiresSubscriber(includePublisher)) {
launch { subscriberState.waitUntilConnected() }
}
Comment on lines +129 to +131

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.

🔴 Premature rejoin after subscribe grant

If permission is granted during a publisher-only resume, waitUntilConnected still returns as soon as the publisher connects. isConnected then requires the subscriber. If subscriber ICE is still starting, the engine abandons the resume and starts a full rejoin.

Learn more

The subscriber is the connection that receives remote media. The soft reconnect path starts collecting signaling responses asynchronously through onReadyForResponses. A participant update can therefore change the local subscribe permission while the reconnect waits for ICE. The wait uses the permission at entry, but the final connection check uses it at completion. If these decisions disagree, the reconnect loop moves on to a full rejoin even though the ICE deadline has not expired. onFullReconnecting then tears down remote participant state.

Example: A publisher starts resuming with subscribe permission denied and an idle subscriber peer. A server update grants permission while publisher ICE is still recovering. The publisher connects first and the subscriber is still connecting. The resume fails immediately instead of waiting for the subscriber within the remaining ICE budget.

Recommended fix: Make reconnect readiness observe both permission and peer state until the existing ICE deadline. If the final check observes that the subscriber has just become required, continue waiting within that deadline instead of falling through to a full rejoin. Add a test that grants permission after the wait starts and connects the subscriber after the publisher.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I confirmed this race in the reconnect path. waitUntilConnected() decides whether to wait for the subscriber when it starts, while isConnected() reads the latest permission. If a grant arrives before publisher ICE connects, the final check can reject the resume while the subscriber is still connecting and there’s time left in the ICE timeout.

The fix should use one readiness check that observes permission and peer state within the existing ICE timeout. A regression test should grant subscribe permission after the wait starts, connect the publisher first, and verify that the resume completes only after the subscriber connects.

Unit
}

override suspend fun isConnected(includePublisher: Boolean): Boolean {
if (includePublisher) {
return publisher.isConnected() && subscriber.isConnected()
}
return subscriber.isConnected()
return (!includePublisher || publisher.isConnected()) &&
(!requiresSubscriber(includePublisher) || subscriber.isConnected())
}

// The SFU can leave the subscriber peer idle for a participant that is only allowed to publish.
private fun requiresSubscriber(includePublisher: Boolean): Boolean =
subscriberPrimary || !includePublisher || canSubscribe() != false

override suspend fun syncStateDescriptions(): Transport.SyncStateDescriptions {
var answer: LivekitRtc.SessionDescription? = null
var offer: LivekitRtc.SessionDescription? = null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,9 @@ internal constructor(
private var connectOptions: ConnectOptions? = null
private var lastRoomOptions: RoomOptions? = null
private var participantSid: String? = null

@Volatile
private var localCanSubscribe: Boolean? = null
private var localParticipantIdentity: String? = null

internal val serverVersion: Semver?
Expand Down Expand Up @@ -352,6 +355,7 @@ internal constructor(
if (joinResponse.hasParticipant()) {
localParticipantIdentity = joinResponse.participant.identity
}
localCanSubscribe = joinResponse.participant.takeIf { it.hasPermission() }?.permission?.canSubscribe
// Participants first, then the original join bytes (Swift order): UniFFI discovers
// tracks once publishers are registered, and re-encoding would drop newer fields.
listener?.onJoinResponse(joinResponse)
Expand Down Expand Up @@ -469,6 +473,7 @@ internal constructor(
subscriberObserver,
joinResponse.subscriberPrimary,
joinResponse.fastPublish,
canSubscribe = { localCanSubscribe },
)
}

Expand Down Expand Up @@ -576,6 +581,7 @@ internal constructor(
connectOptions = null
lastRoomOptions = null
participantSid = null
localCanSubscribe = null
localParticipantIdentity = null
regionUrlProvider = null
endSignalSession()
Expand Down Expand Up @@ -1399,6 +1405,9 @@ internal constructor(
}

override fun onParticipantUpdate(updates: List<LivekitModels.ParticipantInfo>, encoded: ByteArray) {
updates.firstOrNull { it.sid == participantSid && it.hasPermission() }?.let {
localCanSubscribe = it.permission.canSubscribe
}
listener?.onUpdateParticipants(updates)
val identity = localParticipantIdentity
if (identity != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import io.livekit.android.util.flowDelegate
import io.livekit.android.webrtc.toProtoSessionDescription
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
Expand Down Expand Up @@ -108,13 +109,15 @@ class DualPeerConnectionTransportTest {
private fun transport(
subscriberPrimary: Boolean = true,
fastPublish: Boolean = false,
canSubscribe: () -> Boolean? = { null },
) = DualPeerConnectionTransport(
publisher = publisher,
subscriber = subscriber,
publisherState = publisherState,
subscriberState = subscriberState,
subscriberPrimary = subscriberPrimary,
fastPublish = fastPublish,
canSubscribe = canSubscribe,
)

// region roles
Expand Down Expand Up @@ -530,6 +533,41 @@ class DualPeerConnectionTransportTest {
assertTrue(job.isCompleted)
}

@Test
fun publisherOnlyReconnectWaitsForPublisherAndIgnoresIdleSubscriber() = runTest {
val transport = transport(subscriberPrimary = false, canSubscribe = { false })
val job = launch { transport.waitUntilConnected(includePublisher = true) }
runCurrent()
assertFalse(job.isCompleted)
assertFalse(transport.isConnected(includePublisher = true))

publisherPc.moveToIceConnectionState(IceConnectionState.CONNECTED)
publisherState.connectionState = PeerConnectionState.CONNECTED
runCurrent()

assertTrue(job.isCompleted)
assertTrue(transport.isConnected(includePublisher = true))
}

@Test
fun subscriberWaitUsesCurrentPermissionAndAlwaysKeepsThePrimarySubscriber() = runTest {
var canSubscribe = false
val publisherPrimary = transport(subscriberPrimary = false, canSubscribe = { canSubscribe })
val subscriberPrimary = transport(subscriberPrimary = true, canSubscribe = { canSubscribe })
publisherPc.moveToIceConnectionState(IceConnectionState.CONNECTED)
publisherState.connectionState = PeerConnectionState.CONNECTED

assertTrue(publisherPrimary.isConnected(includePublisher = true))
assertFalse(subscriberPrimary.isConnected(includePublisher = true))

canSubscribe = true
assertFalse(publisherPrimary.isConnected(includePublisher = true))
val job = launch { publisherPrimary.waitUntilConnected(includePublisher = true) }
runCurrent()
assertFalse(job.isCompleted)
job.cancelAndJoin()
}

@Test
fun waitUntilConnectedWaitsForBothAtOnce() = runTest {
val transport = transport()
Expand Down