Repository navigation
Studio chat: stop re-reading a chat after this tab's own writes - #18483
Conversation
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.
|
@codex review |
Codex Review Summary: ❌ FailedThis 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. |
There was a problem hiding this comment.
💡 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".
| if (historyRevision !== null) { | ||
| historyRevision = advance(historySteps, historyRevision); | ||
| } | ||
| if (historyRevision !== null && result.revision !== historyRevision) { |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
…ced once; fix a null check [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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 |
3 similar comments
|
@codex review |
|
@codex review |
|
@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". |
The open chat polls
/api/chat/revisionevery 4 s (#18143) and re-reads the thread when its counter moves. The counters are bumped by SQLite triggers on every write tochat_messagesandchat_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 endingrecoverCurrentThreadre-reads the chat this tab just wrote: a thread GET, the full message list, an IndexedDB read and twothread.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_atranUPDATE 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 thatupsert_chat_thread,update_chat_thread,upsert_chat_messageandsync_chat_messagesfill. Right afterBEGIN IMMEDIATEand right beforeCOMMITthey read the thread's and the whole history's revision.chat_revision_spanreturns 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}andPUT /threads/{id}/messagesreturnX-Unsloth-Chat-Revision: <thread before>,<thread after>,<history before>,<history after>on success. A rejected or failed write sends no header.main.pyexposes the header for cross-origin clients (Tauri, tunnels)._bump_chat_thread_updated_atskips the write whenupdated_atwould not change. Rows whose value does change are written exactly as before.chat-api.ts:threadWriteFetchreads the header and publishes it tosubscribeOwnChatHistoryWriteslisteners. An older server sends no header, nothing is published, and the poll re-reads as it does today.remote-history-sync.ts:noteOwnWriterecords each own write as a stepbefore -> 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, asmaindoes, 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
localStoragesync and error handling are unchanged.Results
Production builds of
mainand this branch. The realroutes/chat_history.pyruns on a temporarystudio.db, the rest of/apiis 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,mainand this branch interleaved. Earlier runs that were not interleaved (2 more onmain, 3 more on this branch) gave the same counts.mainGET /threads/{id}GET /threads/{id}/messages(full list)POST /sidebar/rowsGET /threads/{id}/forksThe 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 repeatedmainruns 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:
mainlocalStorage(8 runs)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):/revision.main).updated_atstill only moves forward.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 onmain: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 onmain(the difference is the 11 new tests).npm run typecheckandeslinton 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.pyandtests/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 twotest_openai_auto_switch.pyfixture checks fail underpytest -n 4.