Modern Apps git

← Modern-Apps.git

cast: stop the retransmit buffer racing the feedback loop

Commit
99f63a037af27a85ccb8789597983889e34f1e8a
Author
vayun-mathur <[email protected]>
When
2026-08-23 15:59 UTC (3 months ago)
Parents
31eb367

Diff

cast/protocol/src/main/java/com/vayunmathur/cast/protocol/StreamingSession.kt
diff --git a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/StreamingSession.kt b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/StreamingSession.ktindex ac00d823b3..6c9202f855 100644--- a/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/StreamingSession.kt+++ b/cast/protocol/src/main/java/com/vayunmathur/cast/protocol/StreamingSession.kt@@ -9,9 +9,26 @@ package com.vayunmathur.cast.protocol  * Smaller than it used to be: OFFER/ANSWER negotiation lived here when the peer was a Cast receiver  * and had to be asked what it would accept. The handshake settles that now, so what is left is the  * one thing feedback is actually for - deciding what to resend.+ *+ * **Thread-safe, because its two entry points are called from different coroutines.** [record] runs on+ * the encoder loop as each frame is sent; [onFeedback] runs on the RTCP loop as each feedback packet+ * arrives. They both touch [retransmitBuffer], and `onFeedback` *iterates* it - so an insert landing+ * mid-iteration threw `ConcurrentModificationException` and took the whole cast process down.+ *+ * The lock is here rather than in `StreamSender`, which has one of its own: that lock is held for the+ * entire paced emission of a frame, which at 4K is hundreds of datagrams with deliberate pauses+ * between them. Widening it to cover feedback would stall the RTCP loop for milliseconds at exactly+ * the moment a receiver is asking for repairs. These critical sections are a few map operations each.+ *+ * That race was latent for as long as the sender only ever encoded 1080p. It became a crash within+ * seconds once 4K was on the wire, because a 4K frame is four times the packets to pace and a+ * struggling receiver answers with far more NACKs - so the two windows went from rarely overlapping to+ * overlapping constantly.  */ class StreamingSession { +    private val lock = Any()+     /**      * Frames we may still be asked to resend, newest last.      *@@ -22,7 +39,7 @@ class StreamingSession {     private val retransmitBuffer = LinkedHashMap<Long, EncryptedFrame>()      /** Remember a frame in case it has to be resent. */-    fun record(frame: EncryptedFrame) {+    fun record(frame: EncryptedFrame) = synchronized(lock) {         retransmitBuffer[frame.frameId.value] = frame         while (retransmitBuffer.size > RETRANSMIT_BUFFER_FRAMES) {             val oldest = retransmitBuffer.keys.first()@@ -38,7 +55,7 @@ class StreamingSession {      * for a key frame instead - which is the only thing that lets a receiver recover without the      * exact bytes it missed.      */-    fun onFeedback(feedback: ReceiverFeedback): Recovery {+    fun onFeedback(feedback: ReceiverFeedback): Recovery = synchronized(lock) {         retransmitBuffer.keys.removeAll { it <= feedback.checkpoint.value }         val resend = mutableListOf<Retransmission>()         var needKeyFrame = false@@ -57,7 +74,7 @@ class StreamingSession {                 Retransmission(frame, packetIds = listOf(nack.packetId))             }         }-        return Recovery(mergePacketIds(resend), needKeyFrame)+        Recovery(mergePacketIds(resend), needKeyFrame)     }      /** A single frame's worth of NACKs, coalesced. */
cast/protocol/src/test/java/com/vayunmathur/cast/protocol/StreamingSessionTest.kt
diff --git a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/StreamingSessionTest.kt b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/StreamingSessionTest.ktindex 29ed38d616..19a1086e2f 100644--- a/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/StreamingSessionTest.kt+++ b/cast/protocol/src/test/java/com/vayunmathur/cast/protocol/StreamingSessionTest.kt@@ -1,5 +1,8 @@ package com.vayunmathur.cast.protocol +import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicReference import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse@@ -127,4 +130,63 @@ class StreamingSessionTest {         )         assertTrue(assertNotNull(parsed).pictureLoss)     }++    @Test+    fun `recording and feedback from two threads does not blow up the sender`() {+        // **A regression test for a crash that took the whole cast process down.** `record` runs on the+        // encoder loop and `onFeedback` on the RTCP loop, and both touch the retransmit buffer while+        // `onFeedback` *iterates* it - so an insert landing mid-iteration threw+        // ConcurrentModificationException out of a coroutine with nothing to catch it.+        //+        // It stayed hidden for as long as the sender only encoded 1080p, and became a crash within+        // seconds of 4K going out: four times the packets per frame to pace, and a receiver that+        // answers a struggling link with far more NACKs, turned two rarely-overlapping windows into+        // constantly-overlapping ones.+        //+        // Inherently probabilistic, as any test of a data race is. Before the fix this did not merely+        // throw - the unsynchronised `LinkedHashMap` corrupted its own link list and `record` span+        // forever - so the threads are daemons and the joins are bounded: a regression has to fail this+        // test, not hang the build.+        val session = StreamingSession()+        val failure = AtomicReference<Throwable?>(null)+        val start = CountDownLatch(1)+        val rounds = 20_000++        val recorder = Thread {+            runCatching {+                start.await()+                for (id in 0L until rounds) session.record(frame(id))+            }.onFailure { failure.compareAndSet(null, it) }+        }.apply { isDaemon = true }+        val reporter = Thread {+            runCatching {+                start.await()+                for (id in 0L until rounds) {+                    // A checkpoint that trails the writer, plus a NACK ahead of it: the first makes+                    // `removeAll` iterate the buffer, the second makes it read from the same map.+                    session.onFeedback(+                        feedback(+                            checkpoint = (id - 30).coerceAtLeast(0),+                            nacks = listOf(PacketNack(FrameId(id), 0)),+                        ),+                    )+                }+            }.onFailure { failure.compareAndSet(null, it) }+        }.apply { isDaemon = true }++        recorder.start()+        reporter.start()+        start.countDown()+        recorder.join(TimeUnit.SECONDS.toMillis(20))+        reporter.join(TimeUnit.SECONDS.toMillis(20))+        assertFalse(recorder.isAlive, "the encoder side never finished - the buffer is wedged")+        assertFalse(reporter.isAlive, "the feedback side never finished - the buffer is wedged")+        assertNull(failure.get(), "concurrent access failed: ${failure.get()}")++        // And the buffer is still bounded and coherent afterwards, rather than merely un-thrown.+        assertTrue(+            session.onFeedback(feedback(checkpoint = 0)).retransmissions.isEmpty(),+            "a feedback packet with no nacks should ask for nothing",+        )+    } }