Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): older history pages no longer read every run and attempt of the thread #36141

Openjuliusmarmingewants to merge 3 commits intomain fromrefs/pull/36141/headopened View on GitHub

juliusmarmingecommented

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

    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. Approvability

      Verdict: Approved at dff391b

      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](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire5.0 KiB5.0 KiB0 B (0.0%)6.8 KiB✅
      CodexThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      CodexLive turn WebSocket wire1.2 KiB1.2 KiB0 B (0.0%)2.0 KiB✅
      CodexLive turn WebSocket decoded21.5 KiB21.5 KiB0 B (0.0%)24.4 KiB✅
      CodexLive turn messages110 (0.0%)8✅
      ClaudeTotal thread wire5.0 KiB5.0 KiB0 B (0.0%)6.8 KiB✅
      ClaudeThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      ClaudeLive turn WebSocket wire1.2 KiB1.2 KiB0 B (0.0%)2.0 KiB✅
      ClaudeLive turn WebSocket decoded21.9 KiB21.9 KiB0 B (0.0%)24.4 KiB✅
      ClaudeLive turn messages110 (0.0%)8✅

      Other scenarios

      All 64 scenario measurements match main.

      All 64 scenario measurements
      ProviderScenarioMetricMain baselineThis PRImpactPR ceiling
      Codexshort turn resumeWebSocket decoded10.5 KiB10.5 KiB0 B (0.0%)12.7 KiB✅
      Codexshort turn resumeWebSocket messages220 (0.0%)2✅
      Codexlong turn running, cold openHTTP decoded281.7 KiB281.7 KiB0 B (0.0%)302.7 KiB✅
      Codexlong turn running, cold openrows75750 (0.0%)75✅
      Codexlong turn running, history pageHTTP decoded92.4 KiB92.4 KiB0 B (0.0%)107.4 KiB✅
      Codexlong turn running, history pagerows75750 (0.0%)75✅
      Codexlong turn finished, cold openHTTP decoded381.5 KiB381.5 KiB0 B (0.0%)410.2 KiB✅
      Codexlong turn finished, cold openrows1511510 (0.0%)151✅
      Codexlong turn finished, socket cold openWebSocket decoded381.6 KiB381.6 KiB0 B (0.0%)410.2 KiB✅
      Codexlong turn finished, socket cold openWebSocket messages220 (0.0%)2✅
      Codexlong turn finished, socket cold openrows1511510 (0.0%)151✅
      Codexlong turn finished, work pageHTTP decoded186.2 KiB186.2 KiB0 B (0.0%)200.2 KiB✅
      Codexlong turn finished, work pagerows1501500 (0.0%)150✅
      Codexidle thread resumeWebSocket decoded65 B65 B0 B (0.0%)200 B✅
      Codexidle thread resumeWebSocket messages110 (0.0%)1✅
      Codexfleet shell snapshotHTTP decoded42.4 KiB42.4 KiB0 B (0.0%)53.7 KiB✅
      Codexfleet shell snapshotrows27270 (0.0%)27✅
      Codexfleet shell subscribeWebSocket decoded65 B65 B0 B (0.0%)200 B✅
      Codexfleet shell subscribeWebSocket messages110 (0.0%)1✅
      Codexfleet shell resume checkHTTP decoded18 B18 B0 B (0.0%)100 B✅
      Codexfleet shell resume checkrows0000✅
      Codexstale shell reloadHTTP decoded42.4 KiB42.4 KiB0 B (0.0%)53.7 KiB✅
      Codexstale shell reloadrows27270 (0.0%)27✅
      Codexstale shell resumeWebSocket decoded140 B140 B0 B (0.0%)400 B✅
      Codexstale shell resumeWebSocket messages220 (0.0%)2✅
      Codexstale todo list cold openHTTP decoded72.4 KiB72.4 KiB0 B (0.0%)83.0 KiB✅
      Codexstale todo list cold openrows75750 (0.0%)75✅
      Codexstale todo list cold opennodes220 (0.0%)4✅
      Codexstale todo list cold opensubagents220 (0.0%)4✅
      Codexstale todo list cold openplans110 (0.0%)2✅
      Codexstale todo list cold openproviderTurns110 (0.0%)2✅
      Codexstale todo list cold opencheckpoints110 (0.0%)2✅
      Claudeshort turn resumeWebSocket decoded10.6 KiB10.6 KiB0 B (0.0%)12.7 KiB✅
      Claudeshort turn resumeWebSocket messages220 (0.0%)2✅
      Claudelong turn running, cold openHTTP decoded283.3 KiB283.3 KiB0 B (0.0%)302.7 KiB✅
      Claudelong turn running, cold openrows75750 (0.0%)75✅
      Claudelong turn running, history pageHTTP decoded93.4 KiB93.4 KiB0 B (0.0%)107.4 KiB✅
      Claudelong turn running, history pagerows75750 (0.0%)75✅
      Claudelong turn finished, cold openHTTP decoded384.2 KiB384.2 KiB0 B (0.0%)410.2 KiB✅
      Claudelong turn finished, cold openrows1511510 (0.0%)151✅
      Claudelong turn finished, socket cold openWebSocket decoded384.3 KiB384.3 KiB0 B (0.0%)410.2 KiB✅
      Claudelong turn finished, socket cold openWebSocket messages220 (0.0%)2✅
      Claudelong turn finished, socket cold openrows1511510 (0.0%)151✅
      Claudelong turn finished, work pageHTTP decoded188.1 KiB188.1 KiB0 B (0.0%)200.2 KiB✅
      Claudelong turn finished, work pagerows1501500 (0.0%)150✅
      Claudeidle thread resumeWebSocket decoded66 B66 B0 B (0.0%)200 B✅
      Claudeidle thread resumeWebSocket messages110 (0.0%)1✅
      Claudefleet shell snapshotHTTP decoded43.0 KiB43.0 KiB0 B (0.0%)53.7 KiB✅
      Claudefleet shell snapshotrows27270 (0.0%)27✅
      Claudefleet shell subscribeWebSocket decoded66 B66 B0 B (0.0%)200 B✅
      Claudefleet shell subscribeWebSocket messages110 (0.0%)1✅
      Claudefleet shell resume checkHTTP decoded18 B18 B0 B (0.0%)100 B✅
      Claudefleet shell resume checkrows0000✅
      Claudestale shell reloadHTTP decoded43.0 KiB43.0 KiB0 B (0.0%)53.7 KiB✅
      Claudestale shell reloadrows27270 (0.0%)27✅
      Claudestale shell resumeWebSocket decoded140 B140 B0 B (0.0%)400 B✅
      Claudestale shell resumeWebSocket messages220 (0.0%)2✅
      Claudestale todo list cold openHTTP decoded73.4 KiB73.4 KiB0 B (0.0%)83.0 KiB✅
      Claudestale todo list cold openrows75750 (0.0%)75✅
      Claudestale todo list cold opennodes220 (0.0%)4✅
      Claudestale todo list cold opensubagents220 (0.0%)4✅
      Claudestale todo list cold openplans110 (0.0%)2✅
      Claudestale todo list cold openproviderTurns110 (0.0%)2✅
      Claudestale todo list cold opencheckpoints110 (0.0%)2✅

      Baseline: 4aec277 · PR result: dff391b · Source CI: success

      Scenario 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.

    5. Explain Change →

      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.ts
      Migration 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.ts
      Windowed 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.ts
      Timeline rows obtain run status from SQL. openLocalTimeline loads 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 to dff39

      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: Passed 4

      Check nameStatusExplanation
      Title checkPassedThe 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 checkPassedThe 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 checkPassedIssue #36128 asks 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 checkPassedChanges 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 #36128 through '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 #36128 asks 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

      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.ts
      • apps/server/src/orchestration-v2/ProjectionStore.ts
      • apps/server/src/persistence/Migrations.ts
      • apps/server/src/persistence/Migrations/089_ThreadWindowReadIndexes.ts
      • apps/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.

    6. 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.

    7. 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.

      ReadBaseHead
      Open thread A19.4 s (13.0–23.3)4.7 s (2.7–4.7)
      Open thread B17.3 s (14.7–18.6)2.7 s (1.9–3.4)
      Older page, A4.3 s (4.0–6.2)1.1 s (1.1–2.7)
      Older page, B4.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 is dff391b66d. 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. First getThreadSnapshotWindow with rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, deferWork: true and userTurnLimit: THREAD_HISTORY_PAGE_POLICY.maxUserTurns. Then three chained getThreadHistoryPage calls 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.

Sign in to join this conversation.