Skip to content
TypeScript

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

Theo Browneeb1d80c66765
diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts
index 07967834ff4..09808348a0d 100644
--- a/apps/desktop/src/window/DesktopApplicationMenu.ts
+++ b/apps/desktop/src/window/DesktopApplicationMenu.ts
@@ -106,8 +106,10 @@ const handleCheckForUpdatesMenuClick = Effect.gen(function* () {
return;
}
+ // The result dialogs need no main window. Opening one before the backend
+ // answers strands the renderer on a failed auth bootstrap.
const desktopWindow = yield* DesktopWindow.DesktopWindow;
- yield* desktopWindow.ensureMain;
+ yield* desktopWindow.activate;
yield* checkForUpdatesFromMenu;
}).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick"));
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index 4222c3c2702..e222b0d30a1 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -3965,6 +3965,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
`.pipe(Effect.flatMap(decodeRows(decodeRunAttemptPayload, threadId)));
const nodes = yield* sql<PayloadRow>`
SELECT payload_json FROM orchestration_v2_projection_nodes
+ -- Look up the root node by key, not every node in the thread.
+ INDEXED BY sqlite_autoindex_orchestration_v2_projection_nodes_1
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
`.pipe(Effect.flatMap(decodeRows(decodeNodePayload, threadId)));
const subagents = yield* sql<PayloadRow>`
diff --git a/apps/server/src/orchestration-v2/ThreadFind.ts b/apps/server/src/orchestration-v2/ThreadFind.ts
index 6e48e0a651a..10d0b5cecac 100644
--- a/apps/server/src/orchestration-v2/ThreadFind.ts
+++ b/apps/server/src/orchestration-v2/ThreadFind.ts
@@ -296,6 +296,9 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
WHERE json_extract(t.payload_json, '$.forkedFrom.type') = 'run'
)
SELECT COALESCE(MAX(sequence), 0) AS sequence FROM orchestration_events
+ -- The planner otherwise walks every V2 event backwards from the newest,
+ -- which takes seconds for a thread that has been idle a long time.
+ INDEXED BY idx_orch_events_stream_sequence
WHERE application_event_version = 2 AND aggregate_kind = 'thread'
AND stream_id IN (SELECT thread_id FROM source_threads)
`;
diff --git a/apps/server/src/persistence/Sqlite.test.ts b/apps/server/src/persistence/Sqlite.test.ts
index 66380fb60b2..aaa387ed137 100644
--- a/apps/server/src/persistence/Sqlite.test.ts
+++ b/apps/server/src/persistence/Sqlite.test.ts
@@ -66,7 +66,7 @@ it.effect("limits the WAL file size in the shared persistence setup", () =>
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
);
-it.effect("collects planner statistics for an existing database on open", () => {
+it.effect("drops planner statistics a database already has", () => {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-stats-"));
const dbPath = NodePath.join(tempDir, "state.sqlite");
const persistence = () =>
@@ -75,20 +75,33 @@ it.effect("collects planner statistics for an existing database on open", () =>
return Effect.gen(function* () {
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
- yield* sql`CREATE TABLE stats_probe(id INTEGER PRIMARY KEY, thread_id TEXT NOT NULL)`;
- yield* sql`CREATE INDEX stats_probe_thread_idx ON stats_probe(thread_id)`;
- yield* sql`
- WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1000)
- INSERT INTO stats_probe(thread_id) SELECT 'thread-' || (i % 10) FROM n
- `;
+ yield* sql`CREATE TABLE walk_probe(node_id TEXT PRIMARY KEY, parent_node_id TEXT)`;
+ yield* sql`INSERT INTO walk_probe VALUES ('node-1', NULL), ('node-2', 'node-1')`;
+ // Stats from a nearly empty table, as an older build collected on a new install.
+ yield* sql`ANALYZE walk_probe`;
}).pipe(Effect.provide(persistence()));
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
- const rows = yield* sql<{ readonly stat: string }>`
- SELECT stat FROM sqlite_stat1 WHERE idx = 'stats_probe_thread_idx'
+ const stats = yield* sql<{ readonly count: number }>`
+ SELECT COUNT(*) AS count FROM sqlite_stat1
+ `;
+ assert.equal(stats[0]?.count, 0);
+ // A connection still using the old stats scans the table at each step.
+ const plan = yield* sql<{ readonly detail: string }>`
+ EXPLAIN QUERY PLAN
+ WITH RECURSIVE retained(node_id) AS (
+ SELECT 'node-2'
+ UNION
+ SELECT parent.parent_node_id FROM walk_probe AS parent
+ INNER JOIN retained ON parent.node_id = retained.node_id
+ )
+ SELECT node_id FROM retained
`;
- assert.deepEqual([...rows], [{ stat: "1000 100" }]);
+ assert.include(
+ plan.map((row) => row.detail),
+ "SEARCH parent USING INDEX sqlite_autoindex_walk_probe_1 (node_id=?)",
+ );
}).pipe(Effect.provide(persistence()));
}).pipe(
Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
diff --git a/apps/server/src/persistence/Sqlite.ts b/apps/server/src/persistence/Sqlite.ts
index ae023c1e27e..aac4cd840e0 100644
--- a/apps/server/src/persistence/Sqlite.ts
+++ b/apps/server/src/persistence/Sqlite.ts
@@ -37,7 +37,17 @@ const layerSetup = Layer.effectDiscard(
// largest size until the last connection closes.
yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);
yield* runMigrations();
- yield* sql`PRAGMA optimize = 0x10012;`;
+ // No planner statistics. Collecting them reads every page of the large
+ // tables, and stats taken while a table was small make the planner scan it
+ // once it grows. Without them SQLite assumes large tables and uses indexes;
+ // the few queries that still pick a worse index name theirs with INDEXED BY.
+ // Older builds collected stats, so clear them. A connection loads stats
+ // when it opens, so this one must reload them after the delete.
+ const statTables = yield* sql`SELECT 1 FROM sqlite_schema WHERE name = 'sqlite_stat1'`;
+ if (statTables.length > 0) {
+ yield* sql`DELETE FROM sqlite_stat1;`;
+ yield* sql`ANALYZE sqlite_schema;`;
+ }
}),
);
diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts
index dae8b9bbf3c..86470023dcb 100644
--- a/apps/server/src/serviceLauncher.ts
+++ b/apps/server/src/serviceLauncher.ts
@@ -32,9 +32,8 @@ import {
const HANDOFF_DELAY_MS = 2_000;
/**
- * Migrations and the open-time `PRAGMA optimize` count toward it and scale with the database:
- * tens of GB on a cold page cache take minutes. A missed window rolls back the database, so
- * the next attempt pays the same cost.
+ * Migrations count toward it and can scale with the database: tens of GB on a cold page cache
+ * take minutes. A missed window rolls back the database, so the next attempt pays the same cost.
*/
export const PREPARED_TIMEOUT_MS = 30 * 60_000;
const TERMINATE_GRACE_MS = 5_000;
diff --git a/docs/internals/server-updates.md b/docs/internals/server-updates.md
index 3a8774f4d53..5260ea98967 100644
--- a/docs/internals/server-updates.md
+++ b/docs/internals/server-updates.md
@@ -30,12 +30,11 @@ ready to commit.
A failed or timed-out trial returns to the old version. After commit, the target
is authoritative and the service manager's ordinary restart policy applies.
-The prepared deadline is long because migrations and SQLite's open-time optimize
-scale with the database and block the trial's main thread, so it cannot report
-progress. A missed deadline restores the snapshot, and the retry pays the same
-cost again. A crashed trial is caught when it exits; the deadline bounds only a
-stuck one. Client update waits must outlast the deadline, or a slow update shows
-as failed.
+The prepared deadline is long because migrations can scale with the database
+and block the trial's main thread, so it cannot report progress. A missed
+deadline restores the snapshot, and the retry pays the same cost again. A
+crashed trial is caught when it exits; the deadline bounds only a stuck one.
+Client update waits must outlast the deadline, or a slow update shows as failed.
## Database rollback