Repository navigation
Studio: stream durable chat events without re-parsing stored payloads - #16159
Merged
Merged
Conversation
The events route parsed every stored payload_json and re-encoded it with the same json.dumps options it was stored with, which returns the stored text unchanged. Read the rows raw and splice the text into the SSE frame. Replaying a 12k-event run drops from 0.17 s to 0.07 s for one follower, and the full GC passes that stalled the event loop 60 to 95 ms with three followers replaying are gone. Output bytes are unchanged.
… is not one line of JSON A corrupt or hand-edited payload_json row was spliced into the SSE frame as is, so the client failed to parse that frame and reconnected at the same cursor forever. SQLite json_valid plus a CR/LF check now gates the splice in the read (no Python parsing, GIL released); a rejected row is parsed and re-encoded like before, which keeps NaN/Infinity payloads byte-identical too.
This was referenced Oct 30, 2026
danielhanchen
marked this pull request as ready for review
November 1, 2026 09:41
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
danielhanchen
added a commit
to Imagineer99/unsloth
that referenced
this pull request
Nov 1, 2026
…ed request (unslothai#16302) ## What changes A durable chat run stores the whole sanitized request (all prior messages and tool outputs) as `request_json`. During one turn, that text was parsed back into a dict on most run reads and then re-encoded inside every non-chunk SSE frame, even though nothing in those places reads the request. - `POST /api/chat-runs/{id}/events` and `POST /api/chat-runs/{id}/cancel` check that the run exists with `get_run_state` rather than `get_run`. The events check ran synchronously on the event loop. - The stream's opening check reads only the state. - A batch that has a non-chunk event reads `get_run_frame`. That returns the state plus the run already encoded as compact JSON, with the stored `request_json` text spliced in as is. The frame text is the same as `json.dumps(data, ensure_ascii=False, separators=(",", ":"))` with `data["run"] = get_run(...)`. This holds because `canonical_request` writes `request_json` with the same options and sorted keys, so `json.dumps(json.loads(text))` returns the same text. `create_run` is the only writer. The splice is only used when SQLite reports the stored text as `json_valid` with no raw CR or LF (the same guard as the durable replay path); any other row is encoded the old way, so a corrupt or hand-edited row still produces the base frame (`"requestPayload":{}`) instead of a broken SSE line. - The supervisor's first read uses `get_worker_token`, since only the token is used before the fenced `get_worker_run` re-read. `canonical_request`, `create_run`, the stored bytes and every function that returns a run dict are unchanged. ## Results One durable turn, CPU only: POST, then a live events stream through to finish. The turn has 60 chunks and 2 tool events, so 5 non-chunk frames. Time is the median of 5 reps spent in `json.loads`/`json.dumps`/`jsonable_encoder`, split by event loop and worker thread. | request | arm | loads MB (loop / thread) | dumps MB (loop / thread) | JSON ms on loop | JSON ms on threads | total JSON ms | |---|---|---|---|---|---|---| | 54 KB | base | 0.11 / 0.52 | 0.32 / 0.10 | 2.8 | 3.5 | 6.3 | | 54 KB | head | 0.05 / 0.16 | 0.06 / 0.11 | 1.5 | 2.6 | 4.1 | | 1.06 MB | base | 2.06 / 9.99 | 6.0 / 2.0 | 32.0 | 30.9 | 62.9 | | 1.06 MB | head | 1.06 / 3.0 | 1.0 / 2.0 | 9.2 | 14.8 | 24.1 | | 10.6 MB | base | 20.6 / 99.8 | 59.9 / 20.0 | 333.0 | 369.5 | 702.5 | | 10.6 MB | head | 10.6 / 29.9 | 10.0 / 20.0 | 91.3 | 156.3 | 247.6 | The table counts Python JSON calls only. The `json_valid` guard runs inside SQLite on the worker thread: building one run snapshot for a 1.2 MB request took 6.90 ms on base, 3.86 ms with this change (median of 60 interleaved reps), so the per-turn total gain is about 2 ms per non-chunk batch smaller than the table suggests. The event loop time does not include it. What remains is the request body parse, the POST response encoding, `canonical_request`'s two dumps, and the parses in `create_run`, the fenced `get_worker_run` and `finish_run`. ## Tests - A stored request that is not valid JSON, is truncated, or contains a raw LF or a trailing CR falls back to the old encoding (4 new cases; they fail without the guard). - Differential, base vs head: 300 generated requests written through `create_run`. They cover unicode, emoji, control characters, escapes, large ints, floats (`-0.0`, `5e-324`, `1e16`), NaN and Infinity, nested containers and 5000-deep nesting. For each one the test compares the SSE stream text, the `GET` / `cancel` / `finish_run` run dicts, the stored `request_json`, and the 404s for a missing run. The outputs are byte-identical. - `tests/test_chat_generation_events_reads.py`: the read-count test now expects no `get_run` and 3 `get_run_frame` reads. There are new tests that frames equal `json.dumps` of the parsed run, including awkward values. - `tests/test_chat_generation_*.py`, `tests/test_unattended_runs.py` and 40 more test files that use the runs db or routes: 1942 passed on head. Base had 1938 passed, 0 failed. ## Not covered - SQLite 3.42 to 3.44 accept JSON5 in single-argument `json_valid`, so a corrupt row that happens to be valid JSON5 would still be spliced there (same as the replay path). - Merge note: this and the durable replay PR unslothai#16159 both rewrite the frame loop in `routes/chat_generation_runs.py`; whichever lands second keeps both (unslothai#16159's raw payload prefix and this PR's `get_run_frame` run text). - The POST response still parses the request in `create_run` and encodes it on the loop. - Timing was measured on CPU with an in-process TestClient, not through a real browser or Studio session.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 thenjson.dumps'd again on the event loop to build the SSE frame. The storedpayload_jsonis already the output ofjson.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)andwait_for_events(..., raw=True)return the stored text aspayloadJsoninstead of a parsedpayload. The default (parsed) behaviour is unchanged for every other caller.routes/chat_generation_runs.py: the events route asks for raw rows and splicespayloadJsoninto 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._dumps_payloadhelper, 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 (Studio: resume local chat generation after disconnect #9187) uses the same arguments; a database filled by the base writer streams byte-identically through this branch.json_valid(payload_json)plus a check for raw\n/\rin 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'sJSON.parseand 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.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:
With the
json_validfallback 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):afterandLast-Event-ID), cancelled runs and three concurrent live followers: every frame is compared byte for byte against the previous encoding (parse the row,json.dumpsthe event dict). These 9 tests pass on base too, so they pin the old bytes.wait_for_events(..., raw=True)waits and wakes like the parsed read.tests/test_chat_generation_events_reads.py: thelist_eventsstub 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": 1}) is now sent as stored instead of compacted. Clients parse it the same way, and Studio never writes such text.chat-generation-api.ts.ensure_asciiand 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.wait_for_eventsthenget_run_state) were left alone; live numbers did not show them.