Modern Apps git

← Modern-Apps.git

openassistant: stop post-download crash at service initialisation (#928)

Commit
72f9aef198d9a0938f8d4f3ef4d820546bdeee7d
Author
Vayun Mathur <[email protected]>
When
2026-12-04 18:20 UTC (1 day ago)
Parents
f77efe6
The crash log attached to #928 is a PatternSyntaxException from
Android's ICU regex compiler for the [HostSendMsg ...] pattern, surfacing
as ExceptionInInitializerError from InferenceService.<clinit> when the
system instantiated the service. That is the first class loaded after
the model download gate passes, so the app crashed on every launch
after downloading the model files, and reinstalling or clearing data
could not help. It is not the #901 missing/incomplete-file failure or
the #897 maxMemoryAllocationSize refusal: the download gate now
SHA- and size-verifies every file, and those failures already surface
as typed ModelLoadFailure messages.

A one-character escape for that pattern already landed, but the
service companion still eagerly compiled three Regex objects at class
initialisation, where any device regex-dialect rejection is an Error
that no catch (Exception) in the service can intercept, and the engine
factory/load path likewise only survived Exceptions.

Fix at the cause:
- Parse the host markers ([HostSendMsg {json}], [HostConfirm id],
  [HostCancel id]) with plain string code in the new pure domain
  HostMarkers parser instead of Regex, so no regex dialect can take
  the service class down at initialisation again. Marker semantics
  are unchanged (anchored whole-turn match, ]-free ids, brace-wrapped
  JSON payload).
- Convert any Throwable (other than cancellation) from the engine
  factory or load() in ensureEngineInitialized into the existing
  typed ModelLoadFailure (missing vs incomplete vs present-but-failed,
  via the new domain modelLoadException helper), so a class-init or
  native linkage Error becomes the stored "Error: ..." chat message
  instead of a process crash loop.

Regression tests:
- HostMarkersTest pins the marker grammar, including payloads with
  braces/brackets inside the JSON, malformed payloads, and empty or
  bracketed ids.
- InferenceServiceModelLoadTest gains a case where the engine factory
  throws a LinkageError with all model files present: the stored
  error reads as present-but-failed-to-load carrying the reason, not
  as missing and not as a crash. Existing host-marker service tests
  cover the send/confirm/cancel behaviour end to end.

Verified: ./gradlew :openassistant:lint :openassistant:lintVitalRelease
:openassistant:testDevUnitTest — lint green; 282 tests with only the
known InferenceServiceConcurrencyTest load flake failing, which
passes in isolation together with the new HostMarkers,
InferenceServiceModelLoadTest and InferenceServiceHostMarkerTest
tests; a final full invocation is BUILD SUCCESSFUL.
openassistant/AGENTS.md updated for the new domain file.

Diff

openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex 9c1cc05261..f261954db4 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -63,6 +63,7 @@ _Install: ./install openassistant (dev by default)._ - 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+- com/vayunmathur/openassistant/domain/HostMarkers.kt — regex-free parsing of the `[HostSendMsg …]` / `[HostConfirm …]` / `[HostCancel …]` turns (a companion-object Regex in InferenceService crashed service initialisation on Android's ICU regex compiler, #928); engine factory/load Errors are likewise converted to a typed ModelLoadFailure in InferenceService rather than crashing - com/vayunmathur/openassistant/domain/WebPageExtractor.kt — on-device readable-text extraction (title + block text, chrome stripped) and the web_read URL policy; a small tolerant duplicate of the readability idea (news's richer extractor is module-private to news) - com/vayunmathur/openassistant/domain/ReplyStream.kt — bounded chunk buffer between cumulative model callbacks and the DB writer (<=64 pending chunks, 32k live snapshot cap) - com/vayunmathur/openassistant/domain/TurnGate.kt — bounded concurrent turns (max 3 active, per-conversation serialisation)
openassistant/src/main/java/com/vayunmathur/openassistant/domain/HostMarkers.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/HostMarkers.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/HostMarkers.ktnew file mode 100644index 0000000000..28a3714184--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/HostMarkers.kt@@ -0,0 +1,41 @@+package com.vayunmathur.openassistant.domain++/**+ * Host markers the ViewModel writes as user turns and [com.vayunmathur.openassistant.util.InferenceService]+ * intercepts: `[HostSendMsg {json}]`, `[HostConfirm id]`, `[HostCancel id]`.+ *+ * Plain string parsing, deliberately no regex. The send marker used to be a+ * companion-object `Regex` in the service, and Android's ICU regex compiler+ * rejected its unescaped closing brace where the JDK compiler is lenient:+ * instantiation of the service — the first thing that happens after the+ * model download gate passes — died with `ExceptionInInitializerError`+ * and the app crashed on every launch (#928). A marker grammar this small+ * needs no pattern engine, so no device regex dialect can take the whole+ * service class down at initialisation again. Host tests cannot reproduce+ * the ICU rejection, which is why the parser itself is pinned here instead.+ */++/** The JSON payload of a `[HostSendMsg {…}]` turn, or null when [text] is not exactly that marker. */+fun hostSendMsgJson(text: String): String? {+    val payload = hostMarkerPayload(text, "HostSendMsg") ?: return null+    return payload.takeIf { it.length >= 2 && it.first() == '{' && it.last() == '}' }+}++/** The pending-call id of a `[HostConfirm id]` turn, or null when [text] is not exactly that marker. */+fun hostConfirmId(text: String): String? = hostMarkerId(text, "HostConfirm")++/** The pending-call id of a `[HostCancel id]` turn, or null when [text] is not exactly that marker. */+fun hostCancelId(text: String): String? = hostMarkerId(text, "HostCancel")++private fun hostMarkerId(text: String, marker: String): String? {+    val payload = hostMarkerPayload(text, marker) ?: return null+    // The old regex captured `[^\]]+`: an id may contain anything but the closing bracket.+    return payload.takeIf { it.isNotEmpty() && ']' !in it }+}++private fun hostMarkerPayload(text: String, marker: String): String? {+    val trimmed = text.trim()+    val prefix = "[$marker "+    if (!trimmed.startsWith(prefix) || !trimmed.endsWith("]")) return null+    return trimmed.substring(prefix.length, trimmed.length - 1)+}
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.ktindex 379a631026..4cc6836f1d 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ModelLoadFailure.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/ModelLoadFailure.kt@@ -49,6 +49,16 @@ fun classifyModelLoadFailure(     return ModelLoadFailure.FailedToLoad(engineError?.takeIf { it.isNotBlank() }) } +/** The classified load failure for [directory] as the exception the service throws. */+fun modelLoadException(+    sizes: Map<String, Long?>,+    required: List<String>,+    expectedBytes: Map<String, Long>,+    engineError: String?,+    directory: String,+): IllegalStateException =+    IllegalStateException(classifyModelLoadFailure(sizes, required, expectedBytes, engineError).describe(directory))+ /** 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 ->
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 5c10f8bbb3..d9d35d40df 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -66,9 +66,10 @@ 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.modelLoadException+import com.vayunmathur.openassistant.domain.hostCancelId+import com.vayunmathur.openassistant.domain.hostConfirmId+import com.vayunmathur.openassistant.domain.hostSendMsgJson import com.vayunmathur.openassistant.domain.splitA2ui import com.vayunmathur.openassistant.domain.withA2uiBlock import kotlinx.coroutines.channels.Channel@@ -99,9 +100,6 @@ class InferenceService : Service() {         private const val INTENT_QUEUE_TTL_MILLIS = 45000L         private const val DB_WRITE_INTERVAL_MILLIS = 100L         private const val AUDIT_OUTCOME_CHARS = 200-        private val HOST_CONFIRM = Regex("""\[HostConfirm ([^\]]+)]""")-        private val HOST_CANCEL = Regex("""\[HostCancel ([^\]]+)]""")-        private val HOST_SEND_MSG = Regex("""\[HostSendMsg (\{.*\})]""")         private const val INTENT_GATE_KEY = "intent"          /** The system prompt used when the user has not set a custom one. */@@ -453,27 +451,34 @@ class InferenceService : Service() {     private suspend fun ensureEngineInitialized() = engineLock.withLock {         if (engine != null) return@withLock         val dir = ModelUrls.GemmaMaml.modelDir(applicationContext)-        val created = engineFactory(dir)-        if (!created.load()) {-            val detail = created.loadError()-            created.close()-            // 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.-            val names = (Gemma4Handle.FILES + GEMMA4_EXPECTED_BYTES.keys).distinct()-            val sizes = names.associateWith { name ->-                File(dir, name).takeIf { it.isFile }?.length()-            }-            val failure = classifyModelLoadFailure(-                sizes,-                Gemma4Handle.FILES,-                GEMMA4_EXPECTED_BYTES,-                detail,-            )-            throw IllegalStateException(failure.describe(dir.absolutePath))+        // A factory/load failure can surface as an Error (class initialisation+        // or native linkage), not an Exception. Uncaught it kills the process+        // on every launch after the download gate (#928); converted here it+        // becomes the same typed load failure a refused load gets (#917).+        val created = runCatching { engineFactory(dir) }.getOrElse {+            if (it is CancellationException) throw it+            throw modelLoadFailure(dir, it.message ?: it.toString())+        }+        val loaded = runCatching { created.load() }.getOrElse {+            if (it is CancellationException) throw it+            runCatching { created.close() }+            throw modelLoadFailure(dir, it.message ?: it.toString())+        }+        if (!loaded) {+            val detail = runCatching { created.loadError() }.getOrNull()+            runCatching { created.close() }+            throw modelLoadFailure(dir, detail)         }         engine = created     } +    /** The typed load failure for [dir], classified from what is on disk (#917). */+    private fun modelLoadFailure(dir: File, detail: String?): IllegalStateException {+        val names = (Gemma4Handle.FILES + GEMMA4_EXPECTED_BYTES.keys).distinct()+        val sizes = names.associateWith { name -> File(dir, name).takeIf { it.isFile }?.length() }+        return modelLoadException(sizes, Gemma4Handle.FILES, GEMMA4_EXPECTED_BYTES, detail, dir.absolutePath)+    }+     /** 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)@@ -500,7 +505,7 @@ class InferenceService : Service() {      * and is never executed.      */     private suspend fun handleHostSendMarker(conversationId: Long, userText: String): Boolean {-        val json = HOST_SEND_MSG.matchEntire(userText.trim())?.groupValues?.get(1) ?: return false+        val json = hostSendMsgJson(userText) ?: return false         val args = runCatching {             Json.parseToJsonElement(json).jsonObject                 .mapValues { it.value.jsonPrimitive.content }@@ -532,9 +537,8 @@ class InferenceService : Service() {      /** Returns the model-turn text for a host marker, or null when [userText] is not one. */     private suspend fun handleHostMarker(conversationId: Long, userText: String): String? {-        val trimmed = userText.trim()-        val confirmId = HOST_CONFIRM.matchEntire(trimmed)?.groupValues?.get(1)-        val cancelId = HOST_CANCEL.matchEntire(trimmed)?.groupValues?.get(1)+        val confirmId = hostConfirmId(userText)+        val cancelId = hostCancelId(userText)         if (cancelId != null) {             val pending = loadPendingDomain(cancelId)             tools.removePending(cancelId)
openassistant/src/test/java/com/vayunmathur/openassistant/domain/HostMarkersTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HostMarkersTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HostMarkersTest.ktnew file mode 100644index 0000000000..6b3903d705--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/HostMarkersTest.kt@@ -0,0 +1,61 @@+package com.vayunmathur.openassistant.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * The host markers used to be companion-object regexes in InferenceService.+ * Android's ICU regex compiler rejected one of them where the JDK compiler+ * is lenient, so the service class failed to initialise and the app crashed+ * on every launch after the model download (#928). The parser is plain+ * string code now; these tests pin its grammar, including the exact payload+ * shape from the crash report, which host regex tests could not protect.+ */+class HostMarkersTest {++    @Test+    fun sendMarkerReturnsItsJsonPayload() {+        val payload = """{"address":"+15551234","line":"Sim","body":"running late"}"""+        assertEquals(payload, hostSendMsgJson("[HostSendMsg $payload]"))+    }++    @Test+    fun sendMarkerKeepsBracesAndBracketsInsideThePayload() {+        val payload = """{"body":"meet at } ] o'clock {now}"}"""+        assertEquals(payload, hostSendMsgJson("[HostSendMsg $payload]"))+    }++    @Test+    fun sendMarkerAcceptsWhitespaceAroundTheTurn() {+        assertEquals("""{"a":"b"}""", hostSendMsgJson("  [HostSendMsg {\"a\":\"b\"}]  "))+    }++    @Test+    fun sendMarkerRejectsNonMarkersAndMalformedPayloads() {+        assertNull(hostSendMsgJson("hello"))+        assertNull(hostSendMsgJson("[HostSendMsg {not json]"))+        assertNull(hostSendMsgJson("[HostSendMsg no-braces]"))+        assertNull(hostSendMsgJson("[HostSendMsg {}] trailing"))+        assertNull(hostSendMsgJson("prefix [HostSendMsg {}]"))+        assertNull(hostSendMsgJson("[HostConfirm {}]"))+        assertNull(hostSendMsgJson(""))+    }++    @Test+    fun confirmAndCancelReturnTheirIds() {+        assertEquals("abc-123", hostConfirmId("[HostConfirm abc-123]"))+        assertEquals("abc-123", hostCancelId("[HostCancel abc-123]"))+        assertNull(hostConfirmId("[HostCancel abc-123]"))+        assertNull(hostCancelId("[HostConfirm abc-123]"))+    }++    @Test+    fun confirmAndCancelRejectEmptyBracketedOrTrailingIds() {+        assertNull(hostConfirmId("[HostConfirm ]"))+        assertNull(hostCancelId("[HostCancel a]b]"))+        assertNull(hostConfirmId("[HostConfirm abc] extra"))+        assertNull(hostConfirmId("[HostConfirm abc"))+        assertNull(hostCancelId("HostCancel abc]"))+    }+}
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.ktindex b83a7c2307..6fdc1c6a7d 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceModelLoadTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceModelLoadTest.kt@@ -67,14 +67,17 @@ class InferenceServiceModelLoadTest {     }      /** Runs one chat turn against engines that refuse with [reason]; returns the stored error, path masked. */-    private fun errorFor(reason: String?): String {+    private fun errorFor(reason: String?): String = errorForFactory { RefusingEngine(reason) }++    /** Runs one chat turn with [factory] as the engine source; returns the stored error, path masked. */+    private fun errorForFactory(factory: (File) -> MamlChatEngine): 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) }+        service.engineFactory = factory         c.create()         service.onStartCommand(             Intent(ctx, InferenceService::class.java).apply {@@ -117,6 +120,19 @@ class InferenceServiceModelLoadTest {         assertFalse(text.contains("gemma4_embed.maml"), text)     } +    @Test fun anEngineFactoryErrorBecomesATypedLoadFailureNotACrash() {+        // #928's shape: class initialisation of something the engine touches+        // fails with an Error, which the old Exception-only catches let kill+        // the process. With every file present it must read as a refused load.+        writeModel()+        val text = errorForFactory {+            throw LinkageError("Syntax error in regexp pattern near index 20")+        }+        assertFalse(text.contains("missing", ignoreCase = true), text)+        assertTrue(text.contains("present") && text.contains("failed to load"), text)+        assertTrue(text.contains("Syntax error in regexp pattern"), text)+    }+     @Test fun aShortFileIsNamedWithItsSizes() {         writeModel(GEMMA4_EXPECTED_BYTES + ("gemma4_embed.maml" to 10L))         val text = errorFor("short files: gemma4_embed.maml 10/1566576256")