async-migration-startup.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 { afterEach, describe, expect, it, vi } from "vitest";
  6. import { SQLITE_MIGRATIONS } from "../src/storage/session-store/migrations.js";
  7. import {
  8. runSqliteSessionMigrations,
  9. runSqliteSessionMigrationsAsync,
  10. } from "../src/storage/session-store/migration-runner.js";
  11. import type { SqliteMigrationProgress } from "../src/storage/session-store/migration-runner.js";
  12. const dbs: DatabaseSync[] = [];
  13. const dirs: string[] = [];
  14. const open = (path = ":memory:") => {
  15. const db = new DatabaseSync(path);
  16. dbs.push(db);
  17. return db;
  18. };
  19. afterEach(async () => {
  20. vi.restoreAllMocks();
  21. for (const db of dbs.splice(0)) {
  22. if (db.isTransaction) db.exec("ROLLBACK");
  23. db.close();
  24. }
  25. for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true });
  26. });
  27. describe("Todo144:迁移启动状态与真实 SQLite 锁", () => {
  28. it("阶段通知 flush 后才执行 SQL;ready 仅在 commit 之后", async () => {
  29. const db = open();
  30. const exec = vi.spyOn(db, "exec");
  31. const states: SqliteMigrationProgress[] = [];
  32. let release!: () => void;
  33. const barrier = new Promise<void>((resolve) => {
  34. release = resolve;
  35. });
  36. let observed!: () => void;
  37. const started = new Promise<void>((resolve) => {
  38. observed = resolve;
  39. });
  40. const migrating = runSqliteSessionMigrationsAsync(db, ":memory:", {
  41. onProgress: async (state) => {
  42. states.push(state);
  43. if (state.phase === "migrating" && state.migrationId === "0001_base_session_store") {
  44. observed();
  45. await barrier;
  46. }
  47. if (state.phase === "committing") expect(db.isTransaction).toBe(true);
  48. if (state.phase === "ready") expect(db.isTransaction).toBe(false);
  49. },
  50. });
  51. await started;
  52. expect(db.prepare("SELECT 1 FROM sqlite_schema WHERE name='session'").get()).toBeUndefined();
  53. release();
  54. await migrating;
  55. expect(states[0]?.phase).toBe("checking");
  56. expect(states.at(-1)?.phase).toBe("ready");
  57. expect(states.at(-1)?.migration?.lastAppliedMigrationId).toBeNull();
  58. // 本 hotfix 不改迁移算法;状态通知不能让执行路径偏离账本对应的冻结原 SQL。
  59. const frozenSql = SQLITE_MIGRATIONS.filter((migration) => !migration.apply).map(
  60. (migration) => migration.sql,
  61. );
  62. expect(exec.mock.calls.map(([sql]) => sql).filter((sql) => frozenSql.includes(sql))).toEqual(
  63. frozenSql,
  64. );
  65. for (const state of states) {
  66. expect(state).not.toHaveProperty("executionRevision");
  67. expect(state).not.toHaveProperty("implementationHash");
  68. }
  69. const replay: SqliteMigrationProgress[] = [];
  70. await runSqliteSessionMigrationsAsync(db, ":memory:", {
  71. onProgress: async (s) => {
  72. replay.push(s);
  73. },
  74. });
  75. expect(replay.some((s) => s.phase === "migrating")).toBe(false);
  76. expect(replay.at(-1)?.migration?.lastAppliedMigrationId).toBe(
  77. SQLITE_MIGRATIONS.map((m) => m.id)
  78. .sort()
  79. .at(-1),
  80. );
  81. });
  82. it("同库持锁超过旧 5 秒,异步等待不阻塞持有者提交;异库独立就绪", async () => {
  83. const dir = await mkdtemp(join(tmpdir(), "zcode-startup-lock-"));
  84. dirs.push(dir);
  85. const path = join(dir, "db.sqlite");
  86. const holder = open(path);
  87. await runSqliteSessionMigrations(holder, path);
  88. holder.exec("BEGIN IMMEDIATE");
  89. const waiter = open(path);
  90. const phases: string[] = [];
  91. let releaseHolder: ReturnType<typeof setTimeout> | undefined;
  92. try {
  93. await runSqliteSessionMigrationsAsync(waiter, path, {
  94. lockWaitTimeoutMs: 10_000,
  95. onProgress: async (s) => {
  96. phases.push(s.phase);
  97. if (s.phase === "waiting_for_lock" && !releaseHolder) {
  98. await runSqliteSessionMigrationsAsync(open(), ":memory:");
  99. releaseHolder = setTimeout(() => holder.exec("COMMIT"), 5_100);
  100. }
  101. },
  102. });
  103. expect(phases.filter((p) => p === "waiting_for_lock")).toHaveLength(1);
  104. expect(phases.at(-1)).toBe("ready");
  105. expect(waiter.prepare("PRAGMA busy_timeout").get()?.timeout).toBe(5_000);
  106. } finally {
  107. if (releaseHolder) clearTimeout(releaseHolder);
  108. }
  109. }, 15_000);
  110. it("失败发 failed,回滚全部未提交项;不伪造 ready", async () => {
  111. const db = open();
  112. const states: SqliteMigrationProgress[] = [];
  113. await expect(
  114. runSqliteSessionMigrationsAsync(db, ":memory:", {
  115. onProgress: async (s) => {
  116. states.push(s);
  117. if (s.phase === "migrating" && s.migrationId === "0020_provider_model_selection")
  118. db.exec("DROP TABLE message");
  119. },
  120. }),
  121. ).rejects.toMatchObject({ kind: "sql_failed", migrationId: "0020_provider_model_selection" });
  122. expect(states.at(-1)?.phase).toBe("failed");
  123. expect(states.some((s) => s.phase === "ready")).toBe(false);
  124. expect(db.isTransaction).toBe(false);
  125. expect(
  126. db.prepare("SELECT 1 FROM sqlite_schema WHERE name='schema_migration'").get(),
  127. ).toBeUndefined();
  128. });
  129. it("等待预算用尽只失败等待者,保留持有者事务", async () => {
  130. const dir = await mkdtemp(join(tmpdir(), "zcode-startup-deadline-"));
  131. dirs.push(dir);
  132. const path = join(dir, "db.sqlite");
  133. const holder = open(path);
  134. await runSqliteSessionMigrations(holder, path);
  135. holder.exec("BEGIN IMMEDIATE");
  136. const waiter = open(path);
  137. const phases: string[] = [];
  138. await expect(
  139. runSqliteSessionMigrationsAsync(waiter, path, {
  140. lockWaitTimeoutMs: 30,
  141. onProgress: async (s) => {
  142. phases.push(s.phase);
  143. },
  144. }),
  145. ).rejects.toMatchObject({ kind: "lock_timeout" });
  146. expect(phases.at(-1)).toBe("failed");
  147. expect(holder.isTransaction).toBe(true);
  148. });
  149. });
  150. it("openStartup 保留迁移原始错误,即使 close 也失败", async () => {
  151. const { SqliteSessionStore } =
  152. await import("../src/storage/session-store/sqlite-session-store.js");
  153. // 迁移失败发生在 store 实例返回前;应在真正持有连接的 DatabaseSync 上注入关闭失败。
  154. const originalClose = DatabaseSync.prototype.close;
  155. vi.spyOn(DatabaseSync.prototype, "close").mockImplementation(function (this: DatabaseSync) {
  156. originalClose.call(this);
  157. throw new Error("secondary close failure");
  158. });
  159. const original = Object.assign(new Error("primary storage failure"), { errcode: 13 });
  160. await expect(
  161. SqliteSessionStore.openStartup(
  162. { dbPath: ":memory:" },
  163. {
  164. onProgress: async () => {
  165. throw original;
  166. },
  167. },
  168. ),
  169. ).rejects.toBe(original);
  170. });
  171. it("SILENTDB-02/04: reports real migration kind and counts only committed SQL as committed", async () => {
  172. const db = open();
  173. const states: SqliteMigrationProgress[] = [];
  174. await runSqliteSessionMigrationsAsync(db, ":memory:", {
  175. onProgress: async (s) => {
  176. states.push(s);
  177. },
  178. });
  179. expect(states.at(-1)?.migration).toEqual({
  180. kind: "initialize",
  181. executedCount: SQLITE_MIGRATIONS.length,
  182. committedCount: SQLITE_MIGRATIONS.length,
  183. lastAppliedMigrationId: null,
  184. });
  185. const repeated: SqliteMigrationProgress[] = [];
  186. await runSqliteSessionMigrationsAsync(db, ":memory:", {
  187. onProgress: async (s) => {
  188. repeated.push(s);
  189. },
  190. });
  191. expect(repeated.at(-1)?.migration).toEqual({
  192. kind: "none",
  193. executedCount: 0,
  194. committedCount: 0,
  195. lastAppliedMigrationId: SQLITE_MIGRATIONS.map((m) => m.id)
  196. .sort()
  197. .at(-1),
  198. });
  199. db.exec("DELETE FROM schema_migration WHERE id >= '0020'");
  200. const failed: SqliteMigrationProgress[] = [];
  201. await expect(
  202. runSqliteSessionMigrationsAsync(db, ":memory:", {
  203. onProgress: async (s) => {
  204. failed.push(s);
  205. if (s.phase === "committing") throw new Error("commit barrier failed");
  206. },
  207. }),
  208. ).rejects.toThrow("commit barrier failed");
  209. expect(failed.find((s) => s.phase === "migrating")?.migration?.kind).toBe("upgrade");
  210. expect(failed.every((s) => !s.migration?.committedCount)).toBe(true);
  211. expect(failed.at(-1)?.migration?.lastAppliedMigrationId).toBe(
  212. SQLITE_MIGRATIONS.find((m) => m.id.startsWith("0019"))?.id,
  213. );
  214. expect(db.prepare("SELECT 1 FROM schema_migration WHERE id >= '0020'").get()).toBeUndefined();
  215. });
  216. it("SILENTDB-03: another writer can finish the observed migrations without this waiter executing any", async () => {
  217. const dir = await mkdtemp(join(tmpdir(), "zcode-startup-other-writer-"));
  218. dirs.push(dir);
  219. const path = join(dir, "db.sqlite");
  220. const holder = open(path);
  221. await runSqliteSessionMigrations(holder, path);
  222. holder.exec("DELETE FROM schema_migration WHERE id >= '0020'; BEGIN IMMEDIATE");
  223. const waiter = open(path);
  224. const states: SqliteMigrationProgress[] = [];
  225. const exec = vi.spyOn(waiter, "exec");
  226. await runSqliteSessionMigrationsAsync(waiter, path, {
  227. onProgress: async (state) => {
  228. states.push(state);
  229. if (state.phase === "waiting_for_lock") {
  230. expect(state.migration?.kind).toBe("upgrade");
  231. holder.exec("COMMIT");
  232. await runSqliteSessionMigrations(holder, path);
  233. }
  234. },
  235. });
  236. expect(states.at(-1)?.migration).toEqual({
  237. kind: "upgrade",
  238. executedCount: 0,
  239. committedCount: 0,
  240. lastAppliedMigrationId: SQLITE_MIGRATIONS.map((m) => m.id)
  241. .sort()
  242. .at(-1),
  243. });
  244. expect(exec.mock.calls.some(([sql]) => SQLITE_MIGRATIONS.some((m) => m.sql === sql))).toBe(false);
  245. expect(
  246. states.find((s) => s.phase === "waiting_for_lock")?.migration?.lastAppliedMigrationId,
  247. ).toBeUndefined();
  248. expect(states.at(-1)?.migration?.lastAppliedMigrationId).toBe(
  249. SQLITE_MIGRATIONS.map((m) => m.id)
  250. .sort()
  251. .at(-1),
  252. );
  253. });
  254. it("publishes confirmed migration demand when lock contention recurs after precheck", async () => {
  255. const db = open();
  256. const prepare = db.prepare.bind(db);
  257. const exec = db.exec.bind(db);
  258. let journalBusy = true;
  259. let transactionBusy = true;
  260. vi.spyOn(db, "prepare").mockImplementation((sql) => {
  261. if (journalBusy && sql.toLowerCase().includes("pragma journal_mode")) {
  262. journalBusy = false;
  263. throw Object.assign(new Error("busy before precheck"), { errcode: 5 });
  264. }
  265. return prepare(sql);
  266. });
  267. vi.spyOn(db, "exec").mockImplementation((sql) => {
  268. if (transactionBusy && sql.toLowerCase() === "begin immediate") {
  269. transactionBusy = false;
  270. throw Object.assign(new Error("busy after precheck"), { errcode: 5 });
  271. }
  272. exec(sql);
  273. });
  274. const waits: SqliteMigrationProgress[] = [];
  275. await runSqliteSessionMigrationsAsync(db, ":memory:", {
  276. onProgress: async (state) => {
  277. if (state.phase === "waiting_for_lock") waits.push(state);
  278. },
  279. });
  280. expect(waits.map((state) => state.migration?.kind)).toEqual([undefined, "initialize"]);
  281. });
  282. it("does not send malformed ledger IDs as telemetry or fail an otherwise prepared database", async () => {
  283. const db = open();
  284. await runSqliteSessionMigrations(db, ":memory:");
  285. db.prepare("INSERT INTO schema_migration VALUES (?, 'external', NULL, 0)").run(
  286. "private / unexpected ID",
  287. );
  288. const states: SqliteMigrationProgress[] = [];
  289. await runSqliteSessionMigrationsAsync(db, ":memory:", {
  290. onProgress: async (state) => {
  291. states.push(state);
  292. },
  293. });
  294. expect(states.at(-1)?.phase).toBe("ready");
  295. expect(states.at(-1)?.migration?.lastAppliedMigrationId).toBeUndefined();
  296. expect(JSON.stringify(states)).not.toContain("private / unexpected ID");
  297. });