Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(server): shell reads stop counting every turn item #27975

ClosedPyseph(GitHub profile, opens in a new tab)wants to merge 6 commits intomain fromrefs/pull/27975/headopened View on GitHub

Problem

Every shell read counts each thread's turn items by walking the (thread_id, run_id) index, one entry per item. The count runs for every thread in a snapshot, and getThreadShell runs it again for the thread behind each projected shell event. On a large history this is the biggest part of the shell read, and once the index is out of the page cache it reads from disk.

On 2026-10-29, the server in #24192 (2,857 active threads, 645k turn items) spent 4.8 s of a 7.3 s phone reconnect on these counts. That was before #27106; on current main the phone's opted-in shell reads far fewer threads, but they are the busiest ones, and every shell event still recounts its thread.

Change

  • Migration 081 adds orchestration_v2_projection_turn_item_counts, one row per (thread, run), and backfills it.
  • Triggers on turn items keep it exact for every writer: the projector's upsert, projection rebuilds, and migrate-dev-db's pruning. An upsert that hits an existing item fires only the update trigger, which does nothing unless the item moved to another thread or run.
  • The two shell count queries read the table. They keep #25696's json_each ID predicates, and #27106's index-first loading is untouched.
  • docs/internals/performance-regressions.md said shell counts use a covering index; that sentence now says where they come from.

Measurements

All on main at the time, 2b15ba077d, using a static copy of the shell tables from the same server: 3,047 threads, 701,015 turn items and 9,644 (thread, run) pairs. Both arms ran the real ProjectionStore code read-only against the identical file. Times are warm medians; the two rounds alternated main and branch, 15 samples each after 3 warmups. Every output was byte-identical between arms (same SHA-256).

Readmainthis PR
Phone's opted-in HTTP shell (105 threads)107 / 101 ms85 / 83 ms
Full active shell (3,032 threads)445 / 578 ms245 / 258 ms
getThreadShell on the 10 largest threads, total69 / 99 ms45 / 48 ms

Data the counts read, which is what a cold read pays for:

Count readmainthis PR
Phone's opted-in shell84,133 index entries3,750 rows
All threads158 MB index (40,475 pages)1.8 MB table (458 pages)

The thread rows query, the other large part of a cold shell read, is unchanged.

Write cost

20,000 real turn items, replayed through the projector's exact upsert into the same schema (WAL, synchronous = NORMAL), with and without the triggers, in ABBA order:

Workloadmaintriggers
One transaction per upsert, like event commits: insert / re-upsert10.8 s / 5.9 s10.7 s / 4.9 s
One transaction for all, statement cost only: insert1,172 ms1,324 ms (+7.6 µs per item)
Same: re-upsert of existing items1,122 ms1,210 ms (+4.4 µs per item)
DELETE FROM every turn item71 ms503 ms (+22 µs per item)

Per event, the triggers are lost in commit cost: main alone ranged from 6.7 to 13.7 s on the per-event insert run. Deletes cost the most because a delete trigger makes SQLite delete row by row instead of clearing the table. Production code deletes turn items only in the projection rebuild, a startup repair, and in migrate-dev-db. On 700k items that adds about 15 s to a rebuild that also re-applies every event.

The migration took 1.2 s on the 701k-item copy, and its counts matched a GROUP BY over the items with no differing rows.

Verification

  • 081_TurnItemCounts.test.ts: backfills existing items, then follows a new item, a repeated upsert (not counted twice), an item moving into a run, and deletes.
  • The existing ProjectionStore case "counts each shell's own runless and live-run items, skipping rolled back and missing runs" passes unchanged against the new queries. It counts through the projector's real path, covering runless items, a rolled-back run and an item whose run has no row.
  • Passing locally: vp test run on the migration test, reconcileV2PreviewMigration, migrate-dev-db, ProjectionStore, ShellStream, FoundationPersistence (rebuild), ThreadFork.integration and TurnItemCompaction (126 tests); vp run check:changed. The other files that rebuild projections also pass: the 064 and 066 migration tests (which rebuild before 081 exists), LegacyV1ThreadImporter, ProjectService.deletion and ProviderSwitch.integration.

Not checked: cold-cache timing on the new code, since this Windows machine can't drop its file cache; the page counts above stand in for it.

Scope

This replaces #26816, which was closed under the one-problem rule for an unrelated reader-pool test. That test is gone. PixPMusic's review there found the count table useful once rebased: a free migration ID, #25696's predicates kept, and #27106's loading kept. All three are done here, along with the write costs that review measured. The reader-pool queueing gap from that review is in its own PR. Related: #24192.

Claude Opus 5.5 in T3 Code (Claude Code harness).

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

    2. Approvability

      Verdict: Approved at ca75793

      Macroscope's review found this PR approvable — Shell reads use trigger-maintained counts instead of recounting every turn item. The additive table preserves source data and can be rebuilt; reported measurements show equivalent outputs with limited migration and write overhead.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Explain Change →

      Note

      Reviews paused

      It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

      • Last reviewed commit: fed6cd7bd99dd4ae2f8f4d4d5007f6ab6fe28b96

      Use the following commands to manage reviews:

      • @coderabbitai resume to resume automatic reviews.
      • @coderabbitai review to trigger a single review.

      Use the checkboxes below for quick actions:

      • Resume reviews
      • Trigger review

      No actionable comments were generated in the recent review.

      Walkthrough

      The change adds a trigger-maintained table of turn-item counts grouped by thread and run. Shell count queries now read those counts, and migration 81 is registered and covered by migration tests.

      Changes: Turn-item count projections

      Layer / File(s)Summary
      Create and maintain turn-item counts
      apps/server/src/persistence/Migrations/081_TurnItemCounts.ts, apps/server/src/persistence/Migrations/081_TurnItemCounts.test.ts, apps/server/src/persistence/Migrations.ts, apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
      Migration 81 creates and backfills counts grouped by thread and run. Triggers update counts on inserts, changes to thread or run, and deletes. Migration registration and upgrade test expectations include migration 81.
      Read turn-item counts for shell queries
      apps/server/src/orchestration-v2/ProjectionStore.ts, docs/internals/performance-regressions.md
      Shell queries read stored counts instead of counting turn-item rows. Per-run counts exclude runless items; total counts exclude items from rolled-back runs, and runless counts include only runless items. The performance documentation describes the count table and retained indexes.

      Estimated code review effort: 3 (Moderate) | ~20 minutes

      Change: Refactor

      Possibly related issues

      • Issue 23000 reports slow shell-list queries caused by scanning turn-item history. This change targets the same query cost with stored counts, but the issue’s proposed indexes differ and the issue is not resolved by this change.

      Suggested reviewers: juliusmarminge, yash-singh1

      Merge Risk: Minimal · up to fed6c

      No actionable count mismatch is established at the current head. The change is mergeable after normal checks.

      Pre-merge checks: Passed 3 · Inconclusive 1

      Failed Failed checks: 1 inconclusive
      Check nameStatusExplanationResolution
      Description checkInconclusiveThe description follows the repository template and is mostly complete. It has a Problem section with a clear problem statement and measurements, a Change section listing the migration, triggers, quer…Add a link to the triaged bug issue (or the discussion with explicit maintainer approval, including the approval comment) under "Scope and approval". If no prior issue exists, explain why this qualifies as a very small, focused fix of an ob…
      Passed Passed checks: 3 passed

      Check nameStatusExplanation
      Title checkPassedThe title is concise, specific, and accurately describes the main performance change: shell reads no longer count every turn item.
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck skipped because no linked issues were found for this pull request.
      Full details: Description check

      Explanation

      The description follows the repository template and is mostly complete. It has a Problem section with a clear problem statement and measurements, a Change section listing the migration, triggers, query changes, and doc update, and a Verification section listing specific tests and an unchecked item (cold-cache timing). The Scope and approval section is only partly satisfied: it says the PR replaces #26816 and cites related issue #24192, but it does not link a triaged bug issue or a maintainer approval comment, and it does not explain why the change qualifies without one. The Problem section also refers to other PRs (#25696, #27106, #24192) without context for a reviewer who has not read them. The template's trailing agent-model line is present ("Claude Opus 5.5 in T3 Code"). These gaps are not critical, but the scope/approval gap is material under the template's rules.

      Resolution

      Add a link to the triaged bug issue (or the discussion with explicit maintainer approval, including the approval comment) under "Scope and approval". If no prior issue exists, explain why this qualifies as a very small, focused fix of an obvious bug. Briefly explain the context of #25696, #27106, and #24192 so reviewers can follow the Problem section without opening them. Confirm the PR title follows a conventional commit format in plain language, since the template asks for one.

      Finishing Touches

      Generate unit tests (beta)

      • 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 6710e366c5bbbde3d3998edd85ef7d8e121e52d3 and fed6cd7bd99dd4ae2f8f4d4d5007f6ab6fe28b96.

      Files selected for processing: 5

      • apps/server/src/orchestration-v2/ProjectionStore.ts
      • apps/server/src/persistence/Migrations.ts
      • apps/server/src/persistence/Migrations/081_TurnItemCounts.test.ts
      • apps/server/src/persistence/Migrations/081_TurnItemCounts.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; 9 remain after this review.

    4. Note

      Written by gpt-6.1-sol on behalf of Maria

      Merged current main without rebasing. Kept main's migration 076 and moved the stored turn-item counts migration and its existing test to 077, preserving both changes and the six-file scope.

      Blacksmith passed vp run check:changed github/main: formatting, lint, knip, GraphQL, affected typechecks, and 61 tests. A focused migration/projection run also passed 52 tests. Two independent read-only reviews approved 54b50f1106 with no findings.

    5. Note

      Written by gpt-6.1-sol on behalf of Maria

      Verified in a real dev environment

      verified 54b50f11062ab24fa9342a0a49736886d9df5136 as-is on a linux boat vm. installed main and the exact pr head with vp i, then ran one background dev server at a time. used repository playwright with /usr/bin/google-chrome, a project added through the ui, and four real codex gpt-6.1-sol turns. no mocks, replay data, fixtures, or direct database writes.

      • on github/main (ce9e016406), two completed turns produced 7 and 8 items. the client http shell returned 15. confirmed the old count query walks the turn-item covering index.
      • stopped main, copied its isolated app-created database, and started the pr. migration 077 backfilled 7 and 8 exactly. the same conversation rendered and the http shell still returned 15.
      • continued the same codex session through the composer. shell websocket counts advanced from 15 to 21 as real items streamed. stored counts matched raw items during the turn and after completion, with no upsert inflation.
      • forked from the first response and continued through codex. the fork showed 5 own items and 13 visible items including inherited history, preserved after reload.
      • used "edit from here" and "revert and keep changes" on the source's third turn. provider rollback completed. the shell excluded the rolled-back run's 6 items, returning 15 again, while the stored rows remained exact. the fork stayed at 5 own / 13 visible items after reconnect.

      blacksmith passed 69 focused migration/projection/shell tests. vp run check:changed 7195b699547b538e49f758e314dde5c8c5d907cf also passed format, lint, knip, graphql, affected typechecks and 61 tests. latest applicable github checks pass. no source changes needed.

      short runtime transcript

      main: two real codex turns before migration

      pr: the same conversation after migration 077

      pr: real codex turn submitted, streamed and completed

      Not verified

      native mobile and desktop clients, other providers, and remote/relay/tunnel connections were not exercised. large-history speedup and cold-cache latency remain unverified: this small real dataset proves integration and count correctness, not production-scale performance. delete/move triggers passed focused tests; destructive runtime deletion and projection repair were not induced.

    6. Main moved under this PR and it now conflicts. I merged main into the branch (no rebase), as on #22507.

      Two files conflicted, both only because of migration numbering. Main added 077 (RepairBooleanSettledOverride), 078 (DropOrchestrationEventCorrelationIndex) and 079 (DelegatedRecoveryIndexes) after this branch took 077. I kept all three upstream migrations as they are and moved this PR's migration to 080:

      • Migrations.ts: kept 077-079 from main, registered [80, "TurnItemCounts", Migration0080] after them.
      • reconcileV2PreviewMigration.test.ts: kept main's 077-079 history rows and added [80, "TurnItemCounts"] to both expected histories.
      • 077_TurnItemCounts.ts and its test are renamed to 080_TurnItemCounts.ts / .test.ts (test describe name updated). The SQL, triggers and backfill are unchanged, and so is the ProjectionStore change.

      After the merge the diff against main is the same six files the PR had before. Merge commit: 6710e366c5.

      Checks (Node 26.12.1, Windows): the 080_TurnItemCounts, Migrations, reconcileV2PreviewMigration, 064 and 066 migration tests and the ProjectionStore and ProjectionMaintenance tests pass (7 files, 72 tests); tsc --noEmit in apps/server, lint and format on the six changed files are clean.

    7. Note

      Written by Claude Opus 5.5 on behalf of Pyseph

      Main moved under this PR again, so I merged it into the branch (no rebase) in fed6cd7bd9.

      Two files conflicted, both only because of migration numbering. Main's 080_ScheduledTaskThreadMode took the number this PR had, so this PR's migration is now 081:

      • Migrations.ts: kept main's 080 and registered [81, "TurnItemCounts", Migration0081] after it.
      • reconcileV2PreviewMigration.test.ts: kept main's 080 and added [81, "TurnItemCounts"] to both expected histories.
      • 080_TurnItemCounts.ts and its test are renamed to 081_TurnItemCounts.ts and .test.ts, with the test's name updated. The SQL, triggers and backfill are unchanged, and so is the ProjectionStore change.

      The diff against main is still the same six files.

      Checks on Node 26.12.1, Windows: 081_TurnItemCounts, Migrations, reconcileV2PreviewMigration, ProjectionStore and ProjectionMaintenance tests pass (5 files, 71 tests). The server typecheck is clean, and the pre-commit hook (fmt, lint, knip) passes.

    8. Note

      🤖 Claude Fable 5.2 responding on behalf of Theo

      Superseded by https://github.com/pingdotgg/t3code/pull/35167, merged as 3e03072eb63.

      Your trigger-maintained item counts are in that PR with your authorship, and the squash commit carries a Co-authored-by line for you. It was chosen over the other open design (#34666) because it stores one fact, stays exact for every writer, and costs less per write (about +7 to +14 µs per new turn item against +26 to +32 µs, measured on the same data).

      Verified on a real server with 1,813 threads and 153,546 turn items: the two migrations run once, the stored counts match a fresh recount after every kind of write, and the sidebar matches main row for row.

    9. Thanks for this. Main has the change since #35167.

      Main contains the identical count table, backfill and triggers as migration 85, both shell count-query replacements, migration tests and documentation update. Compared your full diff; main also extends coverage for rewrites, moves, rollback, late runs and projection rebuilds.

      Closing as superseded.

    10. juliusmarminge closed this

Sign in to join this conversation.