Skip to content
Merged
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
9 changes: 9 additions & 0 deletions .changeset/rpc-reject-pending-on-disconnect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"client-sdk-android": patch
---

`performRpc` now fails as soon as the room disconnects, rather than staying suspended until its response timeout.

Room cleanup reports every remote participant as disconnected, which already rejected calls addressed to a participant the room knew about. A call to an identity that never appeared in the participant list — an agent that has not joined yet, say — was in no such loop, so it stayed pending for the full `responseTimeout` after the room had gone. The caller's coroutine is now resumed with `RECIPIENT_DISCONNECTED` instead.

This matches the Rust SDK's `fail_all_pending` and the Swift SDK's `handleAllPendingDisconnected` (livekit/client-sdk-js#2251).
Original file line number Diff line number Diff line change
Expand Up @@ -1120,6 +1120,10 @@ constructor(
remoteParticipants.keys.toMutableSet() // copy keys to avoid concurrent modifications.
.forEach { sid -> handleParticipantDisconnect(sid) }

// The loop above only reaches calls addressed to a participant the room knows about.
// Sweep up anything else, so no caller is left waiting on a room that has gone.
localParticipant.failAllPendingRpcs()

sid = null
metadata = null
name = null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1319,6 +1319,10 @@ internal constructor(
rpcClientManager.handleParticipantDisconnect(identity)
}

internal fun failAllPendingRpcs() {
rpcClientManager.failAllPending()
}

/**
* @suppress
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,35 @@ class RpcClientManager @Inject constructor(
}
}

/**
* Rejects every in-flight call, whoever it was addressed to. Called when the room
* disconnects.
*
* Room cleanup already reports each remote participant as disconnected, which
* [handleParticipantDisconnect] turns into a rejection. That only covers calls addressed to
* a participant the room still knows about: a call to an identity that never appeared in the
* participant list -- an agent that has not joined yet, say -- is in neither loop, and would
* otherwise stay pending until its response timeout, long after the room has gone.
*
* No ack or response can arrive once the local participant has left, so there is nothing to
* wait for.
*/
fun failAllPending() {
// Resolve outside the locks: onResolve reaches back into pendingAcks.
val stranded = synchronized(pendingResponses) {
val responses = pendingResponses.values.toList()
pendingResponses.clear()
responses
}
synchronized(pendingAcks) {
pendingAcks.clear()
}
Comment on lines +340 to +347

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.

🟡 Disconnect can return a connection timeout

If an ack timer fires during failAllPending, an unacknowledged RPC can return CONNECTION_TIMEOUT after disconnect begins. The timer still sees its ack after the sweep removes its response.

Learn more

The RPC manager keeps separate maps for acknowledgments and responses. The ack timer removes an ack and completes the call with CONNECTION_TIMEOUT when it finds one. During failAllPending, the response map is cleared before the ack map, so the timer can win after the disconnect sweep has started. The later disconnect completion cannot replace the timeout error on the deferred result.

Example: An unacknowledged call has an ack deadline at 7 seconds. At that deadline, disconnect copies and clears its response; the timer then removes its ack and completes CONNECTION_TIMEOUT; the sweep's RECIPIENT_DISCONNECTED completion loses.

Recommended fix: Clear both maps under their locks in a consistent lock order before invoking any onResolve callbacks. Ensure the ack timer cannot observe an ack whose response was already taken by failAllPending.

Devin Review


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


for (response in stranded) {
response.onResolve(null, RpcError.BuiltinRpcError.RECIPIENT_DISCONNECTED.create())
}
}

private data class PendingRpcAck(
val participantIdentity: Identity,
val onResolve: () -> Unit,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2023-2025 LiveKit, Inc.
* Copyright 2023-2026 LiveKit, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -26,6 +26,7 @@ import io.livekit.android.test.mock.MockPeerConnection
import io.livekit.android.test.mock.TestData
import io.livekit.android.test.mock.TestData.REMOTE_PARTICIPANT
import io.livekit.android.test.util.toDataChannelBuffer
import io.livekit.android.util.toOkioByteString
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
Expand All @@ -38,6 +39,7 @@ import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes

@ExperimentalCoroutinesApi
@RunWith(RobolectricTestRunner::class)
Expand Down Expand Up @@ -414,4 +416,80 @@ class RpcMockE2ETest : MockE2ETest() {
)
assertTrue(methodCalled)
}

/**
* A call to a participant the room knows about is already covered: room cleanup reports
* every remote participant as disconnected. This guards that path.
*/
@Test
fun disconnectRejectsPendingRpcToAKnownParticipant() = runTest {
connect()
wsFactory.listener.onMessage(wsFactory.ws, TestData.PARTICIPANT_JOIN.toOkioByteString())
val destination = Participant.Identity(REMOTE_PARTICIPANT.identity)
assertTrue(
"this test is only meaningful while the destination is a known participant",
room.remoteParticipants.containsKey(destination),
)

val rpcJob = async { performRpcCatchingError(destination) }
subDataChannel.simulateBufferReceived(createAck(sentRequestId()))

room.disconnect()

coroutineRule.dispatcher.scheduler.advanceUntilIdle()
assertEquals(
RpcError.BuiltinRpcError.RECIPIENT_DISCONNECTED.code,
(rpcJob.await() as RpcError).code,
)
}

/**
* A call to an identity that never appeared in the participant list -- an agent that has
* not joined yet, say -- is in no participant loop, so room cleanup never reached it.
*
* The ack here is what makes this the damaging case: it cancels the round-trip timer, so
* before the sweep in `cleanupRoom` nothing failed the call until `responseTimeout`, which
* defaults to minutes. Without it the caller only waited out `maxRoundTripLatency` and got
* the misleading `CONNECTION_TIMEOUT`.
*/
@Test
fun disconnectRejectsAnAckedRpcToAnIdentityTheRoomNeverSaw() = runTest {
connect()
val destination = Participant.Identity("never-joined")
assertFalse(
"this test is only meaningful while the destination is unknown to the room",
room.remoteParticipants.containsKey(destination),
)

val rpcJob = async { performRpcCatchingError(destination) }
subDataChannel.simulateBufferReceived(createAck(sentRequestId()))

room.disconnect()

coroutineRule.dispatcher.scheduler.advanceUntilIdle()
assertEquals(
RpcError.BuiltinRpcError.RECIPIENT_DISCONNECTED.code,
(rpcJob.await() as RpcError).code,
)
}

/** The id of the only RPC request published so far. */
private fun sentRequestId(): String {
val buffers = pubDataChannel.sentBuffers
assertEquals(1, buffers.size)
return LivekitModels.DataPacket.parseFrom(ByteString.copyFrom(buffers[0].data)).rpcRequest.id
}

private suspend fun performRpcCatchingError(destination: Participant.Identity): Exception? =
try {
room.localParticipant.performRpc(
destinationIdentity = destination,
method = "hello",
payload = "hello world",
responseTimeout = 5.minutes,
)
null
} catch (e: Exception) {
e
}
}
Loading