Modern Apps git

← Modern-Apps.git

arrows: count each cleared board exactly once across relaunches

Commit
29d359a5eee0008239ecf2d8e77509de91306460
Author
Vayun Mathur <[email protected]>
When
2026-11-08 02:19 UTC (28 days ago)
Parents
925749c
The lifetime boards-cleared counter was guarded by an in-memory key in
the ViewModel, but the won board persists in DataStore. After process
death a fresh ViewModel replayed the progress collector onto the
still-won board and counted the same clear again, so the boards_10 /
boards_50 achievement progress drifted upward on every relaunch.

Replace the guard with an atomic check-and-set in DataStore:
recordClearedOnce(key) banks the board's key (day for daily, negated
level for casual) and bumps the counter in a single edit, returning
null for already-banked boards. onCleared now treats null as a
replayed win and does nothing, which also keeps replay-after-win via
restart/next-level uncounted, matching the old in-memory semantics.

Tests: new ArrowsViewModelTest.relaunchOnWonBoardDoesNotRecountTheClear
wins via saveProgress, then loads the won board in two fresh ViewModels
and asserts the counter is identical (failed before the fix, passes
after); recordClearedIncrements becomes recordClearedOnceBanksEachKeyOnce
covering the null-on-replay contract; achievements backfill test moves
to the new API. Full :games:arrows:testDevUnitTest suite green.

Diff

