perf(server): index thread-shell and turn-recovery projection queries #23009
Thread-shell listing sorts each thread's run history to find its last executed run. Recovery also scans historical turn items because its filters do not match a covering access path. This addresses the uncovered parts of #23000, with unchanged query semantics and no startup-performance claim.
Migration 68 adds three partial indexes with CREATE INDEX IF NOT EXISTS: unfinished items by thread/status/type and ownership IDs, last executed runs in the shell's exact completion order, and interrupt requests by thread/run. The existing migration manifest owns installation and transactional history recording. No query rewrites or existing-index removals.
Query and overlap map#
All unfinished predicates below are exactly status IN ('pending', 'running', 'waiting'), matching the literal set in the queries.
| Proposed index / measured query | Real query | This PR | #22354 | #21777 | #21193 | #21585 |
|---|---|---|---|---|---|---|
| 1. unfinished status cover: recovery_1/3/6 | ProjectionStore.ts:4364, ProjectionStore.ts:4396, ProjectionStore.ts:4497 | Keep (thread_id,status,type,run_id,node_id,provider_thread_id); partial unfinished | thread/type and run/status indexes do not supply this access path | None | None | Same unfinished row set, different ordinal key; cannot replace this filtering/covering path |
| 2. message order: message_order | ProjectionStore.ts:3511 | Excluded | Owns (thread_id,json_extract(payload_json,'$.messageId')) with matching message-type predicate; reuse this definition rather than add another | None | None | None |
| 3. runs status order: recovery_1/3/10 and shell_all | ProjectionStore.ts:4333, ProjectionStore.ts:5662 | Dropped: repeated recovery plan regressions; existing unique thread/ordinal key already orders runs | Running-only index serves another predicate | None | Delegated-delivery partial serves another predicate | None |
| 4. last executed: shell_all | ProjectionStore.ts:5806 | Keep (thread_id,(completed_at IS NULL) DESC,completed_at DESC,ordinal DESC,run_id DESC) with exact queued/never-started-cancelled exclusions | No equivalent | Thread sweep expressions only | No equivalent | No equivalent |
| 5. interrupt: shell_all | ProjectionStore.ts:5650, ProjectionStore.ts:5705 | Keep (thread_id,run_id) WHERE type='run_interrupt_request' | Thread/type can win the wrong historical scan; does not cover the run/type probe | None | None | None |
| 6. pending ordinal order: recovery_10 | ProjectionStore.ts:4543 | Excluded | No equivalent | None | Other snapshot tables | Owns the exact (thread_id,ordinal,turn_item_id) partial index |
#21585 implements #21578. Its ordered partial index and this status-covering index have the same transient row set but different useful key orders. Their combined maintenance cost is real. The exact combined-PR benchmark proves that the ordered index alone loses recovery_1 to the broad thread/type index: 339/327 ms, status-cover added 14/12 ms, removed again 323/330 ms. This is why the covering index remains.
All three required PR diffs and the turn-start follow-up were inspected before implementation. None already supplies the shell's last-executed ordering. The issue listing was paginated at 100 through all 1,001 open GitCafe issues; searches for “thread-shell”, “recovery queries” and “missing indexes” found only this report's GitCafe mirror, #23003. No competing message or pending-order index is introduced.
EXPLAIN evidence#
- recovery_1 item lookup:
thread_run_idx (thread_id=? AND run_id>?)on main, orthread_type_idx (thread_id=? AND type=?)with the open PRs, becomesCOVERING ...unfinished_status_idx (thread_id=? AND status=? AND type=? [AND run_id>?]). - recovery_3/6 item probes also use the unfinished status index; the provider-thread ID probes become covering reads. Whole-query timings are reported separately below.
- Shell blocked candidate:
runs_thread_ordinal_idxplusUSE TEMP B-TREE FOR ORDER BYbecomesruns_last_executed_idx (thread_id=?), without a temporary sort in that scalar subquery. - Both shell stop requests become
COVERING ...turn_items_interrupt_idx (thread_id=? AND run_id=?)rather than reading historical items through thread/run or thread/type. - recovery_10 keeps its historical ordinal scan on main; the open #21585 index supplies its ordered unfinished access path. The open #22354 message index removes the message GROUP BY temporary B-tree. Those gains are not credited to this migration.
Synthetic measurements#
Node 24.21.0, SQLite 3.53.4; deterministic 1,200 threads, 1,000,000 turn items and 33,980 runs. One thread has 400,000 items / 10,000 runs. Full actual SQL templates, including the complete all-thread shell SELECT, are materialized; two executions each; no statistics or OS-cache flush. All six complete ordered-result and row-multiset hashes are identical before/after.
Milliseconds, first / second execution:
| Query | Main | Main + this PR | Exact open PRs | Exact open PRs + this PR |
|---|---|---|---|---|
| shell_all | 526.293 / 319.416 | 277.198 / 280.993 | 410.595 / 425.222 | 270.297 / 316.154 |
| recovery_1 | 491.897 / 314.318 | 14.085 / 28.913 | 312.865 / 322.812 | 20.837 / 13.904 |
| recovery_3 | 0.118 / 0.091 | 0.110 / 0.048 | 0.130 / 0.075 | 0.120 / 0.055 |
| recovery_6 | 9.090 / 6.043 | 10.309 / 6.417 | 10.359 / 6.914 | 10.066 / 6.681 |
| recovery_10 | 279.672 / 266.857 | 265.846 / 270.655 | 0.455 / 0.284 | 0.476 / 0.160 |
| message_order | 370.000 / 361.903 | 347.143 / 366.049 | 98.327 / 121.445 | 103.654 / 96.103 |
Main-only full-shell timing is directional given the two samples and host/cache noise; recovery_3/6 show plan changes without a meaningful whole-query timing gain. The isolated last-executed lookup across all threads drops from 39.843/27.710 to 2.789/2.160 ms on main. Other shell counts and payload scans remain. The discarded run-status-order index repeatedly made recovery_3/10 slower (roughly 1.4–2 ms instead of fractions of a millisecond), so it is absent.
The exact open-PR configuration installs every definition from the four PRs above and applies only the equivalent recovery_1 predicate removal from #21585. Other query templates are unchanged. This is SQL evidence, excluding Effect decoding, transport, rendering and complete app startup; supporting event/provider-turn/checkpoint tables are empty. Two samples, warm OS caches, dense synthetic interrupt requests and shared-host noise limit generalization. cannot-verify at 26.5 GB.
Migration and write cost#
The baseline DB was 1,169,096,704 bytes (1.089 GiB). These three indexes added about 4.9 MiB: status cover 1.25 MiB, last-executed runs 2.06 MiB and interrupt requests 1.57 MiB. Baseline construction took approximately 1,286 / 74 / 646 ms respectively. SQLite holds its normal writer lock during index creation; the reporter's production-sized build costs can be much larger. Production-scale lock duration is unmeasured.
The status cover adds an index delete/insert even for updates to items that remain unfinished, because the projector upsert sets the indexed columns; this is the main write cost. A rollback-only 1,000-row transition batch measured 38/36 ms without it versus 71/54 ms with it (UPDATE work only, excluding prepare/commit/rollback). This is a real tradeoff, not a production throughput estimate. The run index is maintained per run lifecycle update; the interrupt partial index stores only request rows. Each index is retained for the measured access path above.
Migration 68 is next free on the pinned main. Other open index PRs also use 68 (and older proposals use now-occupied IDs), so integration must renumber whichever lands later. Index names do not collide. DDL and migration history are committed through the existing transactional migrator; no WAL-unsafe operation was added. Existing malformed cancelled-run JSON can fail expression-index construction, as malformed JSON already fails the corresponding read; valid JSON is the persisted invariant.
Validation#
- Tests first: missing-index/plan failures were reproduced. Final whole-file run: 51 passed across 3 files:
ProjectionStore.test.ts,Migrations.test.ts, andreconcileV2PreviewMigration.test.ts. - Fresh installation; populated migration-67 upgrade; names, columns, ordering and partial predicates; direct migration replay and ledger idempotency; indexed versus unindexed row equality; successive-delete ordering; real shell and recovery plans.
- Scoped server typecheck, changed-file lint and formatting passed.
- Independent final code reviews: Codex gpt-6.1-sol MERGE; Claude claude-opus-5-5 MERGE.
- Independent proof audits: Codex gpt-6.1-sol SUFFICIENT (51 tests plus full independent benchmark reproduction, all 32 plans/hashes/sizes matched); Claude claude-opus-5-5 SUFFICIENT (51 tests, real migrated-schema equivalence and all 32 regenerated plans matched).
Reproduction scripts, SQL, complete plans, hashes, raw timings and cleanup evidence are retained outside the worktree at /tmp/t3-v2-bench-23000-20261021/exact/final/; run python3 /tmp/t3-v2-bench-23000-20261021/exact/final/benchmark.py. Every generated DB and sidecar was deleted. Free root disk: 9.0 GB initially, 8.6 GB immediately before dependency installation, 8.4 GB after installation; minimum final measurement headroom exceeded 7.0 GiB. No live userdata access, servers or browser sessions.
Implementation: OpenAI gpt-6.1-sol through the Codex harness in T3 Code. Code reviews and proof audits: Codex gpt-6.1-sol and Claude claude-opus-5-5 through T3 Code delegation.
Fixes #23000 GitCafe: https://git.cafe/pingdotgg/t3code/issues/23000
- 1
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:S
juliusmarminge added labelsvia-triage
juliusmarminge added labelsvia-triage:gates-failing
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
Approvability#
Verdict: Approved at
a947a7cMacroscope's review found this PR approvable — This PR adds three targeted, partial SQLite indexes for existing thread-shell and recovery queries, with tests covering migration upgrades, idempotence, query plans, and unchanged results. Its runtime impact is limited to query performance and routine index maintenance/storage overhead.
No code changes detected at
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).7180469. Prior analysis still applies.No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
-
⚙️ Run configuration
-
- Configuration used: Path: .coderabbit.config.ts
- Review profile: CHILL
- Plan: Team
- Run ID:
8d33c6b1-e35d-4be6-9226-ccb6d3d3dda5
📥 Commits
-
Reviewing files that changed from the base of the PR and between 9179178fdff5ac750c29ef8d6234d5e75538c124 and a947a7c47fc382f080a4fa7aa39e36d1d3fd2059.
📒 Files selected for processing: 4
-
apps/server/src/orchestration-v2/ProjectionStore.test.tsapps/server/src/persistence/Migrations.tsapps/server/src/persistence/Migrations/068_ThreadShellLookupIndexes.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; 4 remain after this review.
-
📝 Walkthrough
-
Migration 68 adds three SQLite indexes for thread-shell lookups and registers the migration. Tests check index definitions, query plans, lookup results, idempotency, and migration upgrade expectations.
Changes: Thread-shell lookup indexes
Layer / File(s) Summary Create and register lookup indexes
apps/server/src/persistence/Migrations/068_ThreadShellLookupIndexes.ts,apps/server/src/persistence/Migrations.tsMigration 68 creates three conditional indexes for run, interrupt-request, and unfinished-item lookups. The migration manifest includes the new migration. Validate index behavior and migration
apps/server/src/orchestration-v2/ProjectionStore.test.ts,apps/server/src/persistence/reconcileV2PreviewMigration.test.tsTests check index definitions, query plans, lookup results before and after migration, and idempotency. Preview-upgrade expectations include migration 68. Priority: ➖ Normal
Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Refactor
Possibly related issues
pingdotgg/t3code#23000reports slow thread-shell and turn-recovery queries and proposes index shapes that this PR adds.
Suggested reviewers:
t3dotgg,maria-rcks
Merge Risk: ⚪ Minimal · up to
a947a-
The lookup indexes align with the queries they are intended to accelerate. No identified issue prevents merging after normal checks.
Pre-merge checks:
4-
Check name Status Explanation Title check The title clearly and concisely describes the main change: adding indexes for thread-shell and turn-recovery projection queries. Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request. Description check The description is comprehensive and covers the problem, implementation, scope, query overlap, performance tradeoffs, migration risks, verification results, and agent usage. It links the tracked issue… Full details: Description check
-
Explanation
The description is comprehensive and covers the problem, implementation, scope, query overlap, performance tradeoffs, migration risks, verification results, and agent usage. It links the tracked issue and records tests, benchmarks, typecheck, lint, and formatting results. The template headings are not used literally, and explicit maintainer approval is not quoted, but the required information is substantially present.
-
✨ Finishing Touches
-
📝 Generate docstrings
-
- Commit to this branch
- Create a new PR
🧪 Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
-
juliusmarminge added labelsbugfix
juliusmarminge removed labelsvia-triage
juliusmarminge added labelspr:gate-failed
juliusmarminge removed labelsvia-triage:gates-failing
Data point from a real install: statev2.sqlite is 17 GB with ~3,200 active threads. Server traces show the shell query (
ProjectionStore.readShellSnapshotRows) taking 19.9 s in one capture and 34–63 s in others, so the Android app on T3 Connect hits the 20 s HTTP deadline on every launch and resume, falls back to the socket snapshot (which runs the same query), and shows "Syncing threads…" for 30+ s. Caveat: some of those traces were captured while the disk was under heavy unrelated load.On a synthetic 3,216-thread copy, your indexes took the query from 84 ms to 53 ms median over five alternating runs, with identical results. That fixture is far smaller than the real history, so it doesn't reproduce the multi-second case. Happy to rerun on the real database once this lands in a nightly.
juliusmarminge removed labelspr:gate-failed
juliusmarminge added labelspr:ready
juliusmarminge added labelspr:needs-julius
juliusmarminge removed labelspr:ready
t3dotgg(GitHub profile, opens in a new tab) closed this
juliusmarminge removed labelspr:needs-julius
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
8d3b061· PR result:7180469· 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.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.