Repository navigation
Studio: skip no-op writes and the discarded re-read when importing external sessions - #18862
Conversation
An unchanged Claude Code / Codex / Cursor session no longer rewrites its identical chat_threads row or its up-to-date import mark, so a re-import with nothing new commits nothing and moves no chat history revision. sync_chat_messages gains return_rows=False for the importer and the scheduler, which discarded the full re-read of the thread's rows. Codex fork and revert rollouts share one rollout scan per import.
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. |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
[skip ci]
|
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". |
…nslothai#18918) After every chat turn the autosave PUTs the whole exported thread to `/api/chat/threads/{id}/messages`. The route writes the rows, then `sync_chat_messages` re-reads the entire thread, the route builds a `ChatMessage` per row and serialises all of it back. The autosave caller (`syncExportedRepositoryToBackend` from `runtime-provider.tsx`) never looks at that echo; only the delete path reads it, to republish the fork boundary. On a 150-turn chat that is a ~720 KB response per turn, and with ten inline images it is ~20 MB re-read, serialised, sent and parsed per turn for nothing. ## Change - Backend: `PUT /api/chat/threads/{id}/messages` takes an opt-in `echoMessages` query flag (camelCase alias, like `allowGenerationEdit` on the single-message route). Default `true` keeps today's response. With `echoMessages=false` the route passes `return_rows=False` to `sync_chat_messages`, which skips the trailing `list_chat_messages` re-read, and answers `{"messages": []}`. The write transaction, stored rows, status codes, error paths and the `X-Unsloth-Chat-Revision` header are unchanged. - `sync_chat_messages(..., return_rows=True)` uses the same signature and docstring as unslothai#18862, so the two branches merge without conflict whichever lands first. - Frontend: `syncChatMessages` / `syncStoredChatMessages` take `echo?: boolean`. `syncExportedRepositoryToBackend` sends `echo: false` only on the non-pruning autosave; any call with `pruneMissing` or `deletedMessageIds` always keeps the echo, so `publishForkBoundary` still receives the stored rows. With `echo: false` the call resolves to the records it sent, so the result is the same whether the backend honours the flag or is an older one that ignores it and echoes as before. ## Results Real `routes/chat_history.py` through FastAPI `TestClient` on a temp `studio.db`, 150 turns (300 rows, ~717 KB payload), each timed PUT is an autosave that resends the thread with the last reply edited. 9 timed PUTs per process after a warm-up, 3 processes per arm, medians per process (shared host, so expect a few ms of jitter): | Thread | Arm | PUT median (ms), 3 processes | Response bytes | |---|---|---|---| | text only | base | 33.99, 26.12, 36.90 | 735,399 | | text only | base A/A | 33.86, 26.44, 31.01 | 735,399 | | text only | head, default | 31.64, 32.55, 26.41 | 735,399 | | text only | head, `echoMessages=false` | 22.56, 23.07, 22.09 | 15 | | 10 inline ~2 MB images | base | 274.41, 272.57, 255.86 | 20,735,899 | | 10 inline ~2 MB images | base A/A | 260.34, 239.47, 246.12 | 20,735,899 | | 10 inline ~2 MB images | head, default | 256.43, 266.71, 250.68 | 20,735,899 | | 10 inline ~2 MB images | head, `echoMessages=false` | 140.12, 134.32, 151.45 | 15 | The text-only PUT drops from about 26 to 37 ms down to about 22 ms, and the image-heavy one from about 240 to 275 ms down to about 135 to 150 ms. Both changes are outside the A/A spread. The default response matches base byte for byte. A base backend sent `echoMessages=false` ignores it and echoes the full body as before (735,399 and 20,735,899 bytes). On the client, `JSON.parse` of the echoed body in Node's V8 takes 0.85 ms for the text-only thread and about 19 ms for the image one; with the flag that parse is now a 15-byte body. Real HTTP transfer of the 20 MB echo over a socket is not part of the numbers above and is also saved. ## Tests - `studio/backend/tests/test_chat_sync_no_echo.py`: stored rows identical with and without the flag across insert, append and edit; the response is `{"messages": []}` and the revision header is still well formed; the default and `echoMessages=true` still echo; prune still deletes under the flag; the 404 and 400 paths are unchanged; `sync_chat_messages(return_rows=False)` skips the re-read and returns `None`. On base, 3 of its 5 tests fail (the flag is ignored there); all pass on head. - `studio/frontend/tests/thread-sync-no-echo.test.ts`: `echo: false` adds `?echoMessages=false` and resolves to the sent records; an echoing older backend is still accepted; the default call and any prune or delete call send no flag and return the server rows; a failed sync still throws; the autosave sends `echo: false` while `deleteThreadMessage` keeps the echo. - 40 backend test files that touch chat history routes, storage, sync and revisions (3,563 tests): base and head have the same failing IDs, apart from the new test's expected base failures. - Full frontend `npm test` on base and head, plus `npm run typecheck` on head.
Clicking Import again in Settings > Data with nothing new in
~/.claude,~/.codexor~/.cursorstill writes to the database for every session._import_sessionrewrites the chat'schat_threadsrow with the same values (BEGIN IMMEDIATEplus a commit), reads it back throughget_chat_threadand throws the result away, then writes the same(turns, revision)import mark again (a second commit). That is 6 connections and 2 write commits per session. The rewrite also fires thechat_threadsUPDATE trigger, so each unchanged session moves the global and per-thread chat history revision by one. Every open Studio tab polls that revision (remote-history-sync.ts) and re-reads history when it moves, so with 2000 imported sessions a no-op click causes 2550 revision bumps.When a session did grow,
sync_chat_messagesends withreturn list_chat_messages(thread_id): a new connection, a SELECT of every row in the thread and ajson.loadsof every message. The importer and the scheduler both drop that list. Only the chat history route uses it.The
codexsource has its own cost. For each revert or fork rollout,_recordsfinds the base rollout with a full_rollouts(home)scan (tworglobwalks ofsessions/andarchived_sessions/), so an import grows quadratically with the number of forks.Change
storage/studio_db.pysync_chat_messages(..., return_rows = True). Withreturn_rows = Falseit returnsNoneand does not re-read the thread. The default is unchanged, so the chat history route behaves as before.chat_thread_upsert_is_noop(thread, stored): True only ifupsert_chat_thread(thread)would leave the stored row exactly as it is. It follows the ON CONFLICT clause column by column:COALESCEforupdated_at,settings_jsonandscheduled_task_id, themodel_gguf_variantCASE,fork_title_basecleared on a title change, andfork_boundary_message_idnever updated. Comparison is type-strict, so5and5.0count as different, and anything it cannot be sure of returns False, which means the write goes ahead. The INSERT values now come from one helper (_chat_thread_upsert_values), so the upsert and the check cannot drift apart.get_chat_thread_with_row(id):get_chat_threadplus the raw columns, from the same single SELECT.core/external_import/__init__.pyupdated_at, an empty title, a movedupdatedAt, a re-serialisedsettings_json._pending_messagesto the caller. It is the same single read, now also used to skiprecord_external_import_markwhen the stored mark already has the same revision and at least as many turns. That is exactly the case where the ON CONFLICTMAXleaves the mark unchanged.return_rows = Falsetosync_chat_messages.core/scheduled_tasks/scheduler.py: passesreturn_rows = False(it discarded the rows).core/external_import/codex.py: fork and revert bases are looked up in one{rollout id: path}map perlist_projectsrun, cleared next to_META. If an id is missing, or its path is no longer a file (for example the base rollout was archived during the import), the map is rebuilt, which is what the old per-fork scan would have seen.A chat with new turns still writes and moves its revision as before. Only writes that would store identical values are skipped.
Results
Synthetic
~/.claudeand~/.codexhomes. 500claudesessions (about 40 messages each, 8% with an inline base64 image) plus 137codexrollouts (10% reverts, 10% forks), 38 MB. Then 2000claudesessions plus 550codexrollouts, 149 MB. Each run does a first import, a re-import with nothing changed, and a re-import after appending turns to 10% of the sessions and rollouts. The 500-session runs were repeated 3 times, each time with base, a second base copy (A/A) and head running side by side on the same disk. Times are theclaudepluscodexrun_importwall time.Database work per import of the 2000-session set. These counts are deterministic and the same on every run.
BEGIN IMMEDIATEThe 31 commits left in an unchanged re-import are the per-project
upsert_chat_projectcalls (20claudeprojects and 11codexfolders), which this PR does not change. The first import gets faster only fromreturn_rows = False. A/A spread is roughly 0.5 s at 500 sessions, so the first-import difference there is close to noise, while the re-import gains are well outside it.codexfork lookup alone (list_projectsplusread_transcriptof every session, no database, median of 5):Database state matches base byte for byte after every scenario at both sizes. I dumped every table (
chat_threads,chat_messages,chat_projects,external_import_sessions, the attachment inventory tables and the rest), typed values included, with three things normalised: file times (pinned in the fixture), the per-run project root path, and the inventorybackfilled_atwall clock. The only differences are the revision counters, which head bumps less on purpose (2000 sessions: global 99576 vs 97026 after the unchanged re-import, 103217 vs 98317 after the grown one).Tests
New
tests/test_external_import_reimport_writes.py:test_unchanged_reimport_moves_no_revisionandtest_unchanged_reimport_skips_the_thread_and_ledger_writesfail onmain.test_the_noop_check_never_skips_a_write_that_changes_the_rowbuilds 1944 stored-row shapes (NULL / empty / set model id, GGUF variant, pair id,updated_atas NULL, int or real, fork title base,settings_jsoncanonical, compact or invalid, scheduled task id), with a set title and with an empty one. For every shape the check calls a no-op, it runs the real upsert and asserts the stored row is unchanged.test_sync_can_skip_reading_the_rows_backandtest_codex_forks_share_one_rollout_scanfail onmain.updated_atrow is still rewritten, a stale mark is still rewritten, and a fork base archived after the scan is still found.tests/test_external_import_atomic.py::test_checkpoint_only_failure_keeps_existing_import_intactrelied on an unchanged re-import rewriting an up-to-date mark. It now deletes the mark first, so a checkpoint-only write is still needed and still rolls back cleanly (passes onmaintoo).test_external_import*.py,test_chat_history_routes.py,test_chat_history_storage.py,test_studio_db_hot_path_indexes.py,test_studio_db_write_lock_contention.py,test_scheduled_tasks.py,test_chat_sync_unchanged_rows.py: 559 passed, 1 skipped.