diff --git a/apps/server/scripts/migrate-dev-db.test.ts b/apps/server/scripts/migrate-dev-db.test.ts index c81b01b0fe604..43ecbdecda38d 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,29 @@ 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( + [...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 }, + "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..b5b2673c3ed52 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; + } }), );