session-store-transaction-isolation.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import { execFile } from "node:child_process";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { promisify } from "node:util";
  7. import { DatabaseSync } from "node:sqlite";
  8. import { afterEach, describe, expect, it } from "vitest";
  9. import { createSessionId, type SharedContextImportCommitBundle } from "@zcode/contracts";
  10. import { createSqliteSessionStore } from "../src/storage/index.js";
  11. import {
  12. CHILD_ID,
  13. EXISTING_ID,
  14. HISTORY_MARKER,
  15. PARENT_ID,
  16. SURVIVOR_ID,
  17. forkBundle,
  18. messageInput,
  19. seedFailedForkRace,
  20. sessionInput,
  21. } from "./fixtures/session-transaction-race.js";
  22. const roots: string[] = [];
  23. const stores: Awaited<ReturnType<typeof createSqliteSessionStore>>[] = [];
  24. async function openStore(failFork = false) {
  25. const directory = await mkdtemp(join(tmpdir(), "session-transaction-"));
  26. roots.push(directory);
  27. const dbPath = join(directory, "db.sqlite");
  28. const store = await createSqliteSessionStore({
  29. dbPath,
  30. ...(failFork ? { forkCommitFaultAt: "beforeCommit" as const } : {}),
  31. });
  32. stores.push(store);
  33. return { store, dbPath, directory };
  34. }
  35. afterEach(async () => {
  36. for (const store of stores.splice(0)) store.close();
  37. await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  38. });
  39. describe("connection-wide transaction isolation", () => {
  40. it("fork 回滚不撤销其他会话已成功的创建、更新和历史写入", async () => {
  41. const { store, directory } = await openStore(true);
  42. const results = await seedFailedForkRace(store, directory);
  43. expect(results[0]).toMatchObject({
  44. status: "rejected",
  45. reason: expect.objectContaining({ message: expect.stringContaining("beforeCommit") }),
  46. });
  47. expect(results.slice(1).map((result) => result.status)).toEqual(Array(4).fill("fulfilled"));
  48. expect(await store.getSession(CHILD_ID)).toBeNull();
  49. expect((await store.getSession(EXISTING_ID))?.title).toBe("independent update");
  50. expect((await store.getSession(SURVIVOR_ID))?.id).toBe(SURVIVOR_ID);
  51. expect((await store.messages({ sessionID: SURVIVOR_ID }))[0]?.parts[0]).toMatchObject({
  52. type: "text",
  53. text: HISTORY_MARKER,
  54. });
  55. });
  56. it("同时发起的成功 fork 各自提交,重启后 child 历史仍在", async () => {
  57. const { store, directory, dbPath } = await openStore();
  58. await store.createSession(sessionInput(PARENT_ID, directory));
  59. const childIds = [createSessionId("fork-one"), createSessionId("fork-two")];
  60. const results = await Promise.allSettled(
  61. childIds.map((id) => store.commitForkBundle(forkBundle(directory, id))),
  62. );
  63. expect(results.map((result) => result.status)).toEqual(["fulfilled", "fulfilled"]);
  64. store.close();
  65. stores.splice(stores.indexOf(store), 1);
  66. const reopened = await createSqliteSessionStore({ dbPath });
  67. stores.push(reopened);
  68. for (const id of childIds) {
  69. expect((await reopened.getSession(id))?.parentID).toBe(PARENT_ID);
  70. expect((await reopened.messages({ sessionID: id }))[0]?.parts[0]).toMatchObject({
  71. text: HISTORY_MARKER,
  72. sessionID: id,
  73. });
  74. }
  75. });
  76. it("写入进程退出后,新进程仍能打开未受 fork 回滚影响的会话", async () => {
  77. const { directory, dbPath, store } = await openStore();
  78. store.close();
  79. stores.splice(stores.indexOf(store), 1);
  80. const worker = fileURLToPath(
  81. new URL("./fixtures/session-transaction-process.ts", import.meta.url),
  82. );
  83. const run = async (mode: string) =>
  84. JSON.parse(
  85. (
  86. await promisify(execFile)(
  87. process.execPath,
  88. ["--import", "tsx", worker, mode, dbPath, directory],
  89. { env: { ...process.env, NODE_NO_WARNINGS: "1" } },
  90. )
  91. ).stdout,
  92. ) as { pid: number; sessionId: string };
  93. const seed = await run("seed");
  94. const resumed = await run("resume");
  95. expect(resumed.pid).not.toBe(seed.pid);
  96. expect(resumed.sessionId).toBe(SURVIVOR_ID);
  97. }, 20_000);
  98. it.each(["import", "transition", "promotion"] as const)(
  99. "%s 回滚也不能撤销同连接上其他会话的创建",
  100. async (operation) => {
  101. const { store, dbPath, directory } = await openStore();
  102. const imported = createSessionId("imported-context");
  103. const context = messageInput(imported);
  104. const bundle: SharedContextImportCommitBundle = {
  105. session: sessionInput(imported, directory),
  106. contextMessage: {
  107. ...context,
  108. info: {
  109. ...context.info,
  110. role: "user",
  111. source: "shared_context",
  112. visibility: "model-only",
  113. metadata: { contextId: "context" },
  114. },
  115. },
  116. provenance: {
  117. id: `${imported}:context`,
  118. sessionID: imported,
  119. type: "v4/shared_context_import",
  120. time: { created: 1, updated: 1 },
  121. data: { contextId: "context", status: "pending" },
  122. },
  123. };
  124. if (operation === "transition") await store.commitSharedContextImportBundle(bundle);
  125. if (operation === "promotion") await store.createSession(sessionInput(imported, directory));
  126. const db = new DatabaseSync(dbPath);
  127. try {
  128. if (operation === "import")
  129. db.exec(
  130. "CREATE TRIGGER fail_import BEFORE INSERT ON session_entry WHEN NEW.type = 'v4/shared_context_import' BEGIN SELECT RAISE(ABORT, 'test rollback'); END",
  131. );
  132. if (operation === "transition")
  133. db.exec(
  134. "CREATE TRIGGER fail_transition BEFORE UPDATE ON message BEGIN SELECT RAISE(ABORT, 'test rollback'); END",
  135. );
  136. } finally {
  137. db.close();
  138. }
  139. const failed =
  140. operation === "import"
  141. ? store.commitSharedContextImportBundle(bundle)
  142. : operation === "transition"
  143. ? store.transitionSharedContextImport({
  144. sessionID: imported,
  145. contextId: "context",
  146. expectedStatus: "pending",
  147. status: "reserved",
  148. })
  149. : store.promoteSessionInput({
  150. id: "input",
  151. sessionID: imported,
  152. message: {
  153. ...context.info,
  154. metadata: {
  155. inputIntent: {
  156. sharedContextRefs: [{ kind: "shared_context_import", context_id: "missing" }],
  157. },
  158. },
  159. },
  160. parts: context.parts,
  161. });
  162. const results = await Promise.allSettled([
  163. failed,
  164. store.createSession(sessionInput(SURVIVOR_ID, directory)),
  165. ]);
  166. expect(results[0]).toMatchObject({
  167. status: "rejected",
  168. reason: expect.objectContaining({
  169. message: expect.stringContaining(
  170. operation === "promotion" ? "shared context import is missing" : "test rollback",
  171. ),
  172. }),
  173. });
  174. expect(results[1]?.status).toBe("fulfilled");
  175. expect((await store.getSession(SURVIVOR_ID))?.id).toBe(SURVIVOR_ID);
  176. if (operation === "import") expect(await store.getSession(imported)).toBeNull();
  177. if (operation === "promotion")
  178. expect(await store.messages({ sessionID: imported })).toEqual([]);
  179. if (operation === "transition")
  180. expect(
  181. (await store.sessionEntries({ sessionID: imported, type: "v4/shared_context_import" }))[0]
  182. ?.data,
  183. ).toMatchObject({ status: "pending" });
  184. },
  185. );
  186. });