Modern Apps git

← Modern-Apps.git

downloadservice: verify model files before treating them as complete (#901)

Commit
54abff3ab53a42258431b55b0d96d6b9cd07b66e
Author
Vayun Mathur <[email protected]>
When
2026-11-06 05:01 UTC (1 month ago)
Parents
789c577
Only existence gated the first-launch download screen, so a truncated or
stale file at the final name passed the gate and died later in native code
with an undifferentiated load error. Every gemma4 file was already
SHA-pinned, but the pins were only checked on the fresh-download path, never
at the gate or on the already-exists skip path, and the UI's done flag came
from a progress float that an older app version could have left at 1.0.

Pin the exact mirror byte size beside each SHA in ModelUrls.GemmaMaml and
carry it through DownloadSpec into the worker input (old enqueues without
sizes keep working: absent means unknown). The launch gate now checks size
(cheap, every launch) plus a verified_<file> marker equal to the
currently-pinned SHA, written only after a file passes hash verification
before the .part rename. A hash bump re-downloads stale files because the
stored marker no longer matches; a truncated file fails the size check
without rehashing gigabytes. The per-file done tick needs the marker too,
so a stale progress 1.0 no longer reads as complete. Unpinned consumers
(maps basemap, beacon stores without a hash) still pass on existence.

VerifiedManifest/specsToManifest/manifestSatisfied/markVerified/checksumMatches/sizeOk
are internal and host-tested (VerifiedManifestTest, 10 tests; ModelUrlsTest
gains a size-pin test; UniqueNameTest untouched and green). Affects every
InitialModelDownloadChecker/downloadModels/enqueueTo caller: openassistant,
translate (NLLB/MADLAD), networklocation beacon stores, and maps basemap.

Diff

library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.ktindex 91f92033c5..09f5bf34c6 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt@@ -67,13 +67,20 @@ internal data class DownloadSpec(     val description: String,     val url: String,     val sha256: String? = null,+    val expectedBytes: Long? = null, )  private fun Triple<String, String, String>.toSpec() =     DownloadSpec(fileName = second, description = third, url = first)  private fun ModelDownloadItem.toSpec() =-    DownloadSpec(fileName = fileName, description = description, url = url, sha256 = sha256)+    DownloadSpec(+        fileName = fileName,+        description = description,+        url = url,+        sha256 = sha256,+        expectedBytes = expectedBytes,+    )  @Composable fun InitialDownloadChecker(@@ -121,7 +128,68 @@ private fun allFilesPresent(     specs: List<DownloadSpec>, ): Boolean {     val dir = context.getExternalFilesDir(null)-    return specs.all { File(dir, it.fileName).exists() }+    val ds = DataStoreUtils.getInstance(context)+    return manifestSatisfied(dir, ds, specsToManifest(specs))+}++/**+ * The on-disk gate state for one download set: the expected SHA-256 and size+ * per file, read from the current [DownloadSpec]s.+ *+ * Compared against the real files plus the `verified_*` markers the download+ * loop writes, so the gate never treats an unverified file as complete. Pure+ * and host-testable: [dir] stands in for the app's external files dir.+ */+internal data class VerifiedManifest(val entries: List<VerifiedEntry>)++internal data class VerifiedEntry(+    val fileName: String,+    val sha256: String?,+    val expectedBytes: Long?,+)++internal fun specsToManifest(specs: List<DownloadSpec>): VerifiedManifest =+    VerifiedManifest(+        specs.map { VerifiedEntry(it.fileName, it.sha256, it.expectedBytes) },+    )++/**+ * Cheap per-launch gate: every file exists at its expected size (when pinned),+ * and every hash-pinned file carries a `verified_<fileName>` marker equal to the+ * currently-expected SHA-256.+ *+ * The marker is what makes a model update re-download: bump the pinned hash and+ * the stored marker no longer matches, so the set reads as incomplete. The size+ * check catches a truncated file without rehashing gigabytes on every start.+ * Files with no pinned hash and no pinned size pass on existence, exactly as+ * before, so unpinned consumers (maps basemap, beacon stores without a hash)+ * see no behaviour change.+ */+internal fun manifestSatisfied(+    dir: File?,+    verifiedMarker: (String) -> String?,+    manifest: VerifiedManifest,+): Boolean {+    if (dir == null) return false+    return manifest.entries.all { entry ->+        val file = File(dir, entry.fileName)+        if (!file.isFile) return@all false+        if (entry.expectedBytes != null && file.length() != entry.expectedBytes) return@all false+        val want = entry.sha256 ?: return@all true+        verifiedMarker("verified_${entry.fileName}") == want+    }+}++internal fun manifestSatisfied(+    dir: File?,+    ds: DataStoreUtils,+    manifest: VerifiedManifest,+): Boolean = manifestSatisfied(dir, ds::getString, manifest)++/** Records that [spec]'s file on disk matches its currently-pinned SHA-256. */+internal suspend fun markVerified(ds: DataStoreUtils, spec: DownloadSpec) {+    val sha = spec.sha256 ?: return+    ds.setString("verified_${spec.fileName}", sha) }  @Composable@@ -145,6 +213,9 @@ private fun InitialDownloadScreen(     val state = workInfo.firstOrNull()?.state      LaunchedEffect(state) {+        // SUCCEEDED means runDownloadsCore verified every file, so the gate below+        // passes; still re-check disk rather than trusting the worker result, so a+        // file deleted between the last byte and this frame re-shows the screen.         if (state == WorkInfo.State.SUCCEEDED && allFilesPresent(context, specs)) {             onAllDownloaded()         }@@ -190,11 +261,15 @@ private fun InitialDownloadScreen(             ) {                 items(specs, key = { it.fileName }) { spec ->                     // Each item observes its own progress and speed from DataStore.-                    // "Done" is derived from progress (1.0) — no separate persisted-                    // flag that could disagree with disk state.+                    // "Done" needs both progress (1.0) and this run's verified+                    // marker — a stale 1.0 left by an older app version must not+                    // read as complete. Unpinned files keep the old threshold.                     val progress by ds.doubleFlow("progress_${spec.fileName}").collectAsState(0.0)                     val speedMbps by ds.doubleFlow("speed_${spec.fileName}").collectAsState(0.0)-                    val isDone = progress >= 0.999+                    val marker by ds.stringFlow("verified_${spec.fileName}")+                        .collectAsState(initial = null as String?)+                    val verified = spec.sha256?.let { marker == it } ?: true+                    val isDone = progress >= 0.999 && verified                      FileProgressItem(                         label = spec.description,@@ -272,11 +347,12 @@ internal suspend fun runDownloadsCore(         migrateLegacyDownload(context, ds, dir, spec)          val file = File(dir, spec.fileName)-        // If the file already exists, verify SHA when pinned; a stale or tiny old-        // bundle (e.g. 593 KB dict vs 2.2 MB, or sherpa .onnx leftover) must be-        // re-downloaded.+        // A file already on disk still has to prove itself: size first (cheap),+        // then the pinned SHA when the verified marker does not match. A stale+        // bundle from an older app version (different pinned hash) or a+        // truncated one (wrong size) is deleted and re-downloaded below.         if (file.exists()) {-            if (checksumOk(file, spec.sha256)) {+            if (sizeOk(file, spec.expectedBytes) && checksumMatches(file, ds, spec)) {                 ds.setDouble("progress_${spec.fileName}", 1.0)                 continue             } else {@@ -290,12 +366,31 @@ internal suspend fun runDownloadsCore( }  /**- * Downloads a single [spec] into `<fileName>.part`, verifies its SHA-256, then- * atomically renames it to the final name. Retries transient failures up to- * [MAX_ATTEMPTS]; on a checksum mismatch the partial is discarded and the file- * is re-fetched from scratch. On final failure any `.part` is left for the next- * run to resume, and false is returned so the caller can surface it.+ * True when [file] may be skipped without re-downloading: size matches when+ * pinned, and the SHA matches when pinned. The SHA is only recomputed when the+ * file's stored `verified_*` marker differs from the currently-pinned hash —+ * which covers a first install (no marker yet) and a model update (pinned hash+ * bumped, marker stale). A match writes the marker so the launch gate and+ * later runs skip the rehash.  */+internal suspend fun checksumMatches(+    file: File,+    ds: DataStoreUtils,+    spec: DownloadSpec,+): Boolean {+    val want = spec.sha256 ?: return true+    if (ds.getString("verified_${spec.fileName}") == want) return true+    if (!checksumOk(file, want)) return false+    markVerified(ds, spec)+    return true+}++/** True when [file]'s size matches [expectedBytes], or when no size is pinned. */+internal fun sizeOk(file: File, expectedBytes: Long?): Boolean {+    if (expectedBytes == null) return true+    return file.isFile && file.length() == expectedBytes+}+ private suspend fun downloadSpec(     ds: DataStoreUtils,     dir: File?,@@ -307,11 +402,11 @@ private suspend fun downloadSpec(     repeat(MAX_ATTEMPTS) { attempt ->         try {             streamToPart(ds, spec, partFile)-            if (checksumOk(partFile, spec.sha256)) {+            if (sizeOk(partFile, spec.expectedBytes) && checksumOk(partFile, spec.sha256)) {                 finalizeDownload(ds, spec, partFile, finalFile)                 return true             }-            // Corrupt/tampered copy — drop the partial and re-fetch from scratch.+            // Corrupt/tampered/short copy — drop the partial and re-fetch from scratch.             Log.status(TAG, "checksum mismatch for ${spec.fileName}; refetching")             partFile.delete()         } catch (e: CancellationException) {@@ -473,6 +568,9 @@ private suspend fun finalizeDownload(         partFile.copyTo(finalFile, overwrite = true)         partFile.delete()     }+    // The file was hash- (and size-) verified before this rename, so record it:+    // the launch gate trusts this marker instead of rehashing gigabytes.+    markVerified(ds, spec)     ds.setDouble("progress_${spec.fileName}", 1.0)     ds.setDouble("speed_${spec.fileName}", 0.0) }
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.ktindex 61f05b3904..16ac6ae78d 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt@@ -51,12 +51,16 @@ class ModelDownloadWorker(context: Context, params: WorkerParameters) :         private const val KEY_FILE_NAMES = "fileNames"         private const val KEY_DESCRIPTIONS = "descriptions"         private const val KEY_HASHES = "hashes"+        private const val KEY_SIZES = "sizes"         private const val KEY_TARGET_DIR = "targetDir"         private const val KEY_UNMETERED = "unmetered"          /** Absent SHA-256, encoded as an empty string because [Data] holds no nulls. */         private const val NO_HASH = "" +        /** Absent expected size, encoded as -1 because [Data] holds no nulls. */+        private const val NO_SIZE = -1L+         private const val MAX_RUN_ATTEMPTS = 6         private const val BACKOFF_SECONDS = 30L         private const val SINGLETON_LIST_SIZE = 1@@ -103,6 +107,7 @@ class ModelDownloadWorker(context: Context, params: WorkerParameters) :                     description = it.description,                     url = it.url,                     sha256 = it.sha256,+                    expectedBytes = it.expectedBytes,                 )             },             policy = if (replaceExisting) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP,@@ -122,6 +127,7 @@ class ModelDownloadWorker(context: Context, params: WorkerParameters) :                 .putStringArray(KEY_FILE_NAMES, specs.map { it.fileName }.toTypedArray())                 .putStringArray(KEY_DESCRIPTIONS, specs.map { it.description }.toTypedArray())                 .putStringArray(KEY_HASHES, specs.map { it.sha256 ?: NO_HASH }.toTypedArray())+                .putLongArray(KEY_SIZES, specs.map { it.expectedBytes ?: NO_SIZE }.toLongArray())                 .apply { targetDir?.let { putString(KEY_TARGET_DIR, it.absolutePath) } }                 .putBoolean(KEY_UNMETERED, requireUnmetered)                 .build()@@ -147,9 +153,12 @@ class ModelDownloadWorker(context: Context, params: WorkerParameters) :             val fileNames = data.getStringArray(KEY_FILE_NAMES) ?: return emptyList()             val descriptions = data.getStringArray(KEY_DESCRIPTIONS) ?: return emptyList()             val hashes = data.getStringArray(KEY_HASHES) ?: return emptyList()+            // Old enqueues predate sizes: default every entry to unknown.+            val sizes = data.getLongArray(KEY_SIZES)             if (fileNames.size != urls.size ||                 descriptions.size != urls.size ||-                hashes.size != urls.size+                hashes.size != urls.size ||+                (sizes != null && sizes.size != urls.size)             ) {                 return emptyList()             }@@ -159,6 +168,7 @@ class ModelDownloadWorker(context: Context, params: WorkerParameters) :                     description = descriptions[i],                     url = urls[i],                     sha256 = hashes[i].takeIf { it != NO_HASH },+                    expectedBytes = sizes?.get(i)?.takeIf { it != NO_SIZE },                 )             }         }
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.ktindex 52cf358431..0406c04425 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt@@ -25,46 +25,52 @@ object ModelUrls {         const val BASE = "${MIRROR_BASE}gemma4/"          val FILES: List<ModelDownloadItem> = listOf(-            // 1,101,593,392 bytes.             item(                 "gemma4_text.maml",                 "Text Model",                 "f990e8f99d61a127dd329cd4329b081f214067afefb1b3f4778922cc12d210d8",+                1_101_593_392L,             ),-            // 1,566,576,256 bytes.             item(                 "gemma4_embed.maml",                 "Embeddings",                 "11b9e8b316dd8a2c628d58b98908e9a509764c6f63531731b6d94ccf6419a9bd",+                1_566_576_256L,             ),-            // 403,703,360 bytes.             item(                 "gemma4_head.maml",                 "Output Head",                 "338021b6aa4d78eda55e47f5197d186087a73a8dade02001812aa95f0f550937",+                403_703_360L,             ),-            // 97,815,200 bytes.             item(                 "gemma4_vision.maml",                 "Vision Tower",                 "4c53c0a8383f2ea99f8beed50bd5eac203565436313d0c2dd77b389ea1cf38e3",+                97_815_200L,             ),-            // 173,999,072 bytes.             item(                 "gemma4_audio.maml",                 "Audio Tower",                 "be3ac4f968835fa257291f0845be642750f71e63e197a6e199ad5210316cb4f2",+                173_999_072L,             ),-            // 3,889,167 bytes.             item(                 "gemma4_tokenizer.spm1",                 "Tokenizer",                 "e3e03941be666b885f6644cb3d7a0264949f842f8a7b97302589d9deff2334d7",+                3_889_167L,             ),         ) -        private fun item(name: String, description: String, sha256: String) =-            ModelDownloadItem("$BASE$name", "$DIR/$name", "Gemma 4 $description", sha256)+        private fun item(name: String, description: String, sha256: String, expectedBytes: Long) =+            ModelDownloadItem(+                "$BASE$name",+                "$DIR/$name",+                "Gemma 4 $description",+                sha256,+                expectedBytes,+            )          /** Directory `Gemma4Handle.inDirectory` loads from. */         fun modelDir(context: Context): File = File(context.getExternalFilesDir(null), DIR)@@ -85,4 +91,12 @@ data class ModelDownloadItem(     val fileName: String,     val description: String,     val sha256: String? = null,+    /**+     * Exact on-disk size in bytes, or null when unknown.+     *+     * Checked cheaply at the launch gate beside the "verified" marker, so a+     * truncated file left by an interrupted install is re-downloaded without+     * rehashing gigabytes on every start.+     */+    val expectedBytes: Long? = null, )
library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/ModelUrlsTest.kt
diff --git a/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/ModelUrlsTest.kt b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/ModelUrlsTest.ktindex eac056ce4a..5fed1395f4 100644--- a/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/ModelUrlsTest.kt+++ b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/ModelUrlsTest.kt@@ -48,6 +48,22 @@ class ModelUrlsTest {         }     } +    @Test+    fun every_gemma_file_pins_an_exact_expected_size() {+        val expected = mapOf(+            "gemma4_text.maml" to 1_101_593_392L,+            "gemma4_embed.maml" to 1_566_576_256L,+            "gemma4_head.maml" to 403_703_360L,+            "gemma4_vision.maml" to 97_815_200L,+            "gemma4_audio.maml" to 173_999_072L,+            "gemma4_tokenizer.spm1" to 3_889_167L,+        )+        for (item in ModelUrls.GemmaMaml.FILES) {+            val name = item.fileName.removePrefix("${ModelUrls.GemmaMaml.DIR}/")+            assertEquals(expected[name], item.expectedBytes, "$name size drifted from the mirror")+        }+    }+     @Test     fun initial_bundle_is_the_gemma_set_with_distinct_files() {         assertEquals(ModelUrls.GemmaMaml.FILES, ModelUrls.INITIAL)@@ -74,6 +90,7 @@ class ModelUrlsTest {     fun item_sha_defaults_to_null_for_unpinned_files() {         val tokenizer = ModelUrls.GemmaMaml.FILES.last()         assertNull(ModelDownloadItem(tokenizer.url, tokenizer.fileName, "Model").sha256)+        assertNull(ModelDownloadItem(tokenizer.url, tokenizer.fileName, "Model").expectedBytes)     }      @Test
library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/VerifiedManifestTest.kt
diff --git a/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/VerifiedManifestTest.kt b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/VerifiedManifestTest.ktnew file mode 100644index 0000000000..8961f3d07b--- /dev/null+++ b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/VerifiedManifestTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.library.downloadservice++import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Covers the host-safe launch gate behind #901: [specsToManifest] plus+ * [manifestSatisfied].+ *+ * The gate must never treat an unverified file as complete — a truncated file+ * (wrong size), a stale one (pinned hash bumped, stored `verified_*` marker+ * now stale), or a never-verified one (file copied in by hand, marker absent)+ * all read as incomplete so the download screen re-fetches them. Pure Kotlin+ * with no Android dependency, so it runs on the plain host JVM.+ */+class VerifiedManifestTest {++    private fun spec(+        fileName: String,+        sha256: String? = "aa".repeat(32),+        expectedBytes: Long? = 8L,+    ) = DownloadSpec(+        fileName = fileName,+        description = fileName,+        url = "https://data.maproj.org/models/$fileName",+        sha256 = sha256,+        expectedBytes = expectedBytes,+    )++    private fun staged(vararg names: String): File {+        val dir = kotlin.io.path.createTempDirectory("manifest_gate").toFile()+        for (name in names) {+            val file = File(dir, name)+            file.parentFile?.mkdirs()+            // 8 bytes, matching the default expectedBytes above.+            file.writeBytes(ByteArray(8))+        }+        return dir+    }++    @Test+    fun specs_map_to_entries_verbatim() {+        val manifest = specsToManifest(listOf(spec("gemma4/a.bin"), spec("b.bin", null, null)))+        assertEquals(+            listOf(+                VerifiedEntry("gemma4/a.bin", "aa".repeat(32), 8L),+                VerifiedEntry("b.bin", null, null),+            ),+            manifest.entries,+        )+    }++    @Test+    fun all_verified_passes() {+        val dir = staged("gemma4/a.bin")+        val manifest = specsToManifest(listOf(spec("gemma4/a.bin")))+        val markers = mapOf("verified_gemma4/a.bin" to "aa".repeat(32))+        assertTrue(manifestSatisfied(dir, markers::getValue, manifest))+    }++    @Test+    fun missing_file_fails() {+        val dir = staged()+        val manifest = specsToManifest(listOf(spec("gemma4/a.bin")))+        assertFalse(manifestSatisfied(dir, { null }, manifest))+    }++    @Test+    fun null_dir_fails() {+        val manifest = specsToManifest(listOf(spec("a.bin")))+        assertFalse(manifestSatisfied(null, { null }, manifest))+    }++    @Test+    fun short_file_fails_even_when_previously_verified() {+        val dir = staged("a.bin")+        File(dir, "a.bin").writeBytes(ByteArray(4))+        val manifest = specsToManifest(listOf(spec("a.bin")))+        val markers = mapOf("verified_a.bin" to "aa".repeat(32))+        assertFalse(manifestSatisfied(dir, markers::getValue, manifest))+    }++    @Test+    fun stale_marker_after_a_hash_bump_fails() {+        val dir = staged("a.bin")+        val manifest = specsToManifest(listOf(spec("a.bin", sha256 = "bb".repeat(32))))+        val markers = mapOf("verified_a.bin" to "aa".repeat(32))+        assertFalse(manifestSatisfied(dir, markers::getValue, manifest))+    }++    @Test+    fun hand_placed_file_without_a_marker_fails() {+        val dir = staged("a.bin")+        val manifest = specsToManifest(listOf(spec("a.bin")))+        assertFalse(manifestSatisfied(dir, { null }, manifest))+    }++    @Test+    fun unpinned_file_passes_on_existence() {+        val dir = staged("archive.bin")+        val manifest = specsToManifest(listOf(spec("archive.bin", null, null)))+        assertTrue(manifestSatisfied(dir, { null }, manifest))+    }++    @Test+    fun size_only_pin_still_catches_truncation() {+        val dir = staged("archive.bin")+        File(dir, "archive.bin").writeBytes(ByteArray(4))+        val manifest = specsToManifest(listOf(spec("archive.bin", null, 8L)))+        assertFalse(manifestSatisfied(dir, { null }, manifest))+    }++    @Test+    fun size_ok_accepts_exact_and_unpinned() {+        val dir = staged("a.bin")+        val file = File(dir, "a.bin")+        assertTrue(sizeOk(file, 8L))+        assertFalse(sizeOk(file, 9L))+        assertTrue(sizeOk(file, null))+        assertFalse(sizeOk(File(dir, "missing.bin"), 8L))+    }+}