Modern Apps git

← Modern-Apps.git

nonogram: persist off the main thread and harden the VM tests (#ux-audit)

Commit
7dcb6208f1ac17ed3ac64fb9ff17c55666f9a338
Author
Vayun Mathur <[email protected]>
When
2026-11-13 08:20 UTC (23 days ago)
Parents
a41f522
Follow-up to the optimistic-state change (finding 5) and its tests,
from running the module's unit tests in the toolchain container.

Symptom: NonogramViewModelTest failed winningBoardRecordsCompletionOnce
and then hung the whole test task: every later test blocked forever in
runBlocking on a DataStore edit, so testDevUnitTest never finished.

Root cause:
- Board snapshots and the Next-level saveLevel were launched on
  viewModelScope's Main dispatcher. DataStore runs each edit's
  transform in the caller's context, so an edit still in flight when a
  test calls Dispatchers.resetMain() waits on the paused Robolectric
  main looper - and every later edit queues behind it. (In the app the
  same writes simply bounced through the main thread for no reason.)
- winningDailyRecordsDailyWin ended before the streak write landed;
  that write reloads every live ViewModel, whose daily-day edit then
  hit the same reset window.
- winningBoardRecordsCompletionOnce wins level 1, but the new Next
  tests win level 1 first and the store (which outlives each test)
  had already banked that win key, so the count never moved.
- The marks collector and commit() did read-modify-write on the UI
  state; with the tests' Unconfined Main the collector can run on a
  DataStore thread concurrently with a tap.

Fix:
- persist() and nextLevel()'s saveLevel run on Dispatchers.IO (still
  serialised and ordered by the write Mutex). The board is already on
  screen, so nothing waits for them.
- The collector and commit() update the UI state with
  MutableStateFlow.update (compare-and-set), so a move committed while
  an emission is in flight is never overwritten by an older stored
  board.
- Tests: bounded blocking{} helper (15s) instead of bare runBlocking so
  a wedged store fails fast instead of hanging CI; the completion test
  uses a level no other test wins; the daily test waits for the streak
  to land; the await loop no longer trips detekt's EmptyElseBlock
  (the one detekt error the module had on main).
- Document BoardZoom's companion (detekt UndocumentedPublicClass).

User-visible effect: none beyond board writes no longer touching the
main thread.

Verification: NonogramViewModelTest experiments in the container
isolated the wedge to the in-flight edit at resetMain (per-test write
probes before/after reset); full module test/lint/detekt run on this
commit.

