async-migration-startup.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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.map((migration) => migration.sql);
  60. expect(exec.mock.calls.map(([sql]) => sql).filter((sql) => frozenSql.includes(sql))).toEqual(
  61. frozenSql,
  62. );
  63. for (const state of states) {
  64. expect(state).not.toHaveProperty("executionRevision");
  65. expect(state).not.toHaveProperty("implementationHash");
  66. }
  67. const replay: SqliteMigrationProgress[] = [];
  68. await runSqliteSessionMigrationsAsync(db, ":memory:", {
  69. onProgress: async (s) => {
  70. replay.push(s);
  71. },
  72. });
  73. expect(replay.some((s) => s.phase === "migrating")).toBe(false);
  74. expect(replay.at(-1)?.migration?.lastAppliedMigrationId).toBe(SQLITE_MIGRATIONS.at(-1)?.id);
  75. });
  76. it("同库持锁超过旧 5 秒,异步等待不阻塞持有者提交;异库独立就绪", async () => {
  77. const dir = await mkdtemp(join(tmpdir(), "zcode-startup-lock-"));
  78. dirs.push(dir);
  79. const path = join(dir, "db.sqlite");
  80. const holder = open(path);
  81. runSqliteSessionMigrations(holder, path);
  82. holder.exec("BEGIN IMMEDIATE");
  83. const waiter = open(path);
  84. const phases: string[] = [];
  85. let releaseHolder: ReturnType<typeof setTimeout> | undefined;
  86. try {
  87. await runSqliteSessionMigrationsAsync(waiter, path, {
  88. lockWaitTimeoutMs: 10_000,
  89. onProgress: async (s) => {
  90. phases.push(s.phase);
  91. if (s.phase === "waiting_for_lock" && !releaseHolder) {
  92. await runSqliteSessionMigrationsAsync(open(), ":memory:");
  93. releaseHolder = setTimeout(() => holder.exec("COMMIT"), 5_100);
  94. }
  95. },
  96. });
  97. expect(phases.filter((p) => p === "waiting_for_lock")).toHaveLength(1);
  98. expect(phases.at(-1)).toBe("ready");
  99. expect(waiter.prepare("PRAGMA busy_timeout").get()?.timeout).toBe(5_000);
  100. } finally {
  101. if (releaseHolder) clearTimeout(releaseHolder);
  102. }
  103. }, 15_000);
  104. it("失败发 failed,回滚全部未提交项;不伪造 ready", async () => {
  105. const db = open();
  106. const states: SqliteMigrationProgress[] = [];
  107. await expect(
  108. runSqliteSessionMigrationsAsync(db, ":memory:", {
  109. onProgress: async (s) => {
  110. states.push(s);
  111. if (s.phase === "migrating" && s.migrationId === "0020_provider_model_selection")
  112. db.exec("DROP TABLE message");
  113. },
  114. }),
  115. ).rejects.toMatchObject({ kind: "sql_failed", migrationId: "0020_provider_model_selection" });
  116. expect(states.at(-1)?.phase).toBe("failed");
  117. expect(states.some((s) => s.phase === "ready")).toBe(false);
  118. expect(db.isTransaction).toBe(false);
  119. expect(
  120. db.prepare("SELECT 1 FROM sqlite_schema WHERE name='schema_migration'").get(),
  121. ).toBeUndefined();
  122. });
  123. it("等待预算用尽只失败等待者,保留持有者事务", async () => {
  124. const dir = await mkdtemp(join(tmpdir(), "zcode-startup-deadline-"));
  125. dirs.push(dir);
  126. const path = join(dir, "db.sqlite");
  127. const holder = open(path);
  128. runSqliteSessionMigrations(holder, path);
  129. holder.exec("BEGIN IMMEDIATE");
  130. const waiter = open(path);
  131. const phases: string[] = [];
  132. await expect(
  133. runSqliteSessionMigrationsAsync(waiter, path, {
  134. lockWaitTimeoutMs: 30,
  135. onProgress: async (s) => {
  136. phases.push(s.phase);
  137. },
  138. }),
  139. ).rejects.toMatchObject({ kind: "lock_timeout" });
  140. expect(phases.at(-1)).toBe("failed");
  141. expect(holder.isTransaction).toBe(true);
  142. });
  143. });
  144. it("openStartup 保留迁移原始错误,即使 close 也失败", async () => {
  145. const { SqliteSessionStore } =
  146. await import("../src/storage/session-store/sqlite-session-store.js");
  147. const originalClose = SqliteSessionStore.prototype.close;
  148. vi.spyOn(SqliteSessionStore.prototype, "close").mockImplementation(
  149. function (this: InstanceType<typeof SqliteSessionStore>) {
  150. originalClose.call(this);
  151. throw new Error("secondary close failure");
  152. },
  153. );
  154. const original = Object.assign(new Error("primary storage failure"), { errcode: 13 });
  155. await expect(
  156. SqliteSessionStore.openStartup(
  157. { dbPath: ":memory:" },
  158. {
  159. onProgress: async () => {
  160. throw original;
  161. },
  162. },
  163. ),
  164. ).rejects.toBe(original);
  165. });
  166. it("SILENTDB-02/04: reports real migration kind and counts only committed SQL as committed", async () => {
  167. const db = open();
  168. const states: SqliteMigrationProgress[] = [];
  169. await runSqliteSessionMigrationsAsync(db, ":memory:", {
  170. onProgress: async (s) => {
  171. states.push(s);
  172. },
  173. });
  174. expect(states.at(-1)?.migration).toEqual({
  175. kind: "initialize",
  176. executedCount: SQLITE_MIGRATIONS.length,
  177. committedCount: SQLITE_MIGRATIONS.length,
  178. lastAppliedMigrationId: null,
  179. });
  180. const repeated: SqliteMigrationProgress[] = [];
  181. await runSqliteSessionMigrationsAsync(db, ":memory:", {
  182. onProgress: async (s) => {
  183. repeated.push(s);
  184. },
  185. });
  186. expect(repeated.at(-1)?.migration).toEqual({
  187. kind: "none",
  188. executedCount: 0,
  189. committedCount: 0,
  190. lastAppliedMigrationId: SQLITE_MIGRATIONS.at(-1)?.id,
  191. });
  192. db.exec("DELETE FROM schema_migration WHERE id >= '0020'");
  193. const failed: SqliteMigrationProgress[] = [];
  194. await expect(
  195. runSqliteSessionMigrationsAsync(db, ":memory:", {
  196. onProgress: async (s) => {
  197. failed.push(s);
  198. if (s.phase === "committing") throw new Error("commit barrier failed");
  199. },
  200. }),
  201. ).rejects.toThrow("commit barrier failed");
  202. expect(failed.find((s) => s.phase === "migrating")?.migration?.kind).toBe("upgrade");
  203. expect(failed.every((s) => !s.migration?.committedCount)).toBe(true);
  204. expect(failed.at(-1)?.migration?.lastAppliedMigrationId).toBe(
  205. SQLITE_MIGRATIONS.find((m) => m.id.startsWith("0019"))?.id,
  206. );
  207. expect(db.prepare("SELECT 1 FROM schema_migration WHERE id >= '0020'").get()).toBeUndefined();
  208. });
  209. it("SILENTDB-03: another writer can finish the observed migrations without this waiter executing any", async () => {
  210. const dir = await mkdtemp(join(tmpdir(), "zcode-startup-other-writer-"));
  211. dirs.push(dir);
  212. const path = join(dir, "db.sqlite");
  213. const holder = open(path);
  214. runSqliteSessionMigrations(holder, path);
  215. holder.exec("DELETE FROM schema_migration WHERE id >= '0020'; BEGIN IMMEDIATE");
  216. const waiter = open(path);
  217. const states: SqliteMigrationProgress[] = [];
  218. const exec = vi.spyOn(waiter, "exec");
  219. await runSqliteSessionMigrationsAsync(waiter, path, {
  220. onProgress: async (state) => {
  221. states.push(state);
  222. if (state.phase === "waiting_for_lock") {
  223. expect(state.migration?.kind).toBe("upgrade");
  224. holder.exec("COMMIT");
  225. runSqliteSessionMigrations(holder, path);
  226. }
  227. },
  228. });
  229. expect(states.at(-1)?.migration).toEqual({
  230. kind: "upgrade",
  231. executedCount: 0,
  232. committedCount: 0,
  233. lastAppliedMigrationId: SQLITE_MIGRATIONS.at(-1)?.id,
  234. });
  235. expect(exec.mock.calls.some(([sql]) => SQLITE_MIGRATIONS.some((m) => m.sql === sql))).toBe(false);
  236. expect(
  237. states.find((s) => s.phase === "waiting_for_lock")?.migration?.lastAppliedMigrationId,
  238. ).toBeUndefined();
  239. expect(states.at(-1)?.migration?.lastAppliedMigrationId).toBe(SQLITE_MIGRATIONS.at(-1)?.id);
  240. });
  241. it("publishes confirmed migration demand when lock contention recurs after precheck", async () => {
  242. const db = open();
  243. const prepare = db.prepare.bind(db);
  244. const exec = db.exec.bind(db);
  245. let journalBusy = true;
  246. let transactionBusy = true;
  247. vi.spyOn(db, "prepare").mockImplementation((sql) => {
  248. if (journalBusy && sql.toLowerCase().includes("pragma journal_mode")) {
  249. journalBusy = false;
  250. throw Object.assign(new Error("busy before precheck"), { errcode: 5 });
  251. }
  252. return prepare(sql);
  253. });
  254. vi.spyOn(db, "exec").mockImplementation((sql) => {
  255. if (transactionBusy && sql.toLowerCase() === "begin immediate") {
  256. transactionBusy = false;
  257. throw Object.assign(new Error("busy after precheck"), { errcode: 5 });
  258. }
  259. exec(sql);
  260. });
  261. const waits: SqliteMigrationProgress[] = [];
  262. await runSqliteSessionMigrationsAsync(db, ":memory:", {
  263. onProgress: async (state) => {
  264. if (state.phase === "waiting_for_lock") waits.push(state);
  265. },
  266. });
  267. expect(waits.map((state) => state.migration?.kind)).toEqual([undefined, "initialize"]);
  268. });
  269. it("does not send malformed ledger IDs as telemetry or fail an otherwise prepared database", async () => {
  270. const db = open();
  271. runSqliteSessionMigrations(db, ":memory:");
  272. db.prepare("INSERT INTO schema_migration VALUES (?, 'external', NULL, 0)").run(
  273. "private / unexpected ID",
  274. );
  275. const states: SqliteMigrationProgress[] = [];
  276. await runSqliteSessionMigrationsAsync(db, ":memory:", {
  277. onProgress: async (state) => {
  278. states.push(state);
  279. },
  280. });
  281. expect(states.at(-1)?.phase).toBe("ready");
  282. expect(states.at(-1)?.migration?.lastAppliedMigrationId).toBeUndefined();
  283. expect(JSON.stringify(states)).not.toContain("private / unexpected ID");
  284. });