nonogram: fix load starvation, generator cancellation, test waits (#tests)
- Commit
d0e6a0a75754d1c75b75476af637793f7e76baf2- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 18:25 UTC (19 days ago)
- Parents
d772499
Four CI failures (winningBoardRecordsCompletionOnce, achievementsManagerBackfillDoesNotCrash, retryGenerationReloadsBoard, settingsPageWithRealViewModelRenders) plus sibling flakes in this class share roots in how the ViewModel's session collector interacts with the store: Product: the session combine had no distinctUntilChanged, and its inputs are maps over the whole preferences snapshot, so EVERY store write — each board mark a tap persists — made collectLatest cancel the in-flight load and restart it. With repeated writes the current load could be cancelled continuously and the board never appeared. The combine now dedupes identical sessions. The puzzle generator also never checked cancellation (pure CPU, no suspension points), so a cancelled load kept burning a core to the end of its search and starved its replacement; generate/generateSeeded now take a shouldContinue predicate wired to the collecting coroutine. Tests: neither test class initialized WorkManager, whose getInstance throw (from the reminder-reschedule path) landed inside DataStore writes and killed the shared store's write actor for the rest of the JVM — boards then never loaded or persisted in later tests. Both classes now initialize it in setUp (the sibling-suite pattern). loadedVm seeds level/mode/ mark in the store BEFORE creating the ViewModel (writing them afterwards restarted generation up to three times via collectLatest), ViewModels are drained with barrier edits and cleared between tests so stale VMs cannot all regenerate at once on a later mode write, the achievements backfill awaits its IO unlocks, and the double-tap test no longer asserts the transient `generating` flag (the load it starts can legitimately finish first; refusal is proven by the level assertions). The awaits themselves were the last trap, in two layers. Robolectric virtualises every clock/park/sleep on the test thread, so a step cannot literally wait: steps burn a fixed CPU loop instead (slower cores just wait longer). And the poll reads went through runBlocking+withTimeout, whose delay runs on the same substituted clock and fires instantly whenever a read needs an async DataStore round-trip — polls could never observe a landed write. blocking() drops the timeout, await asserts on the value it already observed rather than re-reading at the boundary (a flip or a failing second read failed waits that had succeeded, "timed out after 1 steps"), and the undo-persist condition treats a transiently failed read as "not landed yet". Verified: full combined TZ=UTC 4-worker runs green three consecutive times, plus a TZ=America/New_York spot check.
Diff
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.ktindex 63d7827ed7..1f08908ef5 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramGenerator.kt@@ -27,8 +27,16 @@ object NonogramGenerator { rng: Random, fillRatio: Double = DEFAULT_FILL_RATIO, attempts: Int = DEFAULT_ATTEMPTS,+ shouldContinue: () -> Boolean = { true }, ): NonogramPuzzle? { repeat(attempts) {+ // Cooperative cancellation: this loop is pure CPU with no+ // suspension points, so a cancelled caller (collectLatest+ // dropping a stale load when the level/mode flips) would+ // otherwise keep burning a core to the end of the search and+ // starve its own replacement — on a 4-core box a handful of+ // zombie searches can stall the live one past any timeout.+ if (!shouldContinue()) return null val candidate = paint(size, rng, fillRatio) // An all-blank grid is technically line-solvable and completely pointless to play. if (candidate.none { it }) return@repeat@@ -44,9 +52,16 @@ object NonogramGenerator { * Every seed is a pure function of [seed], so the same level number always yields the same * puzzle however many rounds it takes — that is what lets saved progress stay valid. */- fun generateSeeded(size: Int, seed: Long, rounds: Int = DEFAULT_ROUNDS): NonogramPuzzle? {+ fun generateSeeded(+ size: Int,+ seed: Long,+ rounds: Int = DEFAULT_ROUNDS,+ shouldContinue: () -> Boolean = { true },+ ): NonogramPuzzle? { for (round in 0 until rounds) {- generate(size, Random(seed + round * SEED_STRIDE))?.let { return it }+ if (!shouldContinue()) return null+ generate(size, Random(seed + round * SEED_STRIDE), shouldContinue = shouldContinue)+ ?.let { return it } } return null }
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.ktindex be49e7116f..fa4a6d72e9 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt@@ -23,12 +23,14 @@ import com.vayunmathur.library.util.DailyStreakReporter import com.vayunmathur.library.work.DailyPuzzleReminder import com.vayunmathur.library.work.DailyReminderSettings import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.isActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch@@ -96,6 +98,15 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application dailyStore.currentStreak, _generationAttempt, ) { mode, level, markMode, streak, attempt -> Session(mode, level, markMode, streak, attempt) }+ // distinctUntilChanged is load-bearing, not an optimisation:+ // the upstream flows are maps over the whole preferences+ // snapshot, so EVERY store write (each board mark a tap+ // persists!) re-emits them. Without this, each write made+ // collectLatest cancel the in-flight load and start it+ // again — with several ViewModels alive (or repeated writes+ // in production) the current load could be cancelled+ // continuously and the board never appeared.+ .distinctUntilChanged() .collectLatest { session -> load(session) } } }@@ -136,7 +147,7 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application NonogramGenerator.DEFAULT_ROUNDS + session.attempt * NonogramGenerator.RETRY_EXTRA_ROUNDS ).coerceAtMost(MAX_GENERATION_ROUNDS)- cached ?: NonogramGenerator.generateSeeded(size, seed, rounds)+ cached ?: NonogramGenerator.generateSeeded(size, seed, rounds) { coroutineContext.isActive } } if (puzzle == null) {
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.ktindex 0b3aa1f7e4..22c9be77f7 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt@@ -11,7 +11,6 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking-import kotlinx.coroutines.withTimeout import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.runner.RunWith@@ -28,7 +27,26 @@ import kotlin.test.assertTrue @RunWith(RobolectricTestRunner::class) class NonogramViewModelTest { private val app get() = ApplicationProvider.getApplicationContext<Application>()- @BeforeTest fun setUp() { retrying { Dispatchers.setMain(Dispatchers.Unconfined) } }+ private val vmStore = androidx.lifecycle.ViewModelStore()+ @BeforeTest fun setUp() {+ retrying { Dispatchers.setMain(Dispatchers.Unconfined) }+ // The reminder path (DailyPuzzleReminder rescheduling, reached+ // from the ViewModel and the achievements/daily machinery) calls+ // WorkManager.getInstance, which throws when uninitialized — and+ // that throw lands inside a DataStore write, killing the shared+ // store's write actor for every later test in this JVM (boards+ // then never load or persist: the rotating "game loads" /+ // "persisted" timeouts). Sibling suites initialize it up front.+ runCatching {+ androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+ }+ }++ /** Registers [vm] so tearDown can cancel its viewModelScope (see below). */+ private fun track(vm: NonogramViewModel): NonogramViewModel {+ vmStore.put("vm${System.identityHashCode(vm)}", vm)+ return vm+ } /** * Drains the store before Main is reset.@@ -40,6 +58,17 @@ class NonogramViewModelTest { */ @AfterTest fun tearDown() { val store = com.vayunmathur.games.nonogram.data.NonogramDataStore(app)+ // Drain, then clear, then drain again. Uncleared ViewModels stay+ // subscribed to the shared store, so a later test's mode/level+ // write makes EVERY stale VM regenerate a (possibly daily-sized)+ // puzzle at once and the live VM's own generation queues behind+ // them — the "game loads" timeouts. But clearing while a board+ // or win write is still in flight can cancel that DataStore edit+ // mid-flight, so a barrier edit (which the store's actor applies+ // after everything already queued) goes first, and once more+ // after the clear for anything the cancellation shook loose.+ runCatching { blocking { store.setMarkMode(store.markMode.first()) } }+ vmStore.clear() repeat(2) { runCatching { blocking { store.setMarkMode(store.markMode.first()) } } Thread.sleep(50)@@ -56,32 +85,82 @@ class NonogramViewModelTest { private companion object { const val RETRIES = 20- const val AWAIT_STEPS = 800+ const val AWAIT_STEPS = 2000 const val AWAIT_STEP_NANOS = 25_000_000L } /**- * Polls [cond] for up to ~20s of real time.+ * Polls [cond] for up to [AWAIT_STEPS] steps. * * Counted in steps rather than against System.currentTimeMillis(): Robolectric substitutes its * own clock for test code, which can run far ahead of real time, so a clock-based deadline could- * give up within milliseconds while a background write was still landing. parkNanos is real.+ * give up within milliseconds while a background write was still landing. */- private fun await(desc: String, cond: () -> Boolean) {+ @Volatile+ private var burnSink: Long = 0++ private fun stepSleep() {+ // Robolectric virtualises every clock, park, sleep, wait and+ // scheduled delay reachable from this suite (they all return in+ // ~0.2ms, advancing the substituted clock), so an await step+ // cannot literally wait: step budgets burned out in ~0.16s of+ // real time, before slow-but-healthy IO writes landed on a+ // loaded box — hence the rotating "timed out" failures. The+ // only real time available is CPU work, so a step burns a+ // fixed dependent-arithmetic loop (~10ms on a fast core; a+ // slower CI core just makes each step longer, which is the+ // safe direction). The volatile sink keeps the JIT honest.+ var x = burnSink + 0x9E3779B97F4A7C15uL.toLong()+ for (i in 0 until 20_000_000) {+ x = x * 31 + i+ }+ burnSink = x+ }++++ private fun await(desc: String, maxSteps: Int = AWAIT_STEPS, cond: () -> Boolean) {+ // Assert on the observed value, not a fresh re-read: the old+ // shape evaluated cond() once to leave the loop and again in+ // assertTrue, and a store value that flipped between those two+ // reads (or a transiently failing second read) failed a wait+ // that had actually succeeded — "timed out after 1 steps". var steps = 0- while (steps++ < AWAIT_STEPS && !cond()) LockSupport.parkNanos(AWAIT_STEP_NANOS)- assertTrue(cond(), "timed out: $desc")+ var ok = cond()+ while (!ok && steps++ < maxSteps) {+ stepSleep()+ ok = cond()+ }+ assertTrue(ok, "timed out: $desc after $steps steps") } /**- * runBlocking with a deadline. The DataStore outlives each test, so if one test ever leaves it- * wedged the rest fail fast with a timeout instead of hanging the whole suite.+ * runBlocking for one-shot store reads. Deliberately NO withTimeout:+ * under Robolectric the timeout's delay runs on the substituted+ * clock and fires effectively instantly, so any read that needs an+ * async DataStore round-trip loses the race and the poll conditions+ * in [await] could never observe a landed write (the "undo+ * persisted" flake: every poll timed out before the emission+ * arrived). The store's write actor is kept alive by initializing+ * WorkManager in setUp, so reads complete; [await]'s step budget+ * bounds the total wait instead. */- private fun <T> blocking(block: suspend () -> T): T = runBlocking { withTimeout(15_000) { block() } }+ private fun <T> blocking(block: suspend () -> T): T = runBlocking { block() } private fun loadedVm(level: Int = 1): NonogramViewModel {- val vm = NonogramViewModel(app)- blocking { vm.dataStore.saveLevel(level); vm.dataStore.setGameMode(GameMode.CASUAL); vm.dataStore.setMarkMode(MarkMode.FILL) }+ // Seed the store BEFORE creating the ViewModel: writing level,+ // mode and mark mode after construction makes the VM's session+ // combine emit (and collectLatest cancel) up to three generation+ // passes — each a solver-checked search — before the real one,+ // which on a loaded 4-core CI box starved the 20s load await.+ // Generation itself gets a larger step budget for the same reason:+ // it is genuine CPU work whose duration scales with the box.+ val store = com.vayunmathur.games.nonogram.data.NonogramDataStore(app)+ // No withTimeout here: cancelling a DataStore edit mid-flight+ // (blocking's 15s cap under load) can strand the store's actor+ // for the next collector. These three edits are tiny; let them land.+ runBlocking { store.saveLevel(level); store.setGameMode(GameMode.CASUAL); store.setMarkMode(MarkMode.FILL) }+ val vm = track(NonogramViewModel(app)) await("game loads") { vm.uiState.value.game != null && !vm.uiState.value.generating } return vm }@@ -153,7 +232,7 @@ class NonogramViewModelTest { assertEquals(target.toSet(), vm.uiState.value.game!!.filled) await("last snapshot wins") { blocking { vm.dataStore.filledCells.first() } == target.toSet() } // A fresh ViewModel (a relaunch) loads exactly what was played.- val again = NonogramViewModel(app)+ val again = track(NonogramViewModel(app)) await("reload") { again.uiState.value.game?.filled == target.toSet() } } @@ -207,8 +286,16 @@ class NonogramViewModelTest { assertFalse(vm.uiState.value.canUndo) vm.undo() // empty: no-op assertEquals(s, vm.uiState.value.game)- // Undo is persisted like any move.- await("undo persisted") { blocking { vm.dataStore.filledCells.first() }.isEmpty() }+ // Undo is persisted like any move. A transient failure of the+ // read itself (the Robolectric environment occasionally+ // interrupts the polling runBlocking) must not abort the wait:+ // it just means "not landed yet". The final condition still+ // requires the store to actually read empty.+ await("undo persisted") {+ runCatching { blocking { vm.dataStore.filledCells.first() } }+ .getOrDefault(setOf(-1))+ .isEmpty()+ } // Restart wipes the history. vm.crossCell(correct) assertTrue(vm.uiState.value.canUndo)@@ -246,8 +333,10 @@ class NonogramViewModelTest { winBoard(vm) vm.nextLevel() // The first tap flags the load straight away, so the second is refused rather than- // reading the already-raised level counter and writing level 3.- assertTrue(vm.uiState.value.generating)+ // reading the already-raised level counter and writing level 3. (No assert on the+ // transient `generating` flag itself: the level-2 load it starts can legitimately+ // complete before this thread's next line runs, which made that assert a coin flip.+ // The refusal is what the level assertions below prove.) vm.nextLevel() await("level 2 loaded") { vm.uiState.value.game?.level == 2 && !vm.uiState.value.generating@@ -345,6 +434,12 @@ class NonogramViewModelTest { @Test fun achievementsManagerBackfillDoesNotCrash() { val vm = loadedVm() vm.achievementsManager.checkExistingAchievements()+ // checkExistingAchievements launches on Dispatchers.IO; asserting+ // its unlocks synchronously raced that work and lost under load.+ await("backfill unlocks land") {+ vm.achievementsManager.achievements.any { it.id == "first_puzzle" } &&+ vm.achievementsManager.achievements.any { it.id == "daily_streak_30" }+ } assertTrue(vm.achievementsManager.achievements.any { it.id == "first_puzzle" }) assertTrue(vm.achievementsManager.achievements.any { it.id == "daily_streak_30" }) }
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.ktindex 9f9759d945..3e0e06a3c5 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt@@ -47,6 +47,19 @@ import kotlin.test.assertTrue @RunWith(RobolectricTestRunner::class) class NonogramScreensTest { @get:Rule val rule = createComposeRule()++ @kotlin.test.BeforeTest+ fun setUp() {+ // Real-ViewModel tests reach the reminder/WorkManager path; an+ // uninitialized WorkManager throws inside DataStore writes and+ // poisons the shared store (see NonogramViewModelTest.setUp).+ runCatching {+ androidx.work.WorkManager.initialize(+ ApplicationProvider.getApplicationContext<android.app.Application>(),+ androidx.work.Configuration.Builder().build(),+ )+ }+ } private val ctx get() = ApplicationProvider.getApplicationContext<Context>() private fun str(id: Int, vararg args: Any) = if (args.isEmpty()) ctx.getString(id) else ctx.getString(id, *args) @@ -331,10 +344,24 @@ class NonogramScreensTest { @Test fun settingsPageWithRealViewModelRenders() { val vm = com.vayunmathur.games.nonogram.platform.NonogramViewModel( androidx.test.core.app.ApplicationProvider.getApplicationContext<android.app.Application>())- var backed = false- rule.setContent { SettingsPage(vm, onBack = { backed = true }) }- rule.onNodeWithText(str(UiR.string.settings)).assertExists()- assertTrue(!backed)+ try {+ var backed = false+ rule.setContent { SettingsPage(vm, onBack = { backed = true }) }+ // Await the title (pumping Robolectric's paused main looper,+ // which the real VM's collectors run on) instead of asserting+ // the first frame: under load the first composition lands+ // late and the immediate assert raced it.+ rule.waitUntil(15_000) {+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ rule.onAllNodesWithText(str(UiR.string.settings)).fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText(str(UiR.string.settings)).assertExists()+ assertTrue(!backed)+ } finally {+ // No ViewModelStore.clear(): cancelling the scope can cancel+ // an in-flight DataStore edit and strand the store (see+ // NonogramViewModelTest's tearDown note).+ } } @Test fun settingsScreenRendersAndToggles() {