controller.test.ts 12 KB

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