maauto: move GAL socket writes onto a single IO thread
- Commit
839c5fcd0f4f2300d56c157e8bf40fe5fce8821f- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-13 00:19 UTC (2 months ago)
- Parents
da93b93
Diff
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.ktindex 62efa0812f..f81b3c9d01 100644--- a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/GalConnection.kt@@ -1,10 +1,18 @@ package com.vayunmathur.auto.protocol import java.io.Closeable+import java.util.concurrent.ExecutionException+import java.util.concurrent.ExecutorService+import java.util.concurrent.Executors+import java.util.concurrent.RejectedExecutionException+import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.locks.ReentrantLock import javax.net.ssl.SSLContext import kotlin.concurrent.withLock +/** Name of [GalConnection]'s single I/O thread; asserted by the IoThread tests. */+internal const val GAL_IO_THREAD_NAME = "ma-auto-gal-io"+ /** A message on a service channel, handed to whatever owns that service. */ fun interface ChannelMessageHandler { fun onMessage(message: ChannelMessage)@@ -28,11 +36,16 @@ fun isChannelControlMessage(type: Int): Boolean = when (type) { * Ties a [GalTransport] to the control session. * * Owns the single [javax.net.ssl.SSLEngine] for the connection. The engine is not- * thread-safe, so every wrap and unwrap happens under [engineLock] -- one lock, many- * threads. The pump thread reads and processes; the vsync encoder thread, the audio- * sinks and input injection only ever call [send], which enqueues and flushes under- * the same lock. Callers drive [pump] rather than it spawning threads, which keeps- * the whole thing testable over an in-memory transport.+ * thread-safe, so every wrap and unwrap happens on one dedicated I/O thread+ * ([GAL_IO_THREAD_NAME]) -- one thread, many senders. Every [SSLEngine] op and every+ * socket write runs there, including the ones triggered from the Choreographer+ * vsync drain, the audio sinks and input injection: [send] only enqueues into+ * [ChannelSendQueue] (synchronized, never blocks) and hands the drain to the I/O+ * thread, so a sender never touches the network itself. That keeps socket I/O off+ * the main thread (a first video frame sent out of a vsync callback used to die+ * with NetworkOnMainThreadException and take the whole process with it), while the+ * queue's control-first drain order is unchanged. Callers drive [pump] rather than+ * it spawning threads, which keeps the whole thing testable over an in-memory transport. * * Outbound traffic goes through per-channel queues ([ChannelSendQueue]): channel 0 * always drains first and service channels round-robin, so a video burst never@@ -66,10 +79,28 @@ class GalConnection( /** * The single-engine discipline: every [SSLEngine] wrap/unwrap on this connection- * holds this lock. Reentrant, so [pump] can answer (which [send]s) while holding it.+ * runs on the single [io] thread below. The lock guards the rare synchronous+ * entry when already on that thread (see [runOnIo]), plus the plain-JVM queue+ * tests that drive [flushSends] with no thread of their own. Reentrant, so+ * [pump] can answer (which [send]s) while holding it. */ private val engineLock = ReentrantLock() + /**+ * The only thread that touches the [SSLEngine] or the socket. Single-threaded,+ * so wraps, unwraps and writes serialize in submission order behind one queue+ * into [sendQueue]: submitting a whole drain (or a whole pump processing+ * step) as one task keeps each flush an ordered unit, exactly as the old+ * lock-held drain did. Daemon, so a leaked connection can never pin the+ * process open.+ */+ private val io: ExecutorService = Executors.newSingleThreadExecutor { runnable ->+ Thread(runnable, GAL_IO_THREAD_NAME).apply { isDaemon = true }+ }++ /** Set once [close] parks the I/O thread; late sends are dropped, never run. */+ private val closed = AtomicBoolean(false)+ /** Per-channel outbound queues; see the class KDoc for the drain order. */ private val sendQueue = ChannelSendQueue() @@ -77,11 +108,46 @@ class GalConnection( private val buffer = ByteArray(READ_BUFFER_SIZE) + /**+ * Runs [block] on the single I/O thread, waiting for it.+ *+ * Already there (a reply triggered inside [pump]'s own processing, or a nested+ * flush) it runs inline under [engineLock]: re-entering the executor queue from+ * the I/O thread would self-deadlock waiting on itself. Everywhere else the+ * caller blocks until its drain completes, so submission order is wire order+ * and the sequential channel-open / reply semantics are unchanged.+ *+ * A send racing [close] is dropped with a trace instead of running on a parked+ * thread or throwing [RejectedExecutionException] at the caller.+ */+ private fun runOnIo(block: () -> Unit) {+ if (Thread.currentThread().name == GAL_IO_THREAD_NAME) {+ engineLock.withLock { block() }+ return+ }+ if (closed.get()) {+ trace("drop send after close")+ return+ }+ try {+ io.submit(block).get()+ } catch (e: ExecutionException) {+ throw e.cause ?: e+ } catch (e: RejectedExecutionException) {+ trace("drop send after close")+ } catch (e: InterruptedException) {+ Thread.currentThread().interrupt()+ trace("send interrupted")+ }+ }+ /** * Reads once, handles whatever that produced, then drains the send queue. *- * The blocking read holds no lock; everything engine-touching (unwrap in- * [FrameReader], wrap in [flushSends]) runs under [engineLock].+ * The blocking read holds no lock and runs on the caller's (pump) thread --+ * parking the I/O thread in a read would wedge every send behind it.+ * Everything engine-touching (unwrap in [FrameReader], wrap in+ * [flushSendsLocked]) runs on the single I/O thread instead (see [runOnIo]). * * @return false at end of stream, when the head unit has gone away. */@@ -89,7 +155,9 @@ class GalConnection( val count = transport.read(buffer, 0, buffer.size) if (count < 0) return false - engineLock.withLock {+ // Processing answers and flushes as one task keeps replies and other+ // threads' queued sends in a single ordered drain, exactly as before.+ runOnIo { for (message in reader.offer(buffer, 0, count)) { val decoded = MessageCodec.decode(message.channelId, message.payload) // Channel-open traffic (0x7 out / 0x8 in) rides the TARGET channel,@@ -136,8 +204,9 @@ class GalConnection( } /**- * Enqueues a control message and flushes. Thread-safe: safe from the vsync- * encoder thread, audio sinks and input injection alike.+ * Enqueues a control message and flushes it from the I/O thread. Thread-safe+ * from anywhere, including the main thread: the enqueue never blocks and the+ * socket write runs on [GAL_IO_THREAD_NAME], never on the caller. */ fun send(message: OutboundMessage) { enqueue(message)@@ -145,8 +214,9 @@ class GalConnection( } /**- * Enqueues a service-channel message and flushes. Always encrypted, never- * CONTROL-flagged. Thread-safe; see [send].+ * Enqueues a service-channel message and flushes it from the I/O thread.+ * Always encrypted, never CONTROL-flagged. Thread-safe from anywhere, main+ * thread included; see [send]. * * `jbe.i()` builds flags as `FIRST | LAST | (Lizm.f ? 0x04 : 0) | * (Lizm.h ? 0x08 : 0)`, and every service-channel send goes through@@ -196,10 +266,12 @@ class GalConnection( } /**- * Writes everything queued, control-first. Thread-safe; holds [engineLock]- * across the drain so a burst goes out as one ordered unit.+ * Writes everything queued, control-first, on the single I/O thread.+ * Thread-safe from anywhere, main thread included; the caller waits for its+ * own drain, so ordering matches the old immediate write. Holds [engineLock]+ * across the inline drain so a burst goes out as one ordered unit. */- fun flushSends() = engineLock.withLock { flushSendsLocked() }+ fun flushSends() = runOnIo { engineLock.withLock { flushSendsLocked() } } /** Sends still queued, across all channels. Telemetry and tests. */ fun pendingSends(): Int = sendQueue.pendingCount()@@ -226,7 +298,18 @@ class GalConnection( transport.flush() } - override fun close() = transport.close()+ override fun close() {+ // First mark closed so late sends drop instead of racing the shutdown,+ // then park the I/O thread. The socket close unblocks a pump read, and+ // queued-but-unsent frames are dropped: a new socket starts clean.+ if (!closed.compareAndSet(false, true)) {+ runCatching { transport.close() }+ return+ }+ io.shutdownNow()+ sendQueue.clear()+ transport.close()+ } private companion object { const val CONTROL_CHANNEL = 0
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionIoThreadTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionIoThreadTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionIoThreadTest.ktnew file mode 100644index 0000000000..3fa223d651--- /dev/null+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/GalConnectionIoThreadTest.kt@@ -0,0 +1,174 @@+package com.vayunmathur.auto.protocol++import java.io.ByteArrayOutputStream+import java.nio.ByteBuffer+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.assertTrue++/**+ * The I/O-thread contract behind the main-thread crash fix: every socket write+ * leaves the connection on `ma-auto-gal-io`, never on the caller's thread, while+ * the per-channel queue order (control first, then round-robin service channels,+ * FIFO within a channel) is unchanged.+ *+ * A Choreographer vsync callback used to drain the encoder synchronously into+ * [GalConnection.send], which wrote the socket on the main thread -- StrictMode+ * killed the process with NetworkOnMainThreadException on the first video frame.+ * Plaintext sends exercise the path without a TLS handshake.+ */+class GalConnectionIoThreadTest {++ /** Captures written bytes and the name of every thread that wrote. */+ private class FakeTransport : GalTransport {+ val written = ByteArrayOutputStream()+ val writers = mutableListOf<String>()++ override fun read(buffer: ByteArray, offset: Int, length: Int): Int = -1++ @Synchronized+ override fun write(bytes: ByteArray, offset: Int, length: Int) {+ writers += Thread.currentThread().name+ written.write(bytes, offset, length)+ }++ override fun flush() = Unit++ override fun close() = Unit+ }++ /** Splits the written bytes into frames via their 4-byte headers. */+ private fun framesOf(written: ByteArray): List<ByteArray> {+ val frames = mutableListOf<ByteArray>()+ var offset = 0+ while (offset < written.size) {+ val header = FrameHeader.readFrom(ByteBuffer.wrap(written, offset, written.size - offset))+ val frame = written.copyOfRange(offset, offset + header.size + header.payloadLength)+ frames += frame+ offset += frame.size+ }+ return frames+ }++ @Test+ fun `a send from a foreign thread writes on the IO thread`() {+ val transport = FakeTransport()+ val connection = GalConnection(transport, TestTls.context(), deviceModel = "Pixel 8")+ try {+ val caller = AtomicReference("<unset>")+ val gate = CountDownLatch(1)+ val sender = Thread({+ caller.set(Thread.currentThread().name)+ gate.await(10, TimeUnit.SECONDS)+ connection.send(+ OutboundMessage(+ type = GalMessage.Control.PING_RESPONSE,+ payload = byteArrayOf(0x08, 0x01),+ encrypted = false,+ ),+ )+ }, "fake-main")+ sender.start()+ gate.countDown()+ sender.join(10_000)++ assertTrue(transport.written.size() > 0, "the ping response should have gone out")+ assertEquals(+ listOf(GAL_IO_THREAD_NAME),+ transport.writers.distinct(),+ "no socket write may run on the sender (${caller.get()})",+ )+ } finally {+ connection.close()+ }+ }++ @Test+ fun `control still jumps a queued video burst on the IO path`() {+ val transport = FakeTransport()+ val connection = GalConnection(transport, TestTls.context(), deviceModel = "Pixel 8")+ try {+ connection.enqueue(+ OutboundMessage(+ type = GalMessage.Media.DATA_WITH_TIMESTAMP,+ payload = ByteArray(64),+ encrypted = false,+ channelId = GalService.VIDEO_SINK.id,+ ),+ )+ connection.enqueue(+ OutboundMessage(+ type = GalMessage.Control.PING_RESPONSE,+ payload = byteArrayOf(0x08, 0x01),+ encrypted = false,+ ),+ )+ connection.flushSends()++ val channels = framesOf(transport.written.toByteArray()).map { it[0].toInt() and 0xFF }+ assertEquals(+ listOf(0, GalService.VIDEO_SINK.id),+ channels,+ "channel 0 first, even flushed from the IO thread",+ )+ assertEquals(+ listOf(GAL_IO_THREAD_NAME),+ transport.writers.distinct(),+ "every write on the IO thread",+ )+ } finally {+ connection.close()+ }+ }++ @Test+ fun `concurrent sends from many threads stay ordered per channel`() {+ val transport = FakeTransport()+ val connection = GalConnection(transport, TestTls.context(), deviceModel = "Pixel 8")+ try {+ val threads = (0 until 4).map { index ->+ Thread({+ repeat(10) { round ->+ connection.send(+ GalService.VIDEO_SINK.id,+ GalMessage.Media.DATA_WITH_TIMESTAMP,+ byteArrayOf(index.toByte(), round.toByte()),+ )+ }+ }, "sender-$index")+ }+ threads.forEach { it.start() }+ threads.forEach { it.join(10_000) }++ assertEquals(40, framesOf(transport.written.toByteArray()).size)+ assertEquals(+ listOf(GAL_IO_THREAD_NAME),+ transport.writers.distinct(),+ "every write on the IO thread, from every sender",+ )+ } finally {+ connection.close()+ }+ }++ @Test+ fun `a send after close is dropped, never thrown`() {+ val transport = FakeTransport()+ val connection = GalConnection(transport, TestTls.context(), deviceModel = "Pixel 8")+ connection.close()++ // Must not throw RejectedExecutionException at the caller.+ connection.send(+ OutboundMessage(+ type = GalMessage.Control.PING_RESPONSE,+ payload = byteArrayOf(0x08, 0x01),+ encrypted = false,+ ),+ )++ assertEquals(0, transport.written.size(), "nothing goes out after close")+ }+}
auto/src/main/java/com/vayunmathur/auto/platform/AudioSinkChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/AudioSinkChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/AudioSinkChannel.ktindex fcb50ad9c9..e6cf07999d 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/AudioSinkChannel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/AudioSinkChannel.kt@@ -25,9 +25,10 @@ import java.util.concurrent.atomic.AtomicInteger * Bring-up mirrors video's (`requestSetup` on the grant -> CONFIG answered * with a focus ask on control 0x18 -> START with the confirmed config), and * each sink's samples are written by its own audio thread -- never the pump- * thread, never the video vsync drain. The only thing shared with the pump- * is [GalConnection.send], which enqueues and flushes under the connection's- * engine lock (see `GalConnection`'s one-lock-many-threads discipline). The+ * thread, never the video vsync drain, never the main thread's socket: the only+ * thing shared with the pump is [GalConnection.send], which enqueues and hands+ * the flush to the connection's single I/O thread (see `GalConnection`'s+ * one-thread-many-senders discipline). The * sink's state is written on the audio thread and read off it only through * the atomic frame counter and the [AudioSinkStatus] snapshots, which hop to * the pump/main threads via the thread-safe `StateFlow` set in
auto/src/main/java/com/vayunmathur/auto/platform/MicSourceChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/MicSourceChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/MicSourceChannel.ktindex cd55fb906b..d6f9f79009 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/MicSourceChannel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/MicSourceChannel.kt@@ -23,8 +23,9 @@ import com.vayunmathur.auto.protocol.GalMessage * callback; a TTS/speak turn needs no buffer and only counts. * * All turn work lands on the mic's own thread -- never the pump thread --- * and the only thing shared with the pump is [GalConnection.send], which is- * thread-safe under the connection's engine lock.+ * and the only thing shared with the pump is [GalConnection.send], which+ * enqueues and hands the flush to the connection's single I/O thread+ * (thread-safe from anywhere, main thread included). */ class MicSourceChannel( private val connection: GalConnection,
auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.ktindex 4d22534c94..acfc17fb72 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/VideoSinkChannel.kt@@ -341,8 +341,9 @@ class VideoSinkChannel( /** * Pushes any encoded frames out. Called on the main thread at vsync cadence (see * [startVsyncDrain]), never from the connection's pump loop: the pump thread owns- * net/SSL while this owns media, and sends serialize under the connection's- * engine lock.+ * reads while the connection's single I/O thread owns net/SSL, and sends queue+ * there without blocking the caller -- so no socket write ever runs on this+ * (main) thread. * * Emits a drain observation per vsync so the phone UI can tell "encoder idle" * (drains with nothing ready) from "frames flowing" ([VideoEvent.FrameSent]).
auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.ktindex 7010f237cf..04481181cb 100644--- a/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt+++ b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt@@ -41,13 +41,14 @@ import kotlin.concurrent.thread * Runs a projection session for as long as a head unit is attached. * * Concurrency, by deliberate split: one [javax.net.ssl.SSLEngine] backs the- * connection and an engine is not thread-safe, so every wrap/unwrap holds the- * connection's engine lock -- one lock, many threads. The `ma-auto-projection`- * thread owns net/SSL (the [GalConnection.pump] loop below); the main thread owns- * media (the [VideoSinkChannel] vsync drain); audio sinks, mic, TTS and- * input injection only ever enqueue sends, which flush under the same lock.- * See `ProjectionService` + `CarDisplay` KDoc for the matching discipline on- * the UI side.+ * connection and an engine is not thread-safe, so every wrap/unwrap and every+ * socket write runs on the connection's single I/O thread -- one thread, many+ * senders. The `ma-auto-projection` thread owns reads (the [GalConnection.pump]+ * loop below); the main thread owns media (the [VideoSinkChannel] vsync drain);+ * audio sinks, mic, TTS and input injection only ever enqueue sends, which the+ * I/O thread flushes without blocking the caller -- so no socket write ever runs+ * on the main thread. See `ProjectionService` + `CarDisplay` KDoc for the+ * matching discipline on the UI side. */ class ProjectionService : Service() { @@ -221,6 +222,10 @@ class ProjectionService : Service() { // to runSession so the backoff loop sees the failure. Log.i(TAG, "head unit disconnected: ${connection.session.failure ?: "cleanly"}") AutoSessionState.onSessionEnd(connection.session.failure)+ // Park the connection's I/O thread first: closing the socket+ // unblocks the pump read, and late sends drop rather than racing+ // the shutdown. The socket `use` below closes the streams anyway.+ runCatching { connection.close() } video?.release() video = null messaging?.release()@@ -245,10 +250,11 @@ class ProjectionService : Service() { } /**- * The bring-up + streaming loop. Pump owns net/SSL only -- never the encoder:- * the sink drains itself on the main thread at vsync cadence (see- * VideoSinkChannel.startVsyncDrain). Channel opens go out sequentially in- * HU-discovery wire order, one in flight at a time; see [openNext].+ * The bring-up + streaming loop. Pump owns reads only -- never the encoder and+ * never socket writes: the sink drains itself on the main thread at vsync+ * cadence (see VideoSinkChannel.startVsyncDrain) and the connection's single+ * I/O thread owns every wrap/unwrap/write. Channel opens go out sequentially+ * in HU-discovery wire order, one in flight at a time; see [openNext]. */ private fun pumpUntilGone(connection: GalConnection) { var setupVideo = false