Modern Apps git

← Modern-Apps.git

openassistant: tell missing model files apart from a failed load (#917)

Commit
8913ff49b2719951545e0568b89c60289b9df1ad
Author
Vayun Mathur <[email protected]>
When
2026-11-14 14:02 UTC (22 days ago)
Parents
214ff71
Symptom (#917, also #901): on v2.6.11b the first chat turn fails with
"Error: Model missing or failed to load at .../files/gemma4", while the
reporter's file manager shows every gemma4_*.maml in that folder.

Root cause:
- The files were not missing. On v2.6.11b the first-launch gate only
  renders the chat once all six gemma4 files exist at their final
  names, and a fresh download is renamed from .part only after its
  SHA-256 matches the pin, so a reporter who reaches the chat has the
  complete, verified set. The Kotlin "file is missing" early return in
  createGemma4Handle cannot fire; the failure is native.
- The native failure on these devices is #897: gemma4_text's 1.03 GiB
  of weights went into one VkBuffer, and Qualcomm's Adreno driver
  reports maxMemoryAllocationSize as the spec's 1 GiB floor, so
  ModelRunner refused the model ("1101558320 bytes of weights against a
  maxMemoryAllocationSize of 1073741824"). The moto g75 5G (#917,
  Snapdragon 6 Gen 3 / Adreno 710) and the Motorola Edge 70 Fusion
  (#901) are Snapdragon phones like the #897 Tab S7 / A52s. That is
  already fixed on main by 11258417d (weights past the limit are split
  into overlapping blocks), which is not in any release yet - v2.6.11b
  predates it.
- What made it read as a "false model missing" is the message: every
  cause - files absent, truncated, or present and refused by the GPU -
  became the same "Model missing or failed to load". v2.6.11b appended
  nothing; main (#901) appends the engine's detail but still leads with
  "missing", and a missing required file still gets no detail at all,
  because Gemma4Handle.loadError only carries native's message and
  native is never called when a file is absent.

Fix:
- New pure domain/ModelLoadFailure: classifyModelLoadFailure() looks at
  what is on disk and only then at the engine's error. Missing names
  the absent required files (text, embed, tokenizer - the towers and
  head are optional); Incomplete names files short of their pinned size
  as "name actual/expected" (the loader refuses any short file,
  optional ones included); FailedToLoad means every file is present and
  full size, carrying the runtime's own reason (or saying it gave none).
- InferenceService.ensureEngineInitialized builds the error from that,
  using Gemma4Handle.FILES and GEMMA4_EXPECTED_BYTES from :library:ml
  (the same tables the loader uses), e.g.
  "Model files are all present in .../gemma4 but failed to load: 1101558320
  bytes of weights against a maxMemoryAllocationSize of 1073741824".
  The intent (structured extraction) path surfaces the same message.
- No load-semantics change: same files required, same optional head
  and towers, same retry. The device fix itself is 11258417d and ships
  with the next release.

User-visible effect: a load failure now says which it is - files
missing (named), files incomplete (named with sizes), or files present
but the device could not load them (with the reason) - so a GPU or
memory limit no longer reads as a broken download.

Verification (gbuild, lss-toolchain container, Robolectric mount):
- :openassistant:testDevUnitTest and :openassistant:lint green.
- New InferenceServiceModelLoadTest drives the real service with an
  engine that refuses to load over sparse full-size, short, or absent
  files; run alone against origin/main it fails (the old text says
  "missing" for present-but-refused and short files, and names no file
  when one is absent). ModelLoadFailureTest covers the classifier and
  messages.

Diff

openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex 085e910fdf..ff63d053c6 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -57,6 +57,7 @@ _Install: ./install openassistant (dev by default)._ - com/vayunmathur/openassistant/domain/HistoryFit.kt - com/vayunmathur/openassistant/domain/A2uiBlocks.kt — split/restore ```a2ui blocks, streaming-safe - com/vayunmathur/openassistant/domain/A2uiEnvelope.kt — block → A2UI protocol messages, action → user turn+- com/vayunmathur/openassistant/domain/ModelLoadFailure.kt — missing vs incomplete vs refused model load, for the error text (#917) ### platform/ — engine + tool registry - com/vayunmathur/openassistant/platform/MamlChatEngine.kt - com/vayunmathur/openassistant/platform/AssistantTools.kt
openassistant/src/main/java/com/vayunmathur/openassistant/domain/ModelLoadFailure.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ModelLoadFailure.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ModelLoadFailure.ktnew file mode 100644index 0000000000..379a631026--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ModelLoadFailure.kt@@ -0,0 +1,61 @@+package com.vayunmathur.openassistant.domain++/**+ * Why the on-device model did not come up, told apart for the error the user sees.+ *+ * The service used to say "Model missing or failed to load at <dir>" for every cause, so a+ * user whose files were all there - downloaded and SHA-verified - read it as "missing" and+ * reported a false model-missing bug (#917), when the runtime had refused the files on their+ * GPU. Each variant here is one thing the user (or a bug report) can act on.+ */+sealed interface ModelLoadFailure {+    /** Required files absent from the model directory: a download that never finished. */+    data class Missing(val files: List<String>) : ModelLoadFailure++    /** Files present but short of their pinned size, as `name actual/expected` bytes. */+    data class Incomplete(val files: List<String>) : ModelLoadFailure++    /**+     * Every required file present and full size, yet the runtime refused them: a device or+     * GPU limit, a corrupt file, or a library that did not load. [reason] is the runtime's+     * own words, null when it gave none.+     */+    data class FailedToLoad(val reason: String?) : ModelLoadFailure+}++/**+ * Classify a failed load from what is on disk and what the engine reported.+ *+ * [sizes] maps each file name to its on-disk length, null when it is absent. [required] are+ * the files the text model cannot start without; [expectedBytes] the pinned size of every+ * model file, which the loader refuses to open short of (optional towers included).+ *+ * Disk state wins over [engineError]: a missing or short file is the cause whatever the+ * runtime said about it, and only when the files are all there is the failure the runtime's.+ */+fun classifyModelLoadFailure(+    sizes: Map<String, Long?>,+    required: List<String>,+    expectedBytes: Map<String, Long>,+    engineError: String?,+): ModelLoadFailure {+    val missing = required.filter { sizes[it] == null }+    if (missing.isNotEmpty()) return ModelLoadFailure.Missing(missing)+    val short = expectedBytes.mapNotNull { (name, expected) ->+        val actual = sizes[name] ?: return@mapNotNull null+        if (actual < expected) "$name $actual/$expected" else null+    }+    if (short.isNotEmpty()) return ModelLoadFailure.Incomplete(short)+    return ModelLoadFailure.FailedToLoad(engineError?.takeIf { it.isNotBlank() })+}++/** The message for a failed load from [directory], naming the cause rather than guessing. */+fun ModelLoadFailure.describe(directory: String): String = when (this) {+    is ModelLoadFailure.Missing ->+        "Model files missing from $directory: ${files.joinToString()}"+    is ModelLoadFailure.Incomplete ->+        "Model files incomplete in $directory (bytes on disk/expected): ${files.joinToString()}"+    is ModelLoadFailure.FailedToLoad ->+        "Model files are all present in $directory but failed to load: " ++            (reason ?: "the runtime gave no reason (see the log)")+}
openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.ktindex 307ee1eaa8..59af021b90 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -48,6 +48,11 @@ import com.vayunmathur.openassistant.data.MessageDao import com.vayunmathur.openassistant.data.Message as DbMessage import com.vayunmathur.openassistant.data.OpenAssistantRepository import com.vayunmathur.openassistant.R+import com.vayunmathur.library.ml.GEMMA4_EXPECTED_BYTES+import com.vayunmathur.library.ml.Gemma4Handle+import com.vayunmathur.openassistant.domain.ModelLoadFailure+import com.vayunmathur.openassistant.domain.classifyModelLoadFailure+import com.vayunmathur.openassistant.domain.describe import com.vayunmathur.openassistant.domain.splitA2ui import com.vayunmathur.openassistant.domain.withA2uiBlock import kotlinx.coroutines.channels.Channel@@ -392,16 +397,20 @@ class InferenceService : Service() {         if (!created.load()) {             val detail = created.loadError()             created.close()-            throw IllegalStateException(-                buildString {-                    append("Model missing or failed to load at ${dir.absolutePath}")-                    if (!detail.isNullOrBlank()) append(": $detail")-                },-            )+            // Say which it was (#917): "missing or failed to load" read as "missing" to a+            // user whose verified files were all there and whose GPU had refused them.+            throw IllegalStateException(modelLoadFailure(dir, detail).describe(dir.absolutePath))         }         engine = created     } +    /** What is on disk in [dir], classified against the engine's own [engineError]. */+    private fun modelLoadFailure(dir: File, engineError: String?): ModelLoadFailure {+        val names = (Gemma4Handle.FILES + GEMMA4_EXPECTED_BYTES.keys).distinct()+        val sizes = names.associateWith { name -> File(dir, name).takeIf { it.isFile }?.length() }+        return classifyModelLoadFailure(sizes, Gemma4Handle.FILES, GEMMA4_EXPECTED_BYTES, engineError)+    }+     /** The user's (or default) prompt plus the A2UI section, which custom prompts must not lose. */     private suspend fun systemPrompt(): String {         val stored = DataStoreUtils.getInstance(applicationContext).getStringAwait(KEY_SYSTEM_PROMPT)
openassistant/src/test/java/com/vayunmathur/openassistant/domain/ModelLoadFailureTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ModelLoadFailureTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ModelLoadFailureTest.ktnew file mode 100644index 0000000000..3497f86052--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ModelLoadFailureTest.kt@@ -0,0 +1,60 @@+package com.vayunmathur.openassistant.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class ModelLoadFailureTest {++    private val required = listOf("text", "embed", "tok")+    private val expected = mapOf("text" to 100L, "embed" to 200L, "head" to 50L, "tok" to 5L, "vision" to 30L)+    private val full: Map<String, Long?> = expected++    @Test+    fun allFilesPresentIsAFailureToLoadCarryingTheRuntimeReason() {+        assertEquals(+            ModelLoadFailure.FailedToLoad("weights past maxMemoryAllocationSize"),+            classifyModelLoadFailure(full, required, expected, "weights past maxMemoryAllocationSize"),+        )+        assertEquals(ModelLoadFailure.FailedToLoad(null), classifyModelLoadFailure(full, required, expected, " "))+    }++    @Test+    fun optionalFilesAbsentAreNotMissing() {+        val noOptional = full - "head" - "vision"+        assertEquals(ModelLoadFailure.FailedToLoad(null), classifyModelLoadFailure(noOptional, required, expected, null))+    }++    @Test+    fun absentRequiredFilesAreMissingWhateverTheRuntimeSaid() {+        val sizes = full + ("text" to null) - "tok"+        assertEquals(+            ModelLoadFailure.Missing(listOf("text", "tok")),+            classifyModelLoadFailure(sizes, required, expected, "native said something"),+        )+    }++    @Test+    fun shortFilesAreIncompleteIncludingOptionalOnes() {+        val sizes = full + ("embed" to 199L) + ("vision" to 1L)+        assertEquals(+            ModelLoadFailure.Incomplete(listOf("embed 199/200", "vision 1/30")),+            classifyModelLoadFailure(sizes, required, expected, null),+        )+    }++    @Test+    fun messagesNameTheCauseAndOnlyMissingSaysMissing() {+        val dir = "/x/gemma4"+        val missing = ModelLoadFailure.Missing(listOf("gemma4_text.maml")).describe(dir)+        assertTrue(missing.contains("missing") && missing.contains("gemma4_text.maml") && missing.contains(dir))+        val short = ModelLoadFailure.Incomplete(listOf("embed 1/2")).describe(dir)+        assertTrue(short.contains("incomplete") && short.contains("embed 1/2"))+        val refused = ModelLoadFailure.FailedToLoad("GPU limit").describe(dir)+        assertTrue(refused.contains("present") && refused.endsWith("failed to load: GPU limit"))+        val silent = ModelLoadFailure.FailedToLoad(null).describe(dir)+        assertTrue(silent.contains("no reason"))+        for (text in listOf(short, refused, silent)) assertFalse(text.contains("missing", ignoreCase = true), text)+    }+}
openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceModelLoadTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceModelLoadTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceModelLoadTest.ktnew file mode 100644index 0000000000..b83a7c2307--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceModelLoadTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.openassistant.util++import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.downloadservice.ModelUrls+import com.vayunmathur.library.ml.GEMMA4_EXPECTED_BYTES+import com.vayunmathur.openassistant.platform.AssistantTools+import com.vayunmathur.openassistant.platform.ChatRequest+import com.vayunmathur.openassistant.platform.ChatResult+import com.vayunmathur.openassistant.platform.MamlChatEngine+import com.vayunmathur.openassistant.util.InferenceServiceFakeEngineTest.FakeConversationDao+import com.vayunmathur.openassistant.util.InferenceServiceFakeEngineTest.FakeMemoryDao+import com.vayunmathur.openassistant.util.InferenceServiceFakeEngineTest.FakeMessageDao+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.android.controller.ServiceController+import java.io.File+import java.io.RandomAccessFile+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The load error must say whether the model is missing or present-but-refused (#917).+ *+ * The reporter's files were all in `gemma4/`, downloaded and SHA-verified, but the message+ * read "Model missing or failed to load", so a GPU refusal looked like a missing download.+ * Files here are sparse, so full-size ones cost no disk.+ */+@RunWith(RobolectricTestRunner::class)+class InferenceServiceModelLoadTest {++    /** An engine that never comes up, reporting [error] the way MamlChatEngine does. */+    private class RefusingEngine(private val error: String?) : MamlChatEngine(File("/nonexistent-model")) {+        override suspend fun load(): Boolean = false+        override suspend fun loadError(): String? = error+        override suspend fun chat(+            request: ChatRequest,+            tools: AssistantTools,+            onText: (String) -> Boolean,+        ): ChatResult = ChatResult.Unavailable+    }++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val modelDir: File get() = ModelUrls.GemmaMaml.modelDir(ctx)+    private val messageDao = FakeMessageDao()+    private var controller: ServiceController<InferenceService>? = null++    @BeforeTest fun cleanDir() {+        modelDir.deleteRecursively()+        modelDir.mkdirs()+    }++    @AfterTest fun tearDown() {+        runCatching { controller?.destroy() }+        modelDir.deleteRecursively()+    }++    private fun writeModel(sizes: Map<String, Long> = GEMMA4_EXPECTED_BYTES) {+        for ((name, bytes) in sizes) {+            RandomAccessFile(File(modelDir, name), "rw").use { it.setLength(bytes) }+        }+    }++    /** Runs one chat turn against engines that refuse with [reason]; returns the stored error, path masked. */+    private fun errorFor(reason: String?): String {+        val c = Robolectric.buildService(InferenceService::class.java)+        controller = c+        val service = c.get()+        service.messageDaoOverride = messageDao+        service.conversationDaoOverride = FakeConversationDao()+        service.memoryDaoOverride = FakeMemoryDao()+        service.engineFactory = { RefusingEngine(reason) }+        c.create()+        service.onStartCommand(+            Intent(ctx, InferenceService::class.java).apply {+                putExtra("conversation_id", 1L)+                putExtra("user_text", "hello")+            },+            0,+            1,+        )+        val deadline = System.currentTimeMillis() + 20_000+        while (System.currentTimeMillis() < deadline) {+            // The path is masked: Robolectric names its temp dir after the test method, so a+            // test called "...Missing" would otherwise find "missing" in every message.+            messageDao.assistantTexts(1L).firstOrNull()?.let { return it.replace(modelDir.absolutePath, "<dir>") }+            Thread.sleep(25)+        }+        error("no error message was stored")+    }++    @Test fun presentFilesRefusedByTheDeviceDoNotReadAsMissing() {+        writeModel()+        val reason = "1101558320 bytes of weights against a maxMemoryAllocationSize of 1073741824"+        val text = errorFor(reason)+        assertFalse(text.contains("missing", ignoreCase = true), text)+        assertTrue(text.contains("present") && text.contains("failed to load"), text)+        assertTrue(text.contains(reason) && text.contains("<dir>"), text)+    }++    @Test fun presentFilesWithNoReasonStillSayFailedToLoad() {+        writeModel()+        val text = errorFor(null)+        assertFalse(text.contains("missing", ignoreCase = true), text)+        assertTrue(text.contains("failed to load") && text.contains("no reason"), text)+    }++    @Test fun anAbsentRequiredFileIsNamedAsMissing() {+        writeModel(GEMMA4_EXPECTED_BYTES - "gemma4_text.maml")+        val text = errorFor(null)+        assertTrue(text.contains("missing") && text.contains("gemma4_text.maml"), text)+        assertFalse(text.contains("gemma4_embed.maml"), text)+    }++    @Test fun aShortFileIsNamedWithItsSizes() {+        writeModel(GEMMA4_EXPECTED_BYTES + ("gemma4_embed.maml" to 10L))+        val text = errorFor("short files: gemma4_embed.maml 10/1566576256")+        assertTrue(text.contains("incomplete") && text.contains("gemma4_embed.maml 10/1566576256"), text)+        assertFalse(text.contains("missing", ignoreCase = true), text)+    }+}