Repository navigation
fix(server): older history pages no longer read every run and attempt of the thread - #36141
juliusmarminge wants to merge 3 commits into
Conversation
Reproduces #36128: getThreadHistoryPage reads all of a thread's runs and attempts to render one page, so scrolling back in a long thread costs O(thread) per page. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… of the thread Opening an older page of a thread's history read and decoded all of the thread's runs and attempts, so each page cost O(thread). The local timeline now reads only the runs and attempts that can hide rows (rolled-back, queued and cancelled runs; superseded attempts of runs with a stop result) from their status columns, and takes each window row's run status by key. Fixes #36128 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…, checkpoint and provider turn The thread-open window reads filtered runs, attempts, provider turns and checkpoints with `thread_id = ? AND (status IN (...) OR ... IN json_each(...))`. SQLite can only use the thread index there, so each read fetched every such row of the thread. Each read now collects keys through one indexed SELECT per condition and fetches the rows by key. Migration 089 adds the indexes those SELECTs need. The older-page read of interrupted runs now names the (thread_id, type, status) index: without stats, SQLite picked the run index for DISTINCT and walked every item of the thread. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ApprovabilityVerdict: Approved at Macroscope's review found this PR approvable — Thread history and snapshot reads now use indexed lookups instead of loading every run and attempt. The migration adds indexes without rewriting customer records; remaining exposure is index-build time, storage, and write overhead. You can add or adjust custom eligibility rules. Learn more. |
Thread transfer impact✅ Thread transfer remains within every enforced ceiling.
Other scenariosAll 64 scenario measurements match All 64 scenario measurements
Baseline: Scenario and decoded snapshot size10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed. |
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
|
The automated pipeline stopped on this pull request and will not merge it: the capture step could not show the problem on the base commit, so there is nothing to prove fixed. On both commits, create the same synthetic thread with seven completed read tools and an assistant answer per turn. Capture at 1,000, 2,000 and 2,500 completed runs. Stop seeding and restore the replay script before measurement. Clear the browser thread-cache store, open the thread from the empty screen, and click Load earlier turns four times. Record actual WebSocket snapshot and HTTP history-request timings with a capture-only observer. Save each final still only after screenshots 500 ms apart match. Supplement recordings with three passes through the running server's normal and deferred HTTP reads. At 2,500 runs, also restart both apps and repeat the recorded interaction after evicting only their synthetic SQLite files from the OS file cache; mincore reported zero resident database and WAL pages immediately before each recorded open. It stays open for a person to finish or close. |
|
I measured this PR on the real database from #36128. Thread open and older pages are 4–7× faster, and both commits return the same results.
Median (range) over 4 base and 3 head runs, pages 1–3 pooled. Base and head runs alternated, and base stayed slow after head had read the same pages. Both returned the same projection and pages: the SHA-256 of the results is equal. Setup
Where the time went on baseOpening a thread spent 1.3–8.5 s in each of these reads: the retained-node CTE, checkpoints, provider turns, subagents and context transfers. Every older page re-read all runs and attempts, which took 1.2–1.6 s per table. What remains on headThese three reads are most of head's remaining time:
Measured and written by Claude (Opus 5.5) in T3 Code; posted with the owner's approval. |
Both review items were correct and are fixed. (1) Thread open: the getThreadSnapshotWindow reads for runs, attempts, provider turns and checkpoints, and the run/attempt arms of the retained-node CTE, filtered
thread_id = ? AND (status IN ... OR ... IN json_each(...)), which SQLite can only answer through the thread_id index, fetching every such row of the thread. Each read now collects keys with one indexed SELECT per condition (UNION ALL) and fetches rows by primary key (+thread_id = ? AND <pk> IN (...)); the conditions are unchanged. Migration 089 adds the indexes those arms need: attempts active partial (thread_id) WHERE status IN ('pending','starting','running','waiting'); provider turns active partial (thread_id) WHERE status IN ('starting','running','waiting') and (node_id); checkpoints (thread_id, status, app_run_ordinal), root partial (thread_id) WHERE run_id IS NULL AND ordinal_within_scope = 0 (named with INDEXED BY in its arm), (run_id) and (node_id). EXPLAIN QUERY PLAN on a freshly migrated schema without sqlite_stat1 shows every arm searching an index and the outer read using the primary-key autoindex. (2) Older pages: the interrupted-runs subquery added in round 1 did pick thread_run_idx (thread_id=? AND run_id>?) without stats; it now has INDEXED BY orchestration_v2_projection_turn_items_thread_type_idx, and the plan is SEARCH (thread_id=? AND type=?). Tests: the existing 'reads a fixed SQL turn-item window' VM-step check now also seeds an attempt, provider turn and checkpoint per old run on its copy and deletes them with the history below the window; it fails on the previous head (328133 steps vs at most 271828.7) and passes now. The history-page part of the same test now asserts that no page row read plans a thread_run_idx range; it fails when the hint is removed. reconcileV2PreviewMigration.test.ts lists migration 89. No new regex or parser.Fixes #36128
Reproduction on main
On origin/main 7903b48: a scratch vitest seeded one thread (N runs, one attempt per run, 9 turn items per run) into a file-backed SQLite database through Sqlite.layerFromPath, then timed the real ProjectionStore reads: getThreadSnapshotWindow(rowLimit=THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, userTurnLimit=10, deferWork false and true) and getThreadHistoryPage with a cursor 200 items from the end (workMode undefined and deferred), on a second warm pass, with an SQL statement tracer. An older page returning the same 178 items took 20 ms at 1k runs, 112 ms at 7k runs (63k items) and 428 ms at 28k runs, so its cost grows linearly with thread length. The trace shows the page running unbounded
SELECT payload_json FROM orchestration_v2_projection_runs WHERE thread_id = ? ORDER BY ordinaland the same for run_attempts, which also sorts in a temporary B-tree. EXPLAIN QUERY PLAN shows the open path's checkpoint and provider-turn reads (thread_id = ? AND (status IN (...) OR ... IN json_each(...))) search only the thread_id index, so they fetch every row of the thread from the table. Thread open itself stayed at 8-22 ms here because the synthetic data had no nodes, checkpoints, provider turns or subagents, and nothing in this run came near the reporter's multi-second times: the database was small and warm, while theirs is a cold 49 GB clone where each row is likely a separate disk read. A test on the existing paging case fails on main:getThreadHistoryPage re-read every run and attempt across 4 pages: expected 4 to be at most 2.Evidence
Being captured: before and after in the real app. This section is filled in before the pull request can merge.
Tests
vp test run src/orchestration-v2/ProjectionStore.test.ts: 59 passed (fails on the previous head's ProjectionStore.ts/Migrations.ts). vp run check:changed: format, lint, knip, graphql, typecheck (3 packages), tests (4 files) pass. vp test run on the 12 other server test files that call getThreadSnapshotWindow/getThreadHistoryPage/getTimelinePage: 187 passed. vp test run src/orchestration-v2/ThreadStream src/orchestration-v2/Checkpoint: 6 files, 41 passed. vp test run src/persistence: all pass except src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts, which also fails on the previous head without these changes. EXPLAIN QUERY PLAN via sqlite3 on a migrated schema dump (scratch, not committed) for every rewritten read.
Not in this change
Who did the work
Run by the t3code factory in T3 Code.