session-data.test.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. measureSessionDataWith,
  4. purgeSessionDataWith,
  5. type SessionDataHost,
  6. } from "../src/zcode-protocol/session-data/index.js";
  7. function harness(
  8. options: {
  9. busy?: string[];
  10. loaded?: string[];
  11. failFiles?: string[];
  12. referrers?: Record<string, string[]>;
  13. } = {},
  14. ) {
  15. const trees: Record<string, string[]> = {
  16. sess_a: ["sess_a", "sess_a_child"],
  17. sess_b: ["sess_b"],
  18. sess_c: ["sess_c"],
  19. };
  20. const sizes: Record<string, number> = { sess_a: 10, sess_a_child: 5, sess_b: 7, sess_gone: 3 };
  21. const calls: string[] = [];
  22. const host: SessionDataHost = {
  23. store: {
  24. listOwnedSessionTrees: async (ids) =>
  25. new Map(ids.map((id) => [id, trees[id] ?? []] as const)) as never,
  26. listArtifactReferrers: async (ids) =>
  27. new Map(
  28. ids.flatMap((id) => (options.referrers?.[id] ? [[id, options.referrers[id]] as const] : [])),
  29. ) as never,
  30. purgeSessions: async (ids) => {
  31. calls.push(`purge:${ids.join(",")}`);
  32. },
  33. },
  34. files: {
  35. measureSession: async (id) => sizes[id] ?? 0,
  36. removeSession: async (id) => {
  37. if (options.failFiles?.includes(id)) throw Object.assign(new Error("busy"), { code: "EBUSY" });
  38. calls.push(`files:${id}`);
  39. return sizes[id] ?? 0;
  40. },
  41. measureMemory: async () => 4,
  42. removeMemory: async ({ workspacePath }) => {
  43. calls.push(`memory:${workspacePath}`);
  44. return 4;
  45. },
  46. },
  47. residency: (id) =>
  48. options.busy?.includes(id) ? "busy" : options.loaded?.includes(id) ? "idle" : null,
  49. release: async (id) => {
  50. calls.push(`release:${id}`);
  51. },
  52. forgetIndexed: (id) => {
  53. calls.push(`forget:${id}`);
  54. },
  55. };
  56. return { host, calls };
  57. }
  58. const directories = [{ workspacePath: "/work/a" }];
  59. describe("session data", () => {
  60. it("measures each root with its owned children and each directory's memory", async () => {
  61. const { host } = harness();
  62. expect(
  63. await measureSessionDataWith(host, { sessionIds: ["sess_a", "sess_b"], directories }),
  64. ).toEqual({
  65. sessions: [
  66. { sessionId: "sess_a", bytes: 15 },
  67. { sessionId: "sess_b", bytes: 7 },
  68. ],
  69. memory: [{ workspacePath: "/work/a", bytes: 4 }],
  70. });
  71. });
  72. it("releases loaded idle sessions, removes files before rows, then drops them from the index", async () => {
  73. const { host, calls } = harness({ loaded: ["sess_a_child"] });
  74. const result = await purgeSessionDataWith(host, { sessionIds: ["sess_a"], directories });
  75. expect(result).toEqual({
  76. deleted: [{ sessionId: "sess_a", bytes: 15 }],
  77. kept: [],
  78. failed: [],
  79. memory: [{ workspacePath: "/work/a", bytes: 4 }],
  80. });
  81. expect(calls).toEqual([
  82. "release:sess_a_child",
  83. "files:sess_a",
  84. "files:sess_a_child",
  85. "purge:sess_a",
  86. "forget:sess_a",
  87. "forget:sess_a_child",
  88. "memory:/work/a",
  89. ]);
  90. });
  91. it("keeps a tree whose root or child is running, without touching its files", async () => {
  92. const { host, calls } = harness({ busy: ["sess_a_child"] });
  93. const result = await purgeSessionDataWith(host, {
  94. sessionIds: ["sess_a", "sess_b"],
  95. directories: [],
  96. });
  97. expect(result.kept).toEqual([{ sessionId: "sess_a", reason: "running" }]);
  98. expect(result.deleted).toEqual([{ sessionId: "sess_b", bytes: 7 }]);
  99. expect(calls.some((call) => call.includes("sess_a"))).toBe(false);
  100. });
  101. it("leaves the rows when a file cannot be removed so a retry can find them", async () => {
  102. const { host, calls } = harness({ failFiles: ["sess_a_child"] });
  103. const result = await purgeSessionDataWith(host, { sessionIds: ["sess_a"], directories: [] });
  104. expect(result.failed).toEqual([{ sessionId: "sess_a", code: "EBUSY" }]);
  105. expect(result.deleted).toEqual([]);
  106. expect(calls).not.toContain("purge:sess_a");
  107. // 删除没完成:不能先从列表投影移除,否则 Host 会把仍存在的会话当作已删除。
  108. expect(calls.some((call) => call.startsWith("forget:"))).toBe(false);
  109. });
  110. it("keeps a tree whose attachments a session outside the request still uses", async () => {
  111. const { host, calls } = harness({ referrers: { sess_a_child: ["sess_fork_elsewhere"] } });
  112. const result = await purgeSessionDataWith(host, {
  113. sessionIds: ["sess_a", "sess_b"],
  114. directories: [],
  115. });
  116. expect(result.kept).toEqual([{ sessionId: "sess_a", reason: "referenced" }]);
  117. expect(result.deleted).toEqual([{ sessionId: "sess_b", bytes: 7 }]);
  118. expect(calls.some((call) => call.includes("sess_a"))).toBe(false);
  119. });
  120. it("deletes a source together with a fork that is deleted in the same request", async () => {
  121. const { host } = harness({ referrers: { sess_a: ["sess_b"] } });
  122. const result = await purgeSessionDataWith(host, {
  123. sessionIds: ["sess_a", "sess_b"],
  124. directories: [],
  125. });
  126. expect(result.kept).toEqual([]);
  127. expect(result.deleted.map((entry) => entry.sessionId)).toEqual(["sess_a", "sess_b"]);
  128. });
  129. it("keeps every tree in a chain once one link is kept", async () => {
  130. // sess_c 正在运行并引用 sess_b,sess_b 又引用 sess_a:三棵都不能删。
  131. const { host } = harness({
  132. busy: ["sess_c"],
  133. referrers: { sess_a: ["sess_b"], sess_b: ["sess_c"] },
  134. });
  135. const result = await purgeSessionDataWith(host, {
  136. sessionIds: ["sess_a", "sess_b", "sess_c"],
  137. directories: [],
  138. });
  139. expect(result.kept).toEqual([
  140. { sessionId: "sess_a", reason: "referenced" },
  141. { sessionId: "sess_b", reason: "referenced" },
  142. { sessionId: "sess_c", reason: "running" },
  143. ]);
  144. expect(result.deleted).toEqual([]);
  145. });
  146. it("treats a session that no longer exists as deleted, still clearing leftover files", async () => {
  147. const { host, calls } = harness();
  148. const result = await purgeSessionDataWith(host, { sessionIds: ["sess_gone"], directories: [] });
  149. expect(result.deleted).toEqual([{ sessionId: "sess_gone", bytes: 3 }]);
  150. expect(calls).toEqual(["files:sess_gone", "purge:sess_gone", "forget:sess_gone"]);
  151. });
  152. });