@devries-cameron20 / t3code Mirror · read-only / commits / eb1d80c667
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 05:30 UTC

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

Co-authored-by: Michał Pierzchała <thymikee@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 18, 2026 at 02:03 UTC eb1d80c66765072dd7fd9f96c365820cbae3d48b
7 files changed +49 -21
apps/desktop/src/window/DesktopApplicationMenu.ts
+3 -1
@@ -106,8 +106,10 @@ const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
106 return;
107 }
108
109 + // The result dialogs need no main window. Opening one before the backend
110 + // answers strands the renderer on a failed auth bootstrap.
111 const desktopWindow = yield* DesktopWindow.DesktopWindow;
110 - yield* desktopWindow.ensureMain;
112 + yield* desktopWindow.activate;
113 yield* checkForUpdatesFromMenu;
114 }).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
115
apps/server/src/orchestration-v2/ProjectionStore.ts
+2
@@ -3965,6 +3965,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
3965 `.pipe(Effect.flatMap(decodeRows(decodeRunAttemptPayload, threadId)));
3966 const nodes = yield* sql<PayloadRow>`
3967 SELECT payload_json FROM orchestration_v2_projection_nodes
3968 + -- Look up the root node by key, not every node in the thread.
3969 + INDEXED BY sqlite_autoindex_orchestration_v2_projection_nodes_1
3970 WHERE thread_id = ${threadId} AND node_id IN (SELECT json_extract(payload_json, '$.rootNodeId') FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId} AND run_id = ${runId}) ORDER BY node_id ASC
3971 `.pipe(Effect.flatMap(decodeRows(decodeNodePayload, threadId)));
3972 const subagents = yield* sql<PayloadRow>`
apps/server/src/orchestration-v2/ThreadFind.ts
+3
@@ -296,6 +296,9 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
296 WHERE json_extract(t.payload_json, '$.forkedFrom.type') = 'run'
297 )
298 SELECT COALESCE(MAX(sequence), 0) AS sequence FROM orchestration_events
299 + -- The planner otherwise walks every V2 event backwards from the newest,
300 + -- which takes seconds for a thread that has been idle a long time.
301 + INDEXED BY idx_orch_events_stream_sequence
302 WHERE application_event_version = 2 AND aggregate_kind = 'thread'
303 AND stream_id IN (SELECT thread_id FROM source_threads)
304 `;
apps/server/src/persistence/Sqlite.test.ts
+23 -10
@@ -66,7 +66,7 @@ it.effect("limits the WAL file size in the shared persistence setup", () =>
66 }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
67 );
68
69 -it.effect("collects planner statistics for an existing database on open", () => {
69 +it.effect("drops planner statistics a database already has", () => {
70 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-stats-"));
71 const dbPath = NodePath.join(tempDir, "state.sqlite");
72 const persistence = () =>
@@ -75,20 +75,33 @@ it.effect("collects planner statistics for an existing database on open", () =>
75 return Effect.gen(function* () {
76 yield* Effect.gen(function* () {
77 const sql = yield* SqlClient.SqlClient;
78 - yield* sql`CREATE TABLE stats_probe(id INTEGER PRIMARY KEY, thread_id TEXT NOT NULL)`;
79 - yield* sql`CREATE INDEX stats_probe_thread_idx ON stats_probe(thread_id)`;
80 - yield* sql`
81 - WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1000)
82 - INSERT INTO stats_probe(thread_id) SELECT 'thread-' || (i % 10) FROM n
83 - `;
78 + yield* sql`CREATE TABLE walk_probe(node_id TEXT PRIMARY KEY, parent_node_id TEXT)`;
79 + yield* sql`INSERT INTO walk_probe VALUES ('node-1', NULL), ('node-2', 'node-1')`;
80 + // Stats from a nearly empty table, as an older build collected on a new install.
81 + yield* sql`ANALYZE walk_probe`;
82 }).pipe(Effect.provide(persistence()));
83
84 yield* Effect.gen(function* () {
85 const sql = yield* SqlClient.SqlClient;
88 - const rows = yield* sql<{ readonly stat: string }>`
89 - SELECT stat FROM sqlite_stat1 WHERE idx = 'stats_probe_thread_idx'
86 + const stats = yield* sql<{ readonly count: number }>`
87 + SELECT COUNT(*) AS count FROM sqlite_stat1
88 + `;
89 + assert.equal(stats[0]?.count, 0);
90 + // A connection still using the old stats scans the table at each step.
91 + const plan = yield* sql<{ readonly detail: string }>`
92 + EXPLAIN QUERY PLAN
93 + WITH RECURSIVE retained(node_id) AS (
94 + SELECT 'node-2'
95 + UNION
96 + SELECT parent.parent_node_id FROM walk_probe AS parent
97 + INNER JOIN retained ON parent.node_id = retained.node_id
98 + )
99 + SELECT node_id FROM retained
100 `;
91 - assert.deepEqual([...rows], [{ stat: "1000 100" }]);
101 + assert.include(
102 + plan.map((row) => row.detail),
103 + "SEARCH parent USING INDEX sqlite_autoindex_walk_probe_1 (node_id=?)",
104 + );
105 }).pipe(Effect.provide(persistence()));
106 }).pipe(
107 Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
apps/server/src/persistence/Sqlite.ts
+11 -1
@@ -37,7 +37,17 @@ const layerSetup = Layer.effectDiscard(
37 // largest size until the last connection closes.
38 yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
39 yield* runMigrations();
40 - yield* sql`PRAGMA optimize = 0x10012;`;
40 + // No planner statistics. Collecting them reads every page of the large
41 + // tables, and stats taken while a table was small make the planner scan it
42 + // once it grows. Without them SQLite assumes large tables and uses indexes;
43 + // the few queries that still pick a worse index name theirs with INDEXED BY.
44 + // Older builds collected stats, so clear them. A connection loads stats
45 + // when it opens, so this one must reload them after the delete.
46 + const statTables = yield* sql`SELECT 1 FROM sqlite_schema WHERE name = 'sqlite_stat1'`;
47 + if (statTables.length > 0) {
48 + yield* sql`DELETE FROM sqlite_stat1;`;
49 + yield* sql`ANALYZE sqlite_schema;`;
50 + }
51 }),
52 );
53
apps/server/src/serviceLauncher.ts
+2 -3
@@ -32,9 +32,8 @@ import {
32
33 const HANDOFF_DELAY_MS = 2_000;
34 /**
35 - * Migrations and the open-time `PRAGMA optimize` count toward it and scale with the database:
36 - * tens of GB on a cold page cache take minutes. A missed window rolls back the database, so
37 - * the next attempt pays the same cost.
35 + * Migrations count toward it and can scale with the database: tens of GB on a cold page cache
36 + * take minutes. A missed window rolls back the database, so the next attempt pays the same cost.
37 */
38 export const PREPARED_TIMEOUT_MS = 30 * 60_000;
39 const TERMINATE_GRACE_MS = 5_000;
docs/internals/server-updates.md
+5 -6
@@ -30,12 +30,11 @@ ready to commit.
30 A failed or timed-out trial returns to the old version. After commit, the target
31 is authoritative and the service manager's ordinary restart policy applies.
32
33 -The prepared deadline is long because migrations and SQLite's open-time optimize
34 -scale with the database and block the trial's main thread, so it cannot report
35 -progress. A missed deadline restores the snapshot, and the retry pays the same
36 -cost again. A crashed trial is caught when it exits; the deadline bounds only a
37 -stuck one. Client update waits must outlast the deadline, or a slow update shows
38 -as failed.
33 +The prepared deadline is long because migrations can scale with the database
34 +and block the trial's main thread, so it cannot report progress. A missed
35 +deadline restores the snapshot, and the retry pays the same cost again. A
36 +crashed trial is caught when it exits; the deadline bounds only a stuck one.
37 +Client update waits must outlast the deadline, or a slow update shows as failed.
38
39 ## Database rollback
40