Repository navigation
Studio: resume local chat generation after disconnect - #9187
Conversation
Preserve the durable chat runtime state while carrying forward multimodal projector fallback metadata. Update the combined frontend test harness to resolve the new upstream module.
Resolve queued model capability test imports by registering the bundler resolver before dynamically loading both utility modules. This preserves all PR assertions while carrying forward main's cross-platform Node loader fix.
# Conflicts: # studio/frontend/src/features/chat/api/chat-adapter.ts
Resolve chat history deletion conflicts by preserving durable generation cancellation and adding conversation archive cleanup. Resolve chat adapter metadata conflicts by retaining both resumable-run status and context truncation metadata.
|
@codex address that feedback |
Summary
Testing
|
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Heads up, this needs a merge from you before CI can say anything: the branch is now 21 commits behind Three conflicts, all from upstream Deep Research work landing while this was open, none of them in the durable-generation code:
Also worth knowing for when it does run: the earlier pre-commit.ci failure was not one of yours either. Its autofix push was skipped with "a conflict occurred when applying fixes to the pr", and the 146 files it wanted to reformat are repo-wide kwarg-spacing drift from Nothing else is outstanding on the review side: both of the latest items are answered, and Codex has no open ones. |
Conflicts were all upstream Deep Research work landing while this was open: - studio_db.py: upsert_chat_message keeps allow_generation_edit alongside main's expected_research_run_id / expected_research_attempt and its dict | None return. The body already used both sides. - chat-adapter.ts: taken from main in all three hunks. This branch made no semantic change in those regions, only line reflow; main extracted the withResolvedModel helper, added the research question field, and dropped the setDeepResearchEnabled(false) block on purpose. - test_multi_chat_prompt_queue_contract.py: main's assertion, which pins a string that exists in the merged adapter.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 93f0a74bd9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| token_budget is not None | ||
| and isinstance(completion_tokens, int) | ||
| and not isinstance(completion_tokens, bool) | ||
| and completion_tokens >= token_budget | ||
| ): |
There was a problem hiding this comment.
Override MLX's stop reason when the durable run hits its cap
When MLX reports finish_reason="stop" together with completion_tokens >= token_budget, the earlier named-reason return prevents this new token-budget branch from ever returning length. In that stop-at-cap scenario, the durable run is saved as normally completed, so reload loses the incomplete/Continue state this normalization is intended to preserve; apply the durable MLX cap override before accepting a reported stop.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Checked this against mlx-lm's own source rather than reasoning from the symptom, and the current precedence is right.
stream_generate builds the final response with finish_reason="stop" if token in tokenizer.eos_token_ids else "length". So mlx_lm says stop only when an EOS token was actually sampled, and says length on plain max_tokens exhaustion. The pairing you describe, stop together with completion_tokens >= token_budget, is therefore the legitimate case where a stop token was sampled as the last allowed token. That turn really did finish, and there is nothing further to generate. Overriding it to length would put a "Response hit the Max Tokens limit / Continue" bar on a completed answer, which is the opposite of the truthfulness this normalization is for.
This repo's _mlx_finish_reason already draws the same distinction one layer down, and for mlx_vlm, whose result carries no reason, it falls back to the last token's identity rather than a count, since "a stop token sampled as the final allowed token looks identical to ordinary exhaustion".
The token-budget branch is not dead code either: it is the fallback for stats that name no reason at all, which is the shape _build_generation_stats produces by default and the shape test_only_durable_mlx_normalizes_stop_at_token_cap exercises (its stats is {"usage": {...}} with no finish_reason). A named reason winning over a count is deliberate, so leaving as-is.
A stale tab's snapshot sync could delete an edited generated assistant. Editing a settled answer detaches it, which drops the run row and so takes the id out of the generation-linked set, while the stale tab's copy is filtered out as tombstoned before requested_ids is computed. Absent from both sets, it was pruned. Tombstoned ids now stay in the retention set unless the delete flow names them. Continue could fail outright instead of generating. The partial is yielded into the sibling assistant before the request starts, so its autosave can land before admission, and admission refuses a placeholder that already has content with a 409, which is not a legacy-fallback error. Continuations stay on the legacy stream, as they did before durable runs. A Stop that was recorded but not yet settled became a backend failure across a restart. Reconciliation now branches on cancelling / cancel_requested the way finish_run already does, and emits run.cancelled. A caught-up reconnect to a settled run blocked for the full 15s event wait before reading the snapshot, showing a finished answer as still generating and holding an event-wait worker. The terminal snapshot is read before the wait. Recovered usage and timings lived only in locals while the published cursor advanced past the usage chunk, so a reload lost the token counts for good. They now travel with the cursor, like generationFirstChunkAt and generationChunkCount already do.
|
Third round. Six items, five real and fixed in A stale tab could delete an edited generated answer. The one worth reading twice. Editing a settled generated assistant detaches it, and that same detach drops the run row, so the id stops counting as generation-linked. Meanwhile the other tab's pre-edit copy is filtered out as tombstoned before Continue could fail outright. The partial is yielded into the sibling assistant before the request starts, deliberately ( A Stop that outlived a restart came back as a backend failure. Reproduced: A caught-up reconnect blocked for the full event wait. Measured at 15.00s, now 0.00s. For those 15 seconds a finished answer read as still generating, and an event-wait worker was held for nothing. Recovered usage was lost on reload. Usage and timings sat in locals while the published cursor advanced past the usage chunk, so a reload resumed after it and the token counts were gone permanently. They now travel with the cursor, the same way Rejected: overriding MLX's stop reason at the cap. mlx-lm builds its final response with Each fix has a test that fails without it, and the two that could over-correct have a second test pinning the case they must not swallow: an explicit delete still removes a detached assistant, and an uncancelled run still reconciles as interrupted. What was run: backend 6899 passed, frontend 5278 passed, typecheck clean, ruff clean. Two backend failures ( Also note the branch now merges |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
… moves Source-inspection contracts still pointed at openai_chat_completions after unslothai#9187 split produce_openai_chat_completions out, and at strings that unslothai#7880 and unslothai#9683 moved. Point them at the live sites and defer PEP 604 unions in the new kv-cache estimate tests.
) * Studio: add Chat settings to disable or ease GGUF auto-compaction Local GGUF chats always opted into truncate_oldest, then compacted at the prompt budget with a 25% extra trim (or a full checkpoint reset). Settings now let you turn that off, switch to a sliding window, and choose how much extra room a rolling compaction takes. Compaction still keys off the configured context length, not free VRAM. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: honor Chat compaction settings over process defaults Send checkpoint/error overflow fields from Studio so Chat settings override UNSLOTH_CONTEXT_POLICY and UNSLOTH_CONTEXT_OVERFLOW. Refuse checkpoint-origin sticky boundaries when a request forces rolling, and route search_conversation from the same effective policy as the fitter. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * honor zero compaction headroom * test zero-headroom rolling compaction * preserve server compaction policy by default * test server policy inheritance * mark studio-owned tool history * keep studio tool history on the fitted path * isolate studio tool history provenance * test compaction after local tool use * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * complete locale settings translations * fix sanitized catalog guard coverage * run pip cache guard on workflow changes * set utf-8 for pip cache guard reads * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * mark studio tool history in token counts * reset boundaries when context policy changes * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * mark studio tool history from replayed calls Hosted server builtins such as web_search are dropped during OpenAI serialization, so ownership must be derived from the calls that actually go on the wire. Mixed hosted-plus-local history can then keep the studio_tool_history marker and stay on the compaction path. * align prune contract test with token-count history builder The send and count paths both prune through pruneOutboundHistory into survivingMessages; the source contract still expected the old outboundMessages name on the count path. * align sticky and token-count harnesses with current compaction APIs Recall fixtures store rolling-shaped truncation records, so pin CONTEXT_POLICY to rolling when faking studio_db. Recount and prune harnesses follow the renamed token-count builder, a tighter setActiveThreadId slice, and the send-path prune call rather than the earlier count-path copy. * test(studio): follow main's chat-completions extract and VRAM/keyless moves Source-inspection contracts still pointed at openai_chat_completions after #9187 split produce_openai_chat_completions out, and at strings that #7880 and #9683 moved. Point them at the live sites and defer PEP 604 unions in the new kv-cache estimate tests. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * drop the duplicate workflow guard entry this pr added tests/studio/test_pip_cache_naming.py was already listed at line 141 of .github/workflows/workflow-trigger-lint.yml, so the Workflow guard suites step collected it twice. The trailing newline it also removed goes back. * keep the eviction bite for requests that chose no compaction setting fit_rolling_context gated the 5% floor on each eviction bite on `headroom > 0`, but keeps_boundary = False zeroes the headroom for every threadless API request and incognito chat. Those callers send no new field, so they were handed the "no extra trim" behaviour anyway: on a 201-message transcript at context_length 1100 eviction fell from 12 messages to 2. Gate it on the requested ratio instead, so only a caller that actually asked for no extra trim gives the floor up. * replay a rolling boundary where the fit cannot start an epoch _sticky_compaction_boundary rejected any boundary whose recorded policy differed from the process policy, in both directions. The rolling-to-checkpoint direction is only unsafe where fit_checkpoint_context would read the boundary as an epoch already in force and skip the reset's recall, and that needs _can_reset_epoch. Threads it refuses -- a template that cannot render tools, --disable-tools, no conversation archive -- compact through fit_rolling_context and record a rolling boundary, so on a checkpoint-default server every later turn discarded it and the boundary slid again. Measured on a stored boundary of 6: base restored 6, this branch returned 0. Each call site now computes _can_reset_epoch once and hands the same value to the boundary read and to the fit. * declare studio_tool_history on the token-count request refreshContextUsage forwards the marker, but ChatCountTokensRequest only carried it through extra = "allow", which coerces nothing. A client sending the JSON string "false" reached _only_studio_tool_history as a truthy value and moved the count onto the Unsloth tool path the completion never takes, so the context-usage bar priced a different prompt. The model's own bypass_permissions field is declared for the same reason. * restore the constraint the renamed tool-history helper documented Renaming _only_studio_memory_tool_history to _only_studio_tool_history replaced its docstring with three lines that say what the marker is and no longer say why the strict route exists: a replayed tool pair read as a client contract sends the turn to the llama-server passthrough, which runs no context fit, so the epoch, the carried-forward block and the automatic recall are gone one turn after the compaction that created them. Put that back, and match the sentence case the rest of the file and the api.ts field comments use. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * keep a rolling boundary off the checkpoint replay branch A request that may not reset still takes the checkpoint REPLAY branch in _fit_context under a checkpoint policy, so the rolling-origin boundary the previous commit restored reached fit_checkpoint_context and read as an epoch already in force. The fit returned checkpoint_started false, and _archive_and_recall reads that as "already recalled" and injected nothing. Measured at context_length 1800 with a stored boundary of 30: the reply lost the archived turns the rolling fallback would have pulled back. _sticky_compaction_state now returns the depth and whether a checkpoint reset recorded it, mixed provenance across surviving rows counting as rolling since min(boundaries) may pick either row. _fit_context takes that as sticky_is_checkpoint and enters the replay branch only for a real epoch; otherwise the count stays on the rolling fitter, which reports no checkpoint_started and still recalls. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * discard a boundary cut with more extra trim than the request asks for Phase one of fit_rolling_context re-applies the saved boundary before anything else and returns as soon as the result fits, so an already-compacted chat that moved from 25% extra room down to 10%, 5% or none replayed the deeper cut and never reached the phase that reads the new ratio. Lowering the setting did nothing at all, and the history the client had re-sent stayed dropped. The persisted truncation now carries boundary_headroom_ratio beside boundary_messages and boundary_anchor, written through one _boundary_metadata helper so the three cannot drift apart. _sticky_compaction_state refuses a rolling boundary recorded under a larger ratio than this request wants; a larger request needs no refusal, since phase two moves the boundary out by itself. Rows saved before the ratio existed carry no key and replay as they did, and a checkpoint reset ignores headroom so its depth is never refused over it. * refuse a replayed boundary on any change of extra trim, not just a cut The previous commit only refused a boundary recorded under MORE headroom than the request asked for, on the reasoning that phase two would widen a shallower one by itself. It does not: phase one re-applies the saved count and phase two runs only when the result still does not fit, so a shallower boundary that already fits is just as inert. Measured on a 121-message transcript at context_length 1600, a stored boundary of 86 gave dropped 86 under both 0.05 and 0.25, so raising the setting did nothing either. Compare for equality instead. With the 5%-origin boundary of 86 above, a request at 0.05 still replays it and a request at 0.25 recomputes to 94. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: mahiatlinux <[email protected]>
) * Studio: add Chat settings to disable or ease GGUF auto-compaction Local GGUF chats always opted into truncate_oldest, then compacted at the prompt budget with a 25% extra trim (or a full checkpoint reset). Settings now let you turn that off, switch to a sliding window, and choose how much extra room a rolling compaction takes. Compaction still keys off the configured context length, not free VRAM. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: honor Chat compaction settings over process defaults Send checkpoint/error overflow fields from Studio so Chat settings override UNSLOTH_CONTEXT_POLICY and UNSLOTH_CONTEXT_OVERFLOW. Refuse checkpoint-origin sticky boundaries when a request forces rolling, and route search_conversation from the same effective policy as the fitter. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * honor zero compaction headroom * test zero-headroom rolling compaction * preserve server compaction policy by default * test server policy inheritance * mark studio-owned tool history * keep studio tool history on the fitted path * isolate studio tool history provenance * test compaction after local tool use * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * complete locale settings translations * fix sanitized catalog guard coverage * run pip cache guard on workflow changes * set utf-8 for pip cache guard reads * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * mark studio tool history in token counts * reset boundaries when context policy changes * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * mark studio tool history from replayed calls Hosted server builtins such as web_search are dropped during OpenAI serialization, so ownership must be derived from the calls that actually go on the wire. Mixed hosted-plus-local history can then keep the studio_tool_history marker and stay on the compaction path. * align prune contract test with token-count history builder The send and count paths both prune through pruneOutboundHistory into survivingMessages; the source contract still expected the old outboundMessages name on the count path. * align sticky and token-count harnesses with current compaction APIs Recall fixtures store rolling-shaped truncation records, so pin CONTEXT_POLICY to rolling when faking studio_db. Recount and prune harnesses follow the renamed token-count builder, a tighter setActiveThreadId slice, and the send-path prune call rather than the earlier count-path copy. * test(studio): follow main's chat-completions extract and VRAM/keyless moves Source-inspection contracts still pointed at openai_chat_completions after #9187 split produce_openai_chat_completions out, and at strings that #7880 and #9683 moved. Point them at the live sites and defer PEP 604 unions in the new kv-cache estimate tests. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * drop the duplicate workflow guard entry this pr added tests/studio/test_pip_cache_naming.py was already listed at line 141 of .github/workflows/workflow-trigger-lint.yml, so the Workflow guard suites step collected it twice. The trailing newline it also removed goes back. * keep the eviction bite for requests that chose no compaction setting fit_rolling_context gated the 5% floor on each eviction bite on `headroom > 0`, but keeps_boundary = False zeroes the headroom for every threadless API request and incognito chat. Those callers send no new field, so they were handed the "no extra trim" behaviour anyway: on a 201-message transcript at context_length 1100 eviction fell from 12 messages to 2. Gate it on the requested ratio instead, so only a caller that actually asked for no extra trim gives the floor up. * replay a rolling boundary where the fit cannot start an epoch _sticky_compaction_boundary rejected any boundary whose recorded policy differed from the process policy, in both directions. The rolling-to-checkpoint direction is only unsafe where fit_checkpoint_context would read the boundary as an epoch already in force and skip the reset's recall, and that needs _can_reset_epoch. Threads it refuses -- a template that cannot render tools, --disable-tools, no conversation archive -- compact through fit_rolling_context and record a rolling boundary, so on a checkpoint-default server every later turn discarded it and the boundary slid again. Measured on a stored boundary of 6: base restored 6, this branch returned 0. Each call site now computes _can_reset_epoch once and hands the same value to the boundary read and to the fit. * declare studio_tool_history on the token-count request refreshContextUsage forwards the marker, but ChatCountTokensRequest only carried it through extra = "allow", which coerces nothing. A client sending the JSON string "false" reached _only_studio_tool_history as a truthy value and moved the count onto the Unsloth tool path the completion never takes, so the context-usage bar priced a different prompt. The model's own bypass_permissions field is declared for the same reason. * restore the constraint the renamed tool-history helper documented Renaming _only_studio_memory_tool_history to _only_studio_tool_history replaced its docstring with three lines that say what the marker is and no longer say why the strict route exists: a replayed tool pair read as a client contract sends the turn to the llama-server passthrough, which runs no context fit, so the epoch, the carried-forward block and the automatic recall are gone one turn after the compaction that created them. Put that back, and match the sentence case the rest of the file and the api.ts field comments use. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * keep a rolling boundary off the checkpoint replay branch A request that may not reset still takes the checkpoint REPLAY branch in _fit_context under a checkpoint policy, so the rolling-origin boundary the previous commit restored reached fit_checkpoint_context and read as an epoch already in force. The fit returned checkpoint_started false, and _archive_and_recall reads that as "already recalled" and injected nothing. Measured at context_length 1800 with a stored boundary of 30: the reply lost the archived turns the rolling fallback would have pulled back. _sticky_compaction_state now returns the depth and whether a checkpoint reset recorded it, mixed provenance across surviving rows counting as rolling since min(boundaries) may pick either row. _fit_context takes that as sticky_is_checkpoint and enters the replay branch only for a real epoch; otherwise the count stays on the rolling fitter, which reports no checkpoint_started and still recalls. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * discard a boundary cut with more extra trim than the request asks for Phase one of fit_rolling_context re-applies the saved boundary before anything else and returns as soon as the result fits, so an already-compacted chat that moved from 25% extra room down to 10%, 5% or none replayed the deeper cut and never reached the phase that reads the new ratio. Lowering the setting did nothing at all, and the history the client had re-sent stayed dropped. The persisted truncation now carries boundary_headroom_ratio beside boundary_messages and boundary_anchor, written through one _boundary_metadata helper so the three cannot drift apart. _sticky_compaction_state refuses a rolling boundary recorded under a larger ratio than this request wants; a larger request needs no refusal, since phase two moves the boundary out by itself. Rows saved before the ratio existed carry no key and replay as they did, and a checkpoint reset ignores headroom so its depth is never refused over it. * refuse a replayed boundary on any change of extra trim, not just a cut The previous commit only refused a boundary recorded under MORE headroom than the request asked for, on the reasoning that phase two would widen a shallower one by itself. It does not: phase one re-applies the saved count and phase two runs only when the result still does not fit, so a shallower boundary that already fits is just as inert. Measured on a 121-message transcript at context_length 1600, a stored boundary of 86 gave dropped 86 under both 0.05 and 0.25, so raising the setting did nothing either. Compare for equality instead. With the 5%-origin boundary of 86 above, a request at 0.05 still replays it and a request at 0.25 recomputes to 94. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: mahiatlinux <[email protected]>
test_event_batch_flushes_while_upstream_is_idle slept 0.2s and then asserted the two chunks were durable. The flush it waits on costs _EVENT_BATCH_SECONDS plus a thread hop and a SQLite write, which measures 0.104s to 0.128s over twelve runs on a completely idle machine, so the assertion had under 2x headroom before it ever reached a loaded runner. It lost that race on a Backend tests lane where the other 35,482 tests passed. Neither of the two commits that shaped this loop is at fault. #9187 wrote the test with the margin it has, and the producer loop #9997 later touched only adds work on admission markers, which this stream never emits. So the production behaviour is right and the test was measuring it wrongly. It now polls until the events land, in the same idiom the sibling replay test already uses, bounded by the midpoint between the batch and single-event flush intervals and reading both from the module so the bound tracks the code. That raises the margin from under 2x to roughly 5x while staying strictly below the single-event timer, so the test still fails if these two events ever fall onto that slower path. Confirmed by mutation: raising _EVENT_BATCH_MIN_SIZE to 3, which drops the pair onto the 1.0s timer, and deleting the idle flush outright both still fail. The file passes 24/24, and the test passes 40/40 pinned to one CPU shared with six busy loops. Co-authored-by: danielhanchen <[email protected]>
…unslothai#16159) ## Studio: stream durable chat events without re-parsing stored payloads ### What changes When a client follows or reconnects to a durable chat run, every event row was read from SQLite, `json.loads`'d in the event-wait worker, and then `json.dumps`'d again on the event loop to build the SSE frame. The stored `payload_json` is already the output of `json.dumps(payload, ensure_ascii=False, separators=(",", ":"))`, which is the same encoder the route uses, so the parse and re-encode gave back the stored text byte for byte. - `storage/chat_generation_runs_db.py`: `list_events(..., raw=True)` and `wait_for_events(..., raw=True)` return the stored text as `payloadJson` instead of a parsed `payload`. The default (parsed) behaviour is unchanged for every other caller. - `routes/chat_generation_runs.py`: the events route asks for raw rows and splices `payloadJson` into the frame (`{"seq":..,"type":..,"payload":<stored>,"createdAt":..[,"run":..]}`), same key order as before. The run snapshot is encoded once per batch instead of once per run event. - The writer and the fallback share one `_dumps_payload` helper, and a comment on the single INSERT site notes that the route depends on that encoding. Every version of the writer since the table was added (unslothai#9187) uses the same arguments; a database filled by the base writer streams byte-identically through this branch. - The raw read also selects `json_valid(payload_json)` plus a check for raw `\n` / `\r` in SQLite. A row that fails it (a truncated or hand-edited payload) goes through the old parse and re-encode, so it still goes out exactly as before (`{}` for unparseable text) instead of breaking the client's `JSON.parse` and sending it into a reconnect loop at the same cursor. The check runs in C in the read worker, so the event loop does not pay for it. - On a SQLite built without JSON1 (`no such function: json_valid`), the raw read falls back once to re-encoding every row, so the route streams the old bytes instead of failing. Nothing changes in sequence numbers, cursors (`after` / `Last-Event-ID`), batching, terminal handling, keep-alive comments or the producer. An empty stored payload still goes out as `{}`. The cost this removes is mostly allocation: a reconnect replaying a long run decoded thousands of small dict trees per 1000-event batch, which pushed Python into full GC passes on the event loop. With three followers replaying at once those passes stalled the loop for 60 to 95 ms. ### Results (base = origin/main, head = this branch) Same host, same harness, real supervisor producer + real events route + real SQLite, fake model stream. 3 process runs x 3 replays per arm for replay, 3 runs per arm for live. Replay from cursor 0 of a finished run, 12,003 events (20 tool results of 100 KB, mixed Unicode), 5.6 MB of frames per follower: | Followers | Metric | Base median (range) | Head median (range) | |---|---|---|---| | 1 | replay wall time | 0.170 s (0.153 to 0.214) | 0.074 s (0.063 to 0.084) | | 1 | process CPU | 0.167 s | 0.071 s | | 1 | event loop CPU | 0.103 s | 0.040 s | | 1 | max event loop lag | 8.6 ms (6.4 to 10.5) | 3.7 ms (2.6 to 7.3) | | 3 | replay wall time | 0.847 s (0.758 to 1.085) | 0.451 s (0.433 to 0.532) | | 3 | process CPU | 1.092 s | 0.719 s | | 3 | event loop CPU | 0.306 s | 0.133 s | | 3 | max event loop lag | 62.0 ms (8.4 to 95.3) | 5.7 ms (3.4 to 9.4) | | 3 | loop stalls over 10 ms per replay | 0 to 10 | 0 in all 9 | | 3 | longest GC pause | 61 to 86 ms | 2.0 to 2.7 ms | With the `json_valid` fallback check added, a separate rerun (3 followers, 12,005 events, median of 3) gave base 1.03 s wall / 87 ms max loop lag / 113 ms max GC pause, and this branch 0.57 s / 4.0 to 4.9 ms / 1.0 ms. The check adds about 60 ms of wall time in the read worker and nothing on the event loop. Live streaming (667 events at 150 events/s, reasoning and content deltas plus 50 / 200 / 500 KB tool results) is unchanged within noise: CPU 0.547 s vs 0.528 s with one follower, 0.995 s vs 0.946 s with three; p95 delivery 19.4 ms vs 18.6 ms, dominated by the 16 ms commit cadence. Small chunks cost about 5 us of JSON per follower before this change, so live chats were never bound by it. Byte check: a 12,005-event run (control characters, U+2028, NEL, emoji, CJK, NaN, -0.0, 2**64, a cancel plus terminal events) streamed from cursors 0, 1, 5000 and 11999 through the base route and through this branch against the same database gives identical output (10,755,686 bytes, same sha256). ### Tests New `tests/test_chat_generation_events_passthrough.py` (12 tests): - Replay, cursor resume (`after` and `Last-Event-ID`), cancelled runs and three concurrent live followers: every frame is compared byte for byte against the previous encoding (parse the row, `json.dumps` the event dict). These 9 tests pass on base too, so they pin the old bytes. - Fixed point: 400 random nested payloads (control characters, surrogate-pair emoji, big ints, extreme floats, quoted keys) stored then read raw equal the parse and re-encode of the same row. - Work count: streaming 300 chunks parses no stored payload (fails on base, where every row is parsed). - `wait_for_events(..., raw=True)` waits and wakes like the parsed read. `tests/test_chat_generation_events_reads.py`: the `list_events` stub in one test now forwards keyword arguments. Every backend test file that references `chat_generation_runs` (24 files): base 1254 passed, head 1266 passed (the 12 new ones), no failures on either side. ### Not covered - A hand-edited payload that is valid single-line JSON with different spacing (for example `{"a": 1}`) is now sent as stored instead of compacted. Clients parse it the same way, and Studio never writes such text. - The browser frontend was not run against a corrupted row; the reconnect loop the fallback avoids comes from reading `chat-generation-api.ts`. - The producer still parses each SSE chunk and storage re-encodes it. Storing the producer's text directly would change the stored bytes (`ensure_ascii` and separators differ), and the parse is needed for finish reason and error detection anyway. At live token rates it is a few microseconds per event. - The two executor hops per wake (`wait_for_events` then `get_run_state`) were left alone; live numbers did not show them. - Numbers come from a test process. A real server has a much larger heap, so its full GC passes cost more than measured here.
Summary
Local Studio Chat generations now survive browser disconnects, sleep, and reloads. Studio reconnects to the same server-owned run, replays missing chunks once, and preserves truthful completion status.
Public
/v1/chat/completionsbehavior remains unchanged.Motivation
Local generation was tied to the browser stream. Closing the connection could cancel decoding, and refreshing an interrupted response could display it as completed.
Issue #8925 requires Studio to keep eligible GGUF and safetensors/MLX generations alive while retaining explicit Stop, model lifecycle, thread deletion, and shutdown cancellation.
Changes
Backend storage and API
chat_generation_runsandchat_generation_eventsSQLite tables.Generation lifecycle
/v1/chat/completionson its existing cancel-on-disconnect path.Frontend recovery
onlineevent.Related
Fixes #8925