session-store-permanent-deletion.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. import { createHash } from "node:crypto";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { DatabaseSync } from "node:sqlite";
  6. import { afterEach, describe, expect, it } from "vitest";
  7. import { SqliteSessionStore } from "../src/storage/session-store/sqlite-session-store.js";
  8. import { SQLITE_MIGRATIONS } from "../src/storage/session-store/migrations.js";
  9. import { inspectSessionDeletions } from "../src/storage/session-store/repositories/sessions.js";
  10. import { sqliteMigrations, type MigrationOptions } from "@zcode/shared/sqlite-migrations";
  11. import type { SessionId } from "@zcode/contracts";
  12. const roots: string[] = [];
  13. afterEach(async () => {
  14. await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  15. });
  16. describe("永久删除迁移兼容", () => {
  17. const migrationId = "0025_session_permanent_deletion";
  18. // 固定已发布 SQL 的摘要,防止测试夹具随实现一起变化而漏掉旧库 checksum 不兼容。
  19. const publishedChecksum = "608f3ea3aad458679a4b377968413575749f2231c88133765a088564fc20691e";
  20. function contentHashes(db: DatabaseSync) {
  21. return Object.fromEntries(
  22. db
  23. .prepare(
  24. "select name from sqlite_master where type='table' and name not like 'sqlite_%' and name!='schema_migration' order by name",
  25. )
  26. .all()
  27. .map(({ name }) => {
  28. if (typeof name !== "string") throw new Error("Invalid table name");
  29. const rows = db.prepare(`select * from "${name.replaceAll('"', '""')}"`).all();
  30. return [
  31. name,
  32. createHash("sha256")
  33. .update(JSON.stringify(rows.map((row) => JSON.stringify(row)).sort()))
  34. .digest("hex"),
  35. ];
  36. }),
  37. );
  38. }
  39. async function legacyFixture() {
  40. const root = await mkdtemp(join(tmpdir(), "permanent-delete-migration-"));
  41. roots.push(root);
  42. const db = new DatabaseSync(join(root, "db.sqlite"));
  43. const options = {
  44. database: "cli",
  45. appliedAtColumn: "time_applied",
  46. backupDirectories: [join(root, "backup")],
  47. } satisfies MigrationOptions;
  48. try {
  49. // 旧版 025 直接执行 SQL;夹具必须绕过新增 apply,真实模拟已升级的数据库。
  50. await sqliteMigrations.migrate(
  51. db,
  52. SQLITE_MIGRATIONS.map((migration) =>
  53. migration.id === migrationId ? { ...migration, apply: undefined } : migration,
  54. ),
  55. options,
  56. );
  57. expect(
  58. db.prepare("select checksum from schema_migration where id=?").get(migrationId)?.checksum,
  59. ).toBe(publishedChecksum);
  60. db.exec(`
  61. insert into session(id,project_id,slug,directory,title,version,time_created,time_updated)
  62. values('kept','project','kept','/work/example','保留会话','1',1,1);
  63. insert into message(id,session_id,time_created,time_updated,data)
  64. values('message','kept',1,1,'{"text":"保留正文"}');
  65. insert into session_purge values('deleting','deleting','operation','["artifact"]','/work/example',null,'deleting');
  66. insert into session_purge values('deleted','deleted','operation','[]','/work/example',null,'deleted');
  67. insert into session_runtime_presence values('kept','owner',123);
  68. `);
  69. return { db, options };
  70. } catch (error) {
  71. db.close();
  72. throw error;
  73. }
  74. }
  75. it("已按旧 SQL 记账的数据库跳过 025,保留账本和全部数据", async () => {
  76. const { db, options } = await legacyFixture();
  77. try {
  78. const before = contentHashes(db);
  79. const journal = db.prepare("select * from schema_migration order by id").all();
  80. expect((await sqliteMigrations.migrate(db, SQLITE_MIGRATIONS, options)).applied).toEqual([]);
  81. expect(contentHashes(db)).toEqual(before);
  82. expect(db.prepare("select * from schema_migration order by id").all()).toEqual(journal);
  83. } finally {
  84. db.close();
  85. }
  86. });
  87. it.each([
  88. { name: "尚无 025 结构", keep: [] },
  89. { name: "只有删除凭据表", keep: ["session_purge"] },
  90. { name: "只有运行态表", keep: ["session_runtime_presence"] },
  91. {
  92. name: "已有两表及部分触发器",
  93. keep: ["session_purge", "session_runtime_presence", "session_purge_insert_guard"],
  94. },
  95. { name: "已有完整结构", keep: null },
  96. ])("未记账且$name时补齐结构,保留数据并恢复写入保护", async ({ keep }) => {
  97. const { db, options } = await legacyFixture();
  98. try {
  99. const schema = () =>
  100. db
  101. .prepare(
  102. "select type,name,tbl_name,sql from sqlite_master where sql is not null order by name",
  103. )
  104. .all();
  105. const expectedSchema = schema();
  106. if (keep) {
  107. const objects = db
  108. .prepare(
  109. "select type,name from sqlite_master where sql is not null and (name glob 'session_purge*' or name='session_runtime_presence') order by type='table',name",
  110. )
  111. .all();
  112. for (const { type, name } of objects) {
  113. if (typeof type !== "string" || typeof name !== "string")
  114. throw new Error("Invalid schema object");
  115. if (!keep.includes(name)) db.exec(`drop ${type} "${name}"`);
  116. }
  117. }
  118. db.prepare("delete from schema_migration where id=?").run(migrationId);
  119. const emptyHash = createHash("sha256").update("[]").digest("hex");
  120. const expectedContents = {
  121. session_purge: emptyHash,
  122. session_runtime_presence: emptyHash,
  123. ...contentHashes(db),
  124. };
  125. expect((await sqliteMigrations.migrate(db, SQLITE_MIGRATIONS, options)).applied).toEqual([
  126. migrationId,
  127. ]);
  128. expect(schema()).toEqual(expectedSchema);
  129. expect(contentHashes(db)).toEqual(expectedContents);
  130. expect(
  131. db.prepare("select checksum from schema_migration where id=?").get(migrationId)?.checksum,
  132. ).toBe(publishedChecksum);
  133. db.exec(
  134. "insert or ignore into session_purge values('deleted','deleted','operation','[]','/work/example',null,'deleted')",
  135. );
  136. expect(() =>
  137. db.exec("insert into session_runtime_presence values('deleted','owner',123)"),
  138. ).toThrow("session-data.deleting");
  139. expect(() =>
  140. db.exec(
  141. "insert into message(id,session_id,time_created,time_updated,data) values('late','deleted',1,1,'{}')",
  142. ),
  143. ).toThrow("session-data.deleting");
  144. const journal = db.prepare("select * from schema_migration order by id").all();
  145. expect((await sqliteMigrations.migrate(db, SQLITE_MIGRATIONS, options)).applied).toEqual([]);
  146. expect(db.prepare("select * from schema_migration order by id").all()).toEqual(journal);
  147. } finally {
  148. db.close();
  149. }
  150. });
  151. });
  152. async function setup() {
  153. const root = await mkdtemp(join(tmpdir(), "permanent-delete-"));
  154. roots.push(root);
  155. const store = await SqliteSessionStore.open({ dbPath: join(root, "db.sqlite") });
  156. const session = (id: string, parentID?: string, taskType = "interactive") =>
  157. store.createSession({
  158. id: id as SessionId,
  159. projectID: "project" as never,
  160. slug: id,
  161. directory: "/work/example",
  162. title: id,
  163. version: "1",
  164. parentID: parentID as SessionId | undefined,
  165. taskType: taskType as never,
  166. });
  167. await session("root");
  168. await session("child", "root", "subagent_child");
  169. await session("fork", "root", "fork");
  170. return { store, session };
  171. }
  172. describe("永久删除存储", () => {
  173. it("准入凭据阻止重建和运行态注册,删除 owned tree 但保留独立 fork", async () => {
  174. const { store, session } = await setup();
  175. try {
  176. const preview = await store.inspectSessionDeletion("root" as SessionId);
  177. expect(preview.sessionIds.sort()).toEqual(["child", "root"]);
  178. expect(preview.forks.map((f) => f.sessionId)).toEqual(["fork"]);
  179. await store.beginSessionDeletion("root" as SessionId, preview.revision, "operation", []);
  180. await expect(store.registerSessionRuntime("root" as SessionId)).rejects.toThrow(
  181. "session-data.deleting",
  182. );
  183. await store.completeSessionDeletion("root" as SessionId);
  184. expect(await store.getSession("root" as SessionId)).toBeNull();
  185. expect(await store.getSession("child" as SessionId)).toBeNull();
  186. expect(await store.getSession("fork" as SessionId)).not.toBeNull();
  187. await expect(session("root")).rejects.toThrow("session-data.deleting");
  188. await store.completeSessionDeletion("root" as SessionId);
  189. } finally {
  190. store.close();
  191. }
  192. });
  193. it("确认后出现新子会话时不接受旧计划", async () => {
  194. const { store, session } = await setup();
  195. try {
  196. const preview = await store.inspectSessionDeletion("root" as SessionId);
  197. await session("newchild", "root", "subagent_child");
  198. await expect(
  199. store.beginSessionDeletion("root" as SessionId, preview.revision, "operation", []),
  200. ).rejects.toThrow("session-data.changed");
  201. expect(await store.getSession("root" as SessionId)).not.toBeNull();
  202. } finally {
  203. store.close();
  204. }
  205. });
  206. });
  207. /** 只统计引用扫描 SQL(含 zcode-artifact:// 的 13 条),其余 prepare 原样透传。 */
  208. function countingReferenceScans(db: DatabaseSync) {
  209. const counter = { scans: 0 };
  210. const proxy = new Proxy(db, {
  211. get(target, property) {
  212. if (property === "prepare")
  213. return (sql: string) => {
  214. if (sql.includes("zcode-artifact://")) counter.scans++;
  215. return target.prepare(sql);
  216. };
  217. const value = Reflect.get(target, property, target) as unknown;
  218. return typeof value === "function" ? value.bind(target) : value;
  219. },
  220. });
  221. return { db: proxy, counter };
  222. }
  223. describe("批量删除预检", () => {
  224. async function batchSetup() {
  225. const root = await mkdtemp(join(tmpdir(), "permanent-delete-batch-"));
  226. roots.push(root);
  227. const dbPath = join(root, "db.sqlite");
  228. const store = await SqliteSessionStore.open({ dbPath });
  229. const db = new DatabaseSync(dbPath);
  230. const session = (id: string, parentID?: string, taskType = "interactive") =>
  231. store.createSession({
  232. id: id as SessionId,
  233. projectID: "project" as never,
  234. slug: id,
  235. directory: "/work/example",
  236. title: `标题-${id}`,
  237. version: "1",
  238. parentID: parentID as SessionId | undefined,
  239. taskType: taskType as never,
  240. });
  241. let seq = 0;
  242. const part = (sessionId: string, url: string) => {
  243. const id = `ref-${seq++}`;
  244. db.prepare(
  245. "INSERT INTO message(id,session_id,time_created,time_updated,data) VALUES(?,?,1,1,'{}')",
  246. ).run(`${id}-m`, sessionId);
  247. db.prepare(
  248. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES(?,?,?,1,1,?)",
  249. ).run(id, `${id}-m`, sessionId, JSON.stringify({ url }));
  250. };
  251. return {
  252. store,
  253. db,
  254. session,
  255. part,
  256. close: () => {
  257. db.close();
  258. store.close();
  259. },
  260. };
  261. }
  262. it("批量与逐个预检结果完全一致:跨根引用、树内引用、fork、工作流 journal 与续删回执", async () => {
  263. const { store, db, session, part, close } = await batchSetup();
  264. try {
  265. await session("a");
  266. await session("a-child", "a", "subagent_child");
  267. await session("a-fork", "a", "fork");
  268. await session("b");
  269. await session("c");
  270. await session("d");
  271. await session("kept");
  272. // a 的产物被同批 b 引用:以 a 的视角 b 在树外,必须算外部引用。
  273. part("b", "zcode-artifact://a/shared");
  274. // 同一树内的引用随根删除,不算外部引用。
  275. part("a-child", "zcode-artifact://a/private");
  276. // b 的产物被 a 的附属会话引用;fork 也引用 a。
  277. part("a-child", "zcode-artifact://b/report");
  278. part("a-fork", "zcode-artifact://a/shared");
  279. // c 的产物只出现在保留会话的工作流 journal 里。
  280. db.exec(`INSERT INTO dwf_run(id,parent_session_id,caps_max_concurrency,status,time_created,time_updated) VALUES('run','kept',1,'completed',1,1);
  281. INSERT INTO dwf_event(run_id,sequence,type,payload_json,time_created) VALUES('run',1,'artifact','{"uri":"zcode-artifact://c/chart"}',1);`);
  282. // d 已进入删除中:回执里保留的附件即使没有引用方也要出现在 references。
  283. const fresh = await store.inspectSessionDeletion("d" as SessionId);
  284. await store.beginSessionDeletion("d" as SessionId, fresh.revision, "op", [
  285. { sessionId: "d" as SessionId, artifactId: "kept-file" },
  286. ]);
  287. const ids = ["a", "b", "c", "d", "missing"] as SessionId[];
  288. const single = [];
  289. for (const id of ids) single.push(await store.inspectSessionDeletion(id));
  290. const batch = await store.inspectSessionDeletions(ids.map((sessionId) => ({ sessionId })));
  291. expect(batch).toEqual(single);
  292. expect(batch[0]!.forks.map((fork) => fork.sessionId)).toEqual(["a-fork"]);
  293. expect(batch[0]!.references).toEqual([
  294. {
  295. sessionId: "a",
  296. artifactId: "shared",
  297. referrers: [
  298. { sessionId: "a-fork", title: "标题-a-fork" },
  299. { sessionId: "b", title: "标题-b" },
  300. ],
  301. },
  302. ]);
  303. expect(batch[1]!.references.map((ref) => ref.referrers[0]!.sessionId)).toEqual(["a-child"]);
  304. expect(batch[2]!.references.map((ref) => ref.referrers[0]!.sessionId)).toEqual(["kept"]);
  305. expect(batch[3]).toMatchObject({
  306. deleting: true,
  307. references: [{ sessionId: "d", artifactId: "kept-file", referrers: [] }],
  308. });
  309. expect(batch[4]!.sessionIds).toEqual([]);
  310. // 扫描判定相同时,批量与逐个结果也一致;回执里有保留附件的根仍会扫描。
  311. const flags = ids.map((sessionId, index) => ({
  312. sessionId,
  313. scanArtifactReferences: index % 2 === 0,
  314. }));
  315. const singleFlags = [];
  316. for (const target of flags)
  317. singleFlags.push(
  318. await store.inspectSessionDeletion(target.sessionId, {
  319. scanArtifactReferences: target.scanArtifactReferences,
  320. }),
  321. );
  322. expect(await store.inspectSessionDeletions(flags)).toEqual(singleFlags);
  323. // 重复目标各自独立计算。
  324. expect(
  325. await store.inspectSessionDeletions([
  326. { sessionId: "a" as SessionId },
  327. { sessionId: "a" as SessionId },
  328. ]),
  329. ).toEqual([single[0], single[0]]);
  330. } finally {
  331. close();
  332. }
  333. });
  334. it("无产物的根不执行引用扫描;写锁内复检沿用同一判定", async () => {
  335. const { store, db, session, part, close } = await batchSetup();
  336. try {
  337. await session("a");
  338. await session("b");
  339. part("b", "zcode-artifact://a/lost");
  340. const counted = countingReferenceScans(db);
  341. const skipped = inspectSessionDeletions(
  342. counted.db,
  343. [
  344. { root: "a" as SessionId, scanArtifactReferences: false },
  345. { root: "b" as SessionId, scanArtifactReferences: false },
  346. ],
  347. "owner",
  348. );
  349. expect(counted.counter.scans).toBe(0);
  350. // 产物文件不存在时不再列入保留附件(规格:只对实际存在产物文件的会话扫描)。
  351. expect(skipped[0]!.references).toEqual([]);
  352. const scanned = inspectSessionDeletions(counted.db, [{ root: "a" as SessionId }], "owner");
  353. expect(counted.counter.scans).toBe(13);
  354. expect(scanned[0]!.references.map((ref) => ref.artifactId)).toEqual(["lost"]);
  355. // 预检用 false 得到的 revision,写锁内必须用同一判定才能通过;用不同判定会被视为清单变化。
  356. await expect(
  357. store.beginSessionDeletion("a" as SessionId, skipped[0]!.revision, "op", []),
  358. ).rejects.toThrow("session-data.changed");
  359. await store.beginSessionDeletion("a" as SessionId, skipped[0]!.revision, "op", [], {
  360. scanArtifactReferences: false,
  361. });
  362. expect((await store.inspectSessionDeletion("a" as SessionId)).deleting).toBe(true);
  363. } finally {
  364. close();
  365. }
  366. });
  367. it("300 个会话整批只跑一轮引用 SQL,结果与逐个一致", async () => {
  368. const { store, db, session, part, close } = await batchSetup();
  369. try {
  370. const ids: SessionId[] = [];
  371. for (let index = 0; index < 300; index++) {
  372. const id = `s${String(index).padStart(3, "0")}`;
  373. await session(id);
  374. ids.push(id as SessionId);
  375. }
  376. // 每个会话引用下一个会话的产物,形成跨根引用链。
  377. for (let index = 0; index < 300; index++)
  378. part(ids[index]!, `zcode-artifact://${ids[(index + 1) % 300]}/file-${index}`);
  379. const counted = countingReferenceScans(db);
  380. let started = performance.now();
  381. const single = ids.map(
  382. (root) => inspectSessionDeletions(counted.db, [{ root }], "owner")[0]!,
  383. );
  384. const singleMs = performance.now() - started;
  385. expect(counted.counter.scans).toBe(300 * 13);
  386. counted.counter.scans = 0;
  387. started = performance.now();
  388. const batch = inspectSessionDeletions(
  389. counted.db,
  390. ids.map((root) => ({ root })),
  391. "owner",
  392. );
  393. const batchMs = performance.now() - started;
  394. expect(counted.counter.scans).toBe(13);
  395. expect(batch).toEqual(single);
  396. expect(batch[1]!.references[0]!.referrers).toEqual([
  397. { sessionId: "s000", title: "标题-s000" },
  398. ]);
  399. // 耗时只做记录,不作断言。
  400. console.info(
  401. `[permanent-deletion] 300 根逐个 ${singleMs.toFixed(1)}ms,整批 ${batchMs.toFixed(1)}ms`,
  402. );
  403. } finally {
  404. close();
  405. }
  406. });
  407. });