provider-database-migration.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import { createHash } from "node:crypto";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { DatabaseSync } from "node:sqlite";
  6. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  7. import { createSessionId, createPartId, createMessageId, createProjectId } from "@zcode/contracts";
  8. import { SQLITE_MIGRATIONS } from "../src/storage/session-store/migrations.js";
  9. import { createSqliteSessionStore } from "../src/storage/session-store/sqlite-session-store.js";
  10. import { seedUnrelatedProviderTables } from "./fixtures/provider-migration-unrelated-tables.js";
  11. import {
  12. mapMessageWithParts as oldMap,
  13. modelChangeToModelOf as oldTimeline,
  14. } from "./fixtures/staging-backup-model-readers.mjs";
  15. const migrationId = "0020_provider_model_selection";
  16. const sessionID = createSessionId("provider-migration-session");
  17. const legacyProvider = "builtin:bigmodel-coding-plan";
  18. const historicalSelection = {
  19. providerId: legacyProvider,
  20. modelId: "GLM-5.3",
  21. options: { reasoningLevel: "high" },
  22. };
  23. const currentSelection = {
  24. ...historicalSelection,
  25. providerId: "account:bigmodel-individual-coding-plan",
  26. };
  27. describe("DB109 会话库正式数据迁移", () => {
  28. let root: string;
  29. let path: string;
  30. let db: DatabaseSync;
  31. let store: Awaited<ReturnType<typeof createSqliteSessionStore>> | undefined;
  32. beforeEach(async () => {
  33. root = await mkdtemp(join(tmpdir(), "zcode-db109-"));
  34. path = join(root, "session.sqlite");
  35. db = new DatabaseSync(path);
  36. db.exec("PRAGMA foreign_keys=ON");
  37. db.exec(
  38. "CREATE TABLE schema_migration(id TEXT PRIMARY KEY, checksum TEXT NOT NULL, app_version TEXT, time_applied INTEGER NOT NULL)",
  39. );
  40. // 直接播种发布格式,不能先过新版 Writer 再冒充旧数据。
  41. for (const migration of SQLITE_MIGRATIONS.filter((item) => item.id < migrationId)) {
  42. db.exec(migration.sql);
  43. db.prepare("INSERT INTO schema_migration VALUES(?,?,?,?)").run(
  44. migration.id,
  45. createHash("sha256").update(migration.sql.trim()).digest("hex"),
  46. migration.appVersion,
  47. 1,
  48. );
  49. }
  50. db.prepare(
  51. "INSERT INTO session(id,project_id,slug,directory,title,version,time_created,time_updated) VALUES(?,?,?,?,?,?,?,?)",
  52. ).run(sessionID, "project", "old", root, "旧会话内容", "old", 11, 12);
  53. });
  54. afterEach(async () => {
  55. store?.close();
  56. store = undefined;
  57. db.close();
  58. await rm(root, { recursive: true, force: true });
  59. });
  60. const raw = (table: "message" | "part" | "session_entry", id: string) =>
  61. JSON.parse(String(db.prepare(`SELECT data FROM ${table} WHERE id=?`).get(id)?.data));
  62. const message = (id: string, value: unknown, sequence = 1) =>
  63. db
  64. .prepare(
  65. "INSERT INTO message(id,session_id,time_created,time_updated,data,sequence) VALUES(?,?,?,?,?,?)",
  66. )
  67. .run(id, sessionID, 11, 12, JSON.stringify(value), sequence);
  68. const entry = (value: unknown) =>
  69. db
  70. .prepare("INSERT INTO session_entry VALUES(?,?,?,?,?,?)")
  71. .run("selection", sessionID, "runtime/model_selection", 11, 12, JSON.stringify(value));
  72. const oldModel = { providerID: legacyProvider, modelID: "GLM-5.3", variant: "high" };
  73. it("DB109-01/11:22 张业务表全部有覆盖,无关表、账本旧记录与外键关系不变", async () => {
  74. const unrelated = seedUnrelatedProviderTables(db, sessionID);
  75. const allTables = db
  76. .prepare(
  77. "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name!='schema_migration'",
  78. )
  79. .all()
  80. .map((row) => row.name)
  81. .sort();
  82. expect(allTables).toEqual([...unrelated, "session", "session_entry", "message", "part"].sort());
  83. expect(allTables).toHaveLength(22);
  84. const before = unrelated.map((table) => db.prepare(`SELECT * FROM ${table}`).all());
  85. const ledger = db.prepare("SELECT * FROM schema_migration ORDER BY id").all();
  86. entry({ providerId: legacyProvider, modelId: "GLM-5.3" });
  87. store = await createSqliteSessionStore({ dbPath: path });
  88. expect(unrelated.map((table) => db.prepare(`SELECT * FROM ${table}`).all())).toEqual(before);
  89. expect(
  90. db.prepare("SELECT * FROM schema_migration WHERE id<? ORDER BY id").all(migrationId),
  91. ).toEqual(ledger);
  92. expect(db.prepare("PRAGMA foreign_key_check").all()).toEqual([]);
  93. });
  94. it("DB109-04:当前选择保留旧 parser 的 trim 语义,原值本身不修改", async () => {
  95. entry({ providerId: ` ${legacyProvider} `, modelId: " GLM-5.3 ", thoughtLevel: " high " });
  96. store = await createSqliteSessionStore({ dbPath: path });
  97. expect(raw("session_entry", "selection").modelSelection).toEqual(currentSelection);
  98. expect(raw("session_entry", "selection").providerId).toBe(` ${legacyProvider} `);
  99. });
  100. it("DB109-01/11:一次迁移保留旧成员、正文、来源和元数据,Part 新旧分开存", async () => {
  101. const oldUser = {
  102. role: "user",
  103. time: { created: 11 },
  104. agent: "main",
  105. model: oldModel,
  106. note: { keep: true },
  107. };
  108. const oldAssistant = {
  109. role: "assistant",
  110. time: { created: 11 },
  111. providerID: legacyProvider,
  112. modelID: "GLM-5.3",
  113. variant: "high",
  114. };
  115. message("user", oldUser);
  116. message("assistant", oldAssistant, 2);
  117. const oldEntry = {
  118. providerId: legacyProvider,
  119. modelId: "GLM-5.3",
  120. thoughtLevel: "high",
  121. keep: [1, 2],
  122. };
  123. entry(oldEntry);
  124. const parts = [
  125. { id: "body", value: { type: "text", text: "正文绝不能丢失" } },
  126. {
  127. id: "timeline",
  128. value: {
  129. type: "timeline",
  130. timelineType: "model_change",
  131. toModel: { ...oldModel, label: "GLM" },
  132. fromModel: oldModel,
  133. },
  134. },
  135. {
  136. id: "subtask",
  137. value: {
  138. type: "subtask",
  139. prompt: "子任务正文",
  140. description: "说明",
  141. agent: "worker",
  142. model: oldModel,
  143. },
  144. },
  145. ];
  146. for (const [index, part] of parts.entries()) {
  147. db.prepare(
  148. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data,sequence) VALUES(?,?,?,?,?,?,?)",
  149. ).run(part.id, "assistant", sessionID, 11, 12, JSON.stringify(part.value), index);
  150. }
  151. const sessionBefore = db.prepare("SELECT * FROM session").get();
  152. store = await createSqliteSessionStore({ dbPath: path });
  153. expect(store.debugMigrationIds()).toContain(migrationId);
  154. expect(store.debugMigrationIds()).toEqual(
  155. expect.arrayContaining([
  156. "0023_session_soft_delete_outcome",
  157. "0024_session_database_identity",
  158. ]),
  159. );
  160. expect(raw("session_entry", "selection")).toEqual({
  161. ...oldEntry,
  162. modelSelection: currentSelection,
  163. });
  164. expect(raw("message", "user")).toEqual({ ...oldUser, modelSelection: historicalSelection });
  165. expect(raw("message", "assistant")).toEqual({
  166. ...oldAssistant,
  167. providerId: legacyProvider,
  168. modelId: "GLM-5.3",
  169. reasoningLevel: "high",
  170. });
  171. expect(raw("part", "timeline")).toEqual({
  172. ...parts[1]!.value,
  173. fromModelSelection: historicalSelection,
  174. toModelSelection: { ...historicalSelection, label: "GLM" },
  175. });
  176. expect(raw("part", "subtask")).toMatchObject({
  177. ...parts[2]!.value,
  178. modelSelection: historicalSelection,
  179. });
  180. expect(raw("part", "body")).toEqual(parts[0]!.value);
  181. expect(db.prepare("SELECT * FROM session").get()).toEqual({
  182. ...sessionBefore,
  183. time_deleted: null,
  184. last_outcome: null,
  185. });
  186. const history = await store.messages({ sessionID });
  187. expect(history[0]?.info).not.toHaveProperty("model");
  188. expect(history[1]?.info).not.toHaveProperty("providerID");
  189. expect(history[1]?.parts.find((part) => part.id === "timeline")).toMatchObject({
  190. toModel: { ...historicalSelection, label: "GLM" },
  191. });
  192. });
  193. it("DB109-03/10:再升级缺新字段不补迁,历史正文仍然可读", async () => {
  194. message("user", { role: "user", time: { created: 11 }, agent: "main", model: oldModel });
  195. store = await createSqliteSessionStore({ dbPath: path });
  196. expect(store.debugMigrationIds()).toContain(migrationId);
  197. store.close();
  198. db.prepare("UPDATE message SET data=json_remove(data,'$.modelSelection')").run();
  199. db.prepare("UPDATE session_entry SET data=json_remove(data,'$.modelSelection')").run();
  200. message(
  201. "after-rollback",
  202. { role: "user", time: { created: 13 }, agent: "main", model: oldModel },
  203. 3,
  204. );
  205. store = await createSqliteSessionStore({ dbPath: path });
  206. const history = await store.messages({ sessionID });
  207. expect(history).toHaveLength(2);
  208. expect(history.every((item) => !("modelSelection" in item.info))).toBe(true);
  209. expect((await store.getSession(sessionID))?.title).toBe("旧会话内容");
  210. expect(raw("message", "user")).not.toHaveProperty("modelSelection");
  211. });
  212. it("DB109-04:有明确旧来源时重建目标新字段,未知身份留空而不丢来源", async () => {
  213. entry({
  214. providerId: legacyProvider,
  215. modelId: "GLM-5.3",
  216. thoughtLevel: "high",
  217. modelSelection: null,
  218. });
  219. store = await createSqliteSessionStore({ dbPath: path });
  220. expect(raw("session_entry", "selection").modelSelection).toEqual(currentSelection);
  221. });
  222. it("DB109-05:数据写入失败回滚整个 migration,移除故障后可重试", async () => {
  223. entry({ providerId: legacyProvider, modelId: "GLM-5.3", thoughtLevel: "high" });
  224. const before = db.prepare("SELECT * FROM session_entry").all();
  225. db.exec(
  226. "CREATE TRIGGER reject_entry BEFORE UPDATE ON session_entry BEGIN SELECT RAISE(ABORT,'db109 write failure'); END",
  227. );
  228. await expect(createSqliteSessionStore({ dbPath: path })).rejects.toThrow();
  229. expect(db.prepare("SELECT * FROM session_entry").all()).toEqual(before);
  230. expect(
  231. db.prepare("SELECT id FROM schema_migration WHERE id=?").get(migrationId),
  232. ).toBeUndefined();
  233. db.exec("DROP TRIGGER reject_entry");
  234. store = await createSqliteSessionStore({ dbPath: path });
  235. expect(raw("session_entry", "selection").modelSelection).toEqual(currentSelection);
  236. });
  237. it("DB109-09/12:新模型切换保留旧 Reader 必需的 toModel,更新保留旧快照但正常替换新字段", async () => {
  238. message("user", {
  239. role: "user",
  240. time: { created: 11 },
  241. agent: "main",
  242. model: oldModel,
  243. metadata: { removable: true },
  244. });
  245. store = await createSqliteSessionStore({ dbPath: path });
  246. const first = (await store.messages({ sessionID }))[0]!.info;
  247. await store.saveMessage({ ...first, metadata: {}, modelSelection: undefined } as typeof first);
  248. expect(raw("message", "user").model).toEqual(oldModel);
  249. expect(raw("message", "user").metadata).toEqual({});
  250. const part = {
  251. id: "new-switch" as ReturnType<typeof createPartId>,
  252. messageID: first.id,
  253. sessionID,
  254. type: "timeline" as const,
  255. timelineType: "model_change" as const,
  256. toModel: { ...currentSelection, label: "GLM" },
  257. time: { start: 11, end: 12 },
  258. };
  259. await store.savePart(part);
  260. const disk = raw("part", "new-switch");
  261. expect(disk.toModelSelection).toEqual(part.toModel);
  262. // 来源:staging_backup transcript-hydration.ts 的旧 Reader 直接解引用 toModel。
  263. expect(() => String(disk.toModel.providerID)).not.toThrow();
  264. expect(disk.toModel.providerID).toBe(currentSelection.providerId);
  265. await store.savePart({
  266. ...part,
  267. toModel: { providerId: "custom", modelId: "next", label: "Next" },
  268. });
  269. expect(raw("part", "new-switch").toModel).toEqual(disk.toModel);
  270. expect(raw("part", "new-switch").toModelSelection).toEqual({
  271. providerId: "custom",
  272. modelId: "next",
  273. label: "Next",
  274. });
  275. await store.saveMessage(
  276. { ...first, id: "copied-user" as typeof first.id },
  277. { sessionID, id: first.id },
  278. );
  279. expect(raw("message", "copied-user").model).toEqual(oldModel);
  280. await store.savePart(
  281. { ...part, id: "copied-part" as typeof part.id },
  282. { sessionID, id: part.id },
  283. );
  284. expect(raw("part", "copied-part").toModel).toEqual(disk.toModel);
  285. });
  286. it("DB109-09:新版新增/无模型的用户消息经冻结旧协议 Reader 仍可打开正文", async () => {
  287. store = await createSqliteSessionStore({ dbPath: path });
  288. for (const selection of [undefined, currentSelection]) {
  289. const id = (selection ? "new-selected" : "new-empty") as Parameters<
  290. typeof store.saveMessage
  291. >[0]["id"];
  292. await store.saveMessage({
  293. id,
  294. sessionID,
  295. role: "user",
  296. time: { created: 15 },
  297. agent: "main",
  298. modelSelection: selection,
  299. });
  300. const content = { type: "text", text: "正文不能因选型格式而打不开" };
  301. const mapped = oldMap({ info: { ...raw("message", id), id, sessionID }, parts: [content] });
  302. expect(mapped.parts[0].text).toBe(content.text);
  303. }
  304. const id = "timeline-parent" as Parameters<typeof store.saveMessage>[0]["id"];
  305. await store.saveMessage({ id, sessionID, role: "user", time: { created: 16 }, agent: "main" });
  306. await store.savePart({
  307. id: "empty-switch" as ReturnType<typeof createPartId>,
  308. messageID: id,
  309. sessionID,
  310. type: "timeline",
  311. timelineType: "model_change",
  312. time: { start: 16, end: 17 },
  313. });
  314. const history = { info: raw("message", id), parts: [raw("part", "empty-switch")] };
  315. expect(() => oldMap(history)).not.toThrow();
  316. expect(() => oldTimeline(history)).not.toThrow();
  317. });
  318. it("DB109-12:原子 fork 从父记录搬运旧快照,新子选择与旧快照彼此独立", async () => {
  319. message("parent-user", { role: "user", time: { created: 11 }, agent: "main", model: oldModel });
  320. db.prepare(
  321. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES(?,?,?,?,?,?)",
  322. ).run(
  323. "parent-part",
  324. "parent-user",
  325. sessionID,
  326. 11,
  327. 12,
  328. JSON.stringify({
  329. type: "subtask",
  330. prompt: "子任务正文",
  331. description: "旧描述",
  332. agent: "worker",
  333. model: oldModel,
  334. }),
  335. );
  336. store = await createSqliteSessionStore({ dbPath: path });
  337. const source = (await store.messages({ sessionID }))[0]!;
  338. const childId = createSessionId("copy-child"),
  339. messageId = createMessageId("copy-message"),
  340. partId = createPartId("copy-part");
  341. const childMessage = {
  342. ...source.info,
  343. id: messageId,
  344. sessionID: childId,
  345. modelSelection: currentSelection,
  346. };
  347. const childPart = { ...source.parts[0]!, id: partId, messageID: messageId, sessionID: childId };
  348. await store.commitForkBundle!({
  349. child: {
  350. id: childId,
  351. parentID: sessionID,
  352. projectID: createProjectId("project"),
  353. slug: "copy-child",
  354. directory: root,
  355. title: "副本",
  356. version: "test",
  357. },
  358. messages: [{ info: childMessage, parts: [childPart] }],
  359. entries: [],
  360. copySources: {
  361. messages: { [messageId]: source.info.id },
  362. parts: { [partId]: source.parts[0]!.id },
  363. },
  364. commandFact: {
  365. parentSessionId: sessionID,
  366. sourceCommandId: "copy-command",
  367. ack: {
  368. commandId: "copy-command",
  369. status: "accepted",
  370. revisionAtDecision: 1,
  371. result: { type: "editUserQuery", disposition: "fork", sessionId: childId },
  372. },
  373. metadata: { source: "compact-edit" },
  374. },
  375. });
  376. expect(raw("message", messageId).model).toEqual(oldModel);
  377. expect(raw("message", messageId).modelSelection).toEqual(currentSelection);
  378. expect(raw("part", partId).model).toEqual(oldModel);
  379. expect((await store.messages({ sessionID: childId }))[0]?.parts[0]).toMatchObject({
  380. prompt: "子任务正文",
  381. model: historicalSelection,
  382. });
  383. expect(db.prepare("PRAGMA foreign_key_check").all()).toEqual([]);
  384. });
  385. });