games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowsDataStore.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowsDataStore.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowsDataStore.ktindex 6a2394fb7c..9d0722bce9 100644--- a/games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowsDataStore.kt+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/data/ArrowsDataStore.kt@@ -85,12 +85,21 @@ class ArrowsDataStore(private val context: Context) {         }     } -    /** Bumps and returns the lifetime cleared count. */-    suspend fun recordCleared(): Int {-        var total = 0+    /**+     * Counts one cleared board, unless [key] was already banked.+     *+     * The check and the bump share one edit, so a won board replaying through a fresh ViewModel+     * after process death — or two collectors firing at once — cannot count it twice. Returns the+     * new total, or null if [key] was already counted.+     */+    suspend fun recordClearedOnce(key: Long): Int? {+        var total: Int? = null         context.dataStore.edit { prefs ->-            total = (prefs[CLEARED_KEY] ?: 0) + 1-            prefs[CLEARED_KEY] = total+            if (prefs[BANKED_KEY] == key) return@edit+            val next = (prefs[CLEARED_KEY] ?: 0) + 1+            prefs[BANKED_KEY] = key+            prefs[CLEARED_KEY] = next+            total = next         }         return total     }@@ -112,6 +121,8 @@ class ArrowsDataStore(private val context: Context) {      private companion object {         val LEVEL_KEY = intPreferencesKey("current_level")+        /** The clear key already banked; guards the lifetime counter across process death. */+        val BANKED_KEY = longPreferencesKey("last_banked_clear")         val REMOVED_KEY = stringSetPreferencesKey("removed_arrows")         val HEARTS_KEY = intPreferencesKey("hearts")         val GAME_MODE_KEY = stringPreferencesKey("game_mode")
games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.ktindex 00cfed9bb6..0ec9984d24 100644--- a/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/platform/ArrowsViewModel.kt@@ -339,17 +339,18 @@ class ArrowsViewModel(application: Application) : AndroidViewModel(application),      * The one place a cleared board is recorded.      *      * Reached from the progress collector, so it can fire more than once for the same board as-     * unrelated flows re-emit. Everything it touches is idempotent for a given day, except the-     * lifetime counter, so that is guarded by [recordedClear].+     * unrelated flows re-emit — and on a fresh ViewModel after process death, when the collector+     * replays onto the still-persisted won board. The banked key in [ArrowsDataStore] makes the+     * count exactly-once across all of those: the check and the bump are one atomic edit, which+     * an in-memory guard could never be.      */     private fun onCleared(game: ArrowsGameState, daily: Boolean, day: Long) {         // Daily clears are keyed by day and casual ones by negated level, which cannot collide.         val key = if (daily) day else -game.level.toLong()-        if (recordedClear == key) return-        recordedClear = key          viewModelScope.launch {-            val total = dataStore.recordCleared()+            // Null means this board was already banked — a replayed win, not a new clear.+            val total = dataStore.recordClearedOnce(key) ?: return@launch             val manager = achievementsManager             manager.onAchievementUnlocked("first_board")             if (game.hearts == STARTING_HEARTS) manager.onAchievementUnlocked("flawless")@@ -367,9 +368,6 @@ class ArrowsViewModel(application: Application) : AndroidViewModel(application),         }     } -    /** Which clear has already been banked, so a re-emitted flow cannot double-count it. */-    private var recordedClear: Long? = null-     companion object {         /** Namespace shared by the daily-challenge store and its reminder. */         const val DAILY_KEY_PREFIX = "arrows_daily"
games/arrows/src/test/java/com/vayunmathur/games/arrows/data/ArrowsDataStoreTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/data/ArrowsDataStoreTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/data/ArrowsDataStoreTest.ktindex 837f5cc7bf..077c8ec8fc 100644--- a/games/arrows/src/test/java/com/vayunmathur/games/arrows/data/ArrowsDataStoreTest.kt+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/data/ArrowsDataStoreTest.kt@@ -8,6 +8,7 @@ import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertNull import kotlin.test.assertTrue  @RunWith(RobolectricTestRunner::class)@@ -80,14 +81,18 @@ class ArrowsDataStoreTest {     }      @Test-    fun recordClearedIncrements() = runBlocking {+    fun recordClearedOnceBanksEachKeyOnce() = runBlocking {         val s = store()+        // Unique keys: the DataStore file is shared across test classes in one JVM fork, and+        // other tests bank real board keys (-1L for casual level 1, day numbers for daily).         val before = s.boardsCleared.first()-        val after1 = s.recordCleared()+        val after1 = s.recordClearedOnce(-777001L)         assertEquals(before + 1, after1)         assertEquals(after1, s.boardsCleared.first())-        val after2 = s.recordCleared()-        assertEquals(after1 + 1, after2)+        assertNull(s.recordClearedOnce(-777001L), "replaying the same board must not count twice")+        assertEquals(after1, s.boardsCleared.first())+        val after2 = s.recordClearedOnce(-777002L)+        assertEquals(after1!! + 1, after2)     }      @Test
games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsAchievementsManagerTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsAchievementsManagerTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsAchievementsManagerTest.ktindex 479c0d2538..91a9746fd3 100644--- a/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsAchievementsManagerTest.kt+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/platform/ArrowsAchievementsManagerTest.kt@@ -33,7 +33,7 @@ class ArrowsAchievementsManagerTest {     fun checkExistingAfterClearedBoardBackfills() = runBlocking {         val json = ctx.assets.open("achievements.json").bufferedReader().readText()         val ds = ArrowsDataStore(ctx)-        ds.recordCleared()+        ds.recordClearedOnce(-4242L)         val daily = DailyChallengeStore(ctx, "arrows_test_achievements2")         val manager = ArrowsAchievementsManager(ctx, json, ds, daily)         manager.checkExistingAchievements()
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 458d10a65e..a3618f42c1 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@@ -128,6 +128,36 @@ class ArrowsViewModelTest {         await("back to level 1") { vm.uiState.value.level == 1 && vm.uiState.value.game != null }     } +    @Test+    fun relaunchOnWonBoardDoesNotRecountTheClear() {+        // 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)+        await("board loads") { vm.uiState.value.game != null && !vm.uiState.value.generating }+        val allIds = vm.uiState.value.game!!.puzzle.pieces.map { it.id }.toSet()+        runBlocking { 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)+        await("relaunch loads won board") { first.uiState.value.game?.isWon == true }+        Thread.sleep(2_000)+        val afterFirst = runBlocking { first.dataStore.boardsCleared.first() }++        val second = ArrowsViewModel(app)+        await("second relaunch loads won board") { second.uiState.value.game?.isWon == true }+        Thread.sleep(2_000)+        val afterSecond = runBlocking { second.dataStore.boardsCleared.first() }++        assertEquals(+            afterFirst,+            afterSecond,+            "reloading an already-won board must not count it again",+        )+        runBlocking { second.dataStore.resetBoard(daily = false) }+    }+     @Test     fun dailyFlowAndReminderSettings() {         runCatching {