Skip to content

Studio: skip no-op writes and the discarded re-read when importing external sessions - #18862

Merged
danielhanchen merged 3 commits into
mainfrom
perf/r37-external-import-trims
Nov 23, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
perf/r37-external-import-trims

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Clicking Import again in Settings > Data with nothing new in ~/.claude, ~/.codex or ~/.cursor still writes to the database for every session. _import_session rewrites the chat's chat_threads row with the same values (BEGIN IMMEDIATE plus a commit), reads it back through get_chat_thread and 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 the chat_threads UPDATE 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_messages ends with return list_chat_messages(thread_id): a new connection, a SELECT of every row in the thread and a json.loads of every message. The importer and the scheduler both drop that list. Only the chat history route uses it.

The codex source has its own cost. For each revert or fork rollout, _records finds the base rollout with a full _rollouts(home) scan (two rglob walks of sessions/ and archived_sessions/), so an import grows quadratically with the number of forks.

Change

  • storage/studio_db.py
    • sync_chat_messages(..., return_rows = True). With return_rows = False it returns None and 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 if upsert_chat_thread(thread) would leave the stored row exactly as it is. It follows the ON CONFLICT clause column by column: COALESCE for updated_at, settings_json and scheduled_task_id, the model_gguf_variant CASE, fork_title_base cleared on a title change, and fork_boundary_message_id never updated. Comparison is type-strict, so 5 and 5.0 count 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_thread plus the raw columns, from the same single SELECT.
  • core/external_import/__init__.py
    • The thread upsert is skipped when the stored row would not change. Some cases still write, because the upsert would change them: a NULL updated_at, an empty title, a moved updatedAt, a re-serialised settings_json.
    • The import mark read moves from _pending_messages to the caller. It is the same single read, now also used to skip record_external_import_mark when the stored mark already has the same revision and at least as many turns. That is exactly the case where the ON CONFLICT MAX leaves the mark unchanged.
    • It passes return_rows = False to sync_chat_messages.
  • core/scheduled_tasks/scheduler.py: passes return_rows = False (it discarded the rows).
  • core/external_import/codex.py: fork and revert bases are looked up in one {rollout id: path} map per list_projects run, 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 ~/.claude and ~/.codex homes. 500 claude sessions (about 40 messages each, 8% with an inline base64 image) plus 137 codex rollouts (10% reverts, 10% forks), 38 MB. Then 2000 claude sessions plus 550 codex rollouts, 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 the claude plus codex run_import wall time.

500 sessions base (median, 3 runs) base A/A head
first import 15.36 s 15.14 s 14.01 s
re-import, unchanged 10.86 s 11.35 s 4.16 s
re-import, 10% grown 12.29 s 12.74 s 6.02 s
2000 sessions (1 run) base head
first import 56.4 s 50.5 s
re-import, unchanged 36.9 s 15.6 s
re-import, 10% grown 23.6 s 16.2 s

Database work per import of the 2000-session set. These counts are deterministic and the same on every run.

connections commits BEGIN IMMEDIATE global revision bumps
unchanged, base 15457 5131 2550 2550
unchanged, head 7807 31 0 0
10% grown, base 15725 5162 2787 3641
10% grown, head 8475 499 437 1291
first import, base 12939 5163 5100 97026
first import, head 10389 5163 5100 97026

The 31 commits left in an unchanged re-import are the per-project upsert_chat_project calls (20 claude projects and 11 codex folders), which this PR does not change. The first import gets faster only from return_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.

codex fork lookup alone (list_projects plus read_transcript of every session, no database, median of 5):

rollouts (forks + reverts) base head rollout scans
137 (26) 0.077 to 0.120 s 0.048 s 25 vs 2
550 (110) 0.600 to 0.654 s 0.175 s 101 vs 2

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 inventory backfilled_at wall 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_revision and test_unchanged_reimport_skips_the_thread_and_ledger_writes fail on main.
  • test_the_noop_check_never_skips_a_write_that_changes_the_row builds 1944 stored-row shapes (NULL / empty / set model id, GGUF variant, pair id, updated_at as NULL, int or real, fork title base, settings_json canonical, 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_back and test_codex_forks_share_one_rollout_scan fail on main.
  • Guards that pass on both: a grown session still lands and moves its revision, a NULL updated_at row 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_intact relied 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 on main too).

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.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 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-23T04:06:01.105185Z
We couldn’t complete this review. Comment @codex review to try again.
d7fa6ef 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 4a954449de

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 35bb97d302

ℹ️ 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 23, 2026 04:05
@danielhanchen
danielhanchen merged commit 60d9092 into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the perf/r37-external-import-trims branch November 23, 2026 04:05
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 23, 2026
…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.
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