Diff

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 03bc2f8f87..c12532f267 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@@ -30,6 +30,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock@@ -170,11 +171,9 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application             val stale = daily && storedDay != day             (if (stale) StoredBoard() else board) to (lastCompleted == day)         }.collectLatest { (board, dailyDone) ->-            val previous = _uiState.value.game             // Undo history belongs to one board; a different puzzle, level or mode starts afresh.-            if (previous?.isBoardFor(session, puzzle) != true) undoStack.clear()-            val onScreen = previous?.takeIf { hasPendingWrites && it.isBoardFor(session, puzzle) }-            val game = onScreen ?: NonogramGameState(+            if (_uiState.value.game?.isBoardFor(session, puzzle) != true) undoStack.clear()+            val stored = NonogramGameState(                 puzzle = puzzle,                 filled = board.filled,                 crossed = board.crossed,@@ -183,12 +182,13 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application                 mode = session.mode,                 level = session.level,             )-            _uiState.value = _uiState.value.copy(-                game = game,-                generating = false,-                dailyDone = dailyDone,-                canUndo = canUndo(game),-            )+            var game = stored+            // Compare-and-set, so a move committed while this emission was in flight is never+            // overwritten by the older stored board: the retry sees it, and its pending write.+            _uiState.update { state ->+                game = state.game?.takeIf { hasPendingWrites && it.isBoardFor(session, puzzle) } ?: stored+                state.copy(game = game, generating = false, dailyDone = dailyDone, canUndo = canUndo(game))+            }             if (game.isWon) onWin(game, daily, day)         }     }@@ -222,7 +222,7 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application     private fun commit(next: NonogramGameState) {         val previous = _uiState.value.game ?: return         if (next == previous) return-        _uiState.value = _uiState.value.copy(game = next, canUndo = canUndo(next))+        _uiState.update { it.copy(game = next, canUndo = canUndo(next)) }         persist(next)         if (next.isWon) onWin(next, next.mode == GameMode.DAILY, boardDay)     }@@ -232,7 +232,9 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application         val board = StoredBoard(game.filled, game.crossed, game.revealedBlanks, game.hearts)         val daily = game.mode == GameMode.DAILY         val day = boardDay-        viewModelScope.launch {+        // Off the main thread: the board is already on screen, so nothing waits for this, and the+        // store's write transform then never needs the main looper.+        viewModelScope.launch(Dispatchers.IO) {             writeLock.withLock {                 if (ticket == requestedWrite.get()) dataStore.saveBoard(board, daily, game.level, day)             }@@ -349,7 +351,7 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application         val target = game.level + 1         _uiState.value = state.copy(generating = true)         // Behind the write lock so the winning move's snapshot lands first.-        viewModelScope.launch { writeLock.withLock { dataStore.saveLevel(target) } }+        viewModelScope.launch(Dispatchers.IO) { writeLock.withLock { dataStore.saveLevel(target) } }     }      /** Clears every mark and restores the hearts, on screen at once and on disk behind it. */
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometry.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometry.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometry.ktindex b2da378e42..d6fc8f5345 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometry.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometry.kt@@ -44,7 +44,9 @@ data class BoardZoom(         return BoardZoom(s, offsetX.coerceIn(least, 0f), offsetY.coerceIn(least, 0f))     } +    /** Holds [Identity]. */     companion object {+        /** Unzoomed: the whole grid, exactly filling its viewport. */         val Identity = BoardZoom()     } }
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 83294c68f0..6e91d711aa 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@@ -10,6 +10,7 @@ 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@@ -31,12 +32,19 @@ class NonogramViewModelTest {      private fun await(desc: String, cond: () -> Boolean) {         val deadline = System.currentTimeMillis() + 20_000-        while (System.currentTimeMillis() < deadline) { if (cond()) return; Thread.sleep(25) }+        while (System.currentTimeMillis() < deadline && !cond()) Thread.sleep(25)         assertTrue(cond(), "timed out: $desc")     }-    private fun loadedVm(): NonogramViewModel {++    /**+     * 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.+     */+    private fun <T> blocking(block: suspend () -> T): T = runBlocking { withTimeout(15_000) { block() } }++    private fun loadedVm(level: Int = 1): NonogramViewModel {         val vm = NonogramViewModel(app)-        runBlocking { vm.dataStore.saveLevel(1); vm.dataStore.setGameMode(GameMode.CASUAL); vm.dataStore.setMarkMode(MarkMode.FILL) }+        blocking { vm.dataStore.saveLevel(level); vm.dataStore.setGameMode(GameMode.CASUAL); vm.dataStore.setMarkMode(MarkMode.FILL) }         await("game loads") { vm.uiState.value.game != null && !vm.uiState.value.generating }         return vm     }@@ -92,8 +100,8 @@ class NonogramViewModelTest {         assertFalse(note in vm.uiState.value.game!!.crossed, "second quick tap must clear the X, not add it again")         // And the store catches up to what is on screen.         await("persisted") {-            runBlocking { vm.dataStore.filledCells.first() } == setOf(correct) &&-                runBlocking { vm.dataStore.crossedCells.first() }.isEmpty()+            blocking { vm.dataStore.filledCells.first() } == setOf(correct) &&+                blocking { vm.dataStore.crossedCells.first() }.isEmpty()         }         assertTrue(correct in vm.uiState.value.game!!.filled)         assertFalse(note in vm.uiState.value.game!!.crossed)@@ -106,7 +114,7 @@ class NonogramViewModelTest {         val target = picture.take(picture.size - 1)         for (i in target) vm.tapCell(i)         assertEquals(target.toSet(), vm.uiState.value.game!!.filled)-        await("last snapshot wins") { runBlocking { vm.dataStore.filledCells.first() } == target.toSet() }+        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)         await("reload") { again.uiState.value.game?.filled == target.toSet() }@@ -163,7 +171,7 @@ class NonogramViewModelTest {         vm.undo() // empty: no-op         assertEquals(s, vm.uiState.value.game)         // Undo is persisted like any move.-        await("undo persisted") { runBlocking { vm.dataStore.filledCells.first() }.isEmpty() }+        await("undo persisted") { blocking { vm.dataStore.filledCells.first() }.isEmpty() }         // Restart wipes the history.         vm.crossCell(correct)         assertTrue(vm.uiState.value.canUndo)@@ -193,7 +201,7 @@ class NonogramViewModelTest {         vm.nextLevel()         Thread.sleep(200)         assertEquals(1, vm.uiState.value.level, "Next only exists on a solved board")-        assertEquals(1, runBlocking { vm.dataStore.currentLevel.first() })+        assertEquals(1, blocking { vm.dataStore.currentLevel.first() })     }      @Test fun doubleTappingNextAdvancesExactlyOneLevel() {@@ -210,7 +218,7 @@ class NonogramViewModelTest {         // A late tap that lands on the fresh, unsolved board is ignored too.         vm.nextLevel()         Thread.sleep(200)-        assertEquals(2, runBlocking { vm.dataStore.currentLevel.first() })+        assertEquals(2, blocking { vm.dataStore.currentLevel.first() })         assertEquals(2, vm.uiState.value.level)     } @@ -229,12 +237,14 @@ class NonogramViewModelTest {     }      @Test fun winningBoardRecordsCompletionOnce() {-        val vm = loadedVm()-        val before = runBlocking { vm.dataStore.puzzlesCompleted.first() }+        // A level no other test wins: win keys are banked in the store, which outlives each test,+        // so reusing level 1 would find this win already counted.+        val vm = loadedVm(level = 7)+        val before = blocking { vm.dataStore.puzzlesCompleted.first() }         val g = vm.uiState.value.game!!         for (i in g.puzzle.solution.indices.filter { g.puzzle.solution[it] }) vm.tapCell(i)         await("won") { vm.uiState.value.game?.isWon == true }-        await("completion recorded") { runBlocking { vm.dataStore.puzzlesCompleted.first() } == before + 1 }+        await("completion recorded") { blocking { vm.dataStore.puzzlesCompleted.first() } == before + 1 }         // Taps after game over are ignored.         val hearts = vm.uiState.value.game!!.hearts         vm.tapCell(g.puzzle.solution.indices.first { !g.puzzle.solution[it] })@@ -245,11 +255,17 @@ class NonogramViewModelTest {         val vm = loadedVm()         vm.setGameMode(GameMode.DAILY)         await("daily ready") { vm.uiState.value.mode == GameMode.DAILY && vm.uiState.value.game != null && !vm.uiState.value.generating }-        val before = runBlocking { vm.dataStore.puzzlesCompleted.first() }+        val before = blocking { vm.dataStore.puzzlesCompleted.first() }         val g = vm.uiState.value.game!!         for (i in g.puzzle.solution.indices.filter { g.puzzle.solution[it] }) vm.tapCell(i)         await("daily won") { vm.uiState.value.game?.isWon == true }-        await("daily completion recorded") { runBlocking { vm.dataStore.puzzlesCompleted.first() } > before }+        await("daily completion recorded") { blocking { vm.dataStore.puzzlesCompleted.first() } > before }+        // Let the rest of the win land before the test ends: the streak write reloads every live+        // ViewModel, and a store edit still in flight when Dispatchers.Main is reset would wait on+        // the paused Robolectric main looper and wedge the store for the following tests.+        await("daily streak recorded") {+            vm.uiState.value.dailyDone && vm.uiState.value.dailyStreak >= 1 && !vm.uiState.value.generating+        }     }      @Test fun retryGenerationReloadsBoard() {