Skip to content

Studio chat: stop re-reading a chat after this tab's own writes - #18483

Merged
danielhanchen merged 6 commits into
mainfrom
perf/r36-chat-own-write-echo
Nov 20, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
perf/r36-chat-own-write-echo

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

The open chat polls /api/chat/revision every 4 s (#18143) and re-reads the thread when its counter moves. The counters are bumped by SQLite triggers on every write to chat_messages and chat_threads, so nothing separates this tab's own writes from another device's. Every finished turn moves the counter (user message, assistant message, the final sync). The poll holds the change while the reply streams, then within 4 s of the reply ending recoverCurrentThread re-reads the chat this tab just wrote: a thread GET, the full message list, an IndexedDB read and two thread.export() calls. On a 150 turn chat that list is about 720 KB, every turn. Renames, title updates and thread settings saves from this tab do the same. The history counter echoes too, so the sidebar refreshes a second time.

There is a second source of extra re-reads on other devices. _bump_chat_thread_updated_at ran UPDATE chat_threads SET updated_at = MAX(...) even when the value did not change. AFTER UPDATE triggers fire on no-op updates, so re-saving an unchanged message list still moved the counter, and every other open device re-read a chat that had not changed.

Change

  • storage/studio_db.py: chat_revision_probe(thread_id) is a context variable that upsert_chat_thread, update_chat_thread, upsert_chat_message and sync_chat_messages fill. Right after BEGIN IMMEDIATE and right before COMMIT they read the thread's and the whole history's revision. chat_revision_span returns the before and after values only when every probed transaction committed, and committed back to back. Without a probe (generation runs, research, imports) the writers behave exactly as before.
  • routes/chat_history.py: POST /threads, PATCH /threads/{id}, PUT /threads/{id}/messages/{mid} and PUT /threads/{id}/messages return X-Unsloth-Chat-Revision: <thread before>,<thread after>,<history before>,<history after> on success. A rejected or failed write sends no header. main.py exposes the header for cross-origin clients (Tauri, tunnels).
  • _bump_chat_thread_updated_at skips the write when updated_at would not change. Rows whose value does change are written exactly as before.
  • chat-api.ts: threadWriteFetch reads the header and publishes it to subscribeOwnChatHistoryWrites listeners. An older server sends no header, nothing is published, and the poll re-reads as it does today.
  • remote-history-sync.ts: noteOwnWrite records each own write as a step before -> after. The baseline follows these steps only from the revision it last saw, so a write from anywhere else leaves a gap and is still re-read. Steps can arrive out of order or after a poll already saw the new counter, and they still chain. A poll answer that an own write overtook while it was in flight is ignored instead of rolling the baseline back. Own writes only skip the re-read once the open chat has synced through one successful re-read, because a chat's first baseline can already count another device's write that the loaded view lacks; so the first own turn after opening a chat still re-reads once, as main does, and later turns do not. The history baseline works the same way, so the sidebar refresh fires only for other devices. Re-reads still wait while a reply runs, and a failed re-read is still retried. That retry also holds if this tab writes while the re-read is in flight.

Focus, wake and thread-switch recovery, the busy hold, cross-tab localStorage sync and error handling are unchanged.

Results

Production builds of main and this branch. The real routes/chat_history.py runs on a temporary studio.db, the rest of /api is stubbed, and Chromium is headless. The chat has 150 turns (306 messages). Each assistant turn has reasoning, two tool calls, six sources, code, a table and math, so the message list is about 720 KB. The reply is a fixed 10 ms per frame stream. Counts cover the 14 s after each reply ends (at least 3 polls). There were 3 runs of 3 turns per side, main and this branch interleaved. Earlier runs that were not interleaved (2 more on main, 3 more on this branch) gave the same counts.

per own turn, after the reply main this PR
GET /threads/{id} 1 0
GET /threads/{id}/messages (full list) 1 (722 KB) 0
chat API bytes received 727.6 KB 4.5 KB
POST /sidebar/rows 4 2
GET /threads/{id}/forks 2 1
thread remounted / scroll moved no no

The re-read never remounted the thread: every mounted row survived, and the distance to the bottom did not change, on both sides. Main-thread time over the same window was 163 ms median on main (126 to 263) and 112 ms on this branch (62 to 172). On this shared host the repeated main runs alone spread from 134 to 208 ms, and idle 14 s windows from 46 to 106 ms, so no time saving is claimed. In the page, the network part of one re-read costs 2.9 ms to read the body and 1.8 ms to parse it and build the per-message keys (median of 15). The IndexedDB read, the two exports and the reconcile pass come on top of that.

Two clients on one backend, same thread:

check main this PR
tab B sends a turn while A is idle: A shows it, separate browser contexts (8 runs, B's send at 0 to 3.5 s after one of A's polls) 2.23 s (0.47 to 3.94) 2.22 s (0.37 to 3.88)
same, two tabs of one browser sharing localStorage (8 runs) 2.21 s (0.26 to 3.89) 2.20 s (0.40 to 3.89)
A's own turn: message-list re-reads in the 13 s after it ends 1 0
another device adds a message and renames the chat while A streams: re-reads after A's reply ends 1 1
that re-read carries the other device's message yes yes
the rename shows in A's sidebar yes yes

Cross-tab latency is the time from B's first write reaching the server to A showing it. On both sides it is about 4 s minus the offset to A's next poll, and A always picks the change up at that next poll: own writes only move A's baseline from the revision A last saw, so another tab's writes are never absorbed.

Tests

New studio/backend/tests/test_chat_write_revision.py (6 tests):

  • Each of the four write routes returns the revisions read just before and after its write, and they match /revision.
  • A write from elsewhere between two of this tab's writes shows as a gap.
  • A rejected write (409) sends no header.
  • Re-saving an unchanged message list moves no revision, and a real edit still does (fails on main).
  • updated_at still only moves forward.
  • The header is listed in the CORS expose_headers.

New studio/frontend/tests/own-chat-write-revision.test.ts: the header is published for message saves, message syncs and thread patches. Nothing is published with no header, with a malformed header or for a failed write.

remote-history-sync.test.ts, 7 new tests, all failing on main:

  • An own write is not re-read, and the sidebar does not refresh for it.
  • A write from elsewhere before or after an own write is re-read once.
  • A remote write during a run is recovered once the view is idle.
  • Own writes answered out of order, or after the poll already saw them, stay quiet.
  • An own write to a chat that is not open does not hide its later changes.
  • A failed re-read is retried even if this tab wrote meanwhile.

The existing "a busy view keeps the change pending until it is idle" test is unchanged and passes.

Frontend: 107 test files that import chat-api, runtime-provider, the remote history, saved history or chat history modules. 1559 pass here and 1548 on main (the difference is the 11 new tests). npm run typecheck and eslint on the changed files are clean.

Backend: test_chat_history_routes.py, test_chat_history_storage.py, test_chat_sync_unchanged_rows.py, test_studio_db_hot_path_indexes.py, test_studio_db_write_lock_contention.py, test_research_runs_storage.py and tests/studio/test_chat_thread_title_cas.py: 440 passed on both sides. The chat settings, thread settings, library, sandbox storage, auth lock and OpenAI auto-switch suites: 1632 passed on both sides. In both runs the same two test_openai_auto_switch.py fixture checks fail under pytest -n 4.

The 4 s /api/chat/revision poll could not tell this tab's writes from another
device's, so every finished turn (and every rename or settings save) re-read the
whole chat: a thread GET plus the full message list (about 720 KB at 150 turns).

Chat write routes now return X-Unsloth-Chat-Revision with the thread and history
revisions read inside the write transaction, before and after it. The client
moves its baseline past a write only when 'before' is the revision it last saw,
so a write from elsewhere in between is still re-read. An unchanged re-save no
longer bumps updated_at to the same value, which fired the revision triggers and
made other devices re-read an unchanged chat.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-20T11:39:24.601193Z
We couldn’t complete this review. Comment @codex review to try again.
01d204f Draft marked ready
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0e89191be8

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

Comment on lines 93 to 96
if (historyRevision !== null) {
historyRevision = advance(historySteps, historyRevision);
}
if (historyRevision !== null && result.revision !== historyRevision) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Ignore poll snapshots older than acknowledged own writes

If a revision poll captures the server state before an own write, but its response arrives after noteOwnWrite advances the baselines, the stale snapshot is treated as an external change and moves the baselines backward. Since advance already deleted the own-write steps, the next poll treats the newer revision as another external change. With an idle watcher, a delayed poll followed by an acknowledged own write reproduces two thread recoveries and two sidebar refreshes without any external writes, increasing rather than eliminating the redundant reads. Handle snapshots overtaken by acknowledged writes without rolling their baselines backward, for both history and thread revisions.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in 851ef1d8b3. A poll now notes how many own writes had been acknowledged when it was sent. If one was acknowledged while it was in flight and the answer is behind the current baseline (counters only grow), the snapshot is stale and is skipped for both the history and the thread revisions, so nothing rolls back and the next poll compares against the advanced baseline. Added a poll answered after this tab's own write does not roll the baseline back, which fails without the change (two recoveries) and passes with it; a later write from elsewhere is still read once.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 19, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: f8d97ef289

ℹ️ 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 danielhanchen/unsloth-staging-2 that referenced this pull request Nov 19, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 19, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: b4fab96080

ℹ️ 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 danielhanchen/unsloth-staging-2 that referenced this pull request Nov 19, 2026
@danielhanchen danielhanchen self-assigned this Nov 20, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 20, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

3 similar comments
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 98325ff984

ℹ️ 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
danielhanchen marked this pull request as ready for review November 20, 2026 11:39
@danielhanchen
danielhanchen merged commit d0c5ab2 into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the perf/r36-chat-own-write-echo branch November 20, 2026 11:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant