Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): MCP thread reads skip the item scan they filter to nothing #17038

MergedSunkenInTime(GitHub profile, opens in a new tab)merged 2 commits intomain fromrefs/pull/17038/headmerged by juliusmarminge View on GitHub

On real threads of 3k to 8.5k items, every MCP projection read spent 15 to 39 ms (median, warm) on a SQLite query that returns no rows, and up to 283 ms while the live server was busy. This PR skips that query. Results are byte-identical.

Problem

MCP tools (delegate_task, task_status, t3_thread_read, t3_thread_list, orchestrator_capabilities, and others) load the caller's or target's thread through loadProjection / loadProjectThread in OrchestratorMcpService.ts. Both ask getThreadRecords for turnItems with turnItemTypes: [], and several Orchestrator.ts reads pass the same filter. The server's SQLite connection is synchronous, so while an agent calls MCP tools on a long thread, every client waits on this read.

Cause

readCanonicalProjection turns the empty list into AND type IN (SELECT value FROM json_each('[]')). That matches nothing, but SQLite still walks every item of the thread through turn_items_thread_ordinal_idx and loads each row to check type, which isn't in the index. The cost grows with the thread's item count and payload size.

Fix

When a record read has no window and one of its list filters is empty, the read returns [] without running the query. That covers turnItemTypes, turnItemStatuses and turnItemRunIds for items, runIds for runs, and messageIds, messageRoles and messageRunIds for messages. Each of those filters is an IN (json_each(...)) that can't match an empty list. For turnItemRunIds, the run_id IS NULL branch only applies when the list contains null, so an empty list matches nothing there too. Windowed reads ignore these filters and are unchanged.

Evidence

A/B through the real ProjectionStore, on my live 8.2 GB database opened read-only. I loaded main's ProjectionStore.ts and this branch's in the same process and called getThreadRecords with MCP's exact fields and filter, alternating between the two for 31 rounds. Times come from the sql.execute spans. The first (cold) round of each is left out.

Median read time per MCP call, main vs this branch, on three real threads

Thread itemsEmpty item query on main (p25 / median / p75)This branchWhole read, median (p25–p75): main → branch
8,49933 / 39 / 56 msnot run147 (124–206) → 107 (93–173) ms
5,98221 / 25 / 32 msnot run119 (103–163) → 100 (92–151) ms
3,38813 / 15 / 21 msnot run65 (57–90) → 48 (45–64) ms

The returned records hashed identical on main and this branch for all three threads, in every round. An earlier 8-round run, taken while the live T3 server was busy, showed the same empty query at 67 / 118 / 283 ms (min / median / max) on the 8,499-item thread. On main's first cold read it took 2.2 s.

Live MCP call through a dev server. I seeded a dev server with vp run migrate-dev-db. A Claude Haiku thread in a scratch project called t3_thread_read three times on a copied 867-item thread, first on main's store and then on this branch. In the dev server's trace, each tools/call ran:

main:   McpServer.@effect/mcp/2025-06-18/tools/call | sql statements 77 | empty-filter item reads 1 (0.07ms, 0.12ms, 0.11ms)
branch: McpServer.@effect/mcp/2025-06-18/tools/call | sql statements 76 | empty-filter item reads 0

The seeding script keeps only unsettled threads, so this dev thread is small and fully cached. That's why the query costs a tenth of a millisecond here and up to 283 ms on the large live threads above.

Tests

answers empty record filters without reading the filtered tables records every statement getThreadRecords runs. For each of the seven list filters, an empty list must return [] without touching that filter's table. Non-empty filters must still return the same rows. On main it fails with {"turnItemTypes":[]} read turn_items: expected true to be false.

apps/server> vp test run src/orchestration-v2/ProjectionStore.test.ts src/orchestration-v2/ProjectionControlReads.test.ts src/orchestration-v2/TurnStartReads.test.ts src/orchestration-v2/Orchestrator.control-reads.test.ts src/mcp/OrchestratorMcpService.test.ts src/mcp/OrchestratorMcpService.activity.test.ts
 Test Files  6 passed (6)
      Tests  63 passed (63)

vp lint on the two changed files, vp fmt --check, and tsc --noEmit in apps/server pass.

Environment

Windows 11, Node 24.13.1, branch based on d720210996.

Not checked

  • macOS and Linux. The change is plain SQL-or-skip logic with nothing platform-specific.
  • OrchestratorMcpToolkit.integration.test.ts fails 2 tests on Windows both with and without this change.
  • The two other costly statements in the same MCP read are left alone. The provider-thread lookup walks node rows to collect owner_node_id candidates (25–77 ms warm on the live database after this fix). The message-ordinal query scans user and assistant items (47–101 ms). Each has a separate cause and fix.

Opus 5.5 (Claude Code, inside T3 Code)

🤖 Generated with Claude Code

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

    2. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Approved at 8280132

      Macroscope's review found this PR approvable — This is a small, self-contained server performance fix that avoids SQLite scans for filters proven to match no rows while preserving existing results and windowed-read behavior. Tests cover all affected empty filters plus representative non-empty selections, and no product defaults, schemas, or deployment behavior change.

      Notes:

      • Diff unchanged. Approvability was decided on eligibility alone.
      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
      Review in Change Stack →

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration
      • Configuration used: Path: .coderabbit.config.ts
      • Review profile: CHILL
      • Plan: Advanced
      • Run ID: 27203aab-34cb-419c-82d2-d8a3e6ae7615

      📥 Commits

      Reviewing files that changed from the base of the PR and between d720210996a514368ba99f4860063110033d93fa and 828013267cc952d634a199c6fd958ce26fa0d701.


      📒 Files selected for processing (2)
      • apps/server/src/orchestration-v2/ProjectionStore.test.ts
      • apps/server/src/orchestration-v2/ProjectionStore.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.



      📝 Walkthrough

      Walkthrough

      readCanonicalProjection now skips turn-item, run, and message queries when applicable unwindowed filters are empty. Tests verify that these reads return empty results without querying the projection tables.

      Changes

      Projection read filters

      Layer / File(s)Summary
      Short-circuit empty projection filters
      apps/server/src/orchestration-v2/ProjectionStore.ts, apps/server/src/orchestration-v2/ProjectionStore.test.ts
      matchesNothing detects empty filters. Turn-item, run, and message reads use it to skip applicable queries. Tests check query omission, matching results for non-empty filters, and the result for a nonmatching turn-item type.

      Priority: ⬇️ Low

      Estimated code review effort: 2 (Simple) | ~10 minutes

      Change: Bug fix

      Suggested reviewers: t3dotgg


      Merge Risk: ⚪ Minimal · up to 82801

      This change skips queries that could only return empty results, so returned data should be unchanged. No merge-blocking risk was identified.

      Pre-merge checks | Passed 5
      ✅ Passed checks (5 passed)
      Check nameStatusExplanation
      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.
      ApprovabilityPassedPASS. The pull request changes only ProjectionStore.ts and its test. The product change is a focused bug fix that skips empty-filter queries; it does not change a product default, contracts, persist…
      Title checkPassedThe title clearly and concisely describes the main change: MCP thread reads skip scans when filters match no items.
      Description checkPassedThe description is detailed and covers the problem, cause, fix, evidence, tests, environment, and limitations. It does not include a separate Scope and approval section or explain why prior approval w…

      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR

      • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      Comment `@coderabbitai help` to get the list of available commands.
    4. juliusmarminge added labelsmacroscope-review

    5. juliusmarminge merged thisddafde5

    6. juliusmarminge closed this

Sign in to join this conversation.