session-store-fork-source.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import { mkdtemp, 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 { describe, expect, it } from "vitest";
  6. import type {
  7. ForkCommitBundle,
  8. ForkFromSourceInput,
  9. MessageWithParts,
  10. SessionInfo,
  11. } from "@zcode/contracts";
  12. import { createSqliteSessionStore } from "../src/storage/session-store/sqlite-session-store.js";
  13. const parentId = "source-parent" as never;
  14. const childId = "source-child" as never;
  15. const largeText = "large body ".repeat(100_000);
  16. function bundle(parent: SessionInfo, messages: MessageWithParts[]): ForkCommitBundle {
  17. const copied = messages.map((message, index) => ({
  18. info: {
  19. ...message.info,
  20. id: `copied-${index}` as never,
  21. sessionID: childId,
  22. visibility: "model-only" as const,
  23. metadata: {
  24. ...message.info.metadata,
  25. forkOrigin: { sessionId: parentId, messageId: message.info.id },
  26. },
  27. },
  28. parts: message.parts.map((part, partIndex) => ({
  29. ...part,
  30. id: `copied-${index}-${partIndex}` as never,
  31. sessionID: childId,
  32. messageID: `copied-${index}` as never,
  33. ...(part.type === "tool"
  34. ? {
  35. callID: "copied-call",
  36. state:
  37. part.state.status === "completed"
  38. ? {
  39. ...part.state,
  40. attachments: part.state.attachments?.map((attachment, attachmentIndex) => ({
  41. ...attachment,
  42. id: `attachment-${index}-${attachmentIndex}` as never,
  43. sessionID: childId,
  44. messageID: `copied-${index}` as never,
  45. })),
  46. }
  47. : part.state,
  48. }
  49. : {}),
  50. })),
  51. }));
  52. return {
  53. child: { ...parent, id: childId, parentID: parentId, taskType: "selection_side_chat" },
  54. messages: copied,
  55. entries: [],
  56. copySources: {
  57. messages: Object.fromEntries(
  58. messages.map((message, index) => [copied[index]!.info.id, message.info.id]),
  59. ),
  60. parts: Object.fromEntries(
  61. messages.flatMap((message, index) =>
  62. message.parts.map((part, partIndex) => [copied[index]!.parts[partIndex]!.id, part.id]),
  63. ),
  64. ),
  65. },
  66. commandFact: {
  67. parentSessionId: parentId,
  68. sourceCommandId: "source-command",
  69. ack: {
  70. commandId: "source-command",
  71. status: "accepted",
  72. revisionAtDecision: 1,
  73. result: { type: "createSelectionSideSession", sessionId: childId },
  74. },
  75. metadata: {},
  76. },
  77. };
  78. }
  79. async function fixture(
  80. fault?:
  81. | "afterChild"
  82. | "afterMessages"
  83. | "afterGoal"
  84. | "afterEntries"
  85. | "afterInput"
  86. | "afterCommandFact"
  87. | "beforeCommit",
  88. ) {
  89. const directory = await mkdtemp(join(tmpdir(), "fork-source-"));
  90. const dbPath = join(directory, "sessions.sqlite");
  91. const store = await createSqliteSessionStore({ dbPath, forkCommitFaultAt: fault });
  92. await store.createSession({
  93. id: parentId,
  94. projectID: "project" as never,
  95. slug: "parent",
  96. directory,
  97. title: "parent",
  98. version: "test",
  99. });
  100. await store.saveMessage({
  101. id: "original-message" as never,
  102. sessionID: parentId,
  103. role: "user",
  104. agent: "build",
  105. time: { created: 1 },
  106. tools: {},
  107. modelSelection: { providerId: "provider" as never, modelId: "model" as never },
  108. });
  109. await store.savePart({
  110. id: "original-text" as never,
  111. sessionID: parentId,
  112. messageID: "original-message" as never,
  113. type: "text",
  114. text: largeText,
  115. });
  116. await store.savePart({
  117. id: "original-tool" as never,
  118. sessionID: parentId,
  119. messageID: "original-message" as never,
  120. type: "tool",
  121. callID: "original-call",
  122. tool: "Read",
  123. state: {
  124. status: "completed",
  125. input: { payload: largeText, nullable: null },
  126. output: largeText,
  127. title: "Read",
  128. metadata: {},
  129. attachments: [
  130. {
  131. id: "original-attachment",
  132. sessionID: parentId,
  133. messageID: "original-message",
  134. type: "file",
  135. mime: "image/png",
  136. url: largeText,
  137. },
  138. ],
  139. time: { start: 1, end: 2 },
  140. },
  141. } as never);
  142. const raw = new DatabaseSync(dbPath);
  143. raw
  144. .prepare("update part set data=json_set(data,'$.future',json(?),'$.nullValue',null) where id=?")
  145. .run('{"payload":"keep","nested":[null,{"v":1}]}', "original-text");
  146. raw.close();
  147. return {
  148. store,
  149. dbPath,
  150. async close() {
  151. store.close();
  152. await rm(directory, { recursive: true, force: true });
  153. },
  154. };
  155. }
  156. describe("SQLite fork from source", () => {
  157. it("locks the source through planning and leaves the child independent after commit", async () => {
  158. const f = await fixture();
  159. const writer = new DatabaseSync(f.dbPath);
  160. writer.exec("pragma busy_timeout=0");
  161. try {
  162. await f.store.commitForkFromSource({
  163. sessionID: parentId,
  164. build(source) {
  165. expect(() =>
  166. writer
  167. .prepare("update part set data=json_set(data,'$.text','changed') where id=?")
  168. .run("original-text"),
  169. ).toThrow(/locked/);
  170. return bundle(source.session, source.messages);
  171. },
  172. });
  173. writer
  174. .prepare("update part set data=json_set(data,'$.text','changed') where id=?")
  175. .run("original-text");
  176. expect((await f.store.messages({ sessionID: childId }))[0]!.parts[0]).toMatchObject({
  177. text: largeText,
  178. });
  179. writer.exec("pragma foreign_keys=on");
  180. writer.prepare("delete from session where id=?").run(childId);
  181. expect((await f.store.messages({ sessionID: parentId }))[0]!.parts[0]).toMatchObject({
  182. text: "changed",
  183. });
  184. } finally {
  185. writer.close();
  186. await f.close();
  187. }
  188. });
  189. it("keeps large payloads in SQLite and preserves raw fields while remapping metadata", async () => {
  190. const f = await fixture();
  191. try {
  192. const result = await f.store.commitForkFromSource({
  193. sessionID: parentId,
  194. build(source) {
  195. expect(JSON.stringify(source.messages)).not.toContain(largeText);
  196. return bundle(source.session, source.messages);
  197. },
  198. });
  199. expect(result.id).toBe(childId);
  200. const messages = await f.store.messages({ sessionID: childId });
  201. expect(messages[0]!.parts[0]).toMatchObject({
  202. text: largeText,
  203. future: { payload: "keep", nested: [null, { v: 1 }] },
  204. nullValue: null,
  205. });
  206. expect(messages[0]!.parts[1]).toMatchObject({
  207. callID: "copied-call",
  208. state: {
  209. input: { payload: largeText, nullable: null },
  210. output: largeText,
  211. attachments: [
  212. { id: "attachment-0-0", sessionID: childId, messageID: "copied-0", url: largeText },
  213. ],
  214. },
  215. });
  216. expect((await f.store.messages({ sessionID: parentId }))[0]!.parts[1]).toMatchObject({
  217. callID: "original-call",
  218. });
  219. const raw = new DatabaseSync(f.dbPath, { readOnly: true });
  220. expect(
  221. raw
  222. .prepare(
  223. "select json_extract(data,'$.model.modelID') model from message where session_id=?",
  224. )
  225. .get(childId)?.model,
  226. ).toBe("model");
  227. expect(raw.prepare("pragma quick_check").get()).toMatchObject({ quick_check: "ok" });
  228. raw.close();
  229. } finally {
  230. await f.close();
  231. }
  232. });
  233. it.each([
  234. "afterChild",
  235. "afterMessages",
  236. "afterGoal",
  237. "afterEntries",
  238. "afterInput",
  239. "afterCommandFact",
  240. "beforeCommit",
  241. ] as const)("rolls back all child rows and command facts after %s", async (fault) => {
  242. const f = await fixture(fault);
  243. try {
  244. await expect(
  245. f.store.commitForkFromSource({
  246. sessionID: parentId,
  247. build: (source) => bundle(source.session, source.messages),
  248. }),
  249. ).rejects.toThrow();
  250. expect(await f.store.getSession(childId)).toBeNull();
  251. expect(await f.store.messages({ sessionID: childId })).toEqual([]);
  252. expect(
  253. await f.store.sessionEntries({ sessionID: parentId, type: "v4/command_fact" }),
  254. ).toEqual([]);
  255. expect(await f.store.messages({ sessionID: parentId })).toHaveLength(1);
  256. } finally {
  257. await f.close();
  258. }
  259. });
  260. it("returns the same durable child for concurrent retries", async () => {
  261. const f = await fixture();
  262. try {
  263. const request: ForkFromSourceInput = {
  264. sessionID: parentId,
  265. build: (source) => bundle(source.session, source.messages),
  266. };
  267. const [first, second] = await Promise.all([
  268. f.store.commitForkFromSource(request),
  269. f.store.commitForkFromSource(request),
  270. ]);
  271. expect(second.id).toBe(first.id);
  272. expect(await f.store.messages({ sessionID: childId })).toHaveLength(1);
  273. expect(
  274. await f.store.sessionEntries({ sessionID: parentId, type: "v4/command_fact" }),
  275. ).toHaveLength(1);
  276. } finally {
  277. await f.close();
  278. }
  279. });
  280. it.each(["message", "part", "collision"] as const)(
  281. "rejects an invalid %s copy without changing another session",
  282. async (kind) => {
  283. const f = await fixture();
  284. try {
  285. const siblingId = "sibling" as never;
  286. await f.store.createSession({
  287. id: siblingId,
  288. projectID: "project" as never,
  289. slug: "sibling",
  290. directory: "/workspace",
  291. title: "sibling",
  292. version: "test",
  293. });
  294. await f.store.saveMessage({
  295. id: "sibling-message" as never,
  296. sessionID: siblingId,
  297. role: "user",
  298. time: { created: 1 },
  299. agent: "build",
  300. tools: {},
  301. });
  302. await f.store.savePart({
  303. id: "sibling-part" as never,
  304. sessionID: siblingId,
  305. messageID: "sibling-message" as never,
  306. type: "text",
  307. text: "sibling body",
  308. });
  309. const before = await f.store.messages({ sessionID: siblingId });
  310. await expect(
  311. f.store.commitForkFromSource({
  312. sessionID: parentId,
  313. build(source) {
  314. const result = bundle(source.session, source.messages);
  315. if (kind === "message")
  316. result.copySources!.messages["copied-0"] = "sibling-message" as never;
  317. if (kind === "part")
  318. result.copySources!.parts["copied-0-0"] = "sibling-part" as never;
  319. if (kind === "collision") {
  320. result.messages[0]!.parts[0]!.id = "sibling-part" as never;
  321. result.copySources!.parts["sibling-part"] = "original-text" as never;
  322. }
  323. return result;
  324. },
  325. }),
  326. ).rejects.toThrow();
  327. expect(await f.store.getSession(childId)).toBeNull();
  328. expect(await f.store.messages({ sessionID: siblingId })).toEqual(before);
  329. } finally {
  330. await f.close();
  331. }
  332. },
  333. );
  334. it("rolls back a throwing or asynchronous planner and releases the transaction", async () => {
  335. const f = await fixture();
  336. try {
  337. await expect(
  338. f.store.commitForkFromSource({
  339. sessionID: parentId,
  340. build() {
  341. throw new Error("planner failed");
  342. },
  343. }),
  344. ).rejects.toThrow("planner failed");
  345. await expect(
  346. f.store.commitForkFromSource({
  347. sessionID: parentId,
  348. build: (async (source) =>
  349. bundle(source.session, source.messages)) as unknown as ForkFromSourceInput["build"],
  350. }),
  351. ).rejects.toThrow("must be synchronous");
  352. expect(await f.store.getSession(childId)).toBeNull();
  353. await expect(
  354. f.store.commitForkFromSource({
  355. sessionID: parentId,
  356. build: (source) => bundle(source.session, source.messages),
  357. }),
  358. ).resolves.toMatchObject({ id: childId });
  359. } finally {
  360. await f.close();
  361. }
  362. });
  363. it("preserves JSON scalar types when rewriting existing metadata", async () => {
  364. const f = await fixture();
  365. try {
  366. const message = (await f.store.messages({ sessionID: parentId }))[0]!;
  367. await f.store.saveMessage({
  368. ...message.info,
  369. metadata: {
  370. flag: false,
  371. nullable: "old",
  372. dropped: 1,
  373. ids: Array.from({ length: 1500 }, (_, index) => `source-${index}`),
  374. },
  375. });
  376. await f.store.commitForkFromSource({
  377. sessionID: parentId,
  378. build(source) {
  379. const result = bundle(source.session, source.messages);
  380. result.messages[0]!.info.metadata = {
  381. ...result.messages[0]!.info.metadata,
  382. flag: true,
  383. ids: Array.from({ length: 1500 }, (_, index) => `child-${index}`),
  384. nullable: null,
  385. dropped: undefined,
  386. };
  387. return result;
  388. },
  389. });
  390. expect((await f.store.messages({ sessionID: childId }))[0]!.info.metadata).toMatchObject({
  391. flag: true,
  392. ids: Array.from({ length: 1500 }, (_, index) => `child-${index}`),
  393. nullable: null,
  394. });
  395. expect((await f.store.messages({ sessionID: childId }))[0]!.info.metadata).not.toHaveProperty(
  396. "dropped",
  397. );
  398. } finally {
  399. await f.close();
  400. }
  401. });
  402. it("keeps legacy hidden reminder text available for model selection", async () => {
  403. const f = await fixture();
  404. try {
  405. const message = (await f.store.messages({ sessionID: parentId }))[0]!;
  406. await f.store.saveMessage({
  407. ...message.info,
  408. semantics: {
  409. origin: "migration",
  410. kind: "system_reminder",
  411. uiVisibility: "hidden",
  412. providerVisibility: "visible",
  413. transcriptVisibility: "hidden",
  414. },
  415. });
  416. await f.store.commitForkFromSource({
  417. sessionID: parentId,
  418. build(source) {
  419. expect(source.messages[0]!.parts[0]).toMatchObject({ text: largeText });
  420. expect(source.messages[0]!.parts[1]).not.toHaveProperty("state.output");
  421. return bundle(source.session, source.messages);
  422. },
  423. });
  424. } finally {
  425. await f.close();
  426. }
  427. });
  428. it("preserves ordering across SQL batches including legacy null sequences", async () => {
  429. const f = await fixture();
  430. try {
  431. for (let index = 0; index < 270; index++) {
  432. const id = `ordered-${index}` as never;
  433. await f.store.saveMessage({
  434. id,
  435. sessionID: parentId,
  436. role: "user",
  437. time: { created: 270 - index },
  438. agent: "build",
  439. tools: {},
  440. });
  441. await f.store.savePart({
  442. id: `text-${index}` as never,
  443. sessionID: parentId,
  444. messageID: id,
  445. type: "text",
  446. text: String(index),
  447. });
  448. }
  449. const raw = new DatabaseSync(f.dbPath);
  450. raw.exec("update message set sequence=null where id in ('ordered-1', 'ordered-2')");
  451. raw.close();
  452. const before = await f.store.messages({ sessionID: parentId });
  453. const db = (f.store as unknown as { db: DatabaseSync }).db;
  454. const prepare = db.prepare.bind(db);
  455. const copyPlans: string[][] = [];
  456. db.prepare = (sql) => {
  457. const statement = prepare(sql);
  458. if (sql.includes("from json_each(?) plan")) {
  459. const run = statement.run.bind(statement);
  460. statement.run = (...args) => {
  461. const plan = prepare(`explain query plan ${sql}`).all(...args);
  462. copyPlans.push(plan.map((row) => String(row.detail)));
  463. return run(...args);
  464. };
  465. }
  466. return statement;
  467. };
  468. await f.store.commitForkFromSource({
  469. sessionID: parentId,
  470. build: (source) => bundle(source.session, source.messages),
  471. });
  472. expect(copyPlans.length).toBeGreaterThan(0);
  473. for (const plan of copyPlans) {
  474. expect(plan[0]).toMatch(/SCAN plan/);
  475. expect(plan[1]).toMatch(/SEARCH source USING INDEX .* \(id=\?\)/);
  476. }
  477. const after = await f.store.messages({ sessionID: childId });
  478. expect(
  479. after.map((message) => (message.parts[0]!.type === "text" ? message.parts[0]!.text : "")),
  480. ).toEqual(
  481. before.map((message) => (message.parts[0]!.type === "text" ? message.parts[0]!.text : "")),
  482. );
  483. expect(after.map((message) => message.info.metadata?.forkOrigin?.messageId)).toEqual(
  484. before.map((message) => message.info.id),
  485. );
  486. } finally {
  487. await f.close();
  488. }
  489. });
  490. });