Modern Apps git

← Modern-Apps.git

wearlink: snapshot conduit fan-out to stop ConcurrentModificationException

Commit
485171dde7d57cdae23c19ca16d297b901e83818
Author
Vayun Mathur <[email protected]>
When
2026-12-05 14:09 UTC (19 hours ago)
Parents
adc30be
The phone conduit host (com.vayunmathur.watch) died on
DefaultDispatcher-worker-4 with ConcurrentModificationException from the
WearLinkNode accept path (2026-12-05 05:58:35, Pixel 9 Pro XL) and
restarted; the same crash recurs whenever registrations change while a
link-status fan-out is in flight.

Root cause: ConduitRouter.setLinkStatus iterated the live clients map
while calling downstream sinks. The conduit host's ClientDownstream
unregisters a client from inside deliverStatus when its Messenger send
fails with RemoteException (dead client app), and register/unregister
can likewise arrive during the iteration. Synchronized is reentrant, so
the removal lands mid-iteration and the next iterator step throws CME.
setLinkStatus runs on every WearLinkNode state change, including the
Connected transition right after accept/adopt, which is how the accept
loop's coroutine tree takes the fatal. register() had the identical
pattern, replaying the live dataCache while calling deliverData.

Fix: iterate snapshots under the existing lock, matching the router's
sinks-under-lock contract: clients.values.toList() in setLinkStatus,
and dataCache.filterKeys (a copy) for the registering app in register.
No behaviour change for well-behaved clients; a client removed
mid-fan-out simply also receives that final status.

Sibling audit of WearLinkNode.kt: readLoop closed orphaned streams by
iterating receiving.values while invoking listener sink code under the
receiving lock; it now snapshots and clears under the lock and closes
outside it. connectLoop iterated the list returned by
transport.bondedPeers() across blocking connects; it now iterates an
ArrayList snapshot. DataReassembler, fed from the session read loop,
kept plain HashMaps that two overlapping read loops (old session plus
newly adopted) could mutate concurrently; onFrame and
lastAppliedGeneration are now @Synchronized, the SeenMessageIds idiom.
RequestTracker (ConcurrentHashMap plus snapshot failAll) and
SeenMessageIds were already safe and are unchanged.

Tests: two new ConduitRouterTest cases reproduce the crash
deterministically - clients unregistering each other during a status
fan-out, and a downstream publishing into the data cache during its own
register replay. Both fail with ConcurrentModificationException on the
unmodified code and pass with the fix.

Verified: ./gradlew :library:wearlink:lint
:library:wearlink:testDebugUnitTest :watch:lint :watch:lintVitalRelease
:watch:testDevUnitTest all pass. ktlint already fails on unmodified
files of this module at base (formatting rolls out module by module);
this change adds no new files to that set and keeps the module's
prevailing style.

Diff

