session-reasoning-repair-migration.test.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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 } 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. const REPAIR_ID = "0022_backfilled_session_reasoning";
  11. const ORIGINAL_ID = "0020_provider_model_selection";
  12. const APPLIED_AT = 1_000;
  13. const SESSION_ID = createSessionId("reasoning-repair");
  14. const ENTRY_ID = `${SESSION_ID}:runtime-model-selection`;
  15. describe("Todo121:只补 0020 回填后未动过的会话档位", () => {
  16. let root: string;
  17. let path: string;
  18. let db: DatabaseSync;
  19. let store: Awaited<ReturnType<typeof createSqliteSessionStore>> | undefined;
  20. function applyBefore(id: string) {
  21. for (const migration of SQLITE_MIGRATIONS.filter((item) => item.id < id)) {
  22. if (db.prepare("SELECT 1 FROM schema_migration WHERE id=?").get(migration.id)) continue;
  23. db.exec(migration.sql);
  24. db.prepare("INSERT INTO schema_migration VALUES(?,?,?,?)").run(
  25. migration.id,
  26. createHash("sha256").update(migration.sql.trim()).digest("hex"),
  27. migration.appVersion,
  28. APPLIED_AT,
  29. );
  30. }
  31. }
  32. function insertMessage(id: string, data: unknown, sequence: number) {
  33. db.prepare(
  34. "INSERT INTO message(id,session_id,time_created,time_updated,data,sequence) VALUES(?,?,?,?,?,?)",
  35. ).run(id, SESSION_ID, 11, 12, JSON.stringify(data), sequence);
  36. }
  37. function seed(providerId = "custom-provider", modelId = "stealth/ox-alpha") {
  38. insertMessage(
  39. "user",
  40. {
  41. role: "user",
  42. agent: "main",
  43. time: { created: 11 },
  44. model: { providerID: providerId, modelID: modelId, variant: "max" },
  45. },
  46. 1,
  47. );
  48. insertMessage(
  49. "assistant",
  50. {
  51. role: "assistant",
  52. parentID: "user",
  53. time: { created: 11, completed: 12 },
  54. providerID: providerId,
  55. modelID: modelId,
  56. },
  57. 2,
  58. );
  59. }
  60. function setEntry(data: unknown) {
  61. db.prepare("UPDATE session_entry SET data=? WHERE id=?").run(JSON.stringify(data), ENTRY_ID);
  62. }
  63. function readEntry() {
  64. return JSON.parse(
  65. String(db.prepare("SELECT data FROM session_entry WHERE id=?").get(ENTRY_ID)?.data),
  66. );
  67. }
  68. beforeEach(async () => {
  69. root = await mkdtemp(join(tmpdir(), "zcode-reasoning-repair-"));
  70. path = join(root, "session.sqlite");
  71. db = new DatabaseSync(path);
  72. db.exec(
  73. "CREATE TABLE schema_migration(id TEXT PRIMARY KEY, checksum TEXT NOT NULL, app_version TEXT, time_applied INTEGER NOT NULL)",
  74. );
  75. applyBefore(ORIGINAL_ID);
  76. db.prepare(
  77. "INSERT INTO session(id,project_id,slug,directory,title,version,time_created,time_updated) VALUES(?,?,?,?,?,?,?,?)",
  78. ).run(SESSION_ID, "project", "old", root, "旧会话正文不能丢", "old", 11, 12);
  79. });
  80. afterEach(async () => {
  81. store?.close();
  82. store = undefined;
  83. db.close();
  84. await rm(root, { recursive: true, force: true });
  85. });
  86. it.each([
  87. ["custom-provider", "stealth/ox-alpha", "custom-provider", "stealth/ox-alpha"],
  88. [
  89. "builtin:bigmodel-coding-plan",
  90. "glm-5.3",
  91. "account:bigmodel-individual-coding-plan",
  92. "GLM-5.3",
  93. ],
  94. ["builtin:zai-start-plan", "glm-5.3-flash", "account:zai-start-plan", "GLM-5.3-Flash"],
  95. ])(
  96. "首次升级 %s/%s:同一启动完成补值,正式 Reader 读到档位",
  97. async (provider, model, targetProvider, targetModel) => {
  98. seed(provider, model);
  99. store = await createSqliteSessionStore({ dbPath: path });
  100. expect(store.debugMigrationIds()).toContain(REPAIR_ID);
  101. expect(readEntry().modelSelection).toEqual({
  102. providerId: targetProvider,
  103. modelId: targetModel,
  104. options: { reasoningLevel: "max" },
  105. });
  106. expect(
  107. (await store.sessionEntries({ sessionID: SESSION_ID, type: "runtime/model_selection" }))[0]
  108. ?.data,
  109. ).toEqual(readEntry().modelSelection);
  110. expect((await store.getSession(SESSION_ID))?.title).toBe("旧会话正文不能丢");
  111. expect(await store.messages({ sessionID: SESSION_ID })).toHaveLength(2);
  112. },
  113. );
  114. it("已执行 0020:仅补新档位,历史字段/时间/消息/旧账本均不动,重启不重跑", async () => {
  115. seed();
  116. applyBefore(REPAIR_ID);
  117. const messages = db.prepare("SELECT * FROM message").all();
  118. const session = db.prepare("SELECT * FROM session").get();
  119. const entry = db.prepare("SELECT * FROM session_entry").get();
  120. const ledger = db.prepare("SELECT * FROM schema_migration ORDER BY id").all();
  121. store = await createSqliteSessionStore({ dbPath: path });
  122. expect(readEntry().modelSelection.options).toEqual({ reasoningLevel: "max" });
  123. expect(db.prepare("SELECT * FROM message").all()).toEqual(messages);
  124. expect(db.prepare("SELECT * FROM session").get()).toEqual({
  125. ...session,
  126. time_deleted: null,
  127. last_outcome: null,
  128. });
  129. expect(db.prepare("SELECT * FROM session_entry").get()).toEqual({
  130. ...entry,
  131. data: JSON.stringify(readEntry()),
  132. });
  133. expect(
  134. db.prepare("SELECT * FROM schema_migration WHERE id<? ORDER BY id").all(REPAIR_ID),
  135. ).toEqual(ledger);
  136. store.close();
  137. store = undefined;
  138. db.prepare("UPDATE session_entry SET data=json_remove(data,'$.modelSelection.options')").run();
  139. store = await createSqliteSessionStore({ dbPath: path });
  140. expect(readEntry().modelSelection).not.toHaveProperty("options");
  141. });
  142. it.each([
  143. "session-touched",
  144. "selection-touched",
  145. "options-empty",
  146. "options-null",
  147. "selection-cleared",
  148. "old-flat",
  149. "different-model",
  150. "different-provider",
  151. "third-party-case",
  152. "latest-user-empty",
  153. "latest-user-no-level",
  154. "bad-json",
  155. "invalid-identity",
  156. "wrong-entry-id",
  157. ])("不修复不确定或用户改过的记录:%s", async (scenario) => {
  158. seed();
  159. applyBefore(REPAIR_ID);
  160. const data = readEntry();
  161. switch (scenario) {
  162. case "session-touched":
  163. db.prepare("UPDATE session SET time_updated=?").run(APPLIED_AT + 1);
  164. break;
  165. case "selection-touched":
  166. db.prepare("UPDATE session_entry SET time_updated=?").run(APPLIED_AT + 1);
  167. break;
  168. case "options-empty":
  169. setEntry({ modelSelection: { ...data.modelSelection, options: {} } });
  170. break;
  171. case "options-null":
  172. setEntry({ modelSelection: { ...data.modelSelection, options: null } });
  173. break;
  174. case "selection-cleared":
  175. setEntry({ modelSelection: null });
  176. break;
  177. case "old-flat":
  178. setEntry({ ...data, thoughtLevel: null });
  179. break;
  180. case "different-model":
  181. setEntry({ modelSelection: { ...data.modelSelection, modelId: "other" } });
  182. break;
  183. case "different-provider":
  184. setEntry({ modelSelection: { ...data.modelSelection, providerId: "other" } });
  185. break;
  186. case "third-party-case":
  187. setEntry({ modelSelection: { ...data.modelSelection, modelId: "STEALTH/OX-ALPHA" } });
  188. break;
  189. case "latest-user-empty":
  190. insertMessage("later-user", { role: "user", modelSelection: null }, 3);
  191. break;
  192. case "latest-user-no-level":
  193. insertMessage("later-user", { role: "user", modelSelection: data.modelSelection }, 3);
  194. break;
  195. case "bad-json":
  196. db.prepare("UPDATE session_entry SET data='{' ").run();
  197. break;
  198. case "invalid-identity":
  199. setEntry({ modelSelection: { providerId: 123, modelId: "stealth/ox-alpha" } });
  200. break;
  201. case "wrong-entry-id":
  202. db.prepare("UPDATE session_entry SET id='another-entry'").run();
  203. break;
  204. }
  205. const before = db.prepare("SELECT * FROM session_entry").all();
  206. store = await createSqliteSessionStore({ dbPath: path });
  207. expect(store.debugMigrationIds()).toContain(REPAIR_ID);
  208. expect(db.prepare("SELECT * FROM session_entry").all()).toEqual(before);
  209. });
  210. it("迁移失败整笔回滚,重试可成功", async () => {
  211. seed();
  212. applyBefore(REPAIR_ID);
  213. const before = db.prepare("SELECT * FROM session_entry").all();
  214. db.exec(
  215. "CREATE TRIGGER reject_repair BEFORE UPDATE ON session_entry BEGIN SELECT RAISE(ABORT, 'test write failure'); END;",
  216. );
  217. await expect(createSqliteSessionStore({ dbPath: path })).rejects.toThrow();
  218. expect(db.prepare("SELECT * FROM session_entry").all()).toEqual(before);
  219. expect(db.prepare("SELECT 1 FROM schema_migration WHERE id=?").get(REPAIR_ID)).toBeUndefined();
  220. db.exec("DROP TRIGGER reject_repair");
  221. store = await createSqliteSessionStore({ dbPath: path });
  222. expect(readEntry().modelSelection.options).toEqual({ reasoningLevel: "max" });
  223. });
  224. });