Modern Apps git

← Modern-Apps.git

updater: a found update survives restart instead of collapsing to 'up to date'

Commit
5f2cad28657b30edf70f28a6c1857f5727124771
Author
Vayun Mathur <[email protected]>
When
2026-11-30 23:33 UTC (5 days ago)
Parents
501a585
Only the check timestamp was persisted; the check outcome
lived solely in ViewModel memory. The screen infers outcome
from the timestamp, so any restart collapsed both Available
and Failed into 'Your system is up to date' โ€” a device told
it was current while its found update sat uninstalled, and a
device whose only check ever failed likewise claimed
up-to-date (the failure string is memory-only, yet the
worker stamped LAST_CHECKED even on failure).

The outcome is now persisted at both producers:
AVAILABLE_BUILD/AVAILABLE_BUILD_DATE on an available result,
cleared on a confirmed up-to-date result, untouched on
failure; LAST_CHECKED means last successful check.
UpdaterViewModel.init restores the persisted update only if
it is still newer than the running build, so the entry
self-invalidates after rebooting into that build. New
regression tests cover restart-restore, stale-entry dropping
and failure-not-up-to-date; build comparison, resume,
signature gating and the boot guards were audited and
cleared. Verified: :updater:testDevUnitTest 156 tests pass;
the one lint error is identical to the pre-change baseline.

Diff

