Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): opening a large database no longer blocks startup for minutes #21122

Mergedt3dotgg(GitHub profile, opens in a new tab)merged 5 commits intomain fromrefs/pull/21122/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHub

Opening a database without planner statistics blocked server startup for minutes. Since #18471, the server runs PRAGMA optimize = 0x10012 on open. When sqlite_stat1 is missing, that pass reads every page of the large tables: 108.5 s cold on an 11 GB copy of a real database, and almost 4 minutes on 48 GB. Stats taken while a table is small also make the planner scan it once it grows. That is the #19916 freeze: 2 ms with no stats, 1.7 s with stale-small stats.

Fix

Stop using planner statistics.

  • After migrations, the server clears sqlite_stat1 and reloads with ANALYZE sqlite_schema. That reads no user table. Stats that older builds collected go away, and the writer connection stops using them. The reader worker starts after setup, so it never loads them.
  • Without stats, SQLite assumes tables are large and uses indexes. Only two queries picked a worse index, and each now names its index with INDEXED BY, as other event-store reads already do:
    • ThreadFind revision lookup: walked every V2 event backwards, which took seconds on long-idle threads.
    • getTurnStartContext node read: read every node in the thread instead of looking up the root node by key.
  • Check for Updates in the desktop menu now calls activate instead of ensureMain. It no longer opens the main window before the backend is ready, which left the renderer on a failed auth bootstrap.

Cold open of the 11 GB copy, with its stats removed or restored: main 108.5 s, this branch 50 to 66 ms.

How we know stats are not needed

We extracted every static SQL statement from the server and ran EXPLAIN QUERY PLAN with and without stats on 10 real databases (0.2 to 26 GB, macOS and Linux). 452 statements prepare.

QueryNo statsWith statsNo stats + hint
ThreadFind revision9 to 3,205 ms0 ms0 ms
Turn-start node read0 to 28 ms0 ms0 ms
Thread text search1 to 126 ms1 to 173 msno change needed

The no-stats plan depends only on the schema, so it is the same on every machine. I reviewed it for every location whose plan changed on any machine. I timed the risky ones on the largest database: agent event reads by thread, the startup recovery query, and thread search. None was slower without stats. Some, such as the provider-thread reads at ProjectionStore.ts:3139 and :3156, use an index only without stats.

Takeover

This continues #19407 by @thymikee, whose commits are kept with his authorship. His PR seeded fixed sqlite_stat1 rows instead of collecting them. The fleet measurements showed that the stats themselves are not needed, so this branch removes them. His desktop menu fix is unchanged.

#19917 (hourly PRAGMA optimize) goes the other way and would bring the stats back.

Verification

  • New test: an older build's stale-small stats on a probe table are cleared on reopen. On the same writer connection, a recursive walk then uses the index. The test fails with the old optimize line, and it fails if the reload is missing.
  • vp test run passes for Sqlite.test.ts, ProjectionStore.test.ts, ThreadFind.test.ts, TurnStartReads.test.ts, ProviderTurnControlService.test.ts, ProviderTurnStartService.test.ts and DesktopApplicationMenu.test.ts. Server and desktop typecheck pass. Lint and format pass on the changed files.
  • Not checked: Windows databases, and clicking Check for Updates in a packaged desktop build during a slow startup.

Reviewed with sol-loop: 3 rounds with GPT-6.1 Sol. Sol verdict: approved

Original work by Michał Pierzchała with Claude Opus 5.5 in Claude Code. Takeover by Claude Opus 5.5 in Claude Code, working in T3 Code.

Co-authored-by: Michał Pierzchała <thymikee@gmail.com>

🤖 Generated with Claude Code

    1. juliusmarminge added labelsmacroscope-review

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

      Approvability

      Verdict: Needs Human Approval

      Macroscope's review found this PR requires human approval — The PR changes the default SQLite planner policy for every server database, clears persisted statistics at startup, and alters query plans on existing request paths. The update-menu change is small, but the server-wide runtime default warrants human review.

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

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire5.0 KiB5.0 KiB−7 B (−0.1%)6.8 KiB✅
      CodexThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      CodexLive turn WebSocket wire1.2 KiB1.2 KiB−7 B (−0.6%)2.0 KiB✅
      CodexLive turn WebSocket decoded20.9 KiB20.9 KiB0 B (0.0%)29.3 KiB✅
      CodexLive turn messages220 (0.0%)8✅
      ClaudeTotal thread wire5.0 KiB5.0 KiB+7 B (+0.1%)6.8 KiB✅
      ClaudeThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      ClaudeLive turn WebSocket wire1.2 KiB1.2 KiB+7 B (+0.6%)2.0 KiB✅
      ClaudeLive turn WebSocket decoded21.2 KiB21.2 KiB0 B (0.0%)29.3 KiB✅
      ClaudeLive turn messages220 (0.0%)8✅

      Baseline: 9ba6143 · PR result: 425abfa · 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.

    4. 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: Team
      • Run ID: 303d6808-7079-49d0-a5a2-78962a70836e
      📥 Commits

      Reviewing files that changed from the base of the PR and between d414e5a7811fee2da840640ce971853279c7700b and 425abfa97cd8e6196709220fb1df544ee713de83.

      📒 Files selected for processing: 4
      • apps/server/src/orchestration-v2/ProjectionStore.ts
      • apps/server/src/orchestration-v2/ThreadFind.ts
      • apps/server/src/persistence/Sqlite.test.ts
      • apps/server/src/persistence/Sqlite.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.

      📝 Walkthrough

      SQLite setup now clears collected planner statistics and reloads them for the connection. Two orchestration queries specify indexes. The desktop update-check handler activates the main window before starting the check.

      Changes: SQLite Query Planning

      Layer / File(s)Summary
      Clear planner statistics during setup
      apps/server/src/persistence/Sqlite.ts, apps/server/src/persistence/Sqlite.test.ts, apps/server/src/serviceLauncher.ts, docs/internals/server-updates.md
      SQLite setup clears sqlite_stat1 when present and runs ANALYZE sqlite_schema. The test checks that statistics are cleared and that a recursive query uses the primary-key index. The launcher comment and documentation remove the reference to open-time optimization.
      Specify indexes for orchestration queries
      apps/server/src/orchestration-v2/ProjectionStore.ts, apps/server/src/orchestration-v2/ThreadFind.ts
      The root-node query specifies the primary-key autoindex. The revision query specifies idx_orch_events_stream_sequence.

      Desktop Update Menu

      Layer / File(s)Summary
      Activate the main window before checking
      apps/desktop/src/window/DesktopApplicationMenu.ts
      The update-check handler activates the main window before checking for updates, replacing its call to ensureMain.

      Priority: ⬆️ High

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

      Change: Bug fix

      Suggested reviewers: maria-rcks, otavio

      Merge Risk: ⚪ Minimal · up to 425ab

      The change avoids slow server startup on large databases by clearing planner statistics and pinning two query indexes. No concrete merge-blocking risk was found.

      Pre-merge checks: Passed 4
      Check nameStatusExplanation
      Title checkPassedThe title clearly identifies the primary change: preventing large database startup from blocking for minutes.
      Description checkPassedThe description clearly covers the problem, technical changes, scope, performance impact, verification results, and untested areas. It includes issue and pull request references, although it does not …
      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 clearly covers the problem, technical changes, scope, performance impact, verification results, and untested areas. It includes issue and pull request references, although it does not use the template's exact “Scope and approval” heading or provide an explicit approval comment.

      ✨ 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
      Comment `@coderabbitai help` to get the list of available commands.
    5. Thanks for getting this in, appreciate it!

Sign in to join this conversation.