frozen-migration-startup.test.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import { createHash } from "node:crypto";
  2. import { DatabaseSync } from "node:sqlite";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import { SQLITE_MIGRATIONS } from "../src/storage/session-store/migrations.js";
  5. import {
  6. runSqliteSessionMigrations,
  7. runSqliteSessionMigrationsAsync,
  8. } from "../src/storage/session-store/migration-runner.js";
  9. const SELECTION = "0020_provider_model_selection";
  10. const REASONING = "0022_backfilled_session_reasoning";
  11. const APPLIED_AT = 1_000;
  12. const databases: DatabaseSync[] = [];
  13. const checksum = (sql: string) => createHash("sha256").update(sql.trim()).digest("hex");
  14. const legacy = { providerID: "builtin:bigmodel-coding-plan", modelID: "glm-5.3", variant: "high" };
  15. function createFixture() {
  16. const db = new DatabaseSync(":memory:");
  17. databases.push(db);
  18. db.exec(
  19. "PRAGMA foreign_keys=ON; CREATE TABLE schema_migration(id TEXT PRIMARY KEY, checksum TEXT NOT NULL, app_version TEXT, time_applied INTEGER NOT NULL)",
  20. );
  21. applyFrozen(db, SELECTION);
  22. return db;
  23. }
  24. function applyFrozen(db: DatabaseSync, before = "9999") {
  25. for (const migration of SQLITE_MIGRATIONS.filter((m) => m.id < before)) {
  26. if (db.prepare("SELECT 1 FROM schema_migration WHERE id=?").get(migration.id)) continue;
  27. db.exec(migration.sql);
  28. db.prepare("INSERT INTO schema_migration VALUES(?,?,?,?)").run(
  29. migration.id,
  30. checksum(migration.sql),
  31. migration.appVersion,
  32. APPLIED_AT,
  33. );
  34. }
  35. }
  36. function seedSession(db: DatabaseSync, id: string) {
  37. db.prepare(
  38. "INSERT INTO session(id,project_id,slug,directory,title,version,time_created,time_updated) VALUES(?,?,?,?,?,?,?,?)",
  39. ).run(id, "project", id, "/fixture", "历史正文", "old", 1, 2);
  40. }
  41. function message(db: DatabaseSync, session: string, id: string, data: unknown, sequence = 1) {
  42. db.prepare(
  43. "INSERT INTO message(id,session_id,time_created,time_updated,data,sequence) VALUES(?,?,?,?,?,?)",
  44. ).run(id, session, 10, 12, JSON.stringify(data), sequence);
  45. }
  46. function entry(db: DatabaseSync, session: string, data: unknown) {
  47. db.prepare(
  48. "INSERT INTO session_entry(id,session_id,type,time_created,time_updated,data) VALUES(?,?,?,?,?,?)",
  49. ).run(
  50. `${session}:runtime-model-selection`,
  51. session,
  52. "runtime/model_selection",
  53. 1,
  54. 2,
  55. JSON.stringify(data),
  56. );
  57. }
  58. function snapshot(db: DatabaseSync) {
  59. return Object.fromEntries(
  60. ["session", "message", "part", "session_entry", "schema_migration"].map((table) => [
  61. table,
  62. db.prepare(`SELECT * FROM ${table} ORDER BY id`).all(),
  63. ]),
  64. );
  65. }
  66. function seedSelections(db: DatabaseSync) {
  67. const models = [
  68. undefined,
  69. null,
  70. {},
  71. legacy,
  72. { ...legacy, label: "标签", unknown: { body: "保留" } },
  73. { providerID: null },
  74. { providerID: 3, modelID: "x" },
  75. { providerID: " p ", modelID: " m ", variant: " " },
  76. { providerId: "new", modelId: "new" },
  77. ];
  78. for (const [i, model] of models.entries()) {
  79. const session = `session-${i}`;
  80. seedSession(db, session);
  81. message(db, session, `user-${i}`, { role: "user", model, unknown: ["正文", 1] });
  82. message(
  83. db,
  84. session,
  85. `assistant-${i}`,
  86. { role: "assistant", ...legacy, providerId: "existing", reasoningLevel: "low" },
  87. 2,
  88. );
  89. for (const [j, toModel] of models.entries()) {
  90. const data = {
  91. type: "timeline",
  92. timelineType: "model_change",
  93. fromModel: model,
  94. toModel,
  95. fromModelSelection: { existing: true },
  96. unknown: { text: "正文", file: "attachment://ref" },
  97. };
  98. db.prepare(
  99. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES(?,?,?,?,?,?)",
  100. ).run(`part-${i}-${j}`, `user-${i}`, session, 11, 13, JSON.stringify(data));
  101. }
  102. for (const [j, type] of ["subtask", "text", "tool"].entries()) {
  103. db.prepare(
  104. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES(?,?,?,?,?,?)",
  105. ).run(
  106. `sub-${i}-${j}`,
  107. `user-${i}`,
  108. session,
  109. 11,
  110. 13,
  111. JSON.stringify({ type, model, text: "不可删除", modelSelection: null }),
  112. );
  113. }
  114. }
  115. seedSession(db, "explicit-null");
  116. message(db, "explicit-null", "null-old", { role: "user", model: legacy });
  117. // sequence/time_created 相同:必须按 rowid 选最后明确来源,不越过 null。
  118. message(db, "explicit-null", "null-new", { role: "user", modelSelection: null });
  119. seedSession(db, "entry");
  120. entry(db, "entry", { providerId: "custom", modelId: "x", thoughtLevel: "max", unknown: true });
  121. seedSession(db, "bad");
  122. message(db, "bad", "bad-json", {});
  123. db.exec("UPDATE message SET data='{' WHERE id='bad-json'");
  124. db.prepare(
  125. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data) VALUES(?,?,?,?,?,?)",
  126. ).run("bad-part", "bad-json", "bad", 1, 2, "{");
  127. }
  128. afterEach(() => {
  129. vi.restoreAllMocks();
  130. for (const db of databases.splice(0)) db.close();
  131. });
  132. describe("Todo144:启动 runner 保持冻结迁移合同", () => {
  133. it.each(["sync", "async"])(
  134. "%s 启动执行原迁移:所有行、JSON、旧字段、时间与账本一致",
  135. async (mode) => {
  136. vi.spyOn(Date, "now").mockReturnValue(APPLIED_AT);
  137. const oldDb = createFixture();
  138. const nextDb = createFixture();
  139. for (const db of [oldDb, nextDb]) seedSelections(db);
  140. applyFrozen(oldDb);
  141. if (mode === "async") await runSqliteSessionMigrationsAsync(nextDb, ":memory:");
  142. else runSqliteSessionMigrations(nextDb, ":memory:");
  143. expect(snapshot(nextDb)).toEqual(snapshot(oldDb));
  144. expect(nextDb.prepare("SELECT count(*) AS n FROM part").get()?.n).toBe(109);
  145. },
  146. );
  147. it("已迁移的原账本可反复读取;用户清空新选择后不重迁", () => {
  148. const db = createFixture();
  149. seedSelections(db);
  150. applyFrozen(db);
  151. db.exec("UPDATE session_entry SET data=json_set(data,'$.modelSelection',NULL)");
  152. const before = snapshot(db);
  153. runSqliteSessionMigrations(db, ":memory:");
  154. applyFrozen(db);
  155. expect(snapshot(db)).toEqual(before);
  156. });
  157. it("checksum 不符仍失败并回滚,不篡改账本", () => {
  158. const db = createFixture();
  159. applyFrozen(db);
  160. db.prepare("UPDATE schema_migration SET checksum='changed' WHERE id=?").run(SELECTION);
  161. const before = snapshot(db);
  162. expect(() => runSqliteSessionMigrations(db, ":memory:")).toThrow(/checksum mismatch/);
  163. expect(snapshot(db)).toEqual(before);
  164. });
  165. it("原 SQL 遇到 trigger 拒绝写入时整笔回滚,重试可恢复", () => {
  166. const db = createFixture();
  167. seedSelections(db);
  168. db.exec(
  169. "CREATE TRIGGER reject_part BEFORE UPDATE ON part BEGIN SELECT RAISE(ABORT,'fixture failure'); END",
  170. );
  171. const before = snapshot(db);
  172. expect(() => runSqliteSessionMigrations(db, ":memory:")).toThrow(/migration/);
  173. expect(snapshot(db)).toEqual(before);
  174. expect(db.isTransaction).toBe(false);
  175. db.exec("DROP TRIGGER reject_part");
  176. runSqliteSessionMigrations(db, ":memory:");
  177. expect(db.prepare("SELECT 1 FROM schema_migration WHERE id=?").get(REASONING)).toBeDefined();
  178. });
  179. });