updater/src/main/java/com/vayunmathur/updater/platform/UpdateCheckWorker.kt
diff --git a/updater/src/main/java/com/vayunmathur/updater/platform/UpdateCheckWorker.kt b/updater/src/main/java/com/vayunmathur/updater/platform/UpdateCheckWorker.ktindex 0d6eb0460f..77b169ea1f 100644--- a/updater/src/main/java/com/vayunmathur/updater/platform/UpdateCheckWorker.kt+++ b/updater/src/main/java/com/vayunmathur/updater/platform/UpdateCheckWorker.kt@@ -53,22 +53,32 @@ class UpdateCheckWorker(context: Context, params: WorkerParameters) :          // UpdateChecker.check() blocks on a socket, and doWork runs on Dispatchers.Default.         val result = withContext(Dispatchers.IO) { UpdateChecker.check() }-        store.setLong(UpdaterPreferences.LAST_CHECKED, System.currentTimeMillis())          val metadata = when (result) {             is UpdateChecker.Result.Available -> result.metadata             UpdateChecker.Result.UpToDate -> {+                // A successful answer: stamp it and drop any update an earlier check found,+                // so a restarted UI cannot resurrect it.+                store.setLong(UpdaterPreferences.LAST_CHECKED, System.currentTimeMillis())+                store.setString(UpdaterPreferences.AVAILABLE_BUILD, "")+                store.setLong(UpdaterPreferences.AVAILABLE_BUILD_DATE, 0L)                 UpdateNotifications.clearResult(context)                 return WorkResult.success()             }             // Retry rather than fail: the realistic cause is a captive portal or a flaky-            // connection, and there is nothing to tell the user about either.+            // connection, and there is nothing to tell the user about either. Neither the+            // timestamp nor a previously found update is touched โ€” this check learned+            // nothing, so the last successful state stays the honest one.             is UpdateChecker.Result.Failed -> {                 Log.status(TAG, "check failed: ${result.reason}")                 return WorkResult.retry()             }         } +        store.setLong(UpdaterPreferences.LAST_CHECKED, System.currentTimeMillis())+        store.setString(UpdaterPreferences.AVAILABLE_BUILD, metadata.build)+        store.setLong(UpdaterPreferences.AVAILABLE_BUILD_DATE, metadata.buildDateUtcSeconds)+         val decision = AutoInstallPolicy.decide(             AutoInstallPolicy.Conditions(                 autoInstall = store.getBooleanAwait(UpdaterPreferences.AUTO_INSTALL, default = true),
updater/src/main/java/com/vayunmathur/updater/platform/UpdaterPreferences.kt
diff --git a/updater/src/main/java/com/vayunmathur/updater/platform/UpdaterPreferences.kt b/updater/src/main/java/com/vayunmathur/updater/platform/UpdaterPreferences.ktindex e106fe0f29..b027b1f169 100644--- a/updater/src/main/java/com/vayunmathur/updater/platform/UpdaterPreferences.kt+++ b/updater/src/main/java/com/vayunmathur/updater/platform/UpdaterPreferences.kt@@ -15,9 +15,29 @@ internal object UpdaterPreferences {     /** Whether auto-install may use a metered connection. Off by default โ€” an OTA is 1-2 GB. */     const val METERED_ALLOWED = "updater_metered_allowed" -    /** When the last check finished, epoch millis, so the UI can say how stale it is. */+    /**+     * When the last successful check finished, epoch millis, so the UI can say how stale it is.+     *+     * Only a check the server actually answered (an update is available, or there is none)+     * stamps this. A failed check must not: after a restart the failure itself is gone, and a+     * timestamp alone is read by the UI as "up to date".+     */     const val LAST_CHECKED = "updater_last_checked" +    /**+     * The target build of the last successful check that found an update, or empty when the+     * last successful check found none (or none has run).+     *+     * Persisted alongside [LAST_CHECKED] because the timestamp alone cannot distinguish+     * "checked, update available" from "checked, up to date": a ViewModel created after a+     * process restart would restore the time, drop the update, and claim the device is up to+     * date while the older build is still running.+     */+    const val AVAILABLE_BUILD = "updater_available_build"++    /** Build date (epoch seconds) paired with [AVAILABLE_BUILD]; 0 when there is none. */+    const val AVAILABLE_BUILD_DATE = "updater_available_build_date"+     /**      * The build sitting on the inactive slot, waiting for a reboot, or absent when there is      * none.
updater/src/main/java/com/vayunmathur/updater/platform/UpdaterViewModel.kt
diff --git a/updater/src/main/java/com/vayunmathur/updater/platform/UpdaterViewModel.kt b/updater/src/main/java/com/vayunmathur/updater/platform/UpdaterViewModel.ktindex ed8038d08e..402857087b 100644--- a/updater/src/main/java/com/vayunmathur/updater/platform/UpdaterViewModel.kt+++ b/updater/src/main/java/com/vayunmathur/updater/platform/UpdaterViewModel.kt@@ -7,6 +7,7 @@ import androidx.compose.runtime.setValue import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.updater.domain.UpdateComparison import com.vayunmathur.updater.domain.UpdateMetadata import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch@@ -22,8 +23,27 @@ class UpdaterViewModel(application: Application) : AndroidViewModel(application)      init {         viewModelScope.launch {+            val current = SystemBuild.current()+            val availableBuild = store.getStringAwait(UpdaterPreferences.AVAILABLE_BUILD)+            val availableDate = store.getLongAwait(UpdaterPreferences.AVAILABLE_BUILD_DATE) ?: 0L+            val persisted = if (!availableBuild.isNullOrEmpty() && availableDate > 0L) {+                UpdateMetadata(availableBuild, availableDate)+            } else {+                null+            }+            // Restore the update an earlier check found, but only while it is still newer+            // than what is running: after the reboot into it, the same persisted entry is+            // stale and must not be offered again.+            val available = persisted?.takeIf {+                current == null || UpdateComparison.isNewer(current, it)+            }+            if (persisted != null && available == null && current != null) {+                store.setString(UpdaterPreferences.AVAILABLE_BUILD, "")+                store.setLong(UpdaterPreferences.AVAILABLE_BUILD_DATE, 0L)+            }             state = state.copy(-                currentBuild = SystemBuild.current()?.build.orEmpty(),+                currentBuild = current?.build.orEmpty(),+                available = available,                 autoInstall = store.getBooleanAwait(UpdaterPreferences.AUTO_INSTALL, default = true),                 meteredAllowed = store.getBooleanAwait(                     UpdaterPreferences.METERED_ALLOWED,@@ -40,24 +60,38 @@ class UpdaterViewModel(application: Application) : AndroidViewModel(application)         viewModelScope.launch {             val result = withContext(Dispatchers.IO) { UpdateChecker.check() }             val now = System.currentTimeMillis()-            store.setLong(UpdaterPreferences.LAST_CHECKED, now)             state = when (result) {-                is UpdateChecker.Result.Available -> state.copy(-                    checking = false,-                    available = result.metadata,-                    lastCheckedMillis = now,-                )+                is UpdateChecker.Result.Available -> {+                    store.setLong(UpdaterPreferences.LAST_CHECKED, now)+                    store.setString(UpdaterPreferences.AVAILABLE_BUILD, result.metadata.build)+                    store.setLong(+                        UpdaterPreferences.AVAILABLE_BUILD_DATE,+                        result.metadata.buildDateUtcSeconds,+                    )+                    state.copy(+                        checking = false,+                        available = result.metadata,+                        lastCheckedMillis = now,+                    )+                } -                UpdateChecker.Result.UpToDate -> state.copy(-                    checking = false,-                    available = null,-                    lastCheckedMillis = now,-                )+                UpdateChecker.Result.UpToDate -> {+                    store.setLong(UpdaterPreferences.LAST_CHECKED, now)+                    store.setString(UpdaterPreferences.AVAILABLE_BUILD, "")+                    store.setLong(UpdaterPreferences.AVAILABLE_BUILD_DATE, 0L)+                    state.copy(+                        checking = false,+                        available = null,+                        lastCheckedMillis = now,+                    )+                } +                // A failed check learned nothing: the timestamp and any previously found+                // update stay as the last successful check left them, so a later restart+                // cannot turn this failure into "up to date".                 is UpdateChecker.Result.Failed -> state.copy(                     checking = false,                     lastFailure = result.reason,-                    lastCheckedMillis = now,                 )             }         }@@ -81,7 +115,7 @@ data class UpdaterUiState(     val checking: Boolean = false,     /** Non-null when a newer build exists. */     val available: UpdateMetadata? = null,-    /** Epoch millis, or 0 when never checked. */+    /** Epoch millis, or 0 when no check has ever succeeded. */     val lastCheckedMillis: Long = 0L,     /**      * Why the last check failed, or null. Shown verbatim rather than flattened to "try again":
updater/src/test/java/com/vayunmathur/updater/platform/UpdateCheckWorkerTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/platform/UpdateCheckWorkerTest.kt b/updater/src/test/java/com/vayunmathur/updater/platform/UpdateCheckWorkerTest.ktindex fbdae07a56..eb68280438 100644--- a/updater/src/test/java/com/vayunmathur/updater/platform/UpdateCheckWorkerTest.kt+++ b/updater/src/test/java/com/vayunmathur/updater/platform/UpdateCheckWorkerTest.kt@@ -36,6 +36,8 @@ class UpdateCheckWorkerTest {         store.setBoolean(UpdaterPreferences.AUTO_INSTALL, true)         store.setBoolean(UpdaterPreferences.METERED_ALLOWED, false)         store.setLong(UpdaterPreferences.LAST_CHECKED, 0L)+        store.setString(UpdaterPreferences.AVAILABLE_BUILD, "")+        store.setLong(UpdaterPreferences.AVAILABLE_BUILD_DATE, 0L)         Unit     } @@ -66,24 +68,35 @@ class UpdateCheckWorkerTest {      @Test     fun `up to date is a success and stamps the last check`() = runBlocking {+        store.setString(UpdaterPreferences.AVAILABLE_BUILD, "2026090700")+        store.setLong(UpdaterPreferences.AVAILABLE_BUILD_DATE, 2000L)         fakeBody("2026090500 1000 shiba stable")         assertEquals(ListenableWorker.Result.success(), doWork())         assertTrue((store.getLongAwait(UpdaterPreferences.LAST_CHECKED) ?: 0L) > 0L)+        assertTrue(store.getStringAwait(UpdaterPreferences.AVAILABLE_BUILD).isNullOrEmpty())+        assertEquals(0L, store.getLongAwait(UpdaterPreferences.AVAILABLE_BUILD_DATE) ?: 0L)     }      @Test-    fun `a failed check asks WorkManager to retry`() {+    fun `a failed check asks WorkManager to retry`() = runBlocking {         fakeBody("", code = 404)         assertEquals(ListenableWorker.Result.retry(), doWork())+        // No successful check has happened, so no timestamp may be left behind for a+        // restarted UI to read as "up to date".+        assertEquals(0L, store.getLongAwait(UpdaterPreferences.LAST_CHECKED) ?: 0L)     }      @Test-    fun `an update on an unconnected device is held and announced`() {+    fun `an update on an unconnected device is held and announced`() = runBlocking {         fakeBody("2026090700 2000 shiba stable")         assertEquals(ListenableWorker.Result.success(), doWork())         val posted = ctx.getSystemService(android.app.NotificationManager::class.java)             .activeNotifications         assertTrue(posted.any { it.id == 2 }, "held update should post the available notification")+        // Held is still found: a restarted UI must restore it, not claim up to date.+        assertEquals("2026090700", store.getStringAwait(UpdaterPreferences.AVAILABLE_BUILD))+        assertEquals(2000L, store.getLongAwait(UpdaterPreferences.AVAILABLE_BUILD_DATE))+        assertTrue((store.getLongAwait(UpdaterPreferences.LAST_CHECKED) ?: 0L) > 0L)     }      @Test
updater/src/test/java/com/vayunmathur/updater/platform/UpdaterViewModelTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/platform/UpdaterViewModelTest.kt b/updater/src/test/java/com/vayunmathur/updater/platform/UpdaterViewModelTest.ktindex b711b17a14..6febb007d1 100644--- a/updater/src/test/java/com/vayunmathur/updater/platform/UpdaterViewModelTest.kt+++ b/updater/src/test/java/com/vayunmathur/updater/platform/UpdaterViewModelTest.kt@@ -32,6 +32,8 @@ class UpdaterViewModelTest {         store.setBoolean(UpdaterPreferences.AUTO_INSTALL, true)         store.setBoolean(UpdaterPreferences.METERED_ALLOWED, false)         store.setLong(UpdaterPreferences.LAST_CHECKED, 0L)+        store.setString(UpdaterPreferences.AVAILABLE_BUILD, "")+        store.setLong(UpdaterPreferences.AVAILABLE_BUILD_DATE, 0L)         Unit     } @@ -72,6 +74,37 @@ class UpdaterViewModelTest {         assertNull(vm.state.available)     } +    @Test+    fun `init restores an available update found before a restart`() = runBlocking {+        // The exact state a background check that found 2026090700 leaves behind, read by a+        // ViewModel created after the process died. Before the fix this restored only the+        // timestamp, so the screen claimed the still-old build was up to date.+        store.setLong(UpdaterPreferences.LAST_CHECKED, 777L)+        store.setString(UpdaterPreferences.AVAILABLE_BUILD, "2026090700")+        store.setLong(UpdaterPreferences.AVAILABLE_BUILD_DATE, 2000L)+        val vm = UpdaterViewModel(app)+        awaitState(vm) { it.available != null }+        assertEquals("2026090700", vm.state.available?.build)+        assertEquals(2000L, vm.state.available?.buildDateUtcSeconds)+        assertEquals(777L, vm.state.lastCheckedMillis)+    }++    @Test+    fun `init drops a persisted update that is no longer newer than the running build`() = runBlocking {+        // After the reboot into the found build, its date (1000) no longer beats the+        // running build's date (1000), so the persisted entry must not be offered again.+        store.setString(UpdaterPreferences.AVAILABLE_BUILD, "2026090700")+        store.setLong(UpdaterPreferences.AVAILABLE_BUILD_DATE, 1000L)+        val vm = UpdaterViewModel(app)+        awaitState(vm) { it.currentBuild == "2026090500" }+        assertNull(vm.state.available)+        repeat(100) {+            if (store.getStringAwait(UpdaterPreferences.AVAILABLE_BUILD).isNullOrEmpty()) return@runBlocking+            Thread.sleep(20)+        }+        assertTrue(store.getStringAwait(UpdaterPreferences.AVAILABLE_BUILD).isNullOrEmpty())+    }+     @Test     fun `check now surfaces an available update and stamps the check time`() {         fakeBody("2026090700 2000 shiba stable")@@ -87,11 +120,17 @@ class UpdaterViewModelTest {         assertTrue(vm.state.lastCheckedMillis >= before)         assertNull(vm.state.lastFailure)         assertEquals(1, fetchCount.get())-        runBlocking { assertTrue((store.getLongAwait(UpdaterPreferences.LAST_CHECKED) ?: 0L) >= before) }+        runBlocking {+            assertTrue((store.getLongAwait(UpdaterPreferences.LAST_CHECKED) ?: 0L) >= before)+            assertEquals("2026090700", store.getStringAwait(UpdaterPreferences.AVAILABLE_BUILD))+            assertEquals(2000L, store.getLongAwait(UpdaterPreferences.AVAILABLE_BUILD_DATE))+        }     }      @Test-    fun `check now clears the update when the device is up to date`() {+    fun `check now clears the update when the device is up to date`() = runBlocking {+        store.setString(UpdaterPreferences.AVAILABLE_BUILD, "2026090700")+        store.setLong(UpdaterPreferences.AVAILABLE_BUILD_DATE, 2000L)         fakeBody("2026090500 1000 shiba stable")         val vm = UpdaterViewModel(app)         awaitState(vm) { it.currentBuild == "2026090500" }@@ -99,6 +138,8 @@ class UpdaterViewModelTest {         awaitState(vm) { !it.checking && it.lastCheckedMillis > 0L }         assertNull(vm.state.available)         assertNull(vm.state.lastFailure)+        assertTrue(store.getStringAwait(UpdaterPreferences.AVAILABLE_BUILD).isNullOrEmpty())+        assertEquals(0L, store.getLongAwait(UpdaterPreferences.AVAILABLE_BUILD_DATE) ?: 0L)     }      @Test@@ -112,6 +153,25 @@ class UpdaterViewModelTest {         assertNull(vm.state.available)     } +    @Test+    fun `a failed check does not become up to date after a restart`() {+        fakeBody("<html>portal</html>")+        val vm = UpdaterViewModel(app)+        awaitState(vm) { it.currentBuild == "2026090500" }+        vm.checkNow()+        awaitState(vm) { !it.checking && it.lastFailure != null }+        assertEquals(0L, vm.state.lastCheckedMillis)+        runBlocking {+            assertEquals(0L, store.getLongAwait(UpdaterPreferences.LAST_CHECKED) ?: 0L)+        }+        // A fresh ViewModel (the post-restart one) must not read a stamped time and+        // report the device up to date: no check has ever succeeded.+        val restarted = UpdaterViewModel(app)+        awaitState(restarted) { it.currentBuild == "2026090500" }+        assertEquals(0L, restarted.state.lastCheckedMillis)+        assertNull(restarted.state.available)+    }+     @Test     fun `toggles update state immediately and persist`() = runBlocking {         val vm = UpdaterViewModel(app)