session-permanent-deletion.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. v4SessionDeletionPreviewBatchParamsSchema,
  12. v4SessionDeletionPreviewBatchResultSchema,
  13. } from "@zcode/shared/zcode-protocol-v4";
  14. import {
  15. previewSessionDeletionWith,
  16. previewSessionDeletionsWith,
  17. executeSessionDeletionWith,
  18. type SessionDeletionHost,
  19. } from "../src/zcode-protocol/session-data/permanent-deletion.js";
  20. const cleanups: Array<() => Promise<void>> = [];
  21. afterEach(async () => {
  22. for (const cleanup of cleanups.splice(0)) await cleanup();
  23. });
  24. const params = { sessionId: "root", workspace: { workspacePath: "/work/example" } };
  25. async function setup() {
  26. const root = await mkdtemp(join(tmpdir(), "permanent-deletion-runtime-"));
  27. const dbPath = join(root, "db.sqlite");
  28. const store = await SqliteSessionStore.open({ dbPath });
  29. const db = new DatabaseSync(dbPath);
  30. cleanups.push(async () => {
  31. db.close();
  32. store.close();
  33. await rm(root, { recursive: true, force: true });
  34. });
  35. for (const [id, parentID, taskType] of [
  36. ["root", undefined, "interactive"],
  37. ["child", "root", "subagent_child"],
  38. ["fork", "root", "interactive"],
  39. ] as const)
  40. await store.createSession({
  41. id: id as SessionId,
  42. projectID: "project" as never,
  43. slug: id,
  44. directory: params.workspace.workspacePath,
  45. title: id,
  46. version: "1",
  47. parentID: parentID as SessionId | undefined,
  48. taskType,
  49. });
  50. db.prepare(
  51. "INSERT INTO message(id,session_id,time_created,time_updated,data) VALUES('m','fork',1,1,'{}')",
  52. ).run();
  53. db.prepare(
  54. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES('p','m','fork',1,1,?)",
  55. ).run(JSON.stringify({ url: "zcode-artifact://root/shared" }));
  56. const dir = join(root, "artifacts", "root");
  57. await mkdir(dir, { recursive: true });
  58. await writeFile(join(dir, "shared.png"), "shared");
  59. await writeFile(join(dir, "private.txt"), "private");
  60. const files = createNodeSessionDataFiles({
  61. cliStorageRoot: root,
  62. memoryRoot: () => join(root, "memories", "projects", "unused", "memory"),
  63. });
  64. const busy = new Set<string>();
  65. const host: SessionDeletionHost = {
  66. store,
  67. files,
  68. busy: (id) => busy.has(id),
  69. release: async () => {},
  70. forget: () => {},
  71. };
  72. const execute = async (revision: string) =>
  73. executeSessionDeletionWith(host, { ...params, revision, operationId: "op" });
  74. return { root, dbPath, db, store, dir, host, busy, execute };
  75. }
  76. describe("归档永久删除执行面", () => {
  77. it("保留 fork 和引用文件,物理删除正文,重复请求返回已完成", async () => {
  78. const { root, host, store, dir, execute, db } = await setup();
  79. // 用真实正文验证行级清理,不能只以 getSession 隐藏了记录作为永久删除证据。
  80. for (const id of ["root", "child"]) {
  81. db.prepare(
  82. "INSERT INTO message(id,session_id,time_created,time_updated,data) VALUES(?,?,1,1,?)",
  83. ).run(`${id}-message`, id, '{"role":"user","text":"E2E_PRIVATE_BODY"}');
  84. db.prepare(
  85. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES(?,?,?,1,1,?)",
  86. ).run(`${id}-part`, `${id}-message`, id, '{"type":"text","text":"E2E_PRIVATE_BODY"}');
  87. }
  88. db.exec(
  89. "INSERT INTO input_history(id,project_id,session_id,text,kind,time_created) VALUES('history','project','root','E2E_PRIVATE_INPUT','prompt',1)",
  90. );
  91. db.exec(
  92. "INSERT INTO dwf_run(id,parent_session_id,caps_max_concurrency,status,time_created,time_updated) VALUES('owned-run','root',1,'completed',1,1)",
  93. );
  94. db.exec(
  95. `INSERT INTO dwf_event(run_id,sequence,type,payload_json,time_created) VALUES('owned-run',1,'result','{"text":"E2E_PRIVATE_WORKFLOW"}',1)`,
  96. );
  97. await writeFile(join(root, "workspace-file.txt"), "E2E_KEEP_WORKSPACE");
  98. const preview = await previewSessionDeletionWith(host, params);
  99. expect(preview.forks.map((f) => f.sessionId)).toEqual(["fork"]);
  100. expect(preview.retainedArtifacts[0]?.fileName).toBe("shared.png");
  101. expect(preview.deletedFiles).toBe(1);
  102. expect((await execute(preview.revision)).status).toBe("deleted");
  103. expect(await store.getSession("root" as SessionId)).toBeNull();
  104. expect(await store.getSession("fork" as SessionId)).not.toBeNull();
  105. expect(await readFile(join(dir, "shared.png"), "utf8")).toBe("shared");
  106. const artifacts = new NodeToolArtifactStore({
  107. rootDir: join(root, "artifacts"),
  108. imageCacheRootDir: join(root, "image-cache"),
  109. videoCacheRootDir: join(root, "video-cache"),
  110. });
  111. expect(
  112. Buffer.from(
  113. (await artifacts.readToolResultBinaryArtifact({ uri: "zcode-artifact://root/shared" }))
  114. .bytes,
  115. ).toString(),
  116. ).toBe("shared");
  117. await expect(readFile(join(dir, "private.txt"))).rejects.toThrow();
  118. expect(db.prepare("SELECT 1 FROM session WHERE id IN ('root','child')").get()).toBeUndefined();
  119. for (const table of ["message", "part", "input_history"])
  120. expect(
  121. db.prepare(`SELECT 1 FROM ${table} WHERE session_id IN ('root','child')`).get(),
  122. ).toBeUndefined();
  123. expect(db.prepare("SELECT 1 FROM dwf_event WHERE run_id='owned-run'").get()).toBeUndefined();
  124. expect(await readFile(join(root, "workspace-file.txt"), "utf8")).toBe("E2E_KEEP_WORKSPACE");
  125. expect((await execute(preview.revision)).status).toBe("deleted");
  126. });
  127. it("其他会话的工作流产物记录引用也保留附件", async () => {
  128. const { host, db } = await setup();
  129. db.exec(`UPDATE part SET data='{}';
  130. INSERT INTO dwf_run(id,parent_session_id,caps_max_concurrency,status,time_created,time_updated) VALUES('run','fork',1,'completed',1,1);
  131. INSERT INTO dwf_event(run_id,sequence,type,payload_json,time_created) VALUES('run',1,'artifact','{"uri":"zcode-artifact://root/shared"}',1);`);
  132. expect(
  133. (await previewSessionDeletionWith(host, params)).retainedArtifacts.map(
  134. (file) => file.fileName,
  135. ),
  136. ).toEqual(["shared.png"]);
  137. });
  138. it("运行中的 owned child 阻止整棵删除", async () => {
  139. const { host, busy, execute, store } = await setup();
  140. const preview = await previewSessionDeletionWith(host, params);
  141. busy.add("child");
  142. expect(await execute(preview.revision)).toMatchObject({ status: "blocked", reason: "running" });
  143. expect(await store.getSession("root" as SessionId)).not.toBeNull();
  144. });
  145. it("预检后新增文件要求重新确认", async () => {
  146. const { host, dir, execute, store } = await setup();
  147. const preview = await previewSessionDeletionWith(host, params);
  148. await writeFile(join(dir, "new.txt"), "new");
  149. expect(await execute(preview.revision)).toMatchObject({ status: "blocked", reason: "changed" });
  150. expect(await store.getSession("root" as SessionId)).not.toBeNull();
  151. });
  152. it("预检后新增外部引用要求重查,准入后拒绝迟到引用", async () => {
  153. const { host, db, store, execute } = await setup();
  154. const preview = await previewSessionDeletionWith(host, params);
  155. db.prepare("UPDATE part SET data=? WHERE id='p'").run(
  156. JSON.stringify({
  157. url: "zcode-artifact://root/private",
  158. }),
  159. );
  160. expect(await execute(preview.revision)).toMatchObject({ status: "blocked", reason: "changed" });
  161. expect(db.prepare("SELECT 1 FROM session_purge").get()).toBeUndefined();
  162. const fresh = await store.inspectSessionDeletion("root" as SessionId);
  163. await store.beginSessionDeletion("root" as SessionId, fresh.revision, "op", []);
  164. expect(() =>
  165. db.prepare("UPDATE part SET data=? WHERE id='p'").run(
  166. JSON.stringify({
  167. url: "zcode-artifact://root/shared",
  168. }),
  169. ),
  170. ).toThrow("session-data.deleting");
  171. expect(() =>
  172. db
  173. .prepare(
  174. "INSERT INTO dwf_run(id,parent_session_id,caps_max_concurrency,status,time_created,time_updated) VALUES('late-run','root',1,'running',1,1)",
  175. )
  176. .run(),
  177. ).toThrow("session-data.deleting");
  178. });
  179. it("文件清理后数据库失败,新存储连接凭持久凭据续删", async () => {
  180. const { host, store, dir, dbPath, execute } = await setup();
  181. const preview = await previewSessionDeletionWith(host, params);
  182. host.store = {
  183. inspectSessionDeletions: store.inspectSessionDeletions.bind(store),
  184. beginSessionDeletion: store.beginSessionDeletion.bind(store),
  185. completeSessionDeletion: async () => {
  186. throw new Error("injected SQL failure");
  187. },
  188. };
  189. expect((await execute(preview.revision)).status).toBe("incomplete");
  190. await expect(readFile(join(dir, "private.txt"))).rejects.toThrow();
  191. const reopened = await SqliteSessionStore.open({ dbPath });
  192. try {
  193. expect(await reopened.getSession("root" as SessionId)).toBeNull();
  194. expect((await reopened.inspectSessionDeletion("root" as SessionId)).deleting).toBe(true);
  195. host.store = reopened;
  196. expect((await execute(preview.revision)).status).toBe("deleted");
  197. expect(await readFile(join(dir, "shared.png"), "utf8")).toBe("shared");
  198. } finally {
  199. reopened.close();
  200. }
  201. });
  202. it("部分失败留下写屏障,重试只完成余项", async () => {
  203. const { host, execute, store, db } = await setup();
  204. const preview = await previewSessionDeletionWith(host, params);
  205. const remove = host.files.removeSession;
  206. host.files.removeSession = async () => {
  207. throw Object.assign(new Error("locked"), { code: "EBUSY" });
  208. };
  209. expect((await execute(preview.revision)).status).toBe("incomplete");
  210. expect(await store.getSession("root" as SessionId)).toBeNull();
  211. expect(db.prepare("SELECT 1 FROM session WHERE id='root'").get()).toBeDefined();
  212. expect(() =>
  213. db
  214. .prepare(
  215. "INSERT INTO message(id,session_id,time_created,time_updated,data) VALUES('late','root',1,1,'{}')",
  216. )
  217. .run(),
  218. ).toThrow("session-data.deleting");
  219. host.files.removeSession = remove;
  220. expect((await execute(preview.revision)).status).toBe("deleted");
  221. });
  222. it("跨连接运行态互斥且拒绝错误目录身份", async () => {
  223. const { host, store, dbPath, execute } = await setup();
  224. const other = await SqliteSessionStore.open({ dbPath });
  225. try {
  226. const preview = await previewSessionDeletionWith(host, params);
  227. await other.registerSessionRuntime("root" as SessionId);
  228. expect(await execute(preview.revision)).toMatchObject({
  229. status: "blocked",
  230. reason: "in-use",
  231. });
  232. await other.unregisterSessionRuntime("root" as SessionId);
  233. await expect(
  234. previewSessionDeletionWith(host, { ...params, workspace: { workspacePath: "/other" } }),
  235. ).rejects.toThrow("identity-mismatch");
  236. expect(await store.getSession("root" as SessionId)).not.toBeNull();
  237. } finally {
  238. other.close();
  239. }
  240. });
  241. });
  242. describe("归档永久删除批量预检", () => {
  243. async function withSecondRoot() {
  244. const context = await setup();
  245. // other 没有任何产物文件,但库里留有指向它的引用(文件已丢)。
  246. await context.store.createSession({
  247. id: "other" as SessionId,
  248. projectID: "project" as never,
  249. slug: "other",
  250. directory: params.workspace.workspacePath,
  251. title: "other",
  252. version: "1",
  253. taskType: "interactive",
  254. });
  255. context.db
  256. .prepare(
  257. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES('p-lost','m','fork',1,1,?)",
  258. )
  259. .run(JSON.stringify({ url: "zcode-artifact://other/lost" }));
  260. const scans: Array<{ sessionId: string; scanArtifactReferences?: boolean }> = [];
  261. const inspect = context.store.inspectSessionDeletions.bind(context.store);
  262. context.host.store = {
  263. inspectSessionDeletions: async (targets) => {
  264. scans.push(...targets);
  265. return inspect(targets);
  266. },
  267. beginSessionDeletion: context.store.beginSessionDeletion.bind(context.store),
  268. completeSessionDeletion: context.store.completeSessionDeletion.bind(context.store),
  269. };
  270. return { ...context, scans };
  271. }
  272. const other = { sessionId: "other", workspace: params.workspace };
  273. it("参数严格校验:至少 1 项、至多 100 项、拒绝多余字段与非法会话 ID", () => {
  274. const parse = (value: unknown) => v4SessionDeletionPreviewBatchParamsSchema.safeParse(value);
  275. expect(parse({ items: [params] }).success).toBe(true);
  276. expect(parse({ items: [] }).success).toBe(false);
  277. expect(parse({ items: Array.from({ length: 101 }, () => params) }).success).toBe(false);
  278. expect(parse({ items: [params], extra: 1 }).success).toBe(false);
  279. expect(parse({ items: [{ ...params, sessionId: "../x" }] }).success).toBe(false);
  280. expect(parse({ items: [{ ...params, revision: "r" }] }).success).toBe(false);
  281. });
  282. it("结果按顺序逐项返回,与单项预检一致;单项错误不影响其他项", async () => {
  283. const { host } = await withSecondRoot();
  284. const items = [
  285. params,
  286. { ...params, workspace: { workspacePath: "/other" } },
  287. other,
  288. { sessionId: "ghost", workspace: params.workspace },
  289. ];
  290. const batch = await previewSessionDeletionsWith(host, { items });
  291. expect(v4SessionDeletionPreviewBatchResultSchema.parse(batch)).toEqual(batch);
  292. expect(batch.results).toEqual([
  293. { preview: await previewSessionDeletionWith(host, params) },
  294. { error: { code: "session-data.identity-mismatch" } },
  295. { preview: await previewSessionDeletionWith(host, other) },
  296. { preview: await previewSessionDeletionWith(host, items[3]!) },
  297. ]);
  298. expect(batch.results[3]).toMatchObject({ preview: { blockedReason: "not-found" } });
  299. });
  300. it("某个根的存储异常只记为该项错误,同批其他根照常返回", async () => {
  301. const { host, db } = await withSecondRoot();
  302. const expected = await previewSessionDeletionWith(host, params);
  303. // other 的删除凭据损坏:整批存储调用会抛错,应逐根重查,只让 other 失败。
  304. db.prepare(
  305. "INSERT INTO session_purge(session_id,root_id,operation_id,retained_artifacts,workspace_path,workspace_identity,state) VALUES('other','other','op-bad','not-json',?,NULL,'deleting')",
  306. ).run(params.workspace.workspacePath);
  307. const batch = await previewSessionDeletionsWith(host, { items: [params, other] });
  308. expect(batch.results[0]).toEqual({ preview: expected });
  309. expect(batch.results[1]).toHaveProperty("error.code");
  310. });
  311. it("只对有产物文件的根做引用扫描;无产物根的悬空引用不列为保留附件", async () => {
  312. const { host, scans } = await withSecondRoot();
  313. const batch = await previewSessionDeletionsWith(host, { items: [params, other] });
  314. // 首轮整批按无产物检查;root 有 artifact 文件,第二轮只为它扫描引用。
  315. expect(scans).toEqual([
  316. { sessionId: "root", scanArtifactReferences: false },
  317. { sessionId: "other", scanArtifactReferences: false },
  318. { sessionId: "root", scanArtifactReferences: true },
  319. ]);
  320. const [rootResult, otherResult] = batch.results;
  321. expect(rootResult).toMatchObject({
  322. preview: { retainedArtifacts: [{ fileName: "shared.png" }] },
  323. });
  324. expect(otherResult).toMatchObject({ preview: { retainedArtifacts: [], deletedFiles: 0 } });
  325. });
  326. it("批量预检的 revision 可直接执行;执行阶段仍拒绝运行中与变化", async () => {
  327. const { host, busy, store, dir } = await withSecondRoot();
  328. const [rootResult, otherResult] = (
  329. await previewSessionDeletionsWith(host, { items: [params, other] })
  330. ).results;
  331. if (!rootResult || !("preview" in rootResult) || !otherResult || !("preview" in otherResult))
  332. throw new Error("preview missing");
  333. busy.add("child");
  334. expect(
  335. await executeSessionDeletionWith(host, {
  336. ...params,
  337. revision: rootResult.preview.revision,
  338. operationId: "op-root",
  339. }),
  340. ).toMatchObject({ status: "blocked", reason: "running" });
  341. busy.delete("child");
  342. await writeFile(join(dir, "late.txt"), "late");
  343. expect(
  344. await executeSessionDeletionWith(host, {
  345. ...params,
  346. revision: rootResult.preview.revision,
  347. operationId: "op-root",
  348. }),
  349. ).toMatchObject({ status: "blocked", reason: "changed" });
  350. expect(await store.getSession("root" as SessionId)).not.toBeNull();
  351. // 无产物根:预检与写锁内复检都跳过引用扫描,revision 一致,删除成功。
  352. expect(
  353. await executeSessionDeletionWith(host, {
  354. ...other,
  355. revision: otherResult.preview.revision,
  356. operationId: "op-other",
  357. }),
  358. ).toMatchObject({ status: "deleted", retainedArtifacts: 0 });
  359. expect(await store.getSession("other" as SessionId)).toBeNull();
  360. });
  361. });