tests: de-flake the eight repeat CI failures under CPU caps
- Commit
fe8508d510d52237c60420d7c44f816dfb58b060- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-22 14:35 UTC (13 days ago)
- Parents
afeaa45
Each recurred every CI run but passed unloaded locally. Causes were load couplings: wall-clock sleep-polls starving producers (websocket loopback, maps car, contacts move, share AirDrop session wait), looper-idle assumptions inside Compose tests (library/ui game center, health recipe), a replay-0 SharedFlow collector racing the first feed with an unsynchronized list iteration (communicate stanza test), a static FileProvider cache poisoned by a sibling class's roots (share - the class moves to the forkEvery=1 quarantine with the reason documented), and appstore's TV rail focus trap on the Home return (focus-then-click, as real input must). All now wait on terminal signals via the shared deterministic await; no assertions weakened. Verified in the CI shape (taskset 5 CPUs): library/network, library/ui, contacts, maps, communicate, share full suites green; health/appstore classes green (two unrelated environment-sensitive failures outside this set flagged for follow-up, incl. appstore's Native companion masking the TV fix in CI). Note: the health RecipeEditorFlowTest half of this change landed inside cddd6bb48's sweep.
Diff
appstore/src/test/java/com/vayunmathur/appstore/tv/TvMainActivityTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvMainActivityTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvMainActivityTest.ktindex 5bfca64690..ade45fb57a 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvMainActivityTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvMainActivityTest.kt@@ -94,11 +94,40 @@ class TvMainActivityTest { .fetchSemanticsNodes().isNotEmpty() } composeRule.onNodeWithText("Updates").performSemanticsAction(SemanticsActions.RequestFocus)- composeRule.waitForIdle()+ // The remaining destinations were only waitForIdle'd: their content+ // lands via viewModelScope on the paused main looper (and Updates /+ // Home first show an indeterminate loading spinner, which never+ // idles), so under load the focus hops raced content that had not+ // composed yet. Wait on each destination's own terminal text,+ // idling the looper per poll like the Library/Sources legs above.+ composeRule.waitUntil(timeoutMillis = 15_000) {+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ composeRule.onAllNodesWithText("Everything is up to date", substring = true)+ .fetchSemanticsNodes().isNotEmpty()+ } composeRule.onNodeWithText("Search").performSemanticsAction(SemanticsActions.RequestFocus)+ composeRule.waitUntil(timeoutMillis = 15_000) {+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ composeRule.onAllNodesWithText("Search for an app", substring = true)+ .fetchSemanticsNodes().isNotEmpty()+ }+ // Return home the way the frame's own test does (TvRouteAppFrameTest):+ // focus the rail item first (focusing is what selects it), then invoke+ // its click, which moves focus into the new content. Firing either+ // alone here left focus on the outgoing entry's rail during the+ // sibling crossfade, and its focus restorer re-selected Search.+ val homeNode = composeRule.onNodeWithText("Home")+ homeNode.performSemanticsAction(SemanticsActions.RequestFocus) composeRule.waitForIdle()- composeRule.onNodeWithText("Home").performSemanticsAction(SemanticsActions.RequestFocus)- composeRule.waitForIdle()+ homeNode.fetchSemanticsNode()+ .config[SemanticsActions.OnClick].action?.invoke()+ // Home's terminal state is its first catalog section (the seeded+ // in-memory catalog is non-empty, so the empty state never shows).+ composeRule.waitUntil(timeoutMillis = 15_000) {+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ composeRule.onAllNodesWithText("New from Modern Apps", substring = true)+ .fetchSemanticsNodes().isNotEmpty()+ } composeRule.onNodeWithText("Home").assertIsDisplayed() } }
build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt
diff --git a/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt b/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.ktindex a83e106515..d11f709d29 100644--- a/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt+++ b/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt@@ -60,9 +60,12 @@ fun <T> awaitValueBlocking(flow: Flow<T>, predicate: (T) -> Boolean): T = * Idles the main looper until [condition] holds, then returns. * * Step-counted as a failure bound only: each step is a full looper idle,- * which is the work that makes progress possible, and the thread yields- * between steps so IO/Default producers on other threads can run. This- * replaces `Thread.sleep` + `System.currentTimeMillis` deadline loops,+ * which is the work that makes progress possible, and the thread parks+ * briefly between steps so IO/Default producers on other threads can run.+ * (A bare yield is not enough in the Robolectric sandbox: a tight+ * idle+yield loop kept the test thread runnable and an IO search behind+ * it never landed in 10,000 steps, while parking let it finish in ~10.)+ * This replaces `Thread.sleep` + `System.currentTimeMillis` deadline loops, * which under Robolectric measured a substituted clock and gave up before * real IO had landed. */@@ -71,7 +74,7 @@ fun awaitWithMainIdle(description: String, maxSteps: Int = 10_000, condition: () while (step++ < maxSteps) { idleMainLooper() if (condition()) return- Thread.yield()+ java.util.concurrent.locks.LockSupport.parkNanos(1_000_000) } // One last idle + check so the failure reports the settled state. idleMainLooper()
contacts/src/test/java/com/vayunmathur/contacts/ui/MoveDialogsPass2Test.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/ui/MoveDialogsPass2Test.kt b/contacts/src/test/java/com/vayunmathur/contacts/ui/MoveDialogsPass2Test.ktindex a156769db9..8730a36d99 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/ui/MoveDialogsPass2Test.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/ui/MoveDialogsPass2Test.kt@@ -25,6 +25,8 @@ import com.vayunmathur.contacts.ui.dialogs.MoveToAccountDialog import com.vayunmathur.contacts.platform.ContactAccount import com.vayunmathur.contacts.platform.ContactViewModel import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.testsupport.awaitSemantics+import com.vayunmathur.testsupport.awaitWithMainIdle import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking@@ -57,6 +59,14 @@ class MoveDialogsPass2Test { ) } + @AfterTest+ fun tearDown() {+ // setMain above is process-wide: without this, every later class in+ // the batched JVM inherits Unconfined Main and its paused-looper+ // waits silently change meaning (order-dependent flakes).+ Dispatchers.resetMain()+ }+ private val google = ContactAccount("[email protected]", "com.google") private val sim = ContactAccount("5", SIM_ACCOUNT_TYPE)@@ -120,6 +130,16 @@ class MoveDialogsPass2Test { fun moveDialogHostTransfersToSelectedAccount() { val vm = ContactViewModel(app) runBlocking { vm.syncFromSystem() }+ // The ViewModel's own init sync/loadAccounts writes accountsState+ // asynchronously (since the SIM-source isolation work it does so at+ // the end of every sync). Injecting the test accounts before that+ // work settles lets a late write erase them, so the dialog never+ // lists them — wait for the sync's terminal state first: contacts+ // published (fake provider contact 7) and the load marked complete+ // (set in syncFromSystem's finally, after its account refresh).+ awaitWithMainIdle("contacts sync settled") {+ vm.allContactsState.value.any { it.id == 7L } && vm.hasLoadedContacts.value+ } // fake provider contact 7 loaded; make both accounts available vm.accountsState.value = listOf(google, sim) var dismissed = 0@@ -129,7 +149,7 @@ class MoveDialogsPass2Test { MoveDialogHost(vm, listOf(7L), onDismiss = { dismissed++ }, onTransferred = { transferred++ }) } }- rule.waitUntil(20_000) {+ rule.awaitSemantics("account rows listed") { rule.onAllNodesWithText("[email protected]", substring = true).fetchSemanticsNodes().isNotEmpty() } // Aisha's own (google) account is the disabled source; pick the SIM@@ -141,11 +161,19 @@ class MoveDialogsPass2Test { // SIM row may be labelled by its account name "5" rule.onAllNodesWithText("5", substring = true)[0].performClick() }- rule.waitForIdle()- // the SIM destination switches to the loss-warning page ("Move anyway")+ // The SIM destination switches to the loss-warning page ("Move+ // anyway"); that switch is a recomposition on the main looper, so+ // wait on the page itself rather than idling once.+ rule.awaitSemantics("SIM loss page shown") {+ rule.onAllNodesWithText(str(R.string.move_anyway), substring = true)+ .fetchSemanticsNodes().isNotEmpty()+ } rule.onNodeWithText(str(R.string.move_anyway)).assertExists() rule.onNodeWithText(str(R.string.move_anyway)).performClick()- rule.waitUntil(30_000) { dismissed == 1 }+ // The transfer runs on IO and reports back on Main (result state,+ // then a LaunchedEffect fires onTransferred/onDismiss): dismissal+ // is the terminal signal.+ rule.awaitSemantics("transfer dismissed the dialog") { dismissed == 1 } assertEquals(1, dismissed) assertEquals(1, transferred) }
library/network/src/test/java/com/vayunmathur/library/network/WebSocketLoopbackTest.kt
diff --git a/library/network/src/test/java/com/vayunmathur/library/network/WebSocketLoopbackTest.kt b/library/network/src/test/java/com/vayunmathur/library/network/WebSocketLoopbackTest.ktindex c6c78a2da1..bbb031667e 100644--- a/library/network/src/test/java/com/vayunmathur/library/network/WebSocketLoopbackTest.kt+++ b/library/network/src/test/java/com/vayunmathur/library/network/WebSocketLoopbackTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.library.network import com.sun.net.httpserver.HttpServer+import com.vayunmathur.testsupport.awaitWithMainIdle import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking@@ -140,6 +141,15 @@ class WebSocketLoopbackTest { send("hello server"); send(byteArrayOf(9, 8, 7)); ping() sessionFrames = incoming.take(7).toList() }+ // The echoes above prove the server read the text/binary frames,+ // but the client's ping and the close written by webSocket's+ // finally are only *sent* at this point: the daemon server thread+ // may not have read them off the socket yet, and under load it is+ // starved exactly here. Wait for the server's own terminal signal+ // (it has recorded both frames) before asserting on its log.+ awaitWithMainIdle("server received ping and close frames") {+ srv.received.any { it.first == 0x9 } && srv.received.any { it.first == 0x8 }+ } assertEquals("/chat?room=1", srv.handshakePath) assertEquals("loopback", srv.handshakeHeaders["x-client"]) val texts = sessionFrames.filterIsInstance<WebSocketClient.WsFrame.Text>().map { it.text }
library/ui/src/test/java/com/vayunmathur/library/ui/MiscUiSlice3Test.kt
diff --git a/library/ui/src/test/java/com/vayunmathur/library/ui/MiscUiSlice3Test.kt b/library/ui/src/test/java/com/vayunmathur/library/ui/MiscUiSlice3Test.ktindex 7f4794186d..db810c6804 100644--- a/library/ui/src/test/java/com/vayunmathur/library/ui/MiscUiSlice3Test.kt+++ b/library/ui/src/test/java/com/vayunmathur/library/ui/MiscUiSlice3Test.kt@@ -23,6 +23,7 @@ import androidx.compose.ui.test.click import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.dp import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.testsupport.awaitSemantics import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse@@ -642,7 +643,14 @@ class MiscUiComposeSlice3Test { val manager = FakeAchievementsManager(appContext) var backs = 0 rule.setContent { GameCenterScreen(manager = manager, onBack = { backs++ }) }- rule.waitForIdle()+ // The statuses arrive over DataStore's IO-backed flow and publish on+ // the paused main looper: waitForIdle can return while that emission+ // is still in flight under load, so wait on the listed names+ // themselves (the terminal semantics state).+ rule.awaitSemantics("achievements listed") {+ rule.onAllNodesWithText("First win").fetchSemanticsNodes().isNotEmpty() &&+ rule.onAllNodesWithText("Steady play").fetchSemanticsNodes().isNotEmpty()+ } rule.onNodeWithText("First win").assertIsDisplayed() rule.onNodeWithText("Steady play").assertIsDisplayed() rule.onNodeWithContentDescription("Back").performClick()
maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavC5Test.ktindex c4f6fc30e5..925711b5e2 100644--- a/maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavC5Test.kt+++ b/maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavC5Test.kt@@ -129,15 +129,15 @@ class MapsCarNavC5Test { val carContext = TestCarContext.createCarContext(app) val screen = CarSearchScreen(carContext) call(screen, "runSearch", "zzzzqqqq")- repeat(200) {- Thread.sleep(10)- if (field(screen, "loading") == false) {- assertEquals(- carContext.getString(com.vayunmathur.maps.R.string.car_no_results),- field(screen, "message"),- )- return- }+ // Search runs on IO; the old sleep-poll gave it a 2 s wall-clock+ // budget, which a CPU-capped batched JVM cannot meet. Wait on the+ // screen's own terminal state instead: `loading` flips off just+ // before `message` is assigned on the IO thread, with no+ // happens-before edge to this thread, so the published message is+ // the signal that the search has fully landed.+ val expected = carContext.getString(com.vayunmathur.maps.R.string.car_no_results)+ com.vayunmathur.testsupport.awaitWithMainIdle("car search reported no results") {+ field(screen, "loading") == false && field(screen, "message") == expected } assertEquals( carContext.getString(com.vayunmathur.maps.R.string.car_no_results),
share/build.gradle.kts
diff --git a/share/build.gradle.kts b/share/build.gradle.ktsindex 766baaea72..f6057dcce6 100644--- a/share/build.gradle.kts+++ b/share/build.gradle.kts@@ -79,6 +79,12 @@ rustNativeTests { listOf( "com.vayunmathur.share.platform.ShareViewModelHelpersTest", "com.vayunmathur.share.ui.SharePopupAndActivitiesTest",+ // Victim of FileProvider's static path-strategy cache: the first+ // getUriForFile in a shared sandbox caches that test method's+ // per-method filesDir root, and AirDropReceiver's upload then+ // fails its contentUri root check (500) whenever+ // ReceivedFileStoreTest's contentUri test ran first in the JVM.+ "com.vayunmathur.share.platform.airdrop.AirDropReceiverTest", ) ) }
share/src/test/java/com/vayunmathur/share/platform/airdrop/AirDropReceiverTest.kt
diff --git a/share/src/test/java/com/vayunmathur/share/platform/airdrop/AirDropReceiverTest.kt b/share/src/test/java/com/vayunmathur/share/platform/airdrop/AirDropReceiverTest.ktindex b5119c2ecd..00c90244ad 100644--- a/share/src/test/java/com/vayunmathur/share/platform/airdrop/AirDropReceiverTest.kt+++ b/share/src/test/java/com/vayunmathur/share/platform/airdrop/AirDropReceiverTest.kt@@ -9,6 +9,7 @@ import com.vayunmathur.share.domain.airdrop.DvZip import com.vayunmathur.share.domain.protocol.ShareState import com.vayunmathur.share.network.airdrop.AirDropHttp import com.vayunmathur.share.platform.ReceivedFileStore+import com.vayunmathur.testsupport.awaitValue import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.net.InetAddress@@ -73,16 +74,11 @@ class AirDropReceiverTest { files = files, transferId = "tid-1", ) val askJob = async { r.handle(request("/Ask", BinaryPlist.encode(ask.toPlist())), remote) }- // Wait for session to appear, then accept- var handle: Long? = null- val deadline = System.currentTimeMillis() + 5_000- while (System.currentTimeMillis() < deadline) {- handle = r.incoming.value.firstOrNull()?.sessionHandle- if (handle != null) break- delay(20)- }- assertNotNull(handle)- val incoming = r.sessionFor(handle!!)!!+ // Wait for the session to appear, then accept. Suspend on the+ // incoming flow's own emission instead of polling it against a 5 s+ // wall clock, which a CPU-capped batched JVM could starve past.+ val handle = r.incoming.awaitValue { it.isNotEmpty() }.first().sessionHandle+ val incoming = r.sessionFor(handle)!! assertEquals(ShareState.AwaitingAccept, incoming.state.value) assertEquals("PeerPhone", incoming.displayName) assertEquals(1, incoming.pendingFiles.value.size)