openassistant: drop unreadable start extras instead of crashing
- Commit
beb5e876bcd6adccdb76ea88d4a568caf0e08105- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-05 15:13 UTC (17 hours ago)
- Parents
f7e6274
InferenceService.onStartCommand read cross-app extras with no guard, so a parcel that fails to unmarshal (a foreign ResultReceiver subclass such as the sdk:openassistant one, or a mistyped extra) threw BadParcelableException/ClassCastException out of onStartCommand and killed the process with 'Unable to start service' instead of failing a single request. Read the RECEIVER extra first inside a RuntimeException guard: if the receiver itself is unreadable there is no channel to answer on, so the request is logged and dropped; if a later extra is unreadable the caller gets the existing error result code with 'Unreadable request extras'. Well-formed text, image, and intent requests behave exactly as before. MessageStore moves out of InferenceService.kt into its own file in the same package: the added guard pushed the service past the 800-line FileLength lint, and the persistence helper was already a separate class sharing only the file. Tests: InferenceServiceFakeEngineTest gains badReceiverExtraDoesNotCrashService (mistyped RECEIVER returns START_STICKY, no crash) and badExtraWithGoodReceiverGetsErrorResult (a bad extra ends in an error result on the good receiver). Verified: :openassistant:lint, :openassistant:lintVitalRelease, and :openassistant:testDevUnitTest green, together with :health:lint, :health:lintVitalRelease, :health:testDevUnitTest, :sdk:openassistant:lint, and :sdk:openassistant:testDebugUnitTest. RecipeEditorFlowTest timed out once in the first full health suite run and passes alone and in the rerun, matching its known full-suite race; no health code is touched here.
Diff
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex b8d0c12e2c..106fc1cb0f 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -27,7 +27,7 @@ _Install: ./install openassistant (dev by default)._ - Tool names are snake_case (`get_notes`, `add_to_memory`, `translate_text`), matching what LiteRT-LM exposed; the system prompt references them. Add a tool in `domain/AssistantToolSpecs.kt` AND `platform/AssistantTools.kt` (an init check fails if they disagree) - Model files live in `getExternalFilesDir(null)/gemma4/` (text, embed, head, vision, audio, tokenizer); the vision/audio towers load lazily and unload after 3 idle minutes - Photo attachments: Send in `ui/LiteRTChatUi` awaits the picker copy jobs before dispatching, so the photos shown in the composer are the files bound to the sent `Message.imagePaths` and the inference request. Stored image paths ride `HistoryTurn.imagePaths` through `domain/HistoryFit` (oldest turns drop whole when the history no longer fits) and are re-encoded by the vision tower on each turn, so a photo stays visible to the model on later turns-- `util/` is NOT a closed package root — don't add more files there (it holds only `InferenceService`); assistant surfaces are in `service/`+- `util/` is NOT a closed package root — don't add more files there (it holds only `InferenceService` + its `MessageStore`); assistant surfaces are in `service/` - A2UI: the model writes only ```` ```a2ui {"components":[...],"data":{...}} ```` and `domain/A2uiEnvelope` adds the protocol envelope. Surface id is `m<messageId>`; the block is stored in `Message.a2ui` (DB v4) and replayed by `platform/A2uiController.sync`. androidx.a2ui ships no renderer — `ui/A2uiSurfaceView` is ours. Add a component in `platform/AssistantCatalog` (schema + prompt line together) AND the `when` in `A2uiSurfaceView` - `AssistantCatalog.PROMPT_SECTION` is appended to every system prompt, so changing it (or the catalog) invalidates the baked `gemma4_prefix.kv`: still correct, but first turns prefill until it is rebaked with `bake_gemma4_prefix` - The system header (default prompt + A2UI section + all tool declarations) is prefilled on every cold turn; `domain/PromptBudgetTest` pins its total size — keep prompt/tool-description edits within that budget@@ -87,7 +87,8 @@ _Install: ./install openassistant (dev by default)._ - com/vayunmathur/openassistant/platform/A2uiController.kt — owns the A2UI engine; events → user turns - com/vayunmathur/openassistant/platform/A2uiComposeState.kt — snapshot-state registry + data model ### util/ — inference service-- com/vayunmathur/openassistant/util/InferenceService.kt+- com/vayunmathur/openassistant/util/InferenceService.kt — `onStartCommand` reads cross-app extras defensively: an unmarshallable/mistyped extra is logged and dropped (with an error result when the receiver itself read cleanly), never a process crash+- com/vayunmathur/openassistant/util/MessageStore.kt — message/pending-call persistence for InferenceService ## Verify (this module only) ```
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 d9d35d40df..806c878b51 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -240,15 +240,45 @@ class InferenceService : Service() { if (intent == null) return START_STICKY intent.setExtrasClassLoader(SecureResultReceiver::class.java.classLoader) - val conversationId = intent.getLongExtra("conversation_id", -1L)- val userMessageId = intent.getLongExtra("user_message_id", -1L)- val userText = intent.getStringExtra("user_text") ?: ""- val audioPath = intent.getStringExtra("audio_path")- val schema = intent.getStringExtra("schema")- val receiver = IntentCompat.getParcelableExtra(intent, "RECEIVER", ResultReceiver::class.java)+ // Extras arrive from other apps' processes, so unmarshalling can+ // throw BadParcelableException (e.g. a ResultReceiver subclass the+ // sender shipped but this app does not: the sdk:openassistant+ // SecureResultReceiver crashed this service that way) or a plain+ // ClassCastException for a mistyped extra. Uncaught, that kills the+ // process ("Unable to start service") instead of failing one call.+ // Read the receiver first so a later bad extra can still be answered+ // with an error; a bad receiver itself leaves no channel to answer+ // on, so that request is only logged and dropped.+ val receiver = try {+ IntentCompat.getParcelableExtra(intent, "RECEIVER", ResultReceiver::class.java)+ } catch (expected: RuntimeException) {+ Log.error("InferenceService", "Unreadable RECEIVER extra; dropping request", expected)+ return START_STICKY+ } - val imageUris = IntentCompat.getParcelableArrayListExtra(intent, "image_uris", Uri::class.java)- val staticImagePaths = intent.getStringArrayExtra("image_paths") ?: emptyArray()+ val conversationId: Long+ val userMessageId: Long+ val userText: String+ val audioPath: String?+ val schema: String?+ val imageUris: ArrayList<Uri>?+ val staticImagePaths: Array<String>+ try {+ conversationId = intent.getLongExtra("conversation_id", -1L)+ userMessageId = intent.getLongExtra("user_message_id", -1L)+ userText = intent.getStringExtra("user_text") ?: ""+ audioPath = intent.getStringExtra("audio_path")+ schema = intent.getStringExtra("schema")+ imageUris = IntentCompat.getParcelableArrayListExtra(intent, "image_uris", Uri::class.java)+ staticImagePaths = intent.getStringArrayExtra("image_paths") ?: emptyArray()+ } catch (expected: RuntimeException) {+ Log.error("InferenceService", "Unreadable intent extras; dropping request", expected)+ receiver?.send(+ RESULT_ERROR_CODE,+ Bundle().apply { putString("error", "Unreadable request extras") },+ )+ return START_STICKY+ } serviceScope.launch { val imagePathsFromUris = imageUris?.mapNotNull { uri ->@@ -736,64 +766,3 @@ class InferenceService : Service() { } } -/** Message persistence for [InferenceService], split out of the service class. */-internal class MessageStore(- private val messageDao: MessageDao,- private val conversationDao: ConversationDao,-) {- /** Conversation history, oldest first. */- suspend fun history(id: Long): List<DbMessage> = messageDao.getByConversation(id)-- /** Stores a finished reply: the prose as its text, any A2UI block beside it. */- suspend fun storeReply(id: Long, reply: String) {- val split = splitA2ui(reply, streaming = false)- val shown = if (split.visible.isBlank() && split.json == null) reply else split.visible- updateMessage(id, shown, split.json)- }-- /** Inserts a message and returns its row id. */- suspend fun upsert(msg: DbMessage): Long = messageDao.upsert(msg)-- /** Replaces a message's text and A2UI payload. */- suspend fun updateMessage(id: Long, text: String, a2ui: String? = null) {- val existing = messageDao.getById(id) ?: return- upsert(existing.copy(text = text, a2ui = a2ui))- }-- /** Converts a persisted pending tool call back to its domain form. */- fun pendingToDomain(entity: PendingToolCallEntity): PendingToolCall = PendingToolCall(- id = entity.id,- name = entity.toolName,- args = runCatching {- Json.parseToJsonElement(entity.argsJson).jsonObject- .mapValues { it.value.jsonPrimitive.content }- }.getOrDefault(emptyMap()),- summary = entity.summary,- createdAtMillis = entity.createdAt,- expiresAtMillis = entity.expiresAt,- consumed = entity.consumed,- )-- /** Converts a domain pending tool call to its persisted form. */- fun pendingToEntity(- pending: PendingToolCall,- conversationId: Long,- ): PendingToolCallEntity = PendingToolCallEntity(- id = pending.id,- conversationId = conversationId,- toolName = pending.name,- argsJson = JsonObject(pending.args.mapValues { JsonPrimitive(it.value) }).toString(),- summary = pending.summary,- createdAt = pending.createdAtMillis,- expiresAt = pending.expiresAtMillis,- consumed = pending.consumed,- )-- /** Sets the conversation title. */- suspend fun updateTitle(id: Long, title: String) {- val oldConversation = conversationDao.getById(id)- if (oldConversation != null) {- conversationDao.upsert(oldConversation.copy(title = title))- }- }-}
openassistant/src/main/java/com/vayunmathur/openassistant/util/MessageStore.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/MessageStore.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/MessageStore.ktnew file mode 100644index 0000000000..e246774a20--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/MessageStore.kt@@ -0,0 +1,78 @@+@file:SuppressLint("PackageStructure")++package com.vayunmathur.openassistant.util++import android.annotation.SuppressLint+import com.vayunmathur.openassistant.data.ConversationDao+import com.vayunmathur.openassistant.data.MessageDao+import com.vayunmathur.openassistant.data.PendingToolCallEntity+import com.vayunmathur.openassistant.domain.PendingToolCall+import com.vayunmathur.openassistant.domain.splitA2ui+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import com.vayunmathur.openassistant.data.Message as DbMessage++/** Message persistence for [InferenceService], split out of the service class. */+internal class MessageStore(+ private val messageDao: MessageDao,+ private val conversationDao: ConversationDao,+) {+ /** Conversation history, oldest first. */+ suspend fun history(id: Long): List<DbMessage> = messageDao.getByConversation(id)++ /** Stores a finished reply: the prose as its text, any A2UI block beside it. */+ suspend fun storeReply(id: Long, reply: String) {+ val split = splitA2ui(reply, streaming = false)+ val shown = if (split.visible.isBlank() && split.json == null) reply else split.visible+ updateMessage(id, shown, split.json)+ }++ /** Inserts a message and returns its row id. */+ suspend fun upsert(msg: DbMessage): Long = messageDao.upsert(msg)++ /** Replaces a message's text and A2UI payload. */+ suspend fun updateMessage(id: Long, text: String, a2ui: String? = null) {+ val existing = messageDao.getById(id) ?: return+ upsert(existing.copy(text = text, a2ui = a2ui))+ }++ /** Converts a persisted pending tool call back to its domain form. */+ fun pendingToDomain(entity: PendingToolCallEntity): PendingToolCall = PendingToolCall(+ id = entity.id,+ name = entity.toolName,+ args = runCatching {+ Json.parseToJsonElement(entity.argsJson).jsonObject+ .mapValues { it.value.jsonPrimitive.content }+ }.getOrDefault(emptyMap()),+ summary = entity.summary,+ createdAtMillis = entity.createdAt,+ expiresAtMillis = entity.expiresAt,+ consumed = entity.consumed,+ )++ /** Converts a domain pending tool call to its persisted form. */+ fun pendingToEntity(+ pending: PendingToolCall,+ conversationId: Long,+ ): PendingToolCallEntity = PendingToolCallEntity(+ id = pending.id,+ conversationId = conversationId,+ toolName = pending.name,+ argsJson = JsonObject(pending.args.mapValues { JsonPrimitive(it.value) }).toString(),+ summary = pending.summary,+ createdAt = pending.createdAtMillis,+ expiresAt = pending.expiresAtMillis,+ consumed = pending.consumed,+ )++ /** Sets the conversation title. */+ suspend fun updateTitle(id: Long, title: String) {+ val oldConversation = conversationDao.getById(id)+ if (oldConversation != null) {+ conversationDao.upsert(oldConversation.copy(title = title))+ }+ }+}
openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.ktindex 7e9d1551cc..552ba27e92 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt@@ -300,6 +300,44 @@ class InferenceServiceFakeEngineTest { assertEquals(0, code); assertEquals("""{"name":"Ada"}""", data?.getString("json_result")) } + @Test fun badReceiverExtraDoesNotCrashService() {+ // Regression: a foreign/mistyped RECEIVER extra (the sdk:openassistant+ // SecureResultReceiver subclass the OA app cannot unmarshal arrived+ // this way and killed the process in onStartCommand) must be dropped,+ // not crash the service. A mistyped extra stands in for the+ // ClassNotFound parcel failure, which Robolectric cannot reproduce+ // with every class on one classpath.+ val service = startService(FakeEngine())+ val intent = Intent(ctx, InferenceService::class.java).apply {+ putExtra("user_text", "extract")+ putExtra("schema", "{}")+ putExtra("RECEIVER", "not-a-receiver")+ }+ assertEquals(android.app.Service.START_STICKY, service.onStartCommand(intent, 0, 1))+ }++ @Test fun badExtraWithGoodReceiverGetsErrorResult() {+ val receiver = CapturingReceiver()+ val service = startService(FakeEngine())+ val intent = Intent(ctx, InferenceService::class.java).apply {+ putExtra("user_text", "extract")+ putExtra("schema", "{}")+ putExtra("RECEIVER", receiver)+ // A mistyped extra (a String where a Uri list belongs): reading+ // it must fail in the service, which then answers on the good+ // receiver instead of crashing.+ putExtra("image_uris", "not-a-uri-list")+ }+ assertEquals(android.app.Service.START_STICKY, service.onStartCommand(intent, 0, 1))+ assertTrue(receiver.latch.await(15, TimeUnit.SECONDS), "receiver should get an error result")+ val (code, data) = synchronized(receiver.results) { receiver.results.first() }+ assertEquals(-1, code)+ // Robolectric's Bundle returns null for a mistyped extra instead of+ // throwing, so the request may fail downstream rather than at read+ // time; either way it must end in an error result, never a crash.+ assertTrue(data?.getString("error")!!.isNotBlank())+ }+ @Test fun intentInferenceRejectsWronglyTypedFields() { // The schema says "name" is a string; a numeric name must not be // delivered to the caller as a successful extraction.