tests: games failures reproduced under CI-like load and fixed
- Commit
82ce53149609f2949e11d15d83a0023f9ee78d2d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-23 10:04 UTC (13 days ago)
- Parents
4defb21
Under concurrent heavy load the CI failures reproduce: wordmaker/arrows share wiped DataStore/sandbox state and uncancelled ViewModel scopes across batched classes; contacts' init sync erases the fixture mid-scroll; appstore's home test loses the one-shot sections injection to init's loadHome. Fixes: ViewModelStore clear in teardown, shared step-bounded pumped awaits, settle-and- reinject fixture patterns, and (arrows only, pollution proven, clearing insufficient) documented forkEvery=1 isolation. The arrows polluting neighbour wasn't isolated to one class - stated honestly in the build file. Verified under taskset + concurrent office/maps load: wordmaker 158, arrows 140, contacts 571, appstore 677 - all green. No assertions weakened, no production change.
Diff
appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.ktindex f6920e46cd..b4962ae28f 100644--- a/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt+++ b/appstore/src/test/java/com/vayunmathur/appstore/tv/TvStoreViewModelTest.kt@@ -13,7 +13,10 @@ import androidx.sqlite.driver.bundled.BundledSQLiteDriver import androidx.test.core.app.ApplicationProvider import com.vayunmathur.appstore.data.AppDatabase import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.DefaultRepos import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.toEntity+import kotlinx.coroutines.runBlocking import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals@@ -42,6 +45,20 @@ class TvStoreViewModelTest { .setDriver(BundledSQLiteDriver()) .allowMainThreadQueries() .build()+ // Seeded so the ViewModel's init pass has a terminal home+ // signal ("modern-recent", only its loadHome can produce it+ // here) and skips its first sync: see the home test.+ runBlocking {+ db.cachedAppDao().upsert(+ UnifiedApp(+ packageName = "com.example.seed",+ source = AppSource.MODERN_APPS,+ name = "Seed",+ categories = listOf("SeedCategory"),+ repoUrl = DefaultRepos.MODERN_APPS.url,+ ).toEntity().copy(lastUpdated = 300L),+ )+ } vm = TvStoreViewModel(app, db) } @@ -104,10 +121,39 @@ class TvStoreViewModelTest { @Test fun `home follows sections and status flows`() {+ // Let the init pass settle first (the TvStoreLoadHomeTest /+ // LoadHomeTest arrangement): init re-reads the enabled sources,+ // purges disabled sources' rows and runs its own loadHome, and+ // the catalogue collector runs loadHome again per DB emission.+ // Injecting the test section before that pass lands lets a+ // late init loadHome overwrite it with the catalogue's (empty)+ // sections, after which the pumped wait below can never become+ // true again — its 6,000 pumps (~300s) burned exactly that way+ // in CI. "modern-recent" is init's terminal signal here: only+ // its loadHome over the seeded row can produce it, and no DB+ // write remains after it that would retrigger the collector.+ await("init home") { vm.home.value.sections.any { it.id == "modern-recent" } } val section = TvSection(id = "recent", title = "Recently updated", apps = listOf(app("com.example.a", name = "Alpha")))- vm.sectionsFlow.value = listOf(section)- vm.statusMessageFlow.value = "Checking sources"- await("home section") { vm.home.value.sections == listOf(section) }+ // A loadHome launched by an early catalogue emission can still+ // be in flight when init's first home lands, and would+ // overwrite a one-shot injection below. Re-inject on every+ // pump until the home state reflects it: any in-flight+ // loadHome is then repaired on the next pump, and no new+ // loadHome can start after this without a fresh DB write+ // (none remains in this fixture). Step-bounded, like await().+ var steps = 0+ while (true) {+ vm.sectionsFlow.value = listOf(section)+ vm.statusMessageFlow.value = "Checking sources"+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ if (vm.home.value.sections == listOf(section)) break+ java.util.concurrent.locks.LockSupport.parkNanos(+ java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(PARK_MS),+ )+ if (++steps >= MAX_PUMP_STEPS) {+ throw AssertionError("timed out re-injecting home section; home=${vm.home.value}")+ }+ } assertEquals("Checking sources", vm.home.value.statusMessage) }
contacts/src/test/java/com/vayunmathur/contacts/ui/InteractionsPass2Test.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/ui/InteractionsPass2Test.kt b/contacts/src/test/java/com/vayunmathur/contacts/ui/InteractionsPass2Test.ktindex 726427c7d1..f81be8593b 100644--- a/contacts/src/test/java/com/vayunmathur/contacts/ui/InteractionsPass2Test.kt+++ b/contacts/src/test/java/com/vayunmathur/contacts/ui/InteractionsPass2Test.kt@@ -205,17 +205,44 @@ class InteractionsPass2Test { ContactDetailsPage(vm, contactId = 7, onBack = { back++ }, onEdit = {}, onDelete = {}) } }- vm.allContactsState.value = listOf(fixtureContact())+ // The ViewModel's init sync publishes the (empty) provider list+ // whenever its IO lands, erasing the fixture above and unmounting+ // the details list mid-scroll ("node is no longer in the tree" on+ // the captured scroller in CI, where that IO is starved). Reseed+ // until the fixture is what the page actually shows, the same+ // arrangement editPageFieldsUpdateTheDraft uses for the same+ // overwrite; step-counted, not wall-clock, for the same reason.+ var steps = 0+ while (steps++ < 600) {+ vm.allContactsState.value = listOf(fixtureContact())+ if (rule.onAllNodesWithText("Aisha", substring = true).fetchSemanticsNodes().isNotEmpty() &&+ vm.allContactsState.value.firstOrNull()?.id == 7L+ ) {+ // One more pump: a sync that was already past its publish+ // point cannot erase the fixture after this, and a sync+ // still to publish breaks the check below and reseeds.+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ if (vm.allContactsState.value.firstOrNull()?.details?.notes?.firstOrNull()?.content == "hello note") break+ }+ try { Thread.sleep(25) } catch (_: InterruptedException) { }+ } rule.waitUntil(10_000) { rule.onAllNodesWithText("Aisha", substring = true).fetchSemanticsNodes().isNotEmpty() }- val scroller = rule.onNode(hasScrollAction())- scroller.performScrollToNode(hasText("(415) 555-0107", substring = true))- rule.onNodeWithText("(415) 555-0107", substring = true).assertExists()- scroller.performScrollToNode(hasText("[email protected]", substring = true))- rule.onNodeWithText("[email protected]", substring = true).assertExists()- scroller.performScrollToNode(hasText("hello note", substring = true))- rule.onNodeWithText("hello note", substring = true).assertExists()+ // Fresh scroller per scroll, with the fixture re-seeded+ // immediately before it: the LazyColumn node captured before a+ // scroll is a different semantics node afterwards (reusing the+ // stale interaction is the other half of the CI failure), and a+ // sync publish landing between scrolls would otherwise leave+ // the page showing the provider list with no list to scroll.+ fun scrollTo(text: String) {+ vm.allContactsState.value = listOf(fixtureContact())+ rule.onNode(hasScrollAction()).performScrollToNode(hasText(text, substring = true))+ rule.onNodeWithText(text, substring = true).assertExists()+ }+ scrollTo("(415) 555-0107")+ scrollTo("[email protected]")+ scrollTo("hello note") assertEquals(0, back) }
games/arrows/build.gradle.kts
diff --git a/games/arrows/build.gradle.kts b/games/arrows/build.gradle.ktsindex 736be71673..2e98314eb4 100644--- a/games/arrows/build.gradle.kts+++ b/games/arrows/build.gradle.kts@@ -20,3 +20,24 @@ dependencies { implementation(project(":library:work")) implementation(libs.androidx.datastore.preferences) }++// Per-class JVM isolation for unit tests, overriding the shared+// non-Rust batching (forkEvery = 20 in build-logic's RustNative.kt).+// Proven pollution, not a precaution: every class here drives the+// process-wide "settings" preferences DataStore, and classes are+// batched into one JVM per Gradle fork. ArrowsViewModelTest passes+// alone on taskset -c 0-4 and passes batched with its DataStore /+// Pages / Achievements neighbours, but in the full module batch a+// neighbour's leftover store state and actors leave its board won+// or its next-level load starved (CI run 200d0e1f, and reproduced+// locally under the same taskset shape). The ViewModel test classes+// already clear every ViewModel they create; what they cannot clear+// is another class's actors in the shared sandbox. One JVM per class+// makes the store each class sees its own. (Registered in+// afterEvaluate so it runs after the convention plugin's own+// afterEvaluate batching and wins.)+afterEvaluate {+ tasks.withType<org.gradle.api.tasks.testing.Test>().configureEach {+ forkEvery = 1+ }+}
games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsViewModelTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsViewModelTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsViewModelTest.ktindex 540cb8c76f..7480ad4cf2 100644--- a/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsViewModelTest.kt+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsViewModelTest.kt@@ -1,6 +1,7 @@ package com.vayunmathur.games.arrows.platform import android.app.Application+import androidx.lifecycle.ViewModelStore import androidx.test.core.app.ApplicationProvider import androidx.work.Configuration import androidx.work.WorkManager@@ -16,8 +17,10 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import kotlinx.coroutines.test.setMain+import com.vayunmathur.testsupport.awaitWithMainIdle import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals@@ -54,6 +57,30 @@ class ArrowsViewModelTest { var mainInstalled = false } + // Every ViewModel this method creates, cleared at teardown. A+ // ViewModel built directly (not via a store) is never cleared, so+ // its viewModelScope collectors keep reacting to the shared+ // settings DataStore for the rest of the JVM's life: a stale VM+ // regenerates a board on every later level edit and can land a+ // queued store write (e.g. markHeartHintSeen from a blocked tap)+ // in the middle of a later method that reads the store expecting+ // the state it just sampled. Under CI's 5-CPU contention those+ // late writes and regenerations are what starved the wall-clock+ // awaits below past 30s and poisoned the next method's board+ // (a timed-out method also skips its own restore-to-level-1).+ // Clearing cancels viewModelScope, which is the whole leak.+ private val vmStore = ViewModelStore()+ private var vmKeys = 0++ private fun tracked(vm: ArrowsViewModel): ArrowsViewModel {+ vmStore.put("vm-${vmKeys++}", vm)+ return vm+ }++ @AfterTest fun tearDown() {+ vmStore.clear()+ }+ /** * runBlocking with a deadline, so a wedged store fails the test instead of hanging the whole * run (and the shared build slot) forever.@@ -61,17 +88,18 @@ class ArrowsViewModelTest { private fun <T> blocking(block: suspend CoroutineScope.() -> T): T = runBlocking { withTimeout(30_000) { block() } } + // Step-bounded pumped wait (shared DeterministicAwait), not a+ // wall-clock deadline: under CI contention a 30s+ // System.currentTimeMillis budget burned before the DataStore /+ // board-generation work behind the condition got a CPU slice,+ // while each pump step here is itself the looper work that lets+ // that work land, with a park so IO/Default producers run. private fun await(desc: String, cond: () -> Boolean) {- val deadline = System.currentTimeMillis() + 30_000- while (System.currentTimeMillis() < deadline) {- if (cond()) return- Thread.sleep(25)- }- assertTrue(cond(), "timed out: $desc")+ awaitWithMainIdle(desc, maxSteps = 60_000, condition = cond) } private fun loadedViewModel(): ArrowsViewModel {- val vm = ArrowsViewModel(app)+ val vm = tracked(ArrowsViewModel(app)) await("board loads") { vm.uiState.value.game != null && !vm.uiState.value.generating } return vm }@@ -160,6 +188,17 @@ class ArrowsViewModelTest { vm.tapArrow(blocked.id) assertEquals(firstEver, vm.uiState.value.showHeartHint) await("hint marked seen") { blocking { vm.dataStore.heartHintSeen.first() } }+ // Barrier through the ViewModel's own observable pipeline before+ // the second tap: a round-trip of a store-backed setting proves+ // the ViewModel's collectors have processed DataStore emissions+ // issued after the heart-hint edit above. Without it the second+ // tap can be judged against the ViewModel's cached heartHintSeen+ // from before that edit (its collector had not run yet on a+ // contended box), so the hint would be explained a second time.+ vm.setShowRoutes(false)+ await("routes off before second tap") { !vm.uiState.value.showRoutes }+ vm.setShowRoutes(true)+ await("routes on before second tap") { vm.uiState.value.showRoutes } // Restart hides it, and a later blocked tap never explains it again. vm.restartLevel()@@ -218,19 +257,19 @@ class ArrowsViewModelTest { // A won board is persisted, but the comment on onCleared's guard admits the guard is only // in-memory: after process death the progress collector replays onto an already-won board // and counts it again. Each relaunch below must leave the lifetime counter alone.- val vm = ArrowsViewModel(app)+ val vm = tracked(ArrowsViewModel(app)) await("board loads") { vm.uiState.value.game != null && !vm.uiState.value.generating } val allIds = vm.uiState.value.game!!.puzzle.pieces.map { it.id }.toSet() blocking { vm.dataStore.saveProgress(allIds, 3, daily = false) } await("board won") { vm.uiState.value.game?.isWon == true } // A second ViewModel over the same store is a fresh process for guard purposes: its // in-memory clear guard starts empty while the won board is already persisted.- val first = ArrowsViewModel(app)+ val first = tracked(ArrowsViewModel(app)) await("relaunch loads won board") { first.uiState.value.game?.isWon == true } Thread.sleep(2_000) val afterFirst = blocking { first.dataStore.boardsCleared.first() } - val second = ArrowsViewModel(app)+ val second = tracked(ArrowsViewModel(app)) await("second relaunch loads won board") { second.uiState.value.game?.isWon == true } Thread.sleep(2_000) val afterSecond = blocking { second.dataStore.boardsCleared.first() }@@ -248,7 +287,7 @@ class ArrowsViewModelTest { runCatching { WorkManager.initialize(app, Configuration.Builder().build()) }- val vm = ArrowsViewModel(app)+ val vm = tracked(ArrowsViewModel(app)) await("casual loads first") { vm.uiState.value.game != null && !vm.uiState.value.generating } // Keep the WhileSubscribed reminder flows subscribed while we change them.
games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/PagesTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/PagesTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/PagesTest.ktindex 8046a95dcd..e670949612 100644--- a/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/PagesTest.kt+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/PagesTest.kt@@ -6,6 +6,7 @@ import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick+import androidx.lifecycle.ViewModelStore import androidx.test.core.app.ApplicationProvider import com.vayunmathur.games.arrows.Navigation import com.vayunmathur.games.arrows.R@@ -15,13 +16,14 @@ import com.vayunmathur.library.util.NavBackStack import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.setMain+import com.vayunmathur.testsupport.awaitWithMainIdle import org.junit.Rule import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals-import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) @RunWith(RobolectricTestRunner::class)@@ -50,17 +52,29 @@ class PagesTest { var mainInstalled = false } + // Cleared at teardown for the same reason as ArrowsViewModelTest:+ // a directly-built ViewModel is never cleared, so its collectors+ // keep reacting to (and writing) the shared settings DataStore in+ // later classes sharing this JVM/sandbox. Clearing cancels+ // viewModelScope, which is the whole leak; Main stays installed+ // per the note in setUp, so clearing reintroduces no setMain race.+ private val vmStore = ViewModelStore()+ private var vmKeys = 0++ @AfterTest fun tearDown() {+ vmStore.clear()+ }++ // Step-bounded pumped wait (shared DeterministicAwait), not a+ // wall-clock deadline that CI contention can burn before the+ // work behind the condition runs. private fun await(desc: String, cond: () -> Boolean) {- val deadline = System.currentTimeMillis() + 30_000- while (System.currentTimeMillis() < deadline) {- if (cond()) return- Thread.sleep(25)- }- assertTrue(cond(), "timed out: $desc")+ awaitWithMainIdle(desc, maxSteps = 60_000, condition = cond) } private fun loadedVm(): ArrowsViewModel { val vm = ArrowsViewModel(app)+ vmStore.put("vm-${vmKeys++}", vm) await("vm loads") { vm.uiState.value.game != null && !vm.uiState.value.generating } return vm }
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/ViewModelDeepTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/ViewModelDeepTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/ViewModelDeepTest.ktindex 3a0b0b0122..af1afb4f9b 100644--- a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/ViewModelDeepTest.kt+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/ViewModelDeepTest.kt@@ -2,8 +2,10 @@ package com.vayunmathur.games.wordmaker.platform import android.app.Application import android.content.Context+import androidx.lifecycle.ViewModelStore import androidx.test.core.app.ApplicationProvider import com.vayunmathur.games.wordmaker.data.Difficulty+import com.vayunmathur.testsupport.awaitWithMainIdle import com.vayunmathur.games.wordmaker.data.GameMode import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -28,6 +30,18 @@ class ViewModelDeepTest { private val context: Context get() = ApplicationProvider.getApplicationContext() private val scope = CoroutineScope(Dispatchers.Unconfined) + // ViewModels created by this class, cleared at teardown: a+ // directly-built ViewModel is never cleared, so its viewModelScope+ // collectors keep reacting to the shared settings DataStore in+ // later methods/classes in this JVM/sandbox (the wordmaker+ // pollution proven under load — see GameLoaderPageDeepTest).+ private val vmStore = ViewModelStore()+ private var vmKeys = 0+ private fun tracked(vm: WordMakerViewModel): WordMakerViewModel {+ vmStore.put("vm-${vmKeys++}", vm)+ return vm+ }+ @BeforeTest fun setUp() { retryingMain { Dispatchers.setMain(Dispatchers.Unconfined) } runCatching {@@ -36,12 +50,13 @@ class ViewModelDeepTest { } @AfterTest fun tearDown() {+ vmStore.clear() scope.cancel() retryingMain { Dispatchers.resetMain() } } private fun vm(): WordMakerViewModel {- val vm = WordMakerViewModel(ApplicationProvider.getApplicationContext<Application>())+ val vm = tracked(WordMakerViewModel(ApplicationProvider.getApplicationContext<Application>())) scope.launch { vm.crosswordData.collect {} } scope.launch { vm.foundWords.collect {} } scope.launch { vm.bonusWords.collect {} }@@ -74,14 +89,9 @@ class ViewModelDeepTest { if (attempts > 50) action() } private fun pollUntil(deadlineMs: Long = 30000, cond: () -> Boolean) {- // Step-counted, not wall-clock: Robolectric's substituted- // currentTimeMillis only advances when its scheduler runs, so a- // deadline poll could spin forever (the CI build timeout) if the- // condition it waited for never landed, or expire instantly.- // Each step sleeps real time, bounding the wait in real time.- var steps = (deadlineMs / 50).toInt()- while (steps-- > 0 && !cond()) Thread.sleep(50)- assertTrue(cond(), "condition not met within ${deadlineMs}ms")+ // Step-bounded pumped wait (shared DeterministicAwait), not a+ // sleep-poll whose steps are real seconds under CPU contention.+ awaitWithMainIdle("condition not met within ${deadlineMs}ms (step-bounded)", maxSteps = 60_000, condition = cond) } private fun waitFor(deadlineMs: Long = 8000, cond: () -> Boolean): Boolean {
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModelTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModelTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModelTest.ktindex 21e01933a3..c1de4cc043 100644--- a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModelTest.kt+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModelTest.kt@@ -2,8 +2,10 @@ package com.vayunmathur.games.wordmaker.platform import android.app.Application import android.content.Context+import androidx.lifecycle.ViewModelStore import androidx.test.core.app.ApplicationProvider import com.vayunmathur.games.wordmaker.data.CrosswordData+import com.vayunmathur.testsupport.awaitWithMainIdle import com.vayunmathur.games.wordmaker.data.Difficulty import com.vayunmathur.games.wordmaker.data.GameMode import com.vayunmathur.games.wordmaker.data.WheelSpacing@@ -33,6 +35,18 @@ class WordMakerViewModelTest { private val context: Context get() = ApplicationProvider.getApplicationContext() private val collectorScope = CoroutineScope(Dispatchers.Unconfined) + // ViewModels created by this class, cleared at teardown: a+ // directly-built ViewModel is never cleared, so its viewModelScope+ // collectors keep reacting to the shared settings DataStore in+ // later methods/classes in this JVM/sandbox (the wordmaker+ // pollution proven under load — see GameLoaderPageDeepTest).+ private val vmStore = ViewModelStore()+ private var vmKeys = 0+ private fun tracked(vm: WordMakerViewModel): WordMakerViewModel {+ vmStore.put("vm-${vmKeys++}", vm)+ return vm+ }+ @BeforeTest fun setUp() { retryingMain { Dispatchers.setMain(Dispatchers.Unconfined) } // DailyPuzzleReminder reschedules through WorkManager, which Robolectric does not init.@@ -40,11 +54,11 @@ class WordMakerViewModelTest { androidx.work.WorkManager.initialize(context, androidx.work.Configuration.Builder().build()) } }- @AfterTest fun tearDown() { collectorScope.cancel(); retryingMain { Dispatchers.resetMain() } }+ @AfterTest fun tearDown() { vmStore.clear(); collectorScope.cancel(); retryingMain { Dispatchers.resetMain() } } /** StateIn(WhileSubscribed) flows only compute while collected, as the UI collects them. */ private fun vm(): WordMakerViewModel {- val vm = WordMakerViewModel(ApplicationProvider.getApplicationContext<Application>())+ val vm = tracked(WordMakerViewModel(ApplicationProvider.getApplicationContext<Application>())) with(collectorScope) { launch { vm.crosswordData.collect {} } launch { vm.foundWords.collect {} }@@ -73,14 +87,9 @@ class WordMakerViewModelTest { if (attempts > 50) action() } private fun pollUntil(deadlineMs: Long = 15000, cond: () -> Boolean) {- // Step-counted, not wall-clock: Robolectric's substituted- // currentTimeMillis only advances when its scheduler runs, so a- // deadline poll could spin forever (the CI build timeout) if the- // condition it waited for never landed, or expire instantly.- // Each step sleeps real time, bounding the wait in real time.- var steps = (deadlineMs / 50).toInt()- while (steps-- > 0 && !cond()) Thread.sleep(50)- assertTrue(cond())+ // Step-bounded pumped wait (shared DeterministicAwait), not a+ // sleep-poll whose steps are real seconds under CPU contention.+ awaitWithMainIdle("condition not met within ${deadlineMs}ms (step-bounded)", maxSteps = 60_000, condition = cond) } @Test fun loadsFirstCasualLevelFromAssets() {
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/GameLoaderPageDeepTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/GameLoaderPageDeepTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/GameLoaderPageDeepTest.ktindex 43f2b28284..a30bfc4125 100644--- a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/GameLoaderPageDeepTest.kt+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/GameLoaderPageDeepTest.kt@@ -10,12 +10,14 @@ import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollToNode+import androidx.lifecycle.ViewModelStore import androidx.test.core.app.ApplicationProvider import com.vayunmathur.games.wordmaker.Route import com.vayunmathur.games.wordmaker.data.GameMode import com.vayunmathur.games.wordmaker.platform.WordMakerAchievementsManager import com.vayunmathur.games.wordmaker.platform.WordMakerViewModel import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.testsupport.awaitWithMainIdle import com.vayunmathur.library.util.rememberNavBackStack import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -51,13 +53,30 @@ class GameLoaderPageDeepTest { } } + // Every ViewModel this method creates, cleared at teardown. A+ // directly-built ViewModel is never cleared, so its viewModelScope+ // collectors keep reacting to the shared settings DataStore for the+ // rest of the JVM/sandbox: every stale VM regenerates a board on+ // Dispatchers.Default for each later level/mode edit and can land+ // queued DataStore writes in a later class. Proven under load:+ // this class alone passed 11/11 with office+maps tests running on+ // taskset -c 0-4, while the full wordmaker suite under the same+ // load failed 6 of these methods with the CI pollUntil signature —+ // the neighbours are the pollution. Clearing cancels+ // viewModelScope, which is the whole leak, and runs before+ // resetMain so no stale flow can race that either.+ private val vmStore = ViewModelStore()+ private var vmKeys = 0+ @AfterTest fun tearDown() {+ vmStore.clear() scope.cancel() retryingMain { Dispatchers.resetMain() } } private fun vm(): WordMakerViewModel { val vm = WordMakerViewModel(ApplicationProvider.getApplicationContext<Application>())+ vmStore.put("vm-${vmKeys++}", vm) scope.launch { vm.crosswordData.collect {} } scope.launch { vm.foundWords.collect {} } scope.launch { vm.bonusWords.collect {} }@@ -90,14 +109,15 @@ class GameLoaderPageDeepTest { if (attempts > 50) action() } private fun pollUntil(deadlineMs: Long = 30000, cond: () -> Boolean) {- // Step-counted, not wall-clock: Robolectric's substituted- // currentTimeMillis only advances when its scheduler runs, so a- // deadline poll could spin forever (the CI build timeout) if the- // condition it waited for never landed, or expire instantly.- // Each step sleeps real time, bounding the wait in real time.- var steps = (deadlineMs / 50).toInt()- while (steps-- > 0 && !cond()) Thread.sleep(50)- assertTrue(cond(), "condition not met within ${deadlineMs}ms")+ // Step-bounded pumped wait (shared DeterministicAwait): the old+ // sleep-poll's 600 steps were 30 real seconds whether or not the+ // DataStore/Default work behind the condition got a CPU slice,+ // which is exactly how CI (and the local load reproduction)+ // expired it. Each pumped step idles the main looper and parks+ // briefly so IO/Default producers run; the bound is work+ // steps, not seconds. [deadlineMs] is kept at call sites as the+ // nominal budget and used in the failure description only.+ awaitWithMainIdle("condition not met within ${deadlineMs}ms (step-bounded)", maxSteps = 60_000, condition = cond) } private fun resetToCasual(vm: WordMakerViewModel) {
games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordMakerComposeTest.kt
diff --git a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordMakerComposeTest.kt b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordMakerComposeTest.ktindex d4c38c80d1..2b1d3c3bdb 100644--- a/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordMakerComposeTest.kt+++ b/games/wordmaker/src/test/java/com/vayunmathur/games/wordmaker/ui/WordMakerComposeTest.kt@@ -19,8 +19,10 @@ import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.dp+import androidx.lifecycle.ViewModelStore import androidx.test.core.app.ApplicationProvider import com.vayunmathur.games.wordmaker.data.CrosswordData+import com.vayunmathur.testsupport.awaitWithMainIdle import com.vayunmathur.games.wordmaker.data.Difficulty import com.vayunmathur.games.wordmaker.data.GameMode import com.vayunmathur.games.wordmaker.data.WheelSpacing@@ -68,6 +70,18 @@ class WordMakerComposeTest { private val context: Context get() = ApplicationProvider.getApplicationContext() private val scope = CoroutineScope(Dispatchers.Unconfined) + // ViewModels created by this class, cleared at teardown: a+ // directly-built ViewModel is never cleared, so its viewModelScope+ // collectors keep reacting to the shared settings DataStore in+ // later methods/classes in this JVM/sandbox (the wordmaker+ // pollution proven under load — see GameLoaderPageDeepTest).+ private val vmStore = ViewModelStore()+ private var vmKeys = 0+ private fun tracked(vm: WordMakerViewModel): WordMakerViewModel {+ vmStore.put("vm-${vmKeys++}", vm)+ return vm+ }+ @BeforeTest fun setUp() { retryingMain { Dispatchers.setMain(Dispatchers.Unconfined) } // DailyPuzzleReminder reschedules through WorkManager, which Robolectric does not init.@@ -75,7 +89,7 @@ class WordMakerComposeTest { androidx.work.WorkManager.initialize(context, androidx.work.Configuration.Builder().build()) } }- @AfterTest fun tearDown() { scope.cancel(); retryingMain { Dispatchers.resetMain() } }+ @AfterTest fun tearDown() { vmStore.clear(); scope.cancel(); retryingMain { Dispatchers.resetMain() } } /** set/resetMain throw if a background coroutine is using Main at that instant (a stale ViewModel's flow resuming); retry briefly, as the nonogram suite does. */ private fun retryingMain(action: () -> Unit) {@@ -449,7 +463,7 @@ class WordMakerComposeTest { } @Test fun gamePageWithRealViewModel() { val app = ApplicationProvider.getApplicationContext<Application>()- val vm = WordMakerViewModel(app)+ val vm = tracked(WordMakerViewModel(app)) scope.launch { vm.crosswordData.collect {} } // wait for the casual level to load (step-counted: the // substituted clock can freeze, see pollUntil below)@@ -473,6 +487,18 @@ class WordMakerNavAndDragTest { @get:Rule val rule = createComposeRule() private val context: Context get() = ApplicationProvider.getApplicationContext() private val scope = CoroutineScope(Dispatchers.Unconfined)+ // ViewModels created by this class, cleared at teardown: a+ // directly-built ViewModel is never cleared, so its viewModelScope+ // collectors keep reacting to the shared settings DataStore in+ // later methods/classes in this JVM/sandbox (the wordmaker+ // pollution proven under load — see GameLoaderPageDeepTest).+ private val vmStore = ViewModelStore()+ private var vmKeys = 0+ private fun tracked(vm: WordMakerViewModel): WordMakerViewModel {+ vmStore.put("vm-${vmKeys++}", vm)+ return vm+ }+ @BeforeTest fun setUp() { retryingMain { Dispatchers.setMain(Dispatchers.Unconfined) } // DailyPuzzleReminder reschedules through WorkManager, which Robolectric does not init.@@ -480,10 +506,10 @@ class WordMakerNavAndDragTest { androidx.work.WorkManager.initialize(context, androidx.work.Configuration.Builder().build()) } }- @AfterTest fun tearDown() { scope.cancel(); retryingMain { Dispatchers.resetMain() } }+ @AfterTest fun tearDown() { vmStore.clear(); scope.cancel(); retryingMain { Dispatchers.resetMain() } } private fun vm(): WordMakerViewModel {- val vm = WordMakerViewModel(ApplicationProvider.getApplicationContext<Application>())+ val vm = tracked(WordMakerViewModel(ApplicationProvider.getApplicationContext<Application>())) scope.launch { vm.crosswordData.collect {} } scope.launch { vm.gameMode.collect {} } scope.launch { vm.foundWords.collect {} }@@ -499,14 +525,9 @@ class WordMakerNavAndDragTest { if (attempts > 50) action() } private fun pollUntil(deadlineMs: Long = 20000, cond: () -> Boolean) {- // Step-counted, not wall-clock: Robolectric's substituted- // currentTimeMillis only advances when its scheduler runs, so a- // deadline poll could spin forever (the CI build timeout) if the- // condition it waited for never landed, or expire instantly.- // Each step sleeps real time, bounding the wait in real time.- var steps = (deadlineMs / 50).toInt()- while (steps-- > 0 && !cond()) Thread.sleep(50)- assertTrue(cond())+ // Step-bounded pumped wait (shared DeterministicAwait), not a+ // sleep-poll whose steps are real seconds under CPU contention.+ awaitWithMainIdle("condition not met within ${deadlineMs}ms (step-bounded)", maxSteps = 60_000, condition = cond) } @Test fun navigationRendersGameThenLobby() {