session-permanent-deletion.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import type { SessionId } from "@zcode/contracts";
  7. import { SqliteSessionStore } from "../../adapters/src/storage/session-store/sqlite-session-store.js";
  8. import { createNodeSessionDataFiles } from "../../adapters/src/storage/session-data-files/index.js";
  9. import { NodeToolArtifactStore } from "../../adapters/src/storage/index.js";
  10. import {
  11. previewSessionDeletionWith,
  12. executeSessionDeletionWith,
  13. type SessionDeletionHost,
  14. } from "../src/zcode-protocol/session-data/permanent-deletion.js";
  15. const cleanups: Array<() => Promise<void>> = [];
  16. afterEach(async () => {
  17. for (const cleanup of cleanups.splice(0)) await cleanup();
  18. });
  19. const params = { sessionId: "root", workspace: { workspacePath: "/work/example" } };
  20. async function setup() {
  21. const root = await mkdtemp(join(tmpdir(), "permanent-deletion-runtime-"));
  22. const dbPath = join(root, "db.sqlite");
  23. const store = await SqliteSessionStore.open({ dbPath });
  24. const db = new DatabaseSync(dbPath);
  25. cleanups.push(async () => {
  26. db.close();
  27. store.close();
  28. await rm(root, { recursive: true, force: true });
  29. });
  30. for (const [id, parentID, taskType] of [
  31. ["root", undefined, "interactive"],
  32. ["child", "root", "subagent_child"],
  33. ["fork", "root", "interactive"],
  34. ] as const)
  35. await store.createSession({
  36. id: id as SessionId,
  37. projectID: "project" as never,
  38. slug: id,
  39. directory: params.workspace.workspacePath,
  40. title: id,
  41. version: "1",
  42. parentID: parentID as SessionId | undefined,
  43. taskType,
  44. });
  45. db.prepare(
  46. "INSERT INTO message(id,session_id,time_created,time_updated,data) VALUES('m','fork',1,1,'{}')",
  47. ).run();
  48. db.prepare(
  49. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES('p','m','fork',1,1,?)",
  50. ).run(JSON.stringify({ url: "zcode-artifact://root/shared" }));
  51. const dir = join(root, "artifacts", "root");
  52. await mkdir(dir, { recursive: true });
  53. await writeFile(join(dir, "shared.png"), "shared");
  54. await writeFile(join(dir, "private.txt"), "private");
  55. const files = createNodeSessionDataFiles({
  56. cliStorageRoot: root,
  57. memoryRoot: () => join(root, "memories", "projects", "unused", "memory"),
  58. });
  59. const busy = new Set<string>();
  60. const host: SessionDeletionHost = {
  61. store,
  62. files,
  63. busy: (id) => busy.has(id),
  64. release: async () => {},
  65. forget: () => {},
  66. };
  67. const execute = async (revision: string) =>
  68. executeSessionDeletionWith(host, { ...params, revision, operationId: "op" });
  69. return { root, dbPath, db, store, dir, host, busy, execute };
  70. }
  71. describe("归档永久删除执行面", () => {
  72. it("保留 fork 和引用文件,物理删除正文,重复请求返回已完成", async () => {
  73. const { root, host, store, dir, execute, db } = await setup();
  74. // 用真实正文验证行级清理,不能只以 getSession 隐藏了记录作为永久删除证据。
  75. for (const id of ["root", "child"]) {
  76. db.prepare(
  77. "INSERT INTO message(id,session_id,time_created,time_updated,data) VALUES(?,?,1,1,?)",
  78. ).run(`${id}-message`, id, '{"role":"user","text":"E2E_PRIVATE_BODY"}');
  79. db.prepare(
  80. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES(?,?,?,1,1,?)",
  81. ).run(`${id}-part`, `${id}-message`, id, '{"type":"text","text":"E2E_PRIVATE_BODY"}');
  82. }
  83. db.exec(
  84. "INSERT INTO input_history(id,project_id,session_id,text,kind,time_created) VALUES('history','project','root','E2E_PRIVATE_INPUT','prompt',1)",
  85. );
  86. db.exec(
  87. "INSERT INTO dwf_run(id,parent_session_id,caps_max_concurrency,status,time_created,time_updated) VALUES('owned-run','root',1,'completed',1,1)",
  88. );
  89. db.exec(
  90. `INSERT INTO dwf_event(run_id,sequence,type,payload_json,time_created) VALUES('owned-run',1,'result','{"text":"E2E_PRIVATE_WORKFLOW"}',1)`,
  91. );
  92. await writeFile(join(root, "workspace-file.txt"), "E2E_KEEP_WORKSPACE");
  93. const preview = await previewSessionDeletionWith(host, params);
  94. expect(preview.forks.map((f) => f.sessionId)).toEqual(["fork"]);
  95. expect(preview.retainedArtifacts[0]?.fileName).toBe("shared.png");
  96. expect(preview.deletedFiles).toBe(1);
  97. expect((await execute(preview.revision)).status).toBe("deleted");
  98. expect(await store.getSession("root" as SessionId)).toBeNull();
  99. expect(await store.getSession("fork" as SessionId)).not.toBeNull();
  100. expect(await readFile(join(dir, "shared.png"), "utf8")).toBe("shared");
  101. const artifacts = new NodeToolArtifactStore({
  102. rootDir: join(root, "artifacts"),
  103. imageCacheRootDir: join(root, "image-cache"),
  104. videoCacheRootDir: join(root, "video-cache"),
  105. });
  106. expect(
  107. Buffer.from(
  108. (await artifacts.readToolResultBinaryArtifact({ uri: "zcode-artifact://root/shared" }))
  109. .bytes,
  110. ).toString(),
  111. ).toBe("shared");
  112. await expect(readFile(join(dir, "private.txt"))).rejects.toThrow();
  113. expect(db.prepare("SELECT 1 FROM session WHERE id IN ('root','child')").get()).toBeUndefined();
  114. for (const table of ["message", "part", "input_history"])
  115. expect(
  116. db.prepare(`SELECT 1 FROM ${table} WHERE session_id IN ('root','child')`).get(),
  117. ).toBeUndefined();
  118. expect(db.prepare("SELECT 1 FROM dwf_event WHERE run_id='owned-run'").get()).toBeUndefined();
  119. expect(await readFile(join(root, "workspace-file.txt"), "utf8")).toBe("E2E_KEEP_WORKSPACE");
  120. expect((await execute(preview.revision)).status).toBe("deleted");
  121. });
  122. it("其他会话的工作流产物记录引用也保留附件", async () => {
  123. const { host, db } = await setup();
  124. db.exec(`UPDATE part SET data='{}';
  125. INSERT INTO dwf_run(id,parent_session_id,caps_max_concurrency,status,time_created,time_updated) VALUES('run','fork',1,'completed',1,1);
  126. INSERT INTO dwf_event(run_id,sequence,type,payload_json,time_created) VALUES('run',1,'artifact','{"uri":"zcode-artifact://root/shared"}',1);`);
  127. expect(
  128. (await previewSessionDeletionWith(host, params)).retainedArtifacts.map(
  129. (file) => file.fileName,
  130. ),
  131. ).toEqual(["shared.png"]);
  132. });
  133. it("运行中的 owned child 阻止整棵删除", async () => {
  134. const { host, busy, execute, store } = await setup();
  135. const preview = await previewSessionDeletionWith(host, params);
  136. busy.add("child");
  137. expect(await execute(preview.revision)).toMatchObject({ status: "blocked", reason: "running" });
  138. expect(await store.getSession("root" as SessionId)).not.toBeNull();
  139. });
  140. it("预检后新增文件要求重新确认", async () => {
  141. const { host, dir, execute, store } = await setup();
  142. const preview = await previewSessionDeletionWith(host, params);
  143. await writeFile(join(dir, "new.txt"), "new");
  144. expect(await execute(preview.revision)).toMatchObject({ status: "blocked", reason: "changed" });
  145. expect(await store.getSession("root" as SessionId)).not.toBeNull();
  146. });
  147. it("预检后新增外部引用要求重查,准入后拒绝迟到引用", async () => {
  148. const { host, db, store, execute } = await setup();
  149. const preview = await previewSessionDeletionWith(host, params);
  150. db.prepare("UPDATE part SET data=? WHERE id='p'").run(
  151. JSON.stringify({
  152. url: "zcode-artifact://root/private",
  153. }),
  154. );
  155. expect(await execute(preview.revision)).toMatchObject({ status: "blocked", reason: "changed" });
  156. expect(db.prepare("SELECT 1 FROM session_purge").get()).toBeUndefined();
  157. const fresh = await store.inspectSessionDeletion("root" as SessionId);
  158. await store.beginSessionDeletion("root" as SessionId, fresh.revision, "op", []);
  159. expect(() =>
  160. db.prepare("UPDATE part SET data=? WHERE id='p'").run(
  161. JSON.stringify({
  162. url: "zcode-artifact://root/shared",
  163. }),
  164. ),
  165. ).toThrow("session-data.deleting");
  166. expect(() =>
  167. db
  168. .prepare(
  169. "INSERT INTO dwf_run(id,parent_session_id,caps_max_concurrency,status,time_created,time_updated) VALUES('late-run','root',1,'running',1,1)",
  170. )
  171. .run(),
  172. ).toThrow("session-data.deleting");
  173. });
  174. it("文件清理后数据库失败,新存储连接凭持久凭据续删", async () => {
  175. const { host, store, dir, dbPath, execute } = await setup();
  176. const preview = await previewSessionDeletionWith(host, params);
  177. host.store = {
  178. inspectSessionDeletion: store.inspectSessionDeletion.bind(store),
  179. beginSessionDeletion: store.beginSessionDeletion.bind(store),
  180. completeSessionDeletion: async () => {
  181. throw new Error("injected SQL failure");
  182. },
  183. };
  184. expect((await execute(preview.revision)).status).toBe("incomplete");
  185. await expect(readFile(join(dir, "private.txt"))).rejects.toThrow();
  186. const reopened = await SqliteSessionStore.open({ dbPath });
  187. try {
  188. expect(await reopened.getSession("root" as SessionId)).toBeNull();
  189. expect((await reopened.inspectSessionDeletion("root" as SessionId)).deleting).toBe(true);
  190. host.store = reopened;
  191. expect((await execute(preview.revision)).status).toBe("deleted");
  192. expect(await readFile(join(dir, "shared.png"), "utf8")).toBe("shared");
  193. } finally {
  194. reopened.close();
  195. }
  196. });
  197. it("部分失败留下写屏障,重试只完成余项", async () => {
  198. const { host, execute, store, db } = await setup();
  199. const preview = await previewSessionDeletionWith(host, params);
  200. const remove = host.files.removeSession;
  201. host.files.removeSession = async () => {
  202. throw Object.assign(new Error("locked"), { code: "EBUSY" });
  203. };
  204. expect((await execute(preview.revision)).status).toBe("incomplete");
  205. expect(await store.getSession("root" as SessionId)).toBeNull();
  206. expect(db.prepare("SELECT 1 FROM session WHERE id='root'").get()).toBeDefined();
  207. expect(() =>
  208. db
  209. .prepare(
  210. "INSERT INTO message(id,session_id,time_created,time_updated,data) VALUES('late','root',1,1,'{}')",
  211. )
  212. .run(),
  213. ).toThrow("session-data.deleting");
  214. host.files.removeSession = remove;
  215. expect((await execute(preview.revision)).status).toBe("deleted");
  216. });
  217. it("跨连接运行态互斥且拒绝错误目录身份", async () => {
  218. const { host, store, dbPath, execute } = await setup();
  219. const other = await SqliteSessionStore.open({ dbPath });
  220. try {
  221. const preview = await previewSessionDeletionWith(host, params);
  222. await other.registerSessionRuntime("root" as SessionId);
  223. expect(await execute(preview.revision)).toMatchObject({
  224. status: "blocked",
  225. reason: "in-use",
  226. });
  227. await other.unregisterSessionRuntime("root" as SessionId);
  228. await expect(
  229. previewSessionDeletionWith(host, { ...params, workspace: { workspacePath: "/other" } }),
  230. ).rejects.toThrow("identity-mismatch");
  231. expect(await store.getSession("root" as SessionId)).not.toBeNull();
  232. } finally {
  233. other.close();
  234. }
  235. });
  236. });