provider-database-migration.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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: 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 张业务表全部有覆盖,无关表、账本旧记录与外键关系不变", () => {
  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 = 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 语义,原值本身不修改", () => {
  95. entry({ providerId: ` ${legacyProvider} `, modelId: " GLM-5.3 ", thoughtLevel: " high " });
  96. store = 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 = createSqliteSessionStore({ dbPath: path });
  153. expect(store.debugMigrationIds()).toContain(migrationId);
  154. expect(store.debugMigrationIds().at(-1)).toBe("0022_backfilled_session_reasoning");
  155. expect(raw("session_entry", "selection")).toEqual({
  156. ...oldEntry,
  157. modelSelection: currentSelection,
  158. });
  159. expect(raw("message", "user")).toEqual({ ...oldUser, modelSelection: historicalSelection });
  160. expect(raw("message", "assistant")).toEqual({
  161. ...oldAssistant,
  162. providerId: legacyProvider,
  163. modelId: "GLM-5.3",
  164. reasoningLevel: "high",
  165. });
  166. expect(raw("part", "timeline")).toEqual({
  167. ...parts[1]!.value,
  168. fromModelSelection: historicalSelection,
  169. toModelSelection: { ...historicalSelection, label: "GLM" },
  170. });
  171. expect(raw("part", "subtask")).toMatchObject({
  172. ...parts[2]!.value,
  173. modelSelection: historicalSelection,
  174. });
  175. expect(raw("part", "body")).toEqual(parts[0]!.value);
  176. expect(db.prepare("SELECT * FROM session").get()).toEqual(sessionBefore);
  177. const history = await store.messages({ sessionID });
  178. expect(history[0]?.info).not.toHaveProperty("model");
  179. expect(history[1]?.info).not.toHaveProperty("providerID");
  180. expect(history[1]?.parts.find((part) => part.id === "timeline")).toMatchObject({
  181. toModel: { ...historicalSelection, label: "GLM" },
  182. });
  183. });
  184. it("DB109-03/10:再升级缺新字段不补迁,历史正文仍然可读", async () => {
  185. message("user", { role: "user", time: { created: 11 }, agent: "main", model: oldModel });
  186. store = createSqliteSessionStore({ dbPath: path });
  187. expect(store.debugMigrationIds()).toContain(migrationId);
  188. store.close();
  189. db.prepare("UPDATE message SET data=json_remove(data,'$.modelSelection')").run();
  190. db.prepare("UPDATE session_entry SET data=json_remove(data,'$.modelSelection')").run();
  191. message(
  192. "after-rollback",
  193. { role: "user", time: { created: 13 }, agent: "main", model: oldModel },
  194. 3,
  195. );
  196. store = createSqliteSessionStore({ dbPath: path });
  197. const history = await store.messages({ sessionID });
  198. expect(history).toHaveLength(2);
  199. expect(history.every((item) => !("modelSelection" in item.info))).toBe(true);
  200. expect((await store.getSession(sessionID))?.title).toBe("旧会话内容");
  201. expect(raw("message", "user")).not.toHaveProperty("modelSelection");
  202. });
  203. it("DB109-04:有明确旧来源时重建目标新字段,未知身份留空而不丢来源", () => {
  204. entry({
  205. providerId: legacyProvider,
  206. modelId: "GLM-5.3",
  207. thoughtLevel: "high",
  208. modelSelection: null,
  209. });
  210. store = createSqliteSessionStore({ dbPath: path });
  211. expect(raw("session_entry", "selection").modelSelection).toEqual(currentSelection);
  212. });
  213. it("DB109-05:数据写入失败回滚整个 migration,移除故障后可重试", () => {
  214. entry({ providerId: legacyProvider, modelId: "GLM-5.3", thoughtLevel: "high" });
  215. const before = db.prepare("SELECT * FROM session_entry").all();
  216. db.exec(
  217. "CREATE TRIGGER reject_entry BEFORE UPDATE ON session_entry BEGIN SELECT RAISE(ABORT,'db109 write failure'); END",
  218. );
  219. expect(() => createSqliteSessionStore({ dbPath: path })).toThrow();
  220. expect(db.prepare("SELECT * FROM session_entry").all()).toEqual(before);
  221. expect(
  222. db.prepare("SELECT id FROM schema_migration WHERE id=?").get(migrationId),
  223. ).toBeUndefined();
  224. db.exec("DROP TRIGGER reject_entry");
  225. store = createSqliteSessionStore({ dbPath: path });
  226. expect(raw("session_entry", "selection").modelSelection).toEqual(currentSelection);
  227. });
  228. it("DB109-09/12:新模型切换保留旧 Reader 必需的 toModel,更新保留旧快照但正常替换新字段", async () => {
  229. message("user", {
  230. role: "user",
  231. time: { created: 11 },
  232. agent: "main",
  233. model: oldModel,
  234. metadata: { removable: true },
  235. });
  236. store = createSqliteSessionStore({ dbPath: path });
  237. const first = (await store.messages({ sessionID }))[0]!.info;
  238. await store.saveMessage({ ...first, metadata: {}, modelSelection: undefined } as typeof first);
  239. expect(raw("message", "user").model).toEqual(oldModel);
  240. expect(raw("message", "user").metadata).toEqual({});
  241. const part = {
  242. id: "new-switch" as ReturnType<typeof createPartId>,
  243. messageID: first.id,
  244. sessionID,
  245. type: "timeline" as const,
  246. timelineType: "model_change" as const,
  247. toModel: { ...currentSelection, label: "GLM" },
  248. time: { start: 11, end: 12 },
  249. };
  250. await store.savePart(part);
  251. const disk = raw("part", "new-switch");
  252. expect(disk.toModelSelection).toEqual(part.toModel);
  253. // 来源:staging_backup transcript-hydration.ts 的旧 Reader 直接解引用 toModel。
  254. expect(() => String(disk.toModel.providerID)).not.toThrow();
  255. expect(disk.toModel.providerID).toBe(currentSelection.providerId);
  256. await store.savePart({
  257. ...part,
  258. toModel: { providerId: "custom", modelId: "next", label: "Next" },
  259. });
  260. expect(raw("part", "new-switch").toModel).toEqual(disk.toModel);
  261. expect(raw("part", "new-switch").toModelSelection).toEqual({
  262. providerId: "custom",
  263. modelId: "next",
  264. label: "Next",
  265. });
  266. await store.saveMessage(
  267. { ...first, id: "copied-user" as typeof first.id },
  268. { sessionID, id: first.id },
  269. );
  270. expect(raw("message", "copied-user").model).toEqual(oldModel);
  271. await store.savePart(
  272. { ...part, id: "copied-part" as typeof part.id },
  273. { sessionID, id: part.id },
  274. );
  275. expect(raw("part", "copied-part").toModel).toEqual(disk.toModel);
  276. });
  277. it("DB109-09:新版新增/无模型的用户消息经冻结旧协议 Reader 仍可打开正文", async () => {
  278. store = createSqliteSessionStore({ dbPath: path });
  279. for (const selection of [undefined, currentSelection]) {
  280. const id = (selection ? "new-selected" : "new-empty") as Parameters<
  281. typeof store.saveMessage
  282. >[0]["id"];
  283. await store.saveMessage({
  284. id,
  285. sessionID,
  286. role: "user",
  287. time: { created: 15 },
  288. agent: "main",
  289. modelSelection: selection,
  290. });
  291. const content = { type: "text", text: "正文不能因选型格式而打不开" };
  292. const mapped = oldMap({ info: { ...raw("message", id), id, sessionID }, parts: [content] });
  293. expect(mapped.parts[0].text).toBe(content.text);
  294. }
  295. const id = "timeline-parent" as Parameters<typeof store.saveMessage>[0]["id"];
  296. await store.saveMessage({ id, sessionID, role: "user", time: { created: 16 }, agent: "main" });
  297. await store.savePart({
  298. id: "empty-switch" as ReturnType<typeof createPartId>,
  299. messageID: id,
  300. sessionID,
  301. type: "timeline",
  302. timelineType: "model_change",
  303. time: { start: 16, end: 17 },
  304. });
  305. const history = { info: raw("message", id), parts: [raw("part", "empty-switch")] };
  306. expect(() => oldMap(history)).not.toThrow();
  307. expect(() => oldTimeline(history)).not.toThrow();
  308. });
  309. it("DB109-12:原子 fork 从父记录搬运旧快照,新子选择与旧快照彼此独立", async () => {
  310. message("parent-user", { role: "user", time: { created: 11 }, agent: "main", model: oldModel });
  311. db.prepare(
  312. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES(?,?,?,?,?,?)",
  313. ).run(
  314. "parent-part",
  315. "parent-user",
  316. sessionID,
  317. 11,
  318. 12,
  319. JSON.stringify({
  320. type: "subtask",
  321. prompt: "子任务正文",
  322. description: "旧描述",
  323. agent: "worker",
  324. model: oldModel,
  325. }),
  326. );
  327. store = createSqliteSessionStore({ dbPath: path });
  328. const source = (await store.messages({ sessionID }))[0]!;
  329. const childId = createSessionId("copy-child"),
  330. messageId = createMessageId("copy-message"),
  331. partId = createPartId("copy-part");
  332. const childMessage = {
  333. ...source.info,
  334. id: messageId,
  335. sessionID: childId,
  336. modelSelection: currentSelection,
  337. };
  338. const childPart = { ...source.parts[0]!, id: partId, messageID: messageId, sessionID: childId };
  339. await store.commitForkBundle!({
  340. child: {
  341. id: childId,
  342. parentID: sessionID,
  343. projectID: createProjectId("project"),
  344. slug: "copy-child",
  345. directory: root,
  346. title: "副本",
  347. version: "test",
  348. },
  349. messages: [{ info: childMessage, parts: [childPart] }],
  350. entries: [],
  351. copySources: {
  352. messages: { [messageId]: source.info.id },
  353. parts: { [partId]: source.parts[0]!.id },
  354. },
  355. commandFact: {
  356. parentSessionId: sessionID,
  357. sourceCommandId: "copy-command",
  358. ack: {
  359. commandId: "copy-command",
  360. status: "accepted",
  361. revisionAtDecision: 1,
  362. result: { type: "editUserQuery", disposition: "fork", sessionId: childId },
  363. },
  364. metadata: { source: "compact-edit" },
  365. },
  366. });
  367. expect(raw("message", messageId).model).toEqual(oldModel);
  368. expect(raw("message", messageId).modelSelection).toEqual(currentSelection);
  369. expect(raw("part", partId).model).toEqual(oldModel);
  370. expect((await store.messages({ sessionID: childId }))[0]?.parts[0]).toMatchObject({
  371. prompt: "子任务正文",
  372. model: historicalSelection,
  373. });
  374. expect(db.prepare("PRAGMA foreign_key_check").all()).toEqual([]);
  375. });
  376. });