From 76f78e92cbba537ec851d5dce8705dfd937c937e Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 18:40:39 -0800 Subject: [PATCH 1/2] fix(server): migrate-dev-db drops the saved facts of projects it prunes Pruning deleted dropped projects from projection_projects and pruned every thread_id table by kept thread, so tables keyed only by project kept another project's saved facts, fact history, knowledge commands and evaluation resets. Every table with a project_id column now loses rows of dropped projects. The copy also left the fact search index empty, so kept facts were unsearchable and deleting a fact through its trigger fails as a corrupt index. The copy now rebuilds it, and pruning optimizes each FTS5 index so pruned rows' terms do not stay behind as tombstoned segments. Co-Authored-By: Claude Opus 5.5 --- apps/server/scripts/migrate-dev-db.test.ts | 74 +++++++++++++++++++++- apps/server/scripts/migrate-dev-db.ts | 30 +++++++-- 2 files changed, 95 insertions(+), 9 deletions(-) diff --git a/apps/server/scripts/migrate-dev-db.test.ts b/apps/server/scripts/migrate-dev-db.test.ts index c81b01b0fe604..7674d9525dee1 100644 --- a/apps/server/scripts/migrate-dev-db.test.ts +++ b/apps/server/scripts/migrate-dev-db.test.ts @@ -142,7 +142,28 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio VALUES ('delivery-1', 'task-1', 'key-1', 1900000000000, '{}', '{}', '[]')`; yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at) VALUES ('session-1', 'user', '[]', 'pairing', '2026-08-01', '2027-08-01')`; - if (toMigrationInclusive === undefined) yield* insertPeerLink(sql); + if (toMigrationInclusive === undefined) { + yield* insertPeerLink(sql); + for (const [projectId, term] of [ + ["project-kept", "keptfactterm"], + ["project-deleted", "droppedfactterm"], + ] as const) { + const factId = `fact-${projectId}`; + yield* sql`INSERT INTO project_knowledge_facts + (id, project_id, status, revision, content, entities_json, tags_json, kind, trust, + created_at, updated_at, sources_json, origin_json) + VALUES (${factId}, ${projectId}, 'saved', 1, ${`Remember ${term}`}, '[]', '[]', + 'decision', 1, '2026-08-01', '2026-08-01', '[]', '{}')`; + yield* sql`INSERT INTO project_knowledge_fact_history + (project_id, fact_id, revision, event, actor_json, content, sources_json, trust_after, created_at) + VALUES (${projectId}, ${factId}, 1, 'created', '{}', ${`Remember ${term}`}, '[]', 1, '2026-08-01')`; + yield* sql`INSERT INTO project_knowledge_commands + (command_id, project_id, fact_id, request_digest) + VALUES (${`command-${projectId}`}, ${projectId}, ${factId}, 'digest')`; + yield* sql`INSERT INTO model_evaluation_resets (project_id, generation, reset_at) + VALUES (${projectId}, 1, '2026-08-01')`; + } + } }), ); return databasePath; @@ -194,7 +215,38 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { (SELECT COUNT(*) FROM scheduled_task_webhook_pending) AS webhooks, (SELECT COUNT(*) FROM orchestration_v2_projection_context_transfers) AS transfers, (SELECT COUNT(*) FROM peer_environment_links) AS links`; - return { threads, events, sessions, pullRequest, project, leftovers }; + const projectTables = yield* sql<{ name: string }>` + SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c + WHERE m.type = 'table' AND c.name = 'project_id' ORDER BY m.name`; + const projectRows: Record> = {}; + for (const { name } of projectTables) { + const rows = yield* sql.unsafe<{ project_id: string }>( + `SELECT DISTINCT project_id FROM "${name}" ORDER BY project_id`, + ).unprepared; + if (rows.length > 0) projectRows[name] = rows.map((row) => row.project_id); + } + const searched = yield* sql<{ id: string }>` + SELECT f.id FROM project_knowledge_fts + JOIN project_knowledge_facts f ON f.rowid = project_knowledge_fts.rowid + WHERE project_knowledge_fts MATCH 'keptfactterm'`; + // FTS5 keeps a deleted row's terms in older segments until they merge. + const [dropped] = yield* sql<{ blocks: number }>` + SELECT COUNT(*) AS blocks FROM project_knowledge_fts_data + WHERE instr(block, CAST('droppedfactterm' AS BLOB)) > 0`; + const factSearch = { + found: searched.map((row) => row.id), + droppedBlocks: dropped?.blocks, + }; + return { + threads, + events, + sessions, + pullRequest, + project, + leftovers, + projectRows, + factSearch, + }; }), ); assert.deepStrictEqual( @@ -241,6 +293,24 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { transfers: 0, links: 0, }); + assert.deepStrictEqual( + kept.projectRows, + { + model_evaluation_resets: ["project-kept"], + orchestration_v2_projection_threads: ["project-kept"], + project_knowledge_commands: ["project-kept"], + project_knowledge_fact_history: ["project-kept"], + project_knowledge_facts: ["project-kept"], + projection_projects: ["project-kept"], + projection_threads: ["project-kept"], + }, + "rows of a dropped project go with it; the kept project's facts stay", + ); + assert.deepStrictEqual( + kept.factSearch, + { found: ["fact-project-kept"], droppedBlocks: 0 }, + "fact search finds kept facts and its index holds nothing of dropped ones", + ); }), ); diff --git a/apps/server/scripts/migrate-dev-db.ts b/apps/server/scripts/migrate-dev-db.ts index b44e7c52ea14f..3a3b12304f46c 100644 --- a/apps/server/scripts/migrate-dev-db.ts +++ b/apps/server/scripts/migrate-dev-db.ts @@ -239,8 +239,8 @@ const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath: WHERE m.type = 'table' AND c.name = 'thread_id'`; const threadIdNullable = new Map(threadColumns.map((row) => [row.name, row.notnull === 0])); // FTS5 makes its own shadow tables and contentless rows cannot be copied: - // create the virtual table, skip its shadow tables and rows, and rebuild the - // index once the messages and triggers are in. + // create the virtual table, skip its shadow tables and rows, and rebuild each + // index once its rows and triggers are in. const virtualTables = schema .filter((entry) => entry.type === "table" && /^CREATE VIRTUAL TABLE/i.test(entry.sql)) .map((entry) => entry.name); @@ -317,6 +317,9 @@ const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath: if (entry.type !== "table") yield* sql.unsafe(entry.sql).unprepared; } yield* rebuildMessageSearch(sql); + if (virtualTables.includes("project_knowledge_fts")) { + yield* sql`INSERT INTO project_knowledge_fts(project_knowledge_fts) VALUES ('rebuild')`; + } }), ); yield* sql`DETACH DATABASE src`; @@ -389,15 +392,24 @@ const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigra WHERE recency_rank <= ${input.threadsPerProject} )`; - const threadTables = yield* sql<{ name: string }>` + const tablesWithColumn = (column: string) => sql<{ name: string }>` SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c - WHERE m.type = 'table' AND c.name = 'thread_id' - AND m.name <> ${PROVIDER_SESSIONS_TABLE}`; + WHERE m.type = 'table' AND c.name = ${column}`; + const projectTables = yield* tablesWithColumn("project_id"); + const threadTables = (yield* tablesWithColumn("thread_id")).filter( + ({ name }) => name !== PROVIDER_SESSIONS_TABLE, + ); + const searchIndexes = yield* sql<{ name: string }>` + SELECT name FROM sqlite_master + WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE % USING fts5%'`; yield* sql.withTransaction( Effect.gen(function* () { - yield* sql`DELETE FROM projection_projects - WHERE project_id NOT IN (SELECT project_id FROM kept_projects)`; + for (const { name } of projectTables) { + yield* sql.unsafe( + `DELETE FROM "${name}" WHERE project_id NOT IN (SELECT project_id FROM kept_projects)`, + ).unprepared; + } yield* sql`DELETE FROM ${sql(PROVIDER_SESSIONS_TABLE)} WHERE COALESCE(thread_id, '') NOT IN (SELECT thread_id FROM kept_threads) AND provider_session_id NOT IN ( @@ -435,6 +447,10 @@ const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigra for (const table of CLEARED_TABLES) { yield* sql`DELETE FROM ${sql(table)}`; } + // FTS5 deletes only add tombstones; merging drops the pruned rows' terms from the index. + for (const { name } of searchIndexes) { + yield* sql.unsafe(`INSERT INTO "${name}"("${name}") VALUES ('optimize')`).unprepared; + } }), ); From e2269a07069e863ee1b01a0b24b9ed39787e5224 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 18:44:47 -0800 Subject: [PATCH 2/2] fix(server): the dev database prune merges only real full-text indexes The prune matched every virtual table whose module name starts with fts5, which includes an fts5vocab table. The open recall change (#135) adds one, and the optimize command fails on it, so half the migrate-dev-db tests would fail once both changes are on main. The test now checks dropped-project rows across whatever tables carry a project, instead of a fixed table list that the next migration would break. Co-Authored-By: Claude Fable 5.2 --- apps/server/scripts/migrate-dev-db.test.ts | 27 +++++++++++++--------- apps/server/scripts/migrate-dev-db.ts | 2 +- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/apps/server/scripts/migrate-dev-db.test.ts b/apps/server/scripts/migrate-dev-db.test.ts index 7674d9525dee1..43ecbdecda38d 100644 --- a/apps/server/scripts/migrate-dev-db.test.ts +++ b/apps/server/scripts/migrate-dev-db.test.ts @@ -293,19 +293,24 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { transfers: 0, links: 0, }); + // Asserted across whatever tables carry a project, so a later migration's table is covered. assert.deepStrictEqual( - kept.projectRows, - { - model_evaluation_resets: ["project-kept"], - orchestration_v2_projection_threads: ["project-kept"], - project_knowledge_commands: ["project-kept"], - project_knowledge_fact_history: ["project-kept"], - project_knowledge_facts: ["project-kept"], - projection_projects: ["project-kept"], - projection_threads: ["project-kept"], - }, - "rows of a dropped project go with it; the kept project's facts stay", + [...new Set(Object.values(kept.projectRows).flat())], + ["project-kept"], + "rows of a dropped project go with it", ); + for (const table of [ + "model_evaluation_resets", + "project_knowledge_commands", + "project_knowledge_fact_history", + "project_knowledge_facts", + ]) { + assert.deepStrictEqual( + kept.projectRows[table], + ["project-kept"], + `${table} keeps its rows`, + ); + } assert.deepStrictEqual( kept.factSearch, { found: ["fact-project-kept"], droppedBlocks: 0 }, diff --git a/apps/server/scripts/migrate-dev-db.ts b/apps/server/scripts/migrate-dev-db.ts index 3a3b12304f46c..b5b2673c3ed52 100644 --- a/apps/server/scripts/migrate-dev-db.ts +++ b/apps/server/scripts/migrate-dev-db.ts @@ -401,7 +401,7 @@ const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigra ); const searchIndexes = yield* sql<{ name: string }>` SELECT name FROM sqlite_master - WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE % USING fts5%'`; + WHERE type = 'table' AND sql LIKE 'CREATE VIRTUAL TABLE % USING fts5(%'`; yield* sql.withTransaction( Effect.gen(function* () {