workspaceIdentityOffPeakMigration.test.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import { DatabaseSync } from "node:sqlite";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { migrateControllerRemoteWorkspaceIdentity } from "#src/session/controllerRemoteIdentityMigration.js";
  7. import { SourceServerWorkspaceAliasRepo } from "#src/session/sourceServerWorkspaceAliasRepo.js";
  8. import { runTasksDatabaseMigrations } from "#src/session/tasksDatabase/migrations.js";
  9. type MigrationMode = "controller" | "source";
  10. const workspacePath = "/srv/project";
  11. const sourceKey = "remote:ssh:old.example:22:dev:/srv/project";
  12. const canonicalKey = "remote:ssh:canonical.example:22:dev:/srv/project";
  13. const stableKey = "remote:server:3cd4f9da-cd79-426c-9d70-75f36e9f6a87:/srv/project";
  14. const cleanup: Array<() => Promise<void>> = [];
  15. afterEach(async () => {
  16. for (const dispose of cleanup.splice(0)) await dispose();
  17. });
  18. async function createFixture(mode: MigrationMode) {
  19. const root = await mkdtemp(join(tmpdir(), "zcode-offpeak-identity-"));
  20. const dbPath = join(root, "tasks-index.sqlite");
  21. const db = new DatabaseSync(dbPath);
  22. cleanup.push(async () => {
  23. db.close();
  24. await rm(root, { recursive: true, force: true });
  25. });
  26. await runTasksDatabaseMigrations(db);
  27. expect(
  28. db.prepare("SELECT 1 FROM sqlite_master WHERE name = 'idx_off_peak_bound_active'").get(),
  29. ).toBeDefined();
  30. const targetKey = mode === "controller" ? stableKey : canonicalKey;
  31. const insertTask = db.prepare(`INSERT INTO tasks (
  32. workspace_key, workspace_path, workspace_identity, task_id, created_at, updated_at
  33. ) VALUES (?, ?, ?, 'bound-session', 1, ?)`);
  34. insertTask.run(sourceKey, workspacePath, sourceKey, 10);
  35. insertTask.run(targetKey, workspacePath, targetKey, 20);
  36. const repo = new SourceServerWorkspaceAliasRepo({
  37. taskDbPath: dbPath,
  38. sessionDbPath: join(root, "missing.sqlite"),
  39. backupRoot: join(root, "backups"),
  40. now: () => 100,
  41. });
  42. return {
  43. db,
  44. targetKey,
  45. ledger:
  46. mode === "controller"
  47. ? "controller_remote_identity_migrations"
  48. : "workspace_migration_ledger",
  49. async migrate() {
  50. if (mode === "source") {
  51. const result = await repo.resolveCanonicalWorkspaceKey({
  52. workspacePath,
  53. legacyRouteHint: sourceKey,
  54. });
  55. expect(result.canonicalKey).toBe(targetKey);
  56. } else {
  57. const result = await migrateControllerRemoteWorkspaceIdentity({
  58. dbPath,
  59. oldWorkspaceKey: sourceKey,
  60. newWorkspaceKey: targetKey,
  61. now: () => 100,
  62. });
  63. if (result.status === "failed") throw new Error(result.error);
  64. }
  65. },
  66. insertOffPeak(id: string, key: string, session: string | null, status: string) {
  67. db.prepare(`INSERT INTO off_peak_tasks (
  68. off_peak_task_id, server_ticket_id, workspace_key, workspace_path, workspace_identity,
  69. session_id, conversation_id, prompt, permission_mode, status, queued_at,
  70. schedulable, queue_position, next_poll_at, claim_running, claimed_at,
  71. failure_reason, started_at, files_changed, created_at, updated_at
  72. ) VALUES (?, ?, ?, ?, ?, ?, ?, 'test', 'default', ?, 1, 1, 2, 30, 1, 10,
  73. 'previous attempt', 5, 3, 1, 10)`).run(
  74. id,
  75. `ticket-${id}`,
  76. key,
  77. workspacePath,
  78. key,
  79. session,
  80. session,
  81. status,
  82. );
  83. },
  84. };
  85. }
  86. describe.each<MigrationMode>(["controller", "source"])("%s off-peak identity migration", (mode) => {
  87. it.each(["queued", "paused", "running"])(
  88. "preserves the target and cancels only conflicting %s source rows before rekeying",
  89. async (status) => {
  90. const { db, targetKey, ledger, insertOffPeak, migrate } = await createFixture(mode);
  91. insertOffPeak("target-active", targetKey, "bound-session", status);
  92. insertOffPeak("source-conflict", sourceKey, "bound-session", status);
  93. for (const terminal of ["completed", "failed", "cancelled"]) {
  94. insertOffPeak(`source-${terminal}`, sourceKey, "bound-session", terminal);
  95. insertOffPeak(`target-${terminal}`, targetKey, terminal, terminal);
  96. insertOffPeak(`source-with-${terminal}-target`, sourceKey, terminal, status);
  97. }
  98. insertOffPeak("source-unbound", sourceKey, null, status);
  99. insertOffPeak("target-unbound", targetKey, null, "queued");
  100. insertOffPeak("source-other-session", sourceKey, "another-session", status);
  101. insertOffPeak("other-workspace", "/another-project", "bound-session", "queued");
  102. const list = db.prepare("SELECT * FROM off_peak_tasks ORDER BY off_peak_task_id");
  103. const before = list.all();
  104. await migrate();
  105. const expected = before.map((row) => {
  106. if (row.workspace_key !== sourceKey) return row;
  107. const moved = { ...row, workspace_key: targetKey, workspace_identity: targetKey };
  108. return row.off_peak_task_id === "source-conflict"
  109. ? {
  110. ...moved,
  111. status: "cancelled",
  112. ended_at: 100,
  113. updated_at: 100,
  114. failure_reason: null,
  115. schedulable: 0,
  116. claim_running: 0,
  117. claimed_at: null,
  118. }
  119. : moved;
  120. });
  121. expect(list.all()).toEqual(expected);
  122. expect(db.prepare("SELECT workspace_key FROM tasks").all()).toEqual([
  123. { workspace_key: targetKey },
  124. ]);
  125. expect(db.prepare(`SELECT status FROM ${ledger}`).all()).toEqual([{ status: "completed" }]);
  126. await migrate();
  127. expect(list.all()).toEqual(expected);
  128. expect(db.prepare(`SELECT status FROM ${ledger}`).all()).toEqual([{ status: "completed" }]);
  129. },
  130. );
  131. it("rolls cancellation back with the rekey transaction and succeeds on retry", async () => {
  132. const { db, targetKey, ledger, insertOffPeak, migrate } = await createFixture(mode);
  133. insertOffPeak("source-conflict", sourceKey, "bound-session", "running");
  134. insertOffPeak("target-active", targetKey, "bound-session", "queued");
  135. const beforeOffPeak = db
  136. .prepare("SELECT * FROM off_peak_tasks ORDER BY off_peak_task_id")
  137. .all();
  138. const beforeTasks = db.prepare("SELECT * FROM tasks ORDER BY workspace_key").all();
  139. db.exec(`CREATE TRIGGER fail_off_peak_rekey BEFORE UPDATE OF workspace_key ON off_peak_tasks
  140. WHEN OLD.off_peak_task_id = 'source-conflict'
  141. BEGIN SELECT RAISE(ABORT, 'injected rekey failure'); END;`);
  142. await expect(migrate()).rejects.toThrow("injected rekey failure");
  143. expect(db.prepare("SELECT * FROM off_peak_tasks ORDER BY off_peak_task_id").all()).toEqual(
  144. beforeOffPeak,
  145. );
  146. expect(db.prepare("SELECT * FROM tasks ORDER BY workspace_key").all()).toEqual(beforeTasks);
  147. expect(db.prepare(`SELECT status FROM ${ledger}`).all()).toEqual([{ status: "failed" }]);
  148. db.exec("DROP TRIGGER fail_off_peak_rekey");
  149. await migrate();
  150. expect(
  151. db
  152. .prepare("SELECT status, workspace_key FROM off_peak_tasks WHERE off_peak_task_id = ?")
  153. .get("source-conflict"),
  154. ).toEqual({ status: "cancelled", workspace_key: targetKey });
  155. expect(
  156. db.prepare(`SELECT status FROM ${ledger} WHERE status = 'completed'`).all(),
  157. ).toHaveLength(1);
  158. });
  159. });
  160. it("keeps the first merged variant active when canonical has no binding for that session", async () => {
  161. const { db, targetKey, insertOffPeak, migrate } = await createFixture("source");
  162. const laterKey = "remote:ssh:z-later.example:22:dev:/srv/project";
  163. insertOffPeak("first-variant", sourceKey, "bound-session", "queued");
  164. insertOffPeak("later-variant", laterKey, "bound-session", "running");
  165. await migrate();
  166. expect(
  167. db
  168. .prepare(
  169. "SELECT off_peak_task_id, workspace_key, status FROM off_peak_tasks ORDER BY off_peak_task_id",
  170. )
  171. .all(),
  172. ).toEqual([
  173. { off_peak_task_id: "first-variant", workspace_key: targetKey, status: "queued" },
  174. { off_peak_task_id: "later-variant", workspace_key: targetKey, status: "cancelled" },
  175. ]);
  176. });