tasksStartupPreparation.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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 { expect, it, vi } from "vitest";
  6. import { prepareTasksIndexStorage } from "../src/session/tasksDatabase/startup.js";
  7. import { runTasksDatabaseMigrations } from "../src/session/tasksDatabase/migrations.js";
  8. it("prepares the same frozen ledger as the old runner and preserves completed data", async () => {
  9. const dir = await mkdtemp(join(tmpdir(), "zcode-startup-"));
  10. const expected = new DatabaseSync(":memory:");
  11. try {
  12. runTasksDatabaseMigrations(expected);
  13. const path = join(dir, "tasks.sqlite");
  14. const phases: string[] = [];
  15. await prepareTasksIndexStorage(path, (phase) => {
  16. phases.push(phase);
  17. });
  18. const db = new DatabaseSync(path);
  19. try {
  20. expect(
  21. db.prepare("SELECT id, checksum FROM tasks_schema_migration ORDER BY id").all(),
  22. ).toEqual(
  23. expected.prepare("SELECT id, checksum FROM tasks_schema_migration ORDER BY id").all(),
  24. );
  25. db.exec("CREATE TABLE preserved(value TEXT); INSERT INTO preserved VALUES('user change')");
  26. } finally {
  27. db.close();
  28. }
  29. await prepareTasksIndexStorage(path, () => {});
  30. const reopened = new DatabaseSync(path);
  31. try {
  32. expect(reopened.prepare("SELECT value FROM preserved").get()?.value).toBe("user change");
  33. } finally {
  34. reopened.close();
  35. }
  36. expect(phases.at(-1)).toBe("ready");
  37. } finally {
  38. expected.close();
  39. await rm(dir, { recursive: true, force: true });
  40. }
  41. });
  42. it("does not reuse an in-process preparation marker after the database was replaced", async () => {
  43. const { markTasksStoragePrepared, isTasksStoragePrepared } =
  44. await import("../src/session/tasksDatabase/prepared.js");
  45. const db = new DatabaseSync(":memory:");
  46. try {
  47. markTasksStoragePrepared("/replacement-test");
  48. expect(isTasksStoragePrepared("/replacement-test", db)).toBe(false);
  49. runTasksDatabaseMigrations(db);
  50. expect(isTasksStoragePrepared("/replacement-test", db)).toBe(true);
  51. db.exec("UPDATE tasks_schema_migration SET checksum='invalid'");
  52. expect(() => isTasksStoragePrepared("/replacement-test", db)).toThrow("checksum mismatch");
  53. } finally {
  54. db.close();
  55. }
  56. });
  57. it("retains the primary preparation failure when repository cleanup also fails", async () => {
  58. const { TaskIndexRepo } = await import("../src/session/taskIndexRepo.js");
  59. const dir = await mkdtemp(join(tmpdir(), "zcode-startup-cleanup-"));
  60. const primary = Object.assign(new Error("storage full"), { code: "ENOSPC" });
  61. const prepare = vi.spyOn(TaskIndexRepo.prototype, "ensureReady").mockRejectedValue(primary);
  62. const close = vi.spyOn(TaskIndexRepo.prototype, "close").mockImplementation(() => {
  63. throw new Error("cleanup failed");
  64. });
  65. try {
  66. await expect(prepareTasksIndexStorage(join(dir, "tasks.sqlite"), () => {})).rejects.toBe(
  67. primary,
  68. );
  69. } finally {
  70. prepare.mockRestore();
  71. close.mockRestore();
  72. await rm(dir, { recursive: true, force: true });
  73. }
  74. });
  75. it("SILENTDB-01/02: reports maintenance separately and no migration for a prepared database", async () => {
  76. const dir = await mkdtemp(join(tmpdir(), "zcode-silent-startup-"));
  77. const path = join(dir, "tasks.sqlite");
  78. try {
  79. const first: unknown[] = [];
  80. await prepareTasksIndexStorage(path, (phase, migration) => first.push({ phase, migration }));
  81. expect(
  82. (first.at(-1) as { migration: { lastAppliedMigrationId: unknown } }).migration
  83. .lastAppliedMigrationId,
  84. ).toBeNull();
  85. expect(first).toContainEqual({
  86. phase: "checking",
  87. migration: { kind: "initialize", executedCount: 0, committedCount: 0 },
  88. });
  89. expect(first).toContainEqual(
  90. expect.objectContaining({
  91. migration: {
  92. kind: "initialize",
  93. executedCount: 3,
  94. committedCount: 3,
  95. lastAppliedMigrationId: null,
  96. },
  97. }),
  98. );
  99. const second: { phase: string; migration: unknown }[] = [];
  100. await prepareTasksIndexStorage(path, (phase, migration) => second.push({ phase, migration }));
  101. expect(second.some((s) => s.phase === "migrating")).toBe(false);
  102. expect(second.at(-1)).toMatchObject({
  103. migration: { lastAppliedMigrationId: "0003_official_glm_selection" },
  104. });
  105. expect(second.some((s) => s.phase === "maintaining")).toBe(true);
  106. expect(second).toContainEqual(
  107. expect.objectContaining({ migration: { kind: "none", executedCount: 0, committedCount: 0 } }),
  108. );
  109. } finally {
  110. await rm(dir, { recursive: true, force: true });
  111. }
  112. });
  113. it("retains committed facts if closing the migration connection fails", async () => {
  114. const dir = await mkdtemp(join(tmpdir(), "zcode-startup-close-facts-"));
  115. const primary = new Error("migration connection close failed");
  116. const original = DatabaseSync.prototype.close;
  117. const close = vi
  118. .spyOn(DatabaseSync.prototype, "close")
  119. .mockImplementationOnce(function (this: DatabaseSync) {
  120. original.call(this);
  121. throw primary;
  122. });
  123. const states: { phase: string; migration: unknown }[] = [];
  124. try {
  125. await expect(
  126. prepareTasksIndexStorage(join(dir, "tasks.sqlite"), (phase, migration) => {
  127. states.push({ phase, migration });
  128. }),
  129. ).rejects.toBe(primary);
  130. expect(states.at(-1)).toMatchObject({
  131. migration: {
  132. kind: "initialize",
  133. executedCount: 3,
  134. committedCount: 3,
  135. lastAppliedMigrationId: null,
  136. },
  137. });
  138. expect(states.some(({ phase }) => phase === "ready")).toBe(false);
  139. } finally {
  140. close.mockRestore();
  141. await rm(dir, { recursive: true, force: true });
  142. }
  143. });
  144. it("updates wait visibility after migration precheck even if journal setup already waited", async () => {
  145. const dir = await mkdtemp(join(tmpdir(), "zcode-startup-repeated-lock-"));
  146. const original = DatabaseSync.prototype.exec;
  147. const blocked = new Set(["PRAGMA journal_mode = WAL", "BEGIN IMMEDIATE"]);
  148. const exec = vi
  149. .spyOn(DatabaseSync.prototype, "exec")
  150. .mockImplementation(function (this: DatabaseSync, sql) {
  151. if (blocked.delete(sql)) throw Object.assign(new Error("busy"), { errcode: 5 });
  152. original.call(this, sql);
  153. });
  154. const waits: unknown[] = [];
  155. try {
  156. await prepareTasksIndexStorage(join(dir, "tasks.sqlite"), (phase, migration) => {
  157. if (phase === "waiting_for_lock") waits.push(migration?.kind);
  158. });
  159. expect(waits).toEqual([undefined, "initialize"]);
  160. } finally {
  161. exec.mockRestore();
  162. await rm(dir, { recursive: true, force: true });
  163. }
  164. });
  165. it("keeps the pre-upgrade task ledger ID after committing the remaining migration", async () => {
  166. const dir = await mkdtemp(join(tmpdir(), "zcode-task-baseline-"));
  167. const path = join(dir, "tasks.sqlite");
  168. try {
  169. await prepareTasksIndexStorage(path, () => {});
  170. const db = new DatabaseSync(path);
  171. try {
  172. db.exec("DELETE FROM tasks_schema_migration WHERE id='0003_official_glm_selection'");
  173. } finally {
  174. db.close();
  175. }
  176. const states: unknown[] = [];
  177. await prepareTasksIndexStorage(path, (phase, migration) => states.push({ phase, migration }));
  178. expect(states.at(-1)).toMatchObject({
  179. phase: "ready",
  180. migration: {
  181. kind: "upgrade",
  182. executedCount: 1,
  183. committedCount: 1,
  184. lastAppliedMigrationId: "0002_provider_selection",
  185. },
  186. });
  187. } finally {
  188. await rm(dir, { recursive: true, force: true });
  189. }
  190. });