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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 { sqliteMigrations, type MigrationOptions } from "@zcode/shared/sqlite-migrations";
  10. import type { SessionId } from "@zcode/contracts";
  11. const roots: string[] = [];
  12. afterEach(async () => {
  13. await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  14. });
  15. describe("永久删除迁移兼容", () => {
  16. const migrationId = "0025_session_permanent_deletion";
  17. // 固定已发布 SQL 的摘要,防止测试夹具随实现一起变化而漏掉旧库 checksum 不兼容。
  18. const publishedChecksum = "608f3ea3aad458679a4b377968413575749f2231c88133765a088564fc20691e";
  19. function contentHashes(db: DatabaseSync) {
  20. return Object.fromEntries(
  21. db
  22. .prepare(
  23. "select name from sqlite_master where type='table' and name not like 'sqlite_%' and name!='schema_migration' order by name",
  24. )
  25. .all()
  26. .map(({ name }) => {
  27. if (typeof name !== "string") throw new Error("Invalid table name");
  28. const rows = db.prepare(`select * from "${name.replaceAll('"', '""')}"`).all();
  29. return [
  30. name,
  31. createHash("sha256")
  32. .update(JSON.stringify(rows.map((row) => JSON.stringify(row)).sort()))
  33. .digest("hex"),
  34. ];
  35. }),
  36. );
  37. }
  38. async function legacyFixture() {
  39. const root = await mkdtemp(join(tmpdir(), "permanent-delete-migration-"));
  40. roots.push(root);
  41. const db = new DatabaseSync(join(root, "db.sqlite"));
  42. const options = {
  43. database: "cli",
  44. appliedAtColumn: "time_applied",
  45. backupDirectories: [join(root, "backup")],
  46. } satisfies MigrationOptions;
  47. try {
  48. // 旧版 025 直接执行 SQL;夹具必须绕过新增 apply,真实模拟已升级的数据库。
  49. await sqliteMigrations.migrate(
  50. db,
  51. SQLITE_MIGRATIONS.map((migration) =>
  52. migration.id === migrationId ? { ...migration, apply: undefined } : migration,
  53. ),
  54. options,
  55. );
  56. expect(
  57. db.prepare("select checksum from schema_migration where id=?").get(migrationId)?.checksum,
  58. ).toBe(publishedChecksum);
  59. db.exec(`
  60. insert into session(id,project_id,slug,directory,title,version,time_created,time_updated)
  61. values('kept','project','kept','/work/example','保留会话','1',1,1);
  62. insert into message(id,session_id,time_created,time_updated,data)
  63. values('message','kept',1,1,'{"text":"保留正文"}');
  64. insert into session_purge values('deleting','deleting','operation','["artifact"]','/work/example',null,'deleting');
  65. insert into session_purge values('deleted','deleted','operation','[]','/work/example',null,'deleted');
  66. insert into session_runtime_presence values('kept','owner',123);
  67. `);
  68. return { db, options };
  69. } catch (error) {
  70. db.close();
  71. throw error;
  72. }
  73. }
  74. it("已按旧 SQL 记账的数据库跳过 025,保留账本和全部数据", async () => {
  75. const { db, options } = await legacyFixture();
  76. try {
  77. const before = contentHashes(db);
  78. const journal = db.prepare("select * from schema_migration order by id").all();
  79. expect((await sqliteMigrations.migrate(db, SQLITE_MIGRATIONS, options)).applied).toEqual([]);
  80. expect(contentHashes(db)).toEqual(before);
  81. expect(db.prepare("select * from schema_migration order by id").all()).toEqual(journal);
  82. } finally {
  83. db.close();
  84. }
  85. });
  86. it.each([
  87. { name: "尚无 025 结构", keep: [] },
  88. { name: "只有删除凭据表", keep: ["session_purge"] },
  89. { name: "只有运行态表", keep: ["session_runtime_presence"] },
  90. {
  91. name: "已有两表及部分触发器",
  92. keep: ["session_purge", "session_runtime_presence", "session_purge_insert_guard"],
  93. },
  94. { name: "已有完整结构", keep: null },
  95. ])("未记账且$name时补齐结构,保留数据并恢复写入保护", async ({ keep }) => {
  96. const { db, options } = await legacyFixture();
  97. try {
  98. const schema = () =>
  99. db
  100. .prepare(
  101. "select type,name,tbl_name,sql from sqlite_master where sql is not null order by name",
  102. )
  103. .all();
  104. const expectedSchema = schema();
  105. if (keep) {
  106. const objects = db
  107. .prepare(
  108. "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",
  109. )
  110. .all();
  111. for (const { type, name } of objects) {
  112. if (typeof type !== "string" || typeof name !== "string")
  113. throw new Error("Invalid schema object");
  114. if (!keep.includes(name)) db.exec(`drop ${type} "${name}"`);
  115. }
  116. }
  117. db.prepare("delete from schema_migration where id=?").run(migrationId);
  118. const emptyHash = createHash("sha256").update("[]").digest("hex");
  119. const expectedContents = {
  120. session_purge: emptyHash,
  121. session_runtime_presence: emptyHash,
  122. ...contentHashes(db),
  123. };
  124. expect((await sqliteMigrations.migrate(db, SQLITE_MIGRATIONS, options)).applied).toEqual([
  125. migrationId,
  126. ]);
  127. expect(schema()).toEqual(expectedSchema);
  128. expect(contentHashes(db)).toEqual(expectedContents);
  129. expect(
  130. db.prepare("select checksum from schema_migration where id=?").get(migrationId)?.checksum,
  131. ).toBe(publishedChecksum);
  132. db.exec(
  133. "insert or ignore into session_purge values('deleted','deleted','operation','[]','/work/example',null,'deleted')",
  134. );
  135. expect(() =>
  136. db.exec("insert into session_runtime_presence values('deleted','owner',123)"),
  137. ).toThrow("session-data.deleting");
  138. expect(() =>
  139. db.exec(
  140. "insert into message(id,session_id,time_created,time_updated,data) values('late','deleted',1,1,'{}')",
  141. ),
  142. ).toThrow("session-data.deleting");
  143. const journal = db.prepare("select * from schema_migration order by id").all();
  144. expect((await sqliteMigrations.migrate(db, SQLITE_MIGRATIONS, options)).applied).toEqual([]);
  145. expect(db.prepare("select * from schema_migration order by id").all()).toEqual(journal);
  146. } finally {
  147. db.close();
  148. }
  149. });
  150. });
  151. async function setup() {
  152. const root = await mkdtemp(join(tmpdir(), "permanent-delete-"));
  153. roots.push(root);
  154. const store = await SqliteSessionStore.open({ dbPath: join(root, "db.sqlite") });
  155. const session = (id: string, parentID?: string, taskType = "interactive") =>
  156. store.createSession({
  157. id: id as SessionId,
  158. projectID: "project" as never,
  159. slug: id,
  160. directory: "/work/example",
  161. title: id,
  162. version: "1",
  163. parentID: parentID as SessionId | undefined,
  164. taskType: taskType as never,
  165. });
  166. await session("root");
  167. await session("child", "root", "subagent_child");
  168. await session("fork", "root", "fork");
  169. return { store, session };
  170. }
  171. describe("永久删除存储", () => {
  172. it("准入凭据阻止重建和运行态注册,删除 owned tree 但保留独立 fork", async () => {
  173. const { store, session } = await setup();
  174. try {
  175. const preview = await store.inspectSessionDeletion("root" as SessionId);
  176. expect(preview.sessionIds.sort()).toEqual(["child", "root"]);
  177. expect(preview.forks.map((f) => f.sessionId)).toEqual(["fork"]);
  178. await store.beginSessionDeletion("root" as SessionId, preview.revision, "operation", []);
  179. await expect(store.registerSessionRuntime("root" as SessionId)).rejects.toThrow(
  180. "session-data.deleting",
  181. );
  182. await store.completeSessionDeletion("root" as SessionId);
  183. expect(await store.getSession("root" as SessionId)).toBeNull();
  184. expect(await store.getSession("child" as SessionId)).toBeNull();
  185. expect(await store.getSession("fork" as SessionId)).not.toBeNull();
  186. await expect(session("root")).rejects.toThrow("session-data.deleting");
  187. await store.completeSessionDeletion("root" as SessionId);
  188. } finally {
  189. store.close();
  190. }
  191. });
  192. it("确认后出现新子会话时不接受旧计划", async () => {
  193. const { store, session } = await setup();
  194. try {
  195. const preview = await store.inspectSessionDeletion("root" as SessionId);
  196. await session("newchild", "root", "subagent_child");
  197. await expect(
  198. store.beginSessionDeletion("root" as SessionId, preview.revision, "operation", []),
  199. ).rejects.toThrow("session-data.changed");
  200. expect(await store.getSession("root" as SessionId)).not.toBeNull();
  201. } finally {
  202. store.close();
  203. }
  204. });
  205. });