controller.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import { describe, expect, it, vi } from "vitest";
  2. import { SessionLifecycleController } from "../../src/session-lifecycle/index.js";
  3. function fixture() {
  4. const runtimes = new Set<string>();
  5. const known = new Set(["a", "b"]);
  6. const host = {
  7. exists: vi.fn(async (id: string) => known.has(id)),
  8. hasRuntime: (id: string) => runtimes.has(id),
  9. activate: vi.fn(async (id: string) => {
  10. runtimes.add(id);
  11. }),
  12. validateActivation: vi.fn(async () => {}),
  13. assertCanStop: vi.fn(),
  14. release: vi.fn(async (id: string) => {
  15. runtimes.delete(id);
  16. }),
  17. onChange: vi.fn(),
  18. };
  19. return { host, runtimes, known, lifecycle: new SessionLifecycleController(host) };
  20. }
  21. describe("session runtime lifecycle", () => {
  22. it.each(["ensureReady", "initialize"] as const)(
  23. "validates %s joining an old contextless startup",
  24. async (method) => {
  25. const { lifecycle, host } = fixture();
  26. const gate = Promise.withResolvers<void>();
  27. const startup = lifecycle.initialize("a", () => gate.promise);
  28. const workspace = { workspacePath: "/wrong", workspaceKey: "/wrong" };
  29. host.validateActivation.mockRejectedValue(new Error("wrong workspace"));
  30. const unusedActivation = vi.fn(async () => {});
  31. const joined =
  32. method === "ensureReady"
  33. ? lifecycle.ensureReady("a", workspace)
  34. : lifecycle.initialize("a", unusedActivation, workspace);
  35. const rejection = expect(joined).rejects.toThrow("wrong workspace");
  36. gate.resolve();
  37. await startup;
  38. await rejection;
  39. expect(host.validateActivation).toHaveBeenCalledWith("a", workspace);
  40. expect(unusedActivation).not.toHaveBeenCalled();
  41. expect(host.release).not.toHaveBeenCalled();
  42. expect((await lifecycle.getState("a")).state).toBe("ready");
  43. },
  44. );
  45. it("registers creation ownership before persistence without running restore validation", async () => {
  46. const { lifecycle, host } = fixture();
  47. const gate = Promise.withResolvers<void>();
  48. const workspace = { workspacePath: "/repo", workspaceKey: "/repo" };
  49. host.validateActivation.mockRejectedValue(new Error("not persisted yet"));
  50. const startup = lifecycle.initialize("new", () => gate.promise, workspace, "create");
  51. const joined = lifecycle.ensureReady("new", workspace);
  52. await expect(
  53. lifecycle.ensureReady("new", { workspacePath: "/other", workspaceKey: "/other" }),
  54. ).rejects.toMatchObject({ code: "conflict" });
  55. gate.resolve();
  56. await Promise.all([startup, joined]);
  57. expect(host.validateActivation).not.toHaveBeenCalled();
  58. });
  59. it("keeps one workspace per flight and validates restart before releasing", async () => {
  60. const { lifecycle, host } = fixture();
  61. const workspace = { workspacePath: "/repo/", workspaceKey: "/repo/" };
  62. const other = { workspacePath: "/other", workspaceKey: "/other" };
  63. const entered = Promise.withResolvers<void>();
  64. const gate = Promise.withResolvers<void>();
  65. host.activate.mockImplementationOnce(async () => {
  66. entered.resolve();
  67. await gate.promise;
  68. });
  69. const startup = lifecycle.ensureReady("a", workspace);
  70. await entered.promise;
  71. await expect(lifecycle.restart("a", other)).rejects.toMatchObject({ code: "conflict" });
  72. await expect(lifecycle.ensureReady("a", other)).rejects.toMatchObject({ code: "conflict" });
  73. const restarting = lifecycle.restart("a", workspace);
  74. gate.resolve();
  75. await Promise.all([startup, restarting]);
  76. expect(host.activate).toHaveBeenLastCalledWith("a", workspace);
  77. host.release.mockClear();
  78. host.validateActivation.mockRejectedValueOnce(new Error("wrong workspace"));
  79. await expect(lifecycle.restart("a", workspace)).rejects.toThrow("wrong workspace");
  80. expect(host.release).not.toHaveBeenCalled();
  81. expect((await lifecycle.getState("a")).state).toBe("ready");
  82. });
  83. it("does not treat a deleted persistent session as ready even if its old runtime remains", async () => {
  84. const { lifecycle, known } = fixture();
  85. await lifecycle.ensureReady("a");
  86. known.delete("a");
  87. await expect(lifecycle.ensureReady("a")).rejects.toMatchObject({ code: "sessionNotFound" });
  88. });
  89. it("queries without activating and rejects unknown identities", async () => {
  90. const { lifecycle, host } = fixture();
  91. expect(await lifecycle.getState("a")).toMatchObject({
  92. sessionId: "a",
  93. state: "unloaded",
  94. lastError: null,
  95. });
  96. await expect(lifecycle.getState("missing")).rejects.toMatchObject({ code: "sessionNotFound" });
  97. expect(host.activate).not.toHaveBeenCalled();
  98. });
  99. it("joins concurrent startup and does not expose a registered partial instance as ready", async () => {
  100. const { lifecycle, host, runtimes } = fixture();
  101. const gate = Promise.withResolvers<void>();
  102. const entered = Promise.withResolvers<void>();
  103. host.activate.mockImplementation(async (id) => {
  104. runtimes.add(id);
  105. entered.resolve();
  106. await gate.promise;
  107. });
  108. const first = lifecycle.ensureReady("a");
  109. const second = lifecycle.ensureReady("a");
  110. await entered.promise;
  111. expect((await lifecycle.getState("a")).state).toBe("starting");
  112. gate.resolve();
  113. await Promise.all([first, second]);
  114. await lifecycle.ensureReady("a");
  115. expect(host.activate).toHaveBeenCalledTimes(1);
  116. expect((await lifecycle.getState("a")).state).toBe("ready");
  117. });
  118. it("waits for real release before recreating and joins duplicate stops", async () => {
  119. const { lifecycle, host, runtimes } = fixture();
  120. await lifecycle.ensureReady("a");
  121. const gate = Promise.withResolvers<void>();
  122. host.release.mockImplementation(async (id) => {
  123. runtimes.delete(id);
  124. await gate.promise;
  125. });
  126. const stop = lifecycle.stop("a");
  127. const duplicate = lifecycle.stop("a");
  128. const ready = lifecycle.ensureReady("a");
  129. expect((await lifecycle.getState("a")).state).toBe("stopping");
  130. expect(host.activate).toHaveBeenCalledTimes(1);
  131. gate.resolve();
  132. await Promise.all([stop, duplicate, ready]);
  133. expect(host.release).toHaveBeenCalledTimes(1);
  134. expect(host.activate).toHaveBeenCalledTimes(2);
  135. });
  136. it("owns the whole restart including its unloaded interval", async () => {
  137. const { lifecycle, host } = fixture();
  138. await lifecycle.ensureReady("a");
  139. const gate = Promise.withResolvers<void>();
  140. host.release.mockImplementation(async () => gate.promise);
  141. const restart = lifecycle.restart("a");
  142. const duplicate = lifecycle.restart("a");
  143. const ready = lifecycle.ensureReady("a");
  144. await expect(lifecycle.stop("a")).rejects.toMatchObject({ code: "conflict" });
  145. gate.resolve();
  146. await Promise.all([restart, duplicate, ready]);
  147. expect(host.release).toHaveBeenCalledTimes(1);
  148. expect(host.activate).toHaveBeenCalledTimes(2);
  149. });
  150. it("coalesces restart during startup without overlapping instances", async () => {
  151. const { lifecycle, host } = fixture();
  152. const gate = Promise.withResolvers<void>();
  153. host.activate.mockImplementation(async (id) => {
  154. if (id === "a") await gate.promise;
  155. });
  156. const pending = lifecycle.ensureReady("a");
  157. await expect(lifecycle.stop("a")).rejects.toMatchObject({ code: "conflict" });
  158. const restarting = lifecycle.restart("a");
  159. const duplicate = lifecycle.restart("a");
  160. expect(host.release).not.toHaveBeenCalled();
  161. await lifecycle.ensureReady("b");
  162. expect((await lifecycle.getState("b")).state).toBe("ready");
  163. gate.resolve();
  164. await pending;
  165. await Promise.all([restarting, duplicate]);
  166. expect(host.activate.mock.calls.filter(([id]) => id === "a")).toHaveLength(2);
  167. expect(host.release).toHaveBeenCalledTimes(1);
  168. });
  169. it("reserves restart before earlier startup observers can stop the runtime", async () => {
  170. const { lifecycle, host } = fixture();
  171. const gate = Promise.withResolvers<void>();
  172. host.activate.mockImplementationOnce(async () => gate.promise);
  173. const startup = lifecycle.ensureReady("a");
  174. const competingStop = startup.then(() => lifecycle.stop("a"));
  175. const rejection = expect(competingStop).rejects.toMatchObject({ code: "conflict" });
  176. const restart = lifecycle.restart("a");
  177. void restart.catch(() => undefined);
  178. gate.resolve();
  179. await rejection;
  180. await restart;
  181. expect(host.release).toHaveBeenCalledTimes(1);
  182. expect(host.activate).toHaveBeenCalledTimes(2);
  183. });
  184. it("invalidates history-only resources even when no runtime is loaded", async () => {
  185. const { lifecycle, host } = fixture();
  186. await lifecycle.restart("a");
  187. expect(host.release).toHaveBeenCalledWith("a");
  188. expect(host.activate).toHaveBeenCalledTimes(1);
  189. });
  190. it("keeps lifecycle versions monotonic across stop and reopen", async () => {
  191. const { lifecycle } = fixture();
  192. await lifecycle.ensureReady("a");
  193. const first = await lifecycle.getState("a");
  194. await lifecycle.stop("a");
  195. const stopped = await lifecycle.getState("a");
  196. await lifecycle.ensureReady("a");
  197. const reopened = await lifecycle.getState("a");
  198. expect(stopped.revision).toBeGreaterThan(first.revision);
  199. expect(reopened.revision).toBeGreaterThan(stopped.revision);
  200. expect(reopened.generation).toBeGreaterThan(first.generation);
  201. });
  202. it("keeps a rejected preflight ready and preserves its instance", async () => {
  203. const { lifecycle, host } = fixture();
  204. await lifecycle.ensureReady("a");
  205. host.assertCanStop.mockImplementation(() => {
  206. throw new Error("busy");
  207. });
  208. await expect(lifecycle.stop("a")).rejects.toThrow("busy");
  209. expect((await lifecycle.getState("a")).state).toBe("ready");
  210. expect(host.release).not.toHaveBeenCalled();
  211. });
  212. it("cleans partial startup and allows an explicit retry", async () => {
  213. const { lifecycle, host, runtimes } = fixture();
  214. host.activate.mockImplementationOnce(async (id) => {
  215. runtimes.add(id);
  216. throw new Error("init failed");
  217. });
  218. await expect(lifecycle.ensureReady("a")).rejects.toThrow("init failed");
  219. expect(await lifecycle.getState("a")).toMatchObject({
  220. state: "unloaded",
  221. lastError: { operation: "ensureReady" },
  222. });
  223. expect(host.release).toHaveBeenCalledTimes(1);
  224. await lifecycle.ensureReady("a");
  225. expect(await lifecycle.getState("a")).toMatchObject({ state: "ready", lastError: null });
  226. });
  227. it("quarantines failed release and never restarts or replays cleanup", async () => {
  228. const { lifecycle, host, runtimes } = fixture();
  229. await lifecycle.ensureReady("a");
  230. host.release.mockImplementation(async (id) => {
  231. runtimes.delete(id);
  232. throw new Error("resource timeout");
  233. });
  234. const stopping = lifecycle.stop("a");
  235. const waiting = lifecycle.ensureReady("a");
  236. await expect(stopping).rejects.toThrow("resource timeout");
  237. await expect(waiting).rejects.toThrow("resource timeout");
  238. expect((await lifecycle.getState("a")).state).toBe("faulted");
  239. for (const action of ["ensureReady", "stop", "restart"] as const) {
  240. await expect(lifecycle[action]("a")).rejects.toMatchObject({ code: "recoveryRequired" });
  241. }
  242. expect(host.activate).toHaveBeenCalledTimes(1);
  243. expect(host.release).toHaveBeenCalledTimes(1);
  244. });
  245. it("quarantines initialization cleanup failure with both errors retained", async () => {
  246. const { lifecycle, host } = fixture();
  247. host.activate.mockRejectedValue(new Error("init failed"));
  248. host.release.mockRejectedValue(new Error("cleanup failed"));
  249. await expect(lifecycle.ensureReady("a")).rejects.toBeInstanceOf(AggregateError);
  250. expect((await lifecycle.getState("a")).state).toBe("faulted");
  251. });
  252. });