openassistant: retry photo encode at smaller budgets (#929)
- Commit
11e611f01e265aa05f0e59528dcf0d9c78743695- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-04 18:21 UTC (1 day ago)
- Parents
11730ed
Bug: attaching a photo and asking about it got a reply asking for a photo, and sending one again got the same reply. The app had clearly received the picture (it renders in the bubble), yet the conversation acted as if none had been sent. Root cause: every other leg of the photo path was already sound (the composer Send awaits the picker copy jobs, the copied files ride Message.imagePaths and the inference intent, stored paths ride HistoryTurn through fitting and are re-encoded per turn, and the LRU encode cache works), and the JVM tests all stub that chain with fakes that cannot fail. The one production-only leg left was the vision encode itself: MamlChatEngine.encodeImageUncached made exactly one attempt, at the 280-soft-token reference budget, and encodeImages silently dropped the photo on the null that came back. The tower's scratch cost is quadratic in the budget (its own docs put two attention score maps at 254 MB for a square image at 280), so a device where that encode fails loses every photo deterministically and text-only is indistinguishable from never having sent one. There was no fallback and no log. Fix (platform/MamlChatEngine only; no InferenceService change, so it cannot collide with the #928 work there): an encode now walks the tower's accepted budgets down from the reference default (280, then 140, then 70, derived from SOFT_TOKEN_BUDGETS) and the first success wins; a photo that fails every budget is still dropped, but the drop, the fallback recovery, and an undecodable file are now all logged. The successful fallback result goes through the same LRU cache as any encode. AGENTS.md records the fallback next to the existing photo-caching note. Regression tests (MamlChatEngineFakeModelTest, towerEncoder seam): photoFallsBackToSmallerBudgetWhenDefaultEncodeFails fails under the old single-attempt code (the captured turn has no vision input) and now asserts the budget order, the vision input, and that the fallback result is cached; photoThatFailsEveryBudget StillAnswersTextOnly pins the degrade-to-text behaviour. Verified fresh in this worktree: ./gradlew :openassistant:lint :openassistant:lintVitalRelease :openassistant:testDevUnitTest BUILD SUCCESSFUL (276 JVM + 79 native tests, 0 failures; lintVitalRelease also re-run with --rerun-tasks to prove it executes). Baseline before the change had exactly one failure, InferenceServiceConcurrencyTest.twoConversationsGenerate ConcurrentlyAndBothComplete, the known load flake; it passed on the fresh full run, so no unrelated failure remains.
Diff
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex f261954db4..a95a736f7e 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -31,7 +31,7 @@ _Install: ./install openassistant (dev by default)._ - 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-- Kept photos are vision-encoded once and cached in the engine (LRU, 4 images ≈ 7 MB of soft tokens, keyed by path+size+mtime); the shared `AssistantTools` render-UI stash is consumed by whichever turn finishes next, so concurrent turns should not both rely on it in the same instant+- Kept photos are vision-encoded once and cached in the engine (LRU, 4 images ≈ 7 MB of soft tokens, keyed by path+size+mtime); an encode walks the accepted soft-token budgets down from the reference default before a photo is dropped, and a drop is logged — a dropped photo otherwise reads exactly like no photo was sent. The shared `AssistantTools` render-UI stash is consumed by whichever turn finishes next, so concurrent turns should not both rely on it in the same instant ## Key files ### Root — entry + inline navigation
openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.ktindex 47c9193bf0..7a5a82f918 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt@@ -95,6 +95,15 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable { */ internal var imageEncoder: ((String) -> FloatArray?)? = null + /**+ * Behavior-preserving test seam for one tower encode at a given soft-token+ * budget: production leaves this null and encodes through+ * [Gemma4VisionHandle]; tests substitute a fake because the tower cannot+ * load on the JVM. A null result means that budget failed, like a failed+ * encode in production.+ */+ internal var towerEncoder: ((Bitmap, Int) -> FloatArray?)? = null+ /** The text-generation surface [MamlChatEngine] needs from the model. */ internal interface TextModel { val available: Boolean@@ -353,14 +362,42 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable { private fun encodeImageUncached(path: String): FloatArray? { imageEncoder?.let { encode -> return encode(path) }- val tower = vision?.takeIf { it.isAvailable }- ?: Gemma4VisionHandle.inDirectory(modelDir).also { vision = it }- if (!tower.isAvailable) {- Log.status(TAG, "vision tower unavailable; dropping image $path")+ val bitmap = decodeDownscaled(path) ?: run {+ Log.status(TAG, "cannot decode $path; dropping the attached photo") return null }- val bitmap = decodeDownscaled(path) ?: return null- return tower.encode(bitmap, Gemma4VisionHandle.SOFT_TOKENS_DEFAULT).also { bitmap.recycle() }+ // One attempt at the reference budget was the whole story: the+ // tower's scratch cost is quadratic in the budget, so an encode that+ // fails at 280 soft tokens on a device often succeeds at 140 or 70 —+ // but the null came back here and the photo was dropped without a+ // word, so the model answered as if none had been sent and asked+ // for one, on every retry (#929). Walk the accepted budgets down+ // before giving up, and log whichever way it ends.+ try {+ towerEncoder?.let { encode -> return encodeWithBudgetFallback(path) { encode(bitmap, it) } }+ val tower = vision?.takeIf { it.isAvailable }+ ?: Gemma4VisionHandle.inDirectory(modelDir).also { vision = it }+ if (!tower.isAvailable) {+ Log.status(TAG, "vision tower unavailable; dropping image $path")+ return null+ }+ return encodeWithBudgetFallback(path) { tower.encode(bitmap, it) }+ } finally {+ bitmap.recycle()+ }+ }++ /** [encode] at each of [IMAGE_ENCODE_BUDGETS] in turn; the first success wins, null when all fail. */+ private fun encodeWithBudgetFallback(path: String, encode: (Int) -> FloatArray?): FloatArray? {+ for (budget in IMAGE_ENCODE_BUDGETS) {+ val encoded = encode(budget) ?: continue+ if (budget != IMAGE_ENCODE_BUDGETS.first()) {+ Log.status(TAG, "vision tower encoded $path at $budget soft tokens after a larger budget failed")+ }+ return encoded+ }+ Log.status(TAG, "vision tower could not encode $path at any budget; dropping the attached photo")+ return null } /** Cached photo count, for tests. */@@ -428,6 +465,16 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable { const val LOG_CHARS = 120 const val MAX_CACHED_IMAGES = 4 + /**+ * Budgets one photo encode walks down, largest first: the reference+ * default, then every smaller budget the tower accepts. A smaller+ * budget is a coarser picture, never a missing one.+ */+ internal val IMAGE_ENCODE_BUDGETS: List<Int> =+ Gemma4VisionHandle.SOFT_TOKEN_BUDGETS+ .filter { it <= Gemma4VisionHandle.SOFT_TOKENS_DEFAULT }+ .sortedDescending()+ internal fun decodeDownscaled(path: String): Bitmap? { val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } BitmapFactory.decodeFile(path, bounds)
openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.ktindex d9aa5840a9..1bedb6de03 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt@@ -3,6 +3,7 @@ package com.vayunmathur.openassistant.platform import androidx.test.core.app.ApplicationProvider import android.content.Context import com.vayunmathur.library.ml.Gemma4Handle+import com.vayunmathur.library.ml.Gemma4VisionHandle import com.vayunmathur.library.ml.Sampling import com.vayunmathur.openassistant.util.InferenceServiceFakeEngineTest import kotlinx.coroutines.runBlocking@@ -378,6 +379,60 @@ class MamlChatEngineFakeModelTest { e.close() } + // #929: on device the tower encode at the reference budget can fail+ // (its scratch cost is quadratic in the budget) where a smaller accepted+ // budget succeeds. Production had a single attempt, and the null dropped+ // the photo without a word — the turn reached the model text-only and it+ // asked the user to send a picture they had already sent. The fake tower+ // here fails the default budget the way the real one can, so this test+ // only passes if the engine walks the budgets down.+ @Test fun photoFallsBackToSmallerBudgetWhenDefaultEncodeFails() = runBlocking {+ val image = java.awt.image.BufferedImage(8, 6, java.awt.image.BufferedImage.TYPE_INT_ARGB)+ val png = File(ctx.cacheDir, "fallback-photo.png"); javax.imageio.ImageIO.write(image, "png", png)+ val fake = FakeTextModel()+ val e = engine(fake)+ val attempted = mutableListOf<Int>()+ e.towerEncoder = { _, budget ->+ attempted += budget+ if (budget == Gemma4VisionHandle.SOFT_TOKENS_DEFAULT) null else FloatArray(1536)+ }+ val result = e.chat(+ ChatRequest("sys", emptyList(), "what is in this photo?", imagePaths = listOf(png.absolutePath)),+ tools(),+ ) { true }+ assertEquals(ChatResult.Reply("plain answer", halted = false), result)+ assertEquals(+ listOf(Gemma4VisionHandle.SOFT_TOKENS_DEFAULT, 140),+ attempted,+ "encode must retry at the next smaller budget, got $attempted",+ )+ val turn = fake.lastConversation.single()+ assertEquals(1, turn.images.size, "photo must reach the model as a vision input, got ${turn.images.size}")+ // The fallback result is cached like any encode: a later turn over+ // the same photo does not encode again.+ val again = e.chat(ChatRequest("sys", emptyList(), "and now?", imagePaths = listOf(png.absolutePath)), tools()) { true }+ assertEquals(ChatResult.Reply("plain answer", halted = false), again)+ assertEquals(2, attempted.size, "cached photo must not re-encode, got $attempted")+ e.close()+ }++ @Test fun photoThatFailsEveryBudgetStillAnswersTextOnly() = runBlocking {+ val image = java.awt.image.BufferedImage(8, 6, java.awt.image.BufferedImage.TYPE_INT_ARGB)+ val png = File(ctx.cacheDir, "unencodable-photo.png"); javax.imageio.ImageIO.write(image, "png", png)+ val fake = FakeTextModel()+ val e = engine(fake)+ val attempted = mutableListOf<Int>()+ e.towerEncoder = { _, budget -> attempted += budget; null }+ val result = e.chat(+ ChatRequest("sys", emptyList(), "what is in this photo?", imagePaths = listOf(png.absolutePath)),+ tools(),+ ) { true }+ assertEquals(ChatResult.Reply("plain answer", halted = false), result)+ assertEquals(MamlChatEngine.IMAGE_ENCODE_BUDGETS, attempted, "every budget must be tried before dropping")+ assertTrue(fake.lastConversation.single().images.isEmpty())+ e.close()+ }+ @Test fun historyIsTrimmedWhenItCannotFit() = runBlocking { val fake = FakeTextModel() fake.script = { _, onToken -> onToken("ok"); "ok" }