Skip to content

Studio: stream durable chat events without re-parsing stored payloads - #16159

Merged
danielhanchen merged 4 commits into
mainfrom
perf/r12-durable-stream
Nov 1, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
perf/r12-durable-stream

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

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 (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.
  • 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.

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.
@danielhanchen
danielhanchen merged commit 6cd1423 into main Nov 1, 2026
@danielhanchen
danielhanchen deleted the perf/r12-durable-stream branch November 1, 2026 09:14
danielhanchen added a commit that referenced this pull request Nov 1, 2026
@danielhanchen danielhanchen self-assigned this Nov 1, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review November 1, 2026 09:41
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-01T08:42:46.844899Z 906e0f9 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 906e0f9612

ℹ️ 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".

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant