fix(server): older history pages no longer read every run and attempt of the thread #36141
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 pingdotgg/t3code#36128
Reproduction on main#
On origin/main 7903b487ba: 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 ordinal and 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#
- The thread-open reads in readCanonicalProjection's window path (checkpoints: status IN ('pending','capturing') OR ... run_id/node_id/checkpoint_id IN json_each(...); provider turns: status IN ('starting','running','waiting') OR provider_turn_id/node_id IN json_each(...)) still fetch every such row of the thread. Those tables have only a thread_id index (no status, run_id or node_id index), so fixing them needs a migration adding indexes plus a rewrite into one indexed query per condition. The local repro did not show slow thread opens and there is no failing test for them yet.
- readTimelineIndex (the full-index path used by forks, jump-to-entry and search) still reads all runs and attempts by design.
- src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts fails on the previous head too, unrelated to this change.
- The seven new indexes add some write cost to the attempts, provider-turns and checkpoints tables; not measured.
- readTimelineIndex (full-index path for forks, jump-to-entry and search) still reads every run and attempt by design.
- The reporter's 9-12 s on a cold 49 GB database was not benchmarked; the evidence is query plans and the VM-step test.
Who did the work#
- Written by Claude Opus 5.5, in Claude Code
- Reviewed by GPT-6.1 Sol, in Codex, and by Claude Opus 5.5, each on its own
- Proof captured by GPT-6.1 Sol and checked by Claude Opus 5.5
Run by the t3code factory in T3 Code.
- 1
tanstack-source added labelsbug
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
Approvability#
Verdict: Approved at
dff391bMacroscope'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](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Provider Metric Main baseline This PR Impact PR ceiling Codex Total thread wire 5.0 KiB 5.0 KiB 0 B (0.0%) 6.8 KiB ✅ Codex Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Codex Live turn WebSocket wire 1.2 KiB 1.2 KiB 0 B (0.0%) 2.0 KiB ✅ Codex Live turn WebSocket decoded 21.5 KiB 21.5 KiB 0 B (0.0%) 24.4 KiB ✅ Codex Live turn messages 1 1 0 (0.0%) 8 ✅ Claude Total thread wire 5.0 KiB 5.0 KiB 0 B (0.0%) 6.8 KiB ✅ Claude Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Claude Live turn WebSocket wire 1.2 KiB 1.2 KiB 0 B (0.0%) 2.0 KiB ✅ Claude Live turn WebSocket decoded 21.9 KiB 21.9 KiB 0 B (0.0%) 24.4 KiB ✅ Claude Live turn messages 1 1 0 (0.0%) 8 ✅ Other scenarios#
All 64 scenario measurements match
main.All 64 scenario measurements
Provider Scenario Metric Main baseline This PR Impact PR ceiling Codex short turn resumeWebSocket decoded10.5 KiB 10.5 KiB 0 B (0.0%) 12.7 KiB ✅ Codex short turn resumeWebSocket messages2 2 0 (0.0%) 2 ✅ Codex long turn running, cold openHTTP decoded281.7 KiB 281.7 KiB 0 B (0.0%) 302.7 KiB ✅ Codex long turn running, cold openrows75 75 0 (0.0%) 75 ✅ Codex long turn running, history pageHTTP decoded92.4 KiB 92.4 KiB 0 B (0.0%) 107.4 KiB ✅ Codex long turn running, history pagerows75 75 0 (0.0%) 75 ✅ Codex long turn finished, cold openHTTP decoded381.5 KiB 381.5 KiB 0 B (0.0%) 410.2 KiB ✅ Codex long turn finished, cold openrows151 151 0 (0.0%) 151 ✅ Codex long turn finished, socket cold openWebSocket decoded381.6 KiB 381.6 KiB 0 B (0.0%) 410.2 KiB ✅ Codex long turn finished, socket cold openWebSocket messages2 2 0 (0.0%) 2 ✅ Codex long turn finished, socket cold openrows151 151 0 (0.0%) 151 ✅ Codex long turn finished, work pageHTTP decoded186.2 KiB 186.2 KiB 0 B (0.0%) 200.2 KiB ✅ Codex long turn finished, work pagerows150 150 0 (0.0%) 150 ✅ Codex idle thread resumeWebSocket decoded65 B 65 B 0 B (0.0%) 200 B ✅ Codex idle thread resumeWebSocket messages1 1 0 (0.0%) 1 ✅ Codex fleet shell snapshotHTTP decoded42.4 KiB 42.4 KiB 0 B (0.0%) 53.7 KiB ✅ Codex fleet shell snapshotrows27 27 0 (0.0%) 27 ✅ Codex fleet shell subscribeWebSocket decoded65 B 65 B 0 B (0.0%) 200 B ✅ Codex fleet shell subscribeWebSocket messages1 1 0 (0.0%) 1 ✅ Codex fleet shell resume checkHTTP decoded18 B 18 B 0 B (0.0%) 100 B ✅ Codex fleet shell resume checkrows0 0 0 0 ✅ Codex stale shell reloadHTTP decoded42.4 KiB 42.4 KiB 0 B (0.0%) 53.7 KiB ✅ Codex stale shell reloadrows27 27 0 (0.0%) 27 ✅ Codex stale shell resumeWebSocket decoded140 B 140 B 0 B (0.0%) 400 B ✅ Codex stale shell resumeWebSocket messages2 2 0 (0.0%) 2 ✅ Codex stale todo list cold openHTTP decoded72.4 KiB 72.4 KiB 0 B (0.0%) 83.0 KiB ✅ Codex stale todo list cold openrows75 75 0 (0.0%) 75 ✅ Codex stale todo list cold opennodes2 2 0 (0.0%) 4 ✅ Codex stale todo list cold opensubagents2 2 0 (0.0%) 4 ✅ Codex stale todo list cold openplans1 1 0 (0.0%) 2 ✅ Codex stale todo list cold openproviderTurns1 1 0 (0.0%) 2 ✅ Codex stale todo list cold opencheckpoints1 1 0 (0.0%) 2 ✅ Claude short turn resumeWebSocket decoded10.6 KiB 10.6 KiB 0 B (0.0%) 12.7 KiB ✅ Claude short turn resumeWebSocket messages2 2 0 (0.0%) 2 ✅ Claude long turn running, cold openHTTP decoded283.3 KiB 283.3 KiB 0 B (0.0%) 302.7 KiB ✅ Claude long turn running, cold openrows75 75 0 (0.0%) 75 ✅ Claude long turn running, history pageHTTP decoded93.4 KiB 93.4 KiB 0 B (0.0%) 107.4 KiB ✅ Claude long turn running, history pagerows75 75 0 (0.0%) 75 ✅ Claude long turn finished, cold openHTTP decoded384.2 KiB 384.2 KiB 0 B (0.0%) 410.2 KiB ✅ Claude long turn finished, cold openrows151 151 0 (0.0%) 151 ✅ Claude long turn finished, socket cold openWebSocket decoded384.3 KiB 384.3 KiB 0 B (0.0%) 410.2 KiB ✅ Claude long turn finished, socket cold openWebSocket messages2 2 0 (0.0%) 2 ✅ Claude long turn finished, socket cold openrows151 151 0 (0.0%) 151 ✅ Claude long turn finished, work pageHTTP decoded188.1 KiB 188.1 KiB 0 B (0.0%) 200.2 KiB ✅ Claude long turn finished, work pagerows150 150 0 (0.0%) 150 ✅ Claude idle thread resumeWebSocket decoded66 B 66 B 0 B (0.0%) 200 B ✅ Claude idle thread resumeWebSocket messages1 1 0 (0.0%) 1 ✅ Claude fleet shell snapshotHTTP decoded43.0 KiB 43.0 KiB 0 B (0.0%) 53.7 KiB ✅ Claude fleet shell snapshotrows27 27 0 (0.0%) 27 ✅ Claude fleet shell subscribeWebSocket decoded66 B 66 B 0 B (0.0%) 200 B ✅ Claude fleet shell subscribeWebSocket messages1 1 0 (0.0%) 1 ✅ Claude fleet shell resume checkHTTP decoded18 B 18 B 0 B (0.0%) 100 B ✅ Claude fleet shell resume checkrows0 0 0 0 ✅ Claude stale shell reloadHTTP decoded43.0 KiB 43.0 KiB 0 B (0.0%) 53.7 KiB ✅ Claude stale shell reloadrows27 27 0 (0.0%) 27 ✅ Claude stale shell resumeWebSocket decoded140 B 140 B 0 B (0.0%) 400 B ✅ Claude stale shell resumeWebSocket messages2 2 0 (0.0%) 2 ✅ Claude stale todo list cold openHTTP decoded73.4 KiB 73.4 KiB 0 B (0.0%) 83.0 KiB ✅ Claude stale todo list cold openrows75 75 0 (0.0%) 75 ✅ Claude stale todo list cold opennodes2 2 0 (0.0%) 4 ✅ Claude stale todo list cold opensubagents2 2 0 (0.0%) 4 ✅ Claude stale todo list cold openplans1 1 0 (0.0%) 2 ✅ Claude stale todo list cold openproviderTurns1 1 0 (0.0%) 2 ✅ Claude stale todo list cold opencheckpoints1 1 0 (0.0%) 2 ✅ Baseline:
4aec277· PR result:dff391b· Source CI: successScenario and decoded snapshot size
10 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.
- Codex decoded thread snapshot: 108.5 KiB
- Claude decoded thread snapshot: 108.8 KiB
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
-
ProjectionStore now uses indexed selections for windowed reads and loads fewer records for local timeline reads. Migration 89 adds seven projection indexes. Tests add query-plan and read-count assertions and extend snapshot-window performance coverage.
Changes: Projection reads
Layer / File(s) Summary Add projection read indexes
apps/server/src/persistence/Migrations/089_ThreadWindowReadIndexes.ts,apps/server/src/persistence/Migrations.ts,apps/server/src/persistence/reconcileV2PreviewMigration.test.tsMigration 89 adds seven indexes for projection reads and is added to the migration manifest. Migration sequence tests include migration 89. Use indexed selections for windowed reads
apps/server/src/orchestration-v2/ProjectionStore.ts,apps/server/src/orchestration-v2/ProjectionStore.test.tsWindowed reads use separate indexed selections for runs, attempts, provider turns, checkpoints, and retained nodes. Tests check query plans, limit unbounded run and attempt reads across history pages, and compare snapshot-window cost before and after deleting older records. Narrow local timeline reads
apps/server/src/orchestration-v2/ProjectionStore.tsTimeline rows obtain run status from SQL. openLocalTimelineloads selected runs and superseded attempts instead of all runs and attempts.Estimated code review effort: 3 (Moderate) | ~25 minutes
Change: Bug fix · Severity of issue fixed: Medium
Suggested reviewers:
t3dotgg,yash-singh1
Merge Risk:
Minimal · up todff39-
This change reduces the cost of reading older history pages and opening long threads by using indexed selections and a new migration of supporting indexes. I found no concrete defect in the supplied changes. The reported timings were not benchmarked, so the size of the speedup is unconfirmed. Merge-readiness risk is minimal.
Pre-merge checks:
4-
Check name Status Explanation Title check The title names the main change: older history pages no longer read every run and attempt of the thread. The raw summary and objectives confirm that older-page paging now avoids the thread-wide run an… Description check The description follows the template. It has a Problem section that explains the slow thread-open and older-page reads, a Change section that explains the indexed key selection, migration 089, and the… Linked Issues check Issue #36128asks for lower cost in thread open (getThreadSnapshotWindow) and in each older page (getThreadHistoryPage). The diff covers both functions. getThreadHistoryPage no longer reads every run …Out of Scope Changes check Changes map to the two linked read paths. ProjectionStore.ts changes the windowed reads for runs, attempts, provider turns, checkpoints, nodes and root IDs, and the older-page run and attempt reads. T… Full details: Title check
-
Explanation
The title names the main change: older history pages no longer read every run and attempt of the thread. The raw summary and objectives confirm that older-page paging now avoids the thread-wide run and attempt reads. The title uses the conventional commit form and is specific. It does not cover the thread-open index work or migration 089, which is expected for a short title.
Full details: Description check
-
Explanation
The description follows the template. It has a Problem section that explains the slow thread-open and older-page reads, a Change section that explains the indexed key selection, migration 089, and the INDEXED BY hint, a Scope section that links issue
#36128through 'Fixes pingdotgg/t3code#36128', and a Verification section with specific tests, query plans, and before/after results. It also names the model and harness that did the work. The Evidence section says it will be filled before merge, and the description does not state why a small fix needs no issue. The description is long and states the reproduction in detail. Those gaps are minor, so the check passes.
Full details: Linked Issues check
-
Explanation
Issue
#36128asks for lower cost in thread open (getThreadSnapshotWindow) and in each older page (getThreadHistoryPage). The diff covers both functions. getThreadHistoryPage no longer reads every run and attempt for each page. getThreadSnapshotWindow now collects keys through one indexed SELECT per condition, then fetches rows by primary key. Migration 089 adds the indexes these reads need. The interrupted-runs subquery uses INDEXED BY on orchestration_v2_projection_turn_items_thread_type_idx. Evidence: EXPLAIN QUERY PLAN results in the PR description show indexed searches. The 'reads a fixed SQL turn-item window' VM-step test fails on the previous head (328133 steps vs at most 271828.7) and passes now. The history-page test asserts no thread_run_idx range plan, and the paging test allows at most 2 full-thread run and attempt reads. Residual gaps: the PR does not change readCanonicalProjection window-path checkpoint and provider-turn reads, which the issue cites in its breakdown (checkpoints 2.3 s). The PR states this gap. The reporter's cold-database timings were not benchmarked. Those gaps limit the claimed improvement, but the named functions and their coding requirements are addressed.
Full details: Out of Scope Changes check
-
Explanation
Changes map to the two linked read paths. ProjectionStore.ts changes the windowed reads for runs, attempts, provider turns, checkpoints, nodes and root IDs, and the older-page run and attempt reads. The timeline-window change, where openLocalTimeline reads only runs with rolled-back, queued or cancelled status and related superseded attempts, sits in the same window/page read path, so it supports the paging objective. Migration 089 and its Migrations.ts registration support the new indexes. reconcileV2PreviewMigration.test.ts lists migration 89. ProjectionStore.test.ts adds assertions for the changed reads. No unrelated feature change appears in the summary. The readTimelineIndex full-index path is unchanged and is stated as out of scope. Uncertainty: the openLocalTimeline change was taken from the AI-generated summary only. I did not inspect its diff hunks.
-
Finishing Touches
-
Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info-
Run configuration-
- Source mode: Auto
- Repository: pingdotgg/t3code
- Branch: factory/issue-36128
- File: .coderabbit.config.ts
- Commit: dff391b
- Layers: Repository TS config
- Review profile: CHILL
- Plan: Team
- Run ID:
ccf5dc94-636d-48e6-a072-4098bdb6d906
Commits-
Reviewing files that changed from the base of the PR and between 4aec277f79b2d4dabd88f13cfab264d9f80cbcef and dff391b66d4a2e9da865aa5b9344b4d31fd4e868.
Files selected for processing: 5-
apps/server/src/orchestration-v2/ProjectionStore.test.tsapps/server/src/orchestration-v2/ProjectionStore.tsapps/server/src/persistence/Migrations.tsapps/server/src/persistence/Migrations/089_ThreadWindowReadIndexes.tsapps/server/src/persistence/reconcileV2PreviewMigration.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
-
-
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.
Read Base Head Open thread A 19.4 s (13.0–23.3) 4.7 s (2.7–4.7) Open thread B 17.3 s (14.7–18.6) 2.7 s (1.9–3.4) Older page, A 4.3 s (4.0–6.2) 1.1 s (1.1–2.7) Older page, B 4.1 s (3.6–5.7) 1.0 s (0.9–2.0) 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#
- Database: a block clone of our 49 GB
statev2.sqlite, at migration 91 (nightly 4682). I dropped our local indexes, so only upstream's remain. - Commits: base is the merge base
7903b487ba, head isdff391b66d. For head I created migration 089's seven indexes on the clone; together they took 84 s, 7–16 s each. - Threads: A has 8,469 runs, 8,270 provider turns, 8,839 checkpoints and 73,302 turn items. B has 7,804 runs, 7,635 provider turns, 8,206 checkpoints and 67,977 turn items.
- Calls: through the real
ProjectionStore(node:sqlite, read-only), the way the thread subscription calls it. FirstgetThreadSnapshotWindowwithrowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT,deferWork: trueanduserTurnLimit: THREAD_HISTORY_PAGE_POLICY.maxUserTurns. Then three chainedgetThreadHistoryPagecalls with deferred work, starting at the window's oldest item.
Where the time went on base#
Opening 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 head#
These three reads are most of head's remaining time:
- Context transfers, 0.8–2.7 s per open:
(source_thread_id = ? OR target_thread_id = ?) AND (status IN (...) OR target_run_id IN json_each(...)) - Subagents, 0.7–1.5 s per open. This is the same OR form that the PR rewrites for the other tables:
thread_id = ? AND (status IN (...) OR run_id IN json_each(...)) - The turn-item count, 0.5–1.2 s per older page, about half of each page:
SELECT COUNT(*) FROM orchestration_v2_projection_turn_items WHERE thread_id = ? AND (ordinal, turn_item_id) < (?, ?)
Measured and written by Claude (Opus 5.5) in T3 Code; posted with the owner's approval.
- Database: a block clone of our 49 GB
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes