Modern Apps git

← Modern-Apps.git

communicate: isolate state-holding tests; await real signals, not sleeps

Commit
f71d8036b2df26c6b06069089d15ab7bf7101401
Author
Vayun Mathur <[email protected]>
When
2026-11-22 06:11 UTC (14 days ago)
Parents
660f626
CI's batch-exposed communicate failures decompose: victim
classes holding process state (RcsMsrpTls cache, WhatsAppClient
singleton drivers, RcsDatabase overrides) moved to the
quarantine with reasons documented; several tests replaced
10s wall-clock polls with deterministic terminal-signal
awaits; Y1RegistrationScreensTest was non-hermetic (real
SQLCipher + absent AndroidKeyStore under load) and now uses
the in-memory database seam. Same-cause fixes in three
neighbour classes (a settle predicate that could never match
due to a strip bug, async collectors never cancelled,
permission launcher firing in the harness). One possible
production bug reported, not fixed: ConversationScreen
launches a permission request from a send-success coroutine
that can outlive the composition.

Verified per agent: full communicate suite green in
repeated full runs at host load.

Diff

communicate/build.gradle.kts
diff --git a/communicate/build.gradle.kts b/communicate/build.gradle.ktsindex 16409b139a..281bc80a87 100644--- a/communicate/build.gradle.kts+++ b/communicate/build.gradle.kts@@ -231,12 +231,38 @@ rustNativeTests {     // any test instantiating a *LineSession / GoogleVoiceSession or     // using DataStoreUtils.getInstance directly belongs here. All other     // classes batch.+    //+    // Post-batch CI fallout (46858d7faa, 5-CPU) added six more:+    // (The fixed P-CSCF port 5060 shared by the DirectSip/Ims tests is+    // handled in those classes with SO_REUSEADDR + bounded bind retry:+    // forkEvery is a per-worker restart counter, not a fixed batch, so+    // no task placement can serialize them.)+    // - RcsSlice3Pass2DirectSipAuthTest asserts the RcsDirectSip+    //   singleton's SIP CSeq starts at 1; batched neighbours that drive+    //   the same singleton (same Robolectric sandbox classloader)+    //   increment it first ("CSeq: 7 REGISTER" observed).+    // - RcsSlice3Pass2TransportTest asserts RcsCapabilityExchange's+    //   updates flow starts empty; neighbours populate it.+    // - RcsSlice3Pass2TlsAndFtTest holds RcsMsrpTls's process-wide+    //   cached identity + persisted identity files and the+    //   RcsDatabase.overrideForTest seam.+    // - W5Pass2ClientCoreTest / W5Pass2SyncHistoryTest /+    //   W5Pass2ContactUtilsTest drive the WhatsAppClient singleton+    //   (auth/db/socket/state fields and its never-cancelled IO scope),+    //   whose asynchronous leftovers from batched neighbours can land+    //   inside their assertions.     isolatedClasses.addAll(         listOf(             "com.vayunmathur.communicate.data.SecretSealingTest",             "com.vayunmathur.communicate.data.Y1RepositoryLoadersTest",             "com.vayunmathur.communicate.googlevoice.GoogleVoiceSessionSlice4Test",+            "com.vayunmathur.communicate.rcs.RcsSlice3Pass2DirectSipAuthTest",+            "com.vayunmathur.communicate.rcs.RcsSlice3Pass2TlsAndFtTest",+            "com.vayunmathur.communicate.rcs.RcsSlice3Pass2TransportTest",             "com.vayunmathur.communicate.ui.Y2TopLevelScreensTest",+            "com.vayunmathur.communicate.whatsapp.W5Pass2ClientCoreTest",+            "com.vayunmathur.communicate.whatsapp.W5Pass2ContactUtilsTest",+            "com.vayunmathur.communicate.whatsapp.W5Pass2SyncHistoryTest",         )     ) }
communicate/src/test/java/com/vayunmathur/communicate/rcs/DirectSipRcsPass3Test.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/DirectSipRcsPass3Test.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/DirectSipRcsPass3Test.ktindex d16b6fd049..d289034428 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/rcs/DirectSipRcsPass3Test.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/DirectSipRcsPass3Test.kt@@ -105,8 +105,30 @@ class DirectSipRcsPass3Test {         }     } +    /** Bind the fake P-CSCF listener; see [withPcscf] call site for why. */+    private fun bindPcscf(): ServerSocket {+        // Attempt-counted, never clock-bounded: Robolectric substitutes+        // System.currentTimeMillis with its paused scheduler clock.+        var attempts = 0+        while (true) {+            try {+                return ServerSocket().apply {+                    reuseAddress = true+                    bind(java.net.InetSocketAddress(5060))+                }+            } catch (e: java.net.BindException) {+                if (++attempts >= 600) throw e+                Thread.sleep(100)+            }+        }+    }+     private suspend fun withPcscf(handler: (String) -> String?, block: suspend (Pcscf) -> Unit) {-        val server = ServerSocket(5060)+        // Port 5060 is fixed (the shadow advertises it as the P-CSCF) and+        // shared with RcsSlice3Pass2DirectSipAuthTest / RcsSlice3Pass2ImsTest,+        // which Gradle workers can run concurrently: SO_REUSEADDR covers+        // TIME_WAIT, the bounded retry waits out an active listen.+        val server = bindPcscf()         val pcscf = Pcscf(handler)         pcscf.serve(server)         try {
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DirectSipAuthTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DirectSipAuthTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DirectSipAuthTest.ktindex 9282f2b37f..bd1165c34f 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DirectSipAuthTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2DirectSipAuthTest.kt@@ -36,6 +36,33 @@ class RcsSlice3Pass2DirectSipAuthTest {         RcsDirectSip.stop()     } +    /**+     * The fake P-CSCF must listen on 5060 (the shadow advertises it and+     * production dials that port). Three test classes bind it, and Gradle+     * workers pull classes dynamically, so any two can listen at once:+     * SO_REUSEADDR covers TIME_WAIT from earlier registrations, and the+     * bounded retry waits out another class's active listen (bounded by+     * that class's method runtime). Without this, 5060 binds flake with+     * BindException under load (both directions observed).+     */+    private fun pcscfSocket(): ServerSocket {+        // Attempt-counted, never clock-bounded: Robolectric substitutes+        // System.currentTimeMillis with its paused scheduler clock, which+        // can leap past any wall-clock deadline instantly.+        var attempts = 0+        while (true) {+            try {+                return ServerSocket().apply {+                    reuseAddress = true+                    bind(java.net.InetSocketAddress(5060))+                }+            } catch (e: java.net.BindException) {+                if (++attempts >= 600) throw e+                Thread.sleep(100)+            }+        }+    }+     private class PcscfScript(val challengeFirst: Boolean) {         val requests = CopyOnWriteArrayList<String>()         val done = CountDownLatch(1)@@ -109,7 +136,7 @@ class RcsSlice3Pass2DirectSipAuthTest {     @Test     fun akaChallengeRegistrationAndRestart() = runBlocking {         // --- First start: 401 -> AKA digest REGISTER -> 200. ----        val server1 = ServerSocket(5060)+        val server1 = pcscfSocket()         val script1 = PcscfScript(challengeFirst = true)         script1.serve(server1)         assertTrue(RcsDirectSip.start(context, 1), "start failed: ${script1.requests}")@@ -121,7 +148,7 @@ class RcsSlice3Pass2DirectSipAuthTest {         assertEqualsRequests(script1)          // --- Restart after stop: the stack must come back (scope fix). ----        val server2 = ServerSocket(5060)+        val server2 = pcscfSocket()         val script2 = PcscfScript(challengeFirst = false)         script2.serve(server2)         assertTrue(RcsDirectSip.start(context, 1), "restart failed: ${script2.requests}")
communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsTest.ktindex 430bdee333..58b80190ae 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/rcs/RcsSlice3Pass2ImsTest.kt@@ -44,6 +44,24 @@ class RcsSlice3Pass2ImsTest {         RcsImsNetwork.reset()     } +    /** Bind the fake P-CSCF listener on the fixed port 5060. */+    private fun bindPcscf5060(): ServerSocket {+        // Attempt-counted, never clock-bounded: Robolectric substitutes+        // System.currentTimeMillis with its paused scheduler clock.+        var attempts = 0+        while (true) {+            try {+                return ServerSocket().apply {+                    reuseAddress = true+                    bind(java.net.InetSocketAddress(5060))+                }+            } catch (e: java.net.BindException) {+                if (++attempts >= 600) throw e+                Thread.sleep(100)+            }+        }+    }+     @Test     fun imsNetworkScanFindsFakePdn() = runTest {         RcsImsNetwork.reset()@@ -408,7 +426,10 @@ class RcsSlice3Pass2ImsTest {         // The IMS shadow advertises the P-CSCF on 127.0.0.1:5060; bind there         // instead by pointing the accepted server at the shadow's port.         server.close()-        val pcscf = ServerSocket(5060)+        // Port 5060 is shared with the DirectSip test classes, which Gradle+        // workers can run concurrently: SO_REUSEADDR covers TIME_WAIT, the+        // bounded retry waits out another class's active listen.+        val pcscf = bindPcscf5060()         val requests = CopyOnWriteArrayList<String>()         val inboundSent = CountDownLatch(1)         val serverDone = CountDownLatch(1)
communicate/src/test/java/com/vayunmathur/communicate/signal/SignalSlice2MessagingOfflineTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalSlice2MessagingOfflineTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalSlice2MessagingOfflineTest.ktindex f052f9eac8..949b6d3512 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalSlice2MessagingOfflineTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/signal/SignalSlice2MessagingOfflineTest.kt@@ -320,7 +320,12 @@ class SignalSlice2MessagingOfflineTest {         }         SignalClient.reportIdentityChange(peer, key)         assertTrue(SignalClient.pendingIdentityChange(peer)?.contentEquals(key) == true)-        val event = withTimeoutOrNull(5_000) { first.await() }+        // The event is produced off the test scheduler; withTimeoutOrNull+        // inside runTest burns virtual time instantly and returned null+        // under load. Await the same signal on a real dispatcher instead.+        val event = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Default) {+            withTimeoutOrNull(60_000) { first.await() }+        }         assertTrue(event is SignalEvent.IdentityKeyChanged, "got $event")         assertEquals(peer, (event as SignalEvent.IdentityKeyChanged).peerAci)     }
communicate/src/test/java/com/vayunmathur/communicate/ui/Y1RegistrationScreensTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/ui/Y1RegistrationScreensTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/ui/Y1RegistrationScreensTest.ktindex 81088f2ba5..4c0762138b 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/ui/Y1RegistrationScreensTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/ui/Y1RegistrationScreensTest.kt@@ -1,16 +1,21 @@ package com.vayunmathur.communicate.ui +import android.content.Context import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTextInput+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.rcs.RcsDatabase import com.vayunmathur.communicate.ui.rcs.RcsVerifyScreen import com.vayunmathur.communicate.ui.signal.SignalCaptchaWebView import com.vayunmathur.communicate.ui.signal.SignalRegistrationNumberScreen import com.vayunmathur.communicate.ui.whatsapp.WhatsAppBackupImportScreen import com.vayunmathur.communicate.ui.whatsapp.WhatsAppRegistrationNumberScreen+import kotlin.test.AfterTest+import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue@@ -36,6 +41,30 @@ class Y1RegistrationScreensTest {      @get:Rule val rule = createComposeRule() +    // The RCS verify screen's buttons reach RcsDatabase through RcsE2E.+    // Without this seam that is the SQLCipher singleton, whose+    // AndroidKeyStore lookup does not exist on a JVM host: the click+    // coroutine then dies with an uncaught KeyStoreException whenever the+    // IO hop lands inside the test window (load-dependent). An in-memory+    // database keeps the verify flow hermetic and deterministic.+    private lateinit var testDb: RcsDatabase++    @BeforeTest+    fun setUp() {+        val context = ApplicationProvider.getApplicationContext<Context>()+        testDb = androidx.room3.Room.inMemoryDatabaseBuilder(context, RcsDatabase::class.java)+            .setDriver(androidx.sqlite.driver.bundled.BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()+        RcsDatabase.overrideForTest = testDb+    }++    @AfterTest+    fun tearDown() {+        RcsDatabase.overrideForTest = null+        testDb.close()+    }+     // ---- Signal ----      @Test fun `signal registration gates every request on a typed number`() {
communicate/src/test/java/com/vayunmathur/communicate/ui/Y2TopLevelScreensTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/ui/Y2TopLevelScreensTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/ui/Y2TopLevelScreensTest.ktindex 335419cbb9..5f435b7271 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/ui/Y2TopLevelScreensTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/ui/Y2TopLevelScreensTest.kt@@ -107,6 +107,14 @@ class Y2TopLevelScreensTest {             Manifest.permission.READ_CONTACTS,             Manifest.permission.READ_PHONE_STATE,         )+        // ConversationScreen asks for POST_NOTIFICATIONS once after the+        // first successful send (persisted ask-once flag). Pre-setting it+        // keeps that prompt out of these screen tests: in this harness the+        // send completes off the main thread and the launcher launch raced+        // its registration, crashing with "unregistered+        // ActivityResultLauncher" under load.+        app.getSharedPreferences("communicate_notifications", Context.MODE_PRIVATE)+            .edit().putBoolean("has_asked_notifications", true).commit()         val shadow = Shadow.extract<ShadowRoleManager>(app.getSystemService(RoleManager::class.java))         shadow.addHeldRole(RoleManager.ROLE_SMS)         shadow.addHeldRole(RoleManager.ROLE_DIALER)
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Pass2ClientCoreTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Pass2ClientCoreTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Pass2ClientCoreTest.ktindex be927bb50e..93031a40ba 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Pass2ClientCoreTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Pass2ClientCoreTest.kt@@ -137,14 +137,13 @@ class W5Pass2ClientCoreTest {         assertEquals("12345@lid", WhatsAppAuthData.load(WhatsAppClient.appContext)?.lid)         assertTrue(WhatsAppDiag.log.value.any { it.contains("AUTHENTICATED") })         assertTrue(WhatsAppDiag.log.value.any { it.contains("awaiting pushed history") })-        // Prekeys are all uploaded locally, so the upload check logs and skips Rust.-        val deadline = System.currentTimeMillis() + 10_000-        var sawPrekeys = false-        while (System.currentTimeMillis() < deadline && !sawPrekeys) {-            sawPrekeys = WhatsAppDiag.log.value.any { it.contains("prekeys: nothing to upload") }-            if (!sawPrekeys) Thread.sleep(25)+        // Prekeys are all uploaded locally, so the upload check logs and skips+        // Rust. The check runs on the client's IO scope, so wait on the+        // terminal log line itself (step-bounded, no wall clock): a 10 s+        // sleep-poll gave up under CI load before IO landed.+        com.vayunmathur.testsupport.awaitWithMainIdle("prekeys upload check logged", maxSteps = 100_000) {+            WhatsAppDiag.log.value.any { it.contains("prekeys: nothing to upload") }         }-        assertTrue(sawPrekeys, WhatsAppDiag.log.value.takeLast(5).toString())         // A second success with no lid leaves the adopted one in place.         WhatsAppClient.handleConnectSuccess(WhatsAppProtocol.Node(tag = "success"))         assertEquals("12345@lid", WhatsAppClient.authData?.lid)
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Pass2SyncHistoryTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Pass2SyncHistoryTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Pass2SyncHistoryTest.ktindex 37b76b6529..ffd35b501f 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Pass2SyncHistoryTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Pass2SyncHistoryTest.kt@@ -27,6 +27,8 @@ import java.util.zip.Deflater import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec+import java.util.concurrent.CopyOnWriteArrayList+import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals@@ -35,6 +37,7 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.cancel import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest@@ -56,7 +59,10 @@ class W5Pass2SyncHistoryTest {     )      private lateinit var eventScope: CoroutineScope-    private val receivedEvents = mutableListOf<WhatsAppEvent>()+    // Written by the collector on Dispatchers.Default, read by the test+    // thread after a signal wait (see the awaits below): must be the+    // thread-safe list, not a plain ArrayList.+    private val receivedEvents = CopyOnWriteArrayList<WhatsAppEvent>()      @BeforeTest     fun setUp() {@@ -78,6 +84,15 @@ class W5Pass2SyncHistoryTest {         eventScope.launch { WhatsAppClient.events.collect { receivedEvents.add(it) } }     } +    @AfterTest+    fun tearDown() {+        // Stop this method's collector: the SharedFlow broadcasts to every+        // live collector, and an uncancelled scope would keep draining the+        // singleton's stream (and writing into a stale list) for the rest+        // of the JVM.+        eventScope.cancel()+    }+     private fun deflate(data: ByteArray): ByteArray {         val deflater = Deflater()         deflater.setInput(data)@@ -193,6 +208,14 @@ class W5Pass2SyncHistoryTest {         WhatsAppClient.fullHistorySync = false // do not chase on-demand pages in this test         WhatsAppClient.handleHistorySync(notif, "notif-1")         assertEquals("[email protected]", WhatsAppClient.lidToPhoneMap["999@lid"])+        // Events reach the collector on Dispatchers.Default asynchronously;+        // wait for the terminal delivery instead of asserting on whatever+        // has landed already (an immediate read races the collector and+        // failed empty under load).+        com.vayunmathur.testsupport.awaitWithMainIdle("history sync events delivered", maxSteps = 100_000) {+            receivedEvents.filterIsInstance<WhatsAppEvent.MessageUpdate>().size >= 2 &&+                receivedEvents.filterIsInstance<WhatsAppEvent.ConversationUpdate>().isNotEmpty()+        }         val updates = receivedEvents.filterIsInstance<WhatsAppEvent.MessageUpdate>()         assertEquals(listOf("hello from history", "reply from me"), updates.map { it.body })         assertEquals(listOf(false, true), updates.map { it.outgoing })@@ -226,6 +249,11 @@ class W5Pass2SyncHistoryTest {             .addMessages(historyMessage("g1", "group hello", fromMe = false, ts = 1_700_000_000L))             .build()         assertEquals(1, WhatsAppClient.emitHistoryConversation(conv, "[email protected]", requestMore = false))+        // Same delivery race as above: .single() on the not-yet-drained+        // collector list threw NoSuchElementException under load.+        com.vayunmathur.testsupport.awaitWithMainIdle("conversation update delivered", maxSteps = 100_000) {+            receivedEvents.filterIsInstance<WhatsAppEvent.ConversationUpdate>().isNotEmpty()+        }         val update = receivedEvents.filterIsInstance<WhatsAppEvent.ConversationUpdate>().single()         assertTrue(update.isGroup)         assertEquals("wa:[email protected]", update.conversationId)
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Slice1EventProcessorTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Slice1EventProcessorTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Slice1EventProcessorTest.ktindex d2f4ebcd71..cd88df2ade 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Slice1EventProcessorTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/W5Slice1EventProcessorTest.kt@@ -59,18 +59,25 @@ class W5Slice1EventProcessorTest {     }      /**-     * Poll until [cond] holds (bounded). The wait runs on a real-time-     * dispatcher: these tests use runTest, whose virtual clock burns a-     * delay budget instantly, while the processor drains on-     * Dispatchers.IO in real time — polling on the test scheduler lost-     * that race under load.+     * Wait until [cond] holds: the wait is on the terminal signal (the+     * effect visible in the db), polled on a real-time dispatcher.+     * These tests use runTest, whose virtual clock burns a delay budget+     * instantly, while the processor drains on Dispatchers.IO in real+     * time — polling on the test scheduler lost that race under load.+     * The bound counts attempts, never a clock (Robolectric substitutes+     * System.currentTimeMillis, and the earlier 200x10ms budget expired+     * on a 5-CPU box before the IO drain landed, leaving `!!` reads to+     * NPE on empty rows); 6000 attempts is ~60 s of real backoff, far+     * past any drain this processor does.      */     private suspend fun awaitSettled(cond: suspend () -> Boolean) {         kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Default) {-            var waited = 0-            while (waited < 200 && !cond()) {+            var attempts = 0+            while (!cond()) {+                if (++attempts >= 6_000) {+                    throw AssertionError("event processor effect never became visible in db")+                }                 kotlinx.coroutines.delay(10)-                waited++             }         }     }@@ -86,9 +93,15 @@ class W5Slice1EventProcessorTest {         else -> true     } -    private fun stripWa(id: String) = id.removePrefix("wa:").substringBefore(':').let {-        val at = id.removePrefix("wa:").indexOf('@')-        if (at <= 0) id.removePrefix("wa:") else it + id.removePrefix("wa:").substring(at)+    // "wa:" prefix and any ":device" suffix before the '@' come off; the+    // earlier form re-appended the domain for ids without a device suffix+    // ("wa:[email protected]" -> "[email protected]@g.us"), so settled() below never matched and+    // the old bounded poll silently expired as a fixed sleep.+    private fun stripWa(id: String): String {+        val raw = id.removePrefix("wa:")+        val at = raw.indexOf('@')+        if (at <= 0) return raw.substringBefore(':')+        return raw.substring(0, at).substringBefore(':') + raw.substring(at)     }      @Test
communicate/src/test/java/com/vayunmathur/communicate/whatsapp/Y1WaE2eSyncTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/Y1WaE2eSyncTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/Y1WaE2eSyncTest.ktindex 20606388a7..a81458d117 100644--- a/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/Y1WaE2eSyncTest.kt+++ b/communicate/src/test/java/com/vayunmathur/communicate/whatsapp/Y1WaE2eSyncTest.kt@@ -47,6 +47,7 @@ import java.util.zip.Deflater import javax.crypto.Cipher import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.SecretKeySpec+import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals@@ -56,6 +57,7 @@ import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.cancel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch@@ -117,7 +119,15 @@ class Y1WaE2eSyncTest {         WhatsAppClient.onDemandPageCount.clear(); WhatsAppClient.appStateCollectionsFetching.clear()         WhatsAppClient.appStateKeyRequested.clear()         WhatsAppDiag.clear(); events.clear()-        CoroutineScope(Dispatchers.Default + Job()).launch { WhatsAppClient.events.collect { events.add(it) } }+        eventScope = CoroutineScope(Dispatchers.Default + Job())+        eventScope.launch { WhatsAppClient.events.collect { events.add(it) } }+    }++    private lateinit var eventScope: CoroutineScope++    @AfterTest+    fun tearDown() {+        eventScope.cancel()     }      private fun bundleFor(auth: WhatsAppAuthData, withOneTime: Pair<Int, ByteArray>? = null) =@@ -481,6 +491,13 @@ class Y1WaE2eSyncTest {             .setInitialHistBootstrapInlinePayload(ByteString.copyFrom(deflate(history.toByteArray()))).build()         WhatsAppClient.handleHistorySync(notif, "hn-1")         assertEquals("[email protected]", WhatsAppClient.lidToPhoneMap["888@lid"])+        // Events reach the collector on Dispatchers.Default asynchronously;+        // asserting immediately raced it and dropped the last conversation+        // under load. Wait for the terminal delivery (step-bounded).+        com.vayunmathur.testsupport.awaitWithMainIdle("history sync events delivered", maxSteps = 100_000) {+            events.filterIsInstance<WhatsAppEvent.MessageUpdate>().size >= 3 &&+                events.filterIsInstance<WhatsAppEvent.ConversationUpdate>().size >= 2+        }         val updates = events.filterIsInstance<WhatsAppEvent.MessageUpdate>()         assertEquals(listOf("first", "mine", "group hist"), updates.map { it.body })         val convs = events.filterIsInstance<WhatsAppEvent.ConversationUpdate>()