library/wearlink/src/main/java/com/vayunmathur/library/wearlink/DataItems.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/DataItems.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/DataItems.ktindex 84545c7caf..26c24f973f 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/DataItems.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/DataItems.kt@@ -85,7 +85,11 @@ object DataItemCodec {     } } -/** Per-path reassembler. Pure; feed DATA frames, get complete documents. */+/**+ * Per-path reassembler. Pure; feed DATA frames, get complete documents.+ * Synchronized: read loops of an old and a newly adopted session can overlap+ * briefly, and the maps below are not safe for concurrent mutation.+ */ class DataReassembler {     private class Pending(         val generation: Long,@@ -100,6 +104,7 @@ class DataReassembler {     private val appliedGeneration = mutableMapOf<String, Long>()      /** Completed payload for [path], or null while incomplete/stale/corrupt. */+    @Synchronized     fun onFrame(frame: WearLinkFrame): ByteArray? {         if (frame.type != FrameType.DATA) return null         val chunk = DataChunk.decodeBody(frame.body) ?: return null@@ -128,6 +133,7 @@ class DataReassembler {         return bytes     } +    @Synchronized     fun lastAppliedGeneration(path: String): Long? = appliedGeneration[path] } 
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.ktindex 2f02a9113d..c8d0d970d1 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt@@ -282,7 +282,9 @@ class WearLinkNode(                 delay(2_000)                 continue             }-            val peers = transport.bondedPeers()+            // Snapshot: the dial loop iterates this while connects block, so+            // it must not alias a live transport-owned list.+            val peers = ArrayList(transport.bondedPeers())             if (peers.isEmpty()) {                 _state.value = WearLinkState.NoBondedPeer                 delay(backoff.nextDelayMillis())@@ -398,10 +400,12 @@ class WearLinkNode(                 }             }             failPending()-            synchronized(receiving) {-                receiving.values.forEach { runCatching { it.sink.close(false) } }-                receiving.clear()+            // Snapshot under the lock, close outside it: sink.close() is+            // listener code and must not run (or reenter) under the lock.+            val orphaned = synchronized(receiving) {+                receiving.values.toList().also { receiving.clear() }             }+            orphaned.forEach { runCatching { it.sink.close(false) } }         }     } 
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.ktindex d7373f33c9..dcf2c87068 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitRouter.kt@@ -81,7 +81,9 @@ data class ConduitCounters(  * registered client. Outbound traffic whose route key does not match the  * sending registration is refused, so one app cannot speak for another.  * All methods are synchronized; sinks are called under the lock and must- * not block (Messenger sends satisfy this).+ * not block (Messenger sends satisfy this). Iterations that call sinks run+ * over snapshots, so a sink may safely reenter (register/unregister/publish)+ * while a fan-out or replay is in flight.  */ class ConduitRouter(     private val maxQueuedPerApp: Int = DEFAULT_MAX_QUEUED_PER_APP,@@ -142,8 +144,10 @@ class ConduitRouter(         clients[appId] = downstream         if (!callerPackage.isNullOrEmpty()) packages[appId] = callerPackage         counters.putIfAbsent(appId, ConduitCounters())-        for ((key, body) in dataCache) {-            if (key.first == appId) downstream.deliverData(key.second, body)+        // Replay a snapshot: delivering may reenter the router (e.g. the+        // downstream publishing its own data), which mutates dataCache.+        for ((key, body) in dataCache.filterKeys { it.first == appId }) {+            downstream.deliverData(key.second, body)         }         queues.remove(appId)?.let { queued ->             for (message in queued) downstream.deliverMessage(message.path, message.body)@@ -290,7 +294,10 @@ class ConduitRouter(         linkState = state         linkPeer = peerLabel         linkReason = reason-        for (client in clients.values) client.deliverStatus(state, peerLabel, reason)+        // Fan out over a snapshot: delivering may reenter the router and+        // unregister (the host drops a client whose Messenger send fails),+        // which would otherwise mutate clients mid-iteration (CME).+        for (client in clients.values.toList()) client.deliverStatus(state, peerLabel, reason)     }      @Synchronized
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.ktindex c83220d37d..07dc5e59a5 100644--- a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/conduit/ConduitRouterTest.kt@@ -179,6 +179,130 @@ class ConduitRouterTest {         assertEquals(1, router.cachedDataSnapshot().size)     } +    /**+     * A downstream that drops another registration while delivering, the+     * unit-level mirror of ConduitHost.ClientDownstream.send() unregistering+     * a dead client from inside deliverStatus (RemoteException path).+     */+    private class UnregisteringDownstream(+        private val router: ConduitRouter,+        private val otherAppId: String,+    ) : ConduitDownstream {+        val statuses = mutableListOf<String>()++        /** Set after registration (register() itself replays a status). */+        var armed = false++        override fun deliverMessage(+            path: String,+            body: ByteArray,+        ): Boolean = true++        override fun deliverData(+            path: String,+            body: ByteArray,+        ): Boolean = true++        override fun deliverStatus(+            state: String,+            peerLabel: String?,+            reason: String?,+        ): Boolean {+            statuses.add(state)+            if (armed) router.unregister(otherAppId)+            return true+        }++        override fun deliverStreamOpen(+            streamId: Long,+            path: String,+            header: StreamHeader,+        ): Boolean = true++        override fun deliverStreamChunk(+            streamId: Long,+            body: ByteArray,+        ): Boolean = true++        override fun deliverStreamClose(+            streamId: Long,+            verified: Boolean,+        ): Boolean = true+    }++    @Test+    fun `status fan-out survives clients unregistering each other during delivery`() {+        val router = ConduitRouter(upstream = FakeUpstream())+        val clock = UnregisteringDownstream(router, "notes")+        val notes = UnregisteringDownstream(router, "clock")+        router.register("clock", clock)+        router.register("notes", notes)+        clock.armed = true+        notes.armed = true+        clock.statuses.clear()+        notes.statuses.clear()+        // Each delivery removes the other registration mid-iteration (the+        // dead-Messenger path in the conduit host). Pre-fix this throws+        // ConcurrentModificationException from the clients iteration.+        router.setLinkStatus(ConduitProtocol.STATUS_CONNECTED, "watch", null)+        assertEquals(listOf(ConduitProtocol.STATUS_CONNECTED), clock.statuses)+        assertEquals(listOf(ConduitProtocol.STATUS_CONNECTED), notes.statuses)+        assertEquals(emptySet(), router.registeredApps())+    }++    @Test+    fun `register replay survives data cache mutation during replay`() {+        val router = ConduitRouter(upstream = FakeUpstream())+        router.onPeerData("/clock/a", bytes("a"))+        router.onPeerData("/clock/b", bytes("b"))+        // Downstream that publishes new data for its own app while the+        // router is replaying the cache into it (dataCache grows under the+        // replay iteration). Pre-fix this throws CME.+        val delivered = mutableListOf<String>()+        val downstream =+            object : ConduitDownstream {+                override fun deliverMessage(+                    path: String,+                    body: ByteArray,+                ): Boolean = true++                override fun deliverData(+                    path: String,+                    body: ByteArray,+                ): Boolean {+                    delivered.add(path)+                    if (delivered.size == 1) {+                        router.onLocalData("clock", "/clock/extra", bytes("x"))+                    }+                    return true+                }++                override fun deliverStatus(+                    state: String,+                    peerLabel: String?,+                    reason: String?,+                ): Boolean = true++                override fun deliverStreamOpen(+                    streamId: Long,+                    path: String,+                    header: StreamHeader,+                ): Boolean = true++                override fun deliverStreamChunk(+                    streamId: Long,+                    body: ByteArray,+                ): Boolean = true++                override fun deliverStreamClose(+                    streamId: Long,+                    verified: Boolean,+                ): Boolean = true+            }+        router.register("clock", downstream)+        assertEquals(listOf("/clock/a", "/clock/b"), delivered.sorted())+    }+     @Test     fun `stream open is refused for unregistered app and routed when registered`() {         val router = ConduitRouter(upstream = FakeUpstream())