Modern Apps git

← Modern-Apps.git

openassistant: kill per-op descriptor rebinds; bounded turns

Commit
9fa966a68ebbedecbd057f4009f30d2e1e725a54
Author
Vayun Mathur <[email protected]>
When
2026-11-23 22:35 UTC (12 days ago)
Parents
3a245fb
The Vulkan buffer split (files past
max_memory_allocation_size become overlapping blocks,
keeping every allocation under the 1GB-class limit)
rebound the descriptor set unconditionally for every
op - ~1,094 binds per decode step - though consecutive
ops overwhelmingly share a window. record() now skips
the bind when the segment is already bound; the split
layout itself is untouched (existing Adreno-limit
split test passes; no >limit allocation introduced).

Also: standard inference is bounded (300s timeout ->
in-place error, turn loop survives), blank replies
resolve to an error instead of eternal '...', tool
progress is emitted when a tool STARTS, and the reply
writer publishes before its first 100ms tick.

Verified: 190 openassistant tests green + detekt; cargo
segment tests 18 passed, clippy clean. Device GPU
measurement still owed (no Vulkan device on the box).

Diff

library/ml/src/main/rust/src/vulkan/run_part2.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part2.rs b/library/ml/src/main/rust/src/vulkan/run_part2.rsindex 249ec22c4a..8310743a1c 100644--- a/library/ml/src/main/rust/src/vulkan/run_part2.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part2.rs@@ -107,6 +107,17 @@ impl Net {             // `scheduled` path. `None` is clean (nothing pending); `(0, u64::MAX)` is             // the unbounded marker. See `dirty_union`.             let mut dirty: Option<(u64, u64)> = None;+            // The descriptor set currently bound, so an op whose weights fall in+            // the same window as the previous op's does not rebind it. Before the+            // weights were windowed (and then blocked, to stay under the Vulkan+            // per-allocation limit) there was one set, written once and never+            // rebound; the split made this bind unconditional — ~1,094 binds in a+            // Gemma decode step, executed on every token's submit, even though+            // ops read the weights in file order and consecutive ops overwhelmingly+            // share a window. A set stays bound across dispatches and across+            // pipeline binds under the one layout every pipeline here shares, so+            // rebinding the same set is pure overhead on the GPU's front end.+            let mut bound_segment: Option<usize> = None;             for (step, op) in self.plan.ops.iter().enumerate() {                 // `scheduled` barriers go BEFORE the op that needs them: `steps[step]`                 // says whether anything written since the last barrier conflicts with@@ -165,14 +176,17 @@ impl Net {                             Some(&set) => set,                             None => return Err(format!("step {step} wants segment {segment}")),                         };-                        device.cmd_bind_descriptor_sets(-                            buffer,-                            vk::PipelineBindPoint::COMPUTE,-                            self.pipelines.layout(),-                            0,-                            &[set],-                            &[],-                        );+                        if bound_segment != Some(segment) {+                            device.cmd_bind_descriptor_sets(+                                buffer,+                                vk::PipelineBindPoint::COMPUTE,+                                self.pipelines.layout(),+                                0,+                                &[set],+                                &[],+                            );+                            bound_segment = Some(segment);+                        }                         let push = self.segments.rebase(segment, kind, &push);                         lap!(1);                         device.cmd_push_constants(
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 e427f068f4..f0d156ec55 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt@@ -173,6 +173,13 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable {                     Gemma4Handle.parseToolCall(reply)?.let { ParsedToolCall(it.name, it.arguments) }                 },                 executeTool = { call ->+                    // Emit progress the moment a tool starts, not when its+                    // whole round-trip returns: a web search can sit on+                    // socket timeouts for most of a minute, and without this+                    // the first visible feedback waited for the tool result+                    // plus the next generation round. The next generated+                    // token overwrites this with the cumulative reply text.+                    onText(toolProgressLabel(call.name))                     withContext(Dispatchers.IO) { tools.invoke(call) }.also {                         Log.status(TAG, "tool ${call.name} -> ${it.take(LOG_CHARS)}")                     }@@ -317,6 +324,14 @@ open class MamlChatEngine(private val modelDir: File) : AutoCloseable {     }      internal companion object {+        /** Short progress line shown while [toolName] executes, before its result streams back. */+        internal fun toolProgressLabel(toolName: String): String = when (toolName) {+            "web_search" -> "Searching the web…"+            "web_read", "web_read_result" -> "Reading a page…"+            "get_memories" -> "Checking memory…"+            else -> "Using a tool…"+        }+         const val TAG = "MamlChatEngine"         const val CHAT_REPLY_LIMIT = 1024         const val EXTRACT_REPLY_LIMIT = 1024
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 c253bef414..0e05c07cbe 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -93,6 +93,7 @@ class InferenceService : Service() {         private const val RESULT_ERROR_CODE = -1         private const val RESULT_OK_CODE = 0         private const val INTENT_TIMEOUT_MILLIS = 45000L+        private const val STANDARD_INFERENCE_TIMEOUT_MILLIS = 300_000L         private const val INTENT_QUEUE_TTL_MILLIS = 45000L         private const val HISTORY_RECENCY_MILLIS = 1000L         private const val DB_WRITE_INTERVAL_MILLIS = 100L@@ -173,6 +174,15 @@ class InferenceService : Service() {     internal var pendingDaoOverride: PendingToolCallDao? = null     internal var auditDaoOverride: AuditRecordDao? = null     internal var nowMillis: () -> Long = { System.currentTimeMillis() }++    /**+     * Terminal guard for a standard chat turn. The intent path has always had+     * a 45 s bound; the chat path had none, so a hung generation (or a tool+     * round-trip that never returns) left the "..." placeholder on screen+     * forever. Tests shorten this; production keeps a generous bound so a+     * slow-but-live reply still completes.+     */+    internal var standardInferenceTimeoutMillis: Long = STANDARD_INFERENCE_TIMEOUT_MILLIS     private val tools by lazy { AssistantTools(applicationContext, memoryDao) }      private val repository by lazy { OpenAssistantRepository.get(applicationContext) }@@ -602,14 +612,29 @@ class InferenceService : Service() {         val latest = AtomicReference("")         val writer = launchReplyWriter(conversationId, aiMsgId, latest)         val result = try {-            chat.chat(request, tools) { text ->-                if (halt || job?.isActive == false) {-                    false-                } else {-                    latest.set(splitA2ui(text).visible)-                    true+            withTimeout(standardInferenceTimeoutMillis) {+                chat.chat(request, tools) { text ->+                    if (halt || job?.isActive == false) {+                        false+                    } else {+                        latest.set(splitA2ui(text).visible)+                        true+                    }                 }             }+        } catch (e: TimeoutCancellationException) {+            // Terminal guard: resolve the "..." placeholder in place with a+            // friendly error instead of leaving it spinning forever (and+            // instead of the engine-reset retry, which would just make the+            // user wait through the same hang a second time).+            Log.error("InferenceService", "Standard inference timed out", e)+            withContext(NonCancellable) {+                store.updateMessage(+                    aiMsgId,+                    getString(R.string.error_prefix, getString(R.string.error_inference_timeout)),+                )+            }+            return         } catch (e: Exception) {             withContext(NonCancellable) { messageDao.deleteById(aiMsgId) }             throw e@@ -632,6 +657,13 @@ class InferenceService : Service() {                 Log.status("InferenceService", "Standard inference halted successfully.")             } else if (result.text.isNotBlank()) {                 store.storeReply(aiMsgId, result.text)+            } else {+                // An empty reply is still a terminal state: never leave the+                // "..." placeholder standing in for an answer that arrived.+                store.updateMessage(+                    aiMsgId,+                    getString(R.string.error_prefix, getString(R.string.error_empty_reply)),+                )             }             is ChatResult.Pending -> {                 val pending = tools.pendingById(result.pendingId) ?: PendingToolCall(@@ -668,13 +700,18 @@ class InferenceService : Service() {     ) = serviceScope.launch {         var written = ""         while (isActive) {-            delay(DB_WRITE_INTERVAL_MILLIS)+            // Publish before waiting: the first chunk must not sit in the+            // buffer for a whole tick before the user sees anything. After+            // that, flushes stay on the 100 ms cadence — tokens accumulate+            // in [latest] (bounded by the reply, never the whole payload)+            // and are written in chunks, not one DB write per token.             flushTitle(conversationId)             val text = latest.get()             if (text.isNotBlank() && text != written) {                 store.updateMessage(aiMsgId, text)                 written = text             }+            delay(DB_WRITE_INTERVAL_MILLIS)         }     }     private suspend fun flushTitle(conversationId: Long) {
openassistant/src/main/res/values/strings.xml
diff --git a/openassistant/src/main/res/values/strings.xml b/openassistant/src/main/res/values/strings.xmlindex 196a424823..07fe3e94f1 100644--- a/openassistant/src/main/res/values/strings.xml+++ b/openassistant/src/main/res/values/strings.xml@@ -23,7 +23,9 @@     <!-- InferenceService: Error returned via ResultReceiver when intent request has waited >45s in queue and is dropped -->     <string name="error_request_expired">Request expired in queue</string>     <!-- InferenceService: Error when intent inference exceeds timeout inside runIntentInferenceLoop -->-    <string name="error_inference_timeout">Inference timed out</string>+    <string name="error_inference_timeout">Inference timed out. Please try again.</string>+    <!-- InferenceService: Terminal message replacing the typing placeholder when a chat turn ends with no text -->+    <string name="error_empty_reply">The assistant returned an empty reply. Please try again.</string>     <!-- InferenceService: Generic fallback when AI engine throws unexpected exception -->     <string name="error_ai_engine_failed">AI engine failed</string>     <!-- InferenceService: Validation failure when LLM output is not valid JSON matching expected schema after retries -->
openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.ktindex 92a0185d75..2fb5dbd8a0 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/ToolLoopTest.kt@@ -84,6 +84,20 @@ class ToolLoopTest {         assertEquals(ToolLoopOutcome.Finished("Checking.\n\nYou have none."), outcome)     } +    @Test+    fun streamEndingWithoutToolSentinelStillCompletes() = runBlocking<Unit> {+        // The stream just ends: no closing <tool_call|> sentinel ever arrives.+        // That is a finished answer, not a hang — the loop must resolve with+        // the prose it has (markup fragment stripped) instead of waiting for+        // a terminator the provider never sends.+        val generator = FakeGenerator(listOf("Done.<|tool_call>call:get_notes{"))+        var executed = 0+        val outcome = runToolLoop(generator, parse, { executed++; "x" }, render) { true }+        assertEquals(ToolLoopOutcome.Finished("Done."), outcome)+        assertEquals(0, executed)+        assertEquals(1, generator.continuations.size)+    }+     @Test     fun generatorFailureIsReported() = runBlocking<Unit> {         val outcome = runToolLoop(FakeGenerator(emptyList()), parse, { "x" }, render) { true }
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 3712a3e45c..13ccf0bf0b 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/MamlChatEngineFakeModelTest.kt@@ -87,6 +87,30 @@ class MamlChatEngineFakeModelTest {         e.close()     } +    @Test fun toolRoundTripEmitsProgressBeforeFinalText() = runBlocking {+        var calls = 0+        val fake = FakeTextModel(script = { continuation, onToken ->+            calls+++            if (calls == 1) {+                "<|tool_call>call:get_memories{}<tool_call|>"+            } else {+                onToken("you have no memories"); "you have no memories"+            }+        })+        val e = engine(fake)+        val shown = mutableListOf<String>()+        val result = e.chat(ChatRequest("sys", emptyList(), "what do you know?"), tools()) { text ->+            shown += text; true+        }+        assertEquals(ChatResult.Reply("you have no memories", halted = false), result)+        // First visible feedback is the tool progress line, emitted when the+        // tool starts — not after its round-trip plus another generation.+        assertTrue(shown.isNotEmpty())+        assertEquals(MamlChatEngine.toolProgressLabel("get_memories"), shown.first())+        assertEquals("you have no memories", shown.last())+        e.close()+    }+     @Test fun renderUiCallAttachesA2uiFenceToReply() = runBlocking {         var calls = 0         val uiJson = """{"components":[{"id":"root","component":"Text","text":"Pick one"}]}"""
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 b88f40ff0c..27b539ffe6 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt@@ -84,7 +84,7 @@ class InferenceServiceFakeEngineTest {     }      class FakeEngine(-        var chatBehavior: (ChatRequest, (String) -> Boolean) -> ChatResult = { _, _ -> ChatResult.Reply("default reply", false) },+        var chatBehavior: suspend (ChatRequest, (String) -> Boolean) -> ChatResult = { _, _ -> ChatResult.Reply("default reply", false) },         var extractBehavior: (String, (String) -> Boolean) -> String? = { _, _ -> null },     ) : MamlChatEngine(File("/nonexistent-model")) {         var closed = false@@ -190,6 +190,34 @@ class InferenceServiceFakeEngineTest {         assertTrue(!InferenceService.halt)     } +    @Test fun hangingStreamTimesOutToErrorAndLoopSurvives() {+        val fake = FakeEngine(chatBehavior = { _, _ ->+            kotlinx.coroutines.delay(60_000)+            ChatResult.Reply("never arrives", false)+        })+        val service = startService(fake)+        service.standardInferenceTimeoutMillis = 300L+        service.onStartCommand(standardIntent(21L, "hang"), 0, 1)+        await("timeout error replaces placeholder") {+            messageDao.assistantTexts(21L).any { it.contains("timed out", ignoreCase = true) }+        }+        assertTrue(messageDao.assistantTexts(21L).none { it == "..." }, "placeholder must not survive a hang")+        // The job loop must still process the next turn after a timeout.+        fake.chatBehavior = { _, _ -> ChatResult.Reply("back again", false) }+        service.onStartCommand(standardIntent(21L, "again"), 0, 2)+        await("loop survives timeout") { messageDao.assistantTexts(21L).contains("back again") }+    }++    @Test fun blankReplyResolvesPlaceholderToError() {+        val fake = FakeEngine(chatBehavior = { _, _ -> ChatResult.Reply("", false) })+        val service = startService(fake)+        service.onStartCommand(standardIntent(22L, "blank"), 0, 1)+        await("empty-reply error replaces placeholder") {+            messageDao.assistantTexts(22L).any { it.contains("empty reply", ignoreCase = true) }+        }+        assertTrue(messageDao.assistantTexts(22L).none { it == "..." })+    }+     @Test fun tooLongUpdatesPlaceholderWithError() {         val fake = FakeEngine(chatBehavior = { _, _ -> ChatResult.TooLong })         val service = startService(fake)