fix(server): opening a large database no longer blocks startup for minutes #21122
main fromrefs/pull/21122/head·merged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubOpening 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_stat1and reloads withANALYZE 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:ThreadFindrevision lookup: walked every V2 event backwards, which took seconds on long-idle threads.getTurnStartContextnode 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
activateinstead ofensureMain. 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.
| Query | No stats | With stats | No stats + hint |
|---|---|---|---|
| ThreadFind revision | 9 to 3,205 ms | 0 ms | 0 ms |
| Turn-start node read | 0 to 28 ms | 0 ms | 0 ms |
| Thread text search | 1 to 126 ms | 1 to 173 ms | no 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
optimizeline, and it fails if the reload is missing. vp test runpasses forSqlite.test.ts,ProjectionStore.test.ts,ThreadFind.test.ts,TurnStartReads.test.ts,ProviderTurnControlService.test.ts,ProviderTurnStartService.test.tsandDesktopApplicationMenu.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
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:L
juliusmarminge added labelsmacroscope-review
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Provider Metric Main baseline This PR Impact PR ceiling Codex Total thread wire 5.0 KiB 5.0 KiB −7 B (−0.1%) 6.8 KiB ✅ Codex Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Codex Live turn WebSocket wire 1.2 KiB 1.2 KiB −7 B (−0.6%) 2.0 KiB ✅ Codex Live turn WebSocket decoded 20.9 KiB 20.9 KiB 0 B (0.0%) 29.3 KiB ✅ Codex Live turn messages 2 2 0 (0.0%) 8 ✅ Claude Total thread wire 5.0 KiB 5.0 KiB +7 B (+0.1%) 6.8 KiB ✅ Claude Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Claude Live turn WebSocket wire 1.2 KiB 1.2 KiB +7 B (+0.6%) 2.0 KiB ✅ Claude Live turn WebSocket decoded 21.2 KiB 21.2 KiB 0 B (0.0%) 29.3 KiB ✅ Claude Live turn messages 2 2 0 (0.0%) 8 ✅ Baseline:
9ba6143· PR result:425abfa· 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.
- 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.
- apps/desktop/src/window/DesktopApplicationMenu.ts line 112Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -106,5 +106,7 @@106106 return;107107 }108108109+ // The result dialogs need no main window. Opening one before the backend110+ // answers strands the renderer on a failed auth bootstrap.109111 const desktopWindow = yield* DesktopWindow.DesktopWindow;110- yield* desktopWindow.ensureMain;112+ yield* desktopWindow.activate;
This changes the Check for Updates startup behavior, but no focused menu test clicks that item or verifies
Posted via Macroscope — Effect Service Conventionsactivateruns withoutensureMain. Could you add aDesktopApplicationMenu.test.tstest using the window and update service test layers to exercise the click and assert that behavior?Note
🤖 Claude Opus 5.5 responding on behalf of Theo
Not adding this one. A menu test that asserts
activateruns instead ofensureMainwould only restate the call. AGENTS.md asks us not to add tests that assert callback wiring. The behavior that matters, no main window before the backend is ready, belongs toDesktopWindow.activate.DesktopWindow.test.ts:634("does not open a development window until the backend is ready") already covers it:activatecreates no window untilhandleBackendReady. 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.tsapps/server/src/orchestration-v2/ThreadFind.tsapps/server/src/persistence/Sqlite.test.tsapps/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.mdSQLite setup clears sqlite_stat1when present and runsANALYZE 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.tsThe 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.tsThe 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:
4-
Check name Status Explanation Title check The title clearly identifies the primary change: preventing large database startup from blocking for minutes. Description check 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 … 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. 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
-
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
t3dotgg(GitHub profile, opens in a new tab) closed this
Thanks for getting this in, appreciate it!
Sign in to join this conversation.
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).