host-integration-explicit-reset-rearm.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import { mkdtemp, rm } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { tmpdir } from "node:os";
  5. import { digestThreadGoalObjective, type ThreadGoalState } from "@mavis/goal";
  6. import { closeLocalRuntimeDb } from "../../../src/persistence/db.js";
  7. import { LocalThreadGoalIntegration } from "../../../src/thread-goal/host-integration.js";
  8. import { LocalActiveTurnTimingRegistry } from "../../../src/turns/active-turn-timing.js";
  9. /**
  10. * Every explicit user Turn commits a breaker reset, and that reset advances the
  11. * Goal decision epoch. Like a user PATCH, one write invalidates every runner the
  12. * Goal had at once:
  13. *
  14. * 1. the running bound Turn's binding, so its settlement stops at the stale
  15. * stage and never reaches stage 10,
  16. * 2. the post-turn continuation already queued at the old epoch
  17. * (`classifyQueuedItem` -> 'cancel'), and
  18. * 3. any verifier verdict still in flight, whose write-back CAS now misses.
  19. *
  20. * Unlike PATCH, nothing downstream of the reset even observes it: it is a bare
  21. * store write that publishes an SSE `updated` event, not the internal lifecycle
  22. * event `maybeKick` listens on. Before this fix an `active` Goal was therefore
  23. * left with no source of further execution the moment its user typed anything,
  24. * which is what stranded the reported sessions.
  25. *
  26. * These tests drive the real SQLite store so the epoch bump, the staleness
  27. * predicate and the queue classification are the production ones, and they pin
  28. * who owns the follow-up in each way a user Turn can end: it settles normally,
  29. * it never starts at all, its Goal is no longer continuable, or a second writer
  30. * races the drain.
  31. */
  32. const NOW = 1_700_000_000_000;
  33. const SESSION = "sess_explicit_reset_rearm";
  34. const OBJECTIVE = "Ship the release train";
  35. let dataDir: string;
  36. let integration: LocalThreadGoalIntegration;
  37. let turnTimings: LocalActiveTurnTimingRegistry;
  38. let enqueuePostTurnContinuation: ReturnType<typeof vi.fn>;
  39. let enqueueInitialContinuationTurn: ReturnType<typeof vi.fn>;
  40. let cancelInitialContinuation: ReturnType<typeof vi.fn>;
  41. let hasPendingInitialContinuation: ReturnType<typeof vi.fn>;
  42. let startContinuationTurn: ReturnType<typeof vi.fn>;
  43. let reportFailure: ReturnType<typeof vi.fn>;
  44. /** Mirrors the Queue's own view of the pending kickoff item. */
  45. let kickoffQueued: boolean;
  46. beforeEach(async () => {
  47. dataDir = await mkdtemp(join(tmpdir(), "goal-explicit-reset-rearm-"));
  48. turnTimings = new LocalActiveTurnTimingRegistry(() => NOW);
  49. kickoffQueued = false;
  50. enqueuePostTurnContinuation = vi.fn(async () => undefined);
  51. enqueueInitialContinuationTurn = vi.fn(async () => {
  52. kickoffQueued = true;
  53. });
  54. cancelInitialContinuation = vi.fn(async () => {
  55. kickoffQueued = false;
  56. });
  57. hasPendingInitialContinuation = vi.fn(async () => kickoffQueued);
  58. startContinuationTurn = vi.fn(async () => undefined);
  59. reportFailure = vi.fn();
  60. integration = new LocalThreadGoalIntegration({
  61. dataDir,
  62. nowMs: () => NOW,
  63. turnTimingReader: turnTimings,
  64. publishGlobalEvent: () => undefined,
  65. isSessionBusy: (sessionId) =>
  66. turnTimings.getBySession(sessionId) !== undefined,
  67. hasPendingQuestionnaire: async () => false,
  68. retireGoalQuestionnaire: async () => false,
  69. hasPendingPermission: async () => false,
  70. hasAutomationOwnerConflict: async () => false,
  71. hasRequiredBackgroundWork: async () => false,
  72. startContinuationTurn,
  73. enqueuePostTurnContinuation,
  74. enqueueInitialContinuationTurn,
  75. hasPendingInitialContinuation,
  76. cancelInitialContinuation,
  77. requestQueueDispatch: () => undefined,
  78. reportFailure,
  79. emitRuntimeEvent: vi.fn(),
  80. formatError: (error) =>
  81. error instanceof Error ? error.message : String(error),
  82. isEnabled: () => true,
  83. });
  84. });
  85. afterEach(async () => {
  86. closeLocalRuntimeDb(dataDir);
  87. await rm(dataDir, { recursive: true, force: true });
  88. });
  89. /** Create an active Goal whose kickoff has already been delivered. */
  90. async function seedRunningGoal(): Promise<ThreadGoalState> {
  91. const created = await integration.createGoal({
  92. sessionId: SESSION,
  93. objective: OBJECTIVE,
  94. });
  95. const enqueued = await integration.store.getBySession(SESSION);
  96. if (!enqueued) throw new Error("expected the seeded Goal to persist");
  97. await integration.store.transitionKickoffState(
  98. created.goalId,
  99. enqueued.kickoffState,
  100. "consumed",
  101. );
  102. const goal = await integration.store.getBySession(SESSION);
  103. if (goal?.kickoffState !== "consumed") {
  104. throw new Error(
  105. `expected a kickoff-consumed Goal, got ${goal?.kickoffState}`,
  106. );
  107. }
  108. // The kickoff was delivered, so the Queue no longer holds its item.
  109. kickoffQueued = false;
  110. return goal;
  111. }
  112. function continuationOrigin(goal: ThreadGoalState): Record<string, unknown> {
  113. return {
  114. type: "thread-goal-continuation",
  115. goalId: goal.goalId,
  116. goalUpdatedAt: goal.updatedAt,
  117. objectiveDigest: digestThreadGoalObjective(goal.objective),
  118. kind: "active",
  119. };
  120. }
  121. /** Bind and start a Goal continuation Turn, making the session busy. */
  122. async function admitGoalTurn(
  123. goal: ThreadGoalState,
  124. turnId: string,
  125. ): Promise<void> {
  126. turnTimings.begin(SESSION, turnId);
  127. const prepared = await integration.prepareTurnAdmission({
  128. sessionId: SESSION,
  129. turnId,
  130. provenance: {
  131. source: "thread-goal",
  132. sourceContext: { origin: continuationOrigin(goal) },
  133. },
  134. hasPendingPlan: async () => false,
  135. hasPriorityMailboxWork: async () => false,
  136. });
  137. if (prepared?.status !== "ready") {
  138. throw new Error(
  139. `expected a ready Goal admission, got ${JSON.stringify(prepared)}`,
  140. );
  141. }
  142. await prepared.commit();
  143. }
  144. type ReadyPreparation = Extract<
  145. Awaited<ReturnType<LocalThreadGoalIntegration["prepareTurnAdmission"]>>,
  146. { readonly status: "ready" }
  147. >;
  148. /**
  149. * Admit an explicit user Turn exactly the way TurnSystem does, and hand the
  150. * preparation back so a test can choose between `commit`-then-settle and the
  151. * `commit`-then-`compensate` path a failed Turn start takes.
  152. */
  153. async function prepareUserTurn(
  154. turnId: string,
  155. source = "api",
  156. ): Promise<ReadyPreparation | undefined> {
  157. const prepared = await integration.prepareTurnAdmission({
  158. sessionId: SESSION,
  159. turnId,
  160. provenance: { source },
  161. hasPendingPlan: async () => false,
  162. hasPriorityMailboxWork: async () => false,
  163. });
  164. if (prepared !== undefined && prepared.status !== "ready") {
  165. throw new Error(
  166. `expected a ready user admission, got ${JSON.stringify(prepared)}`,
  167. );
  168. }
  169. return prepared;
  170. }
  171. async function admitUserTurn(
  172. turnId: string,
  173. source = "api",
  174. ): Promise<ReadyPreparation> {
  175. const prepared = await prepareUserTurn(turnId, source);
  176. if (!prepared)
  177. throw new Error("expected the breaker reset preparation to be present");
  178. turnTimings.begin(SESSION, turnId);
  179. await prepared.commit();
  180. return prepared;
  181. }
  182. function settleInput(turnId: string) {
  183. return {
  184. sessionId: SESSION,
  185. turnId,
  186. status: "completed" as const,
  187. tokens: 1_200,
  188. retracted: false,
  189. };
  190. }
  191. /** The re-armed follow-up, as it was handed to the Queue transport. */
  192. function enqueuedOrigin(call = 0): Record<string, unknown> {
  193. const [submitted] = enqueuePostTurnContinuation.mock.calls[call] as [
  194. { readonly message: { readonly origin?: unknown } },
  195. ];
  196. return submitted.message.origin as Record<string, unknown>;
  197. }
  198. describe("LocalThreadGoalIntegration explicit-reset continuation re-arm", () => {
  199. it("re-arms the follow-up a user message stole from a running Goal Turn", async () => {
  200. const goal = await seedRunningGoal();
  201. await admitGoalTurn(goal, "turn_goal");
  202. // The verifier shape: the Goal Turn is still in flight — or already inside
  203. // settlement, awaiting a verdict — when the user's message is admitted.
  204. const prepared = await prepareUserTurn("turn_user");
  205. if (!prepared)
  206. throw new Error("expected the breaker reset preparation to be present");
  207. await prepared.commit();
  208. // The epoch moved, so the Goal Turn is stale: its settlement stops before
  209. // stage 10 and continues nothing on its own. The drain is what saves it.
  210. const stale = await integration.settleInjectedTurn(
  211. settleInput("turn_goal"),
  212. );
  213. expect(stale).toMatchObject({ action: "stale" });
  214. expect(enqueuePostTurnContinuation).toHaveBeenCalledOnce();
  215. const current = await integration.store.getBySession(SESSION);
  216. if (!current) throw new Error("expected the Goal to survive the user Turn");
  217. // Rebuilt from durable state at the *current* epoch, so it admits cleanly.
  218. expect(enqueuedOrigin()).toMatchObject({
  219. type: "thread-goal-continuation",
  220. goalId: goal.goalId,
  221. goalUpdatedAt: current.updatedAt,
  222. kind: "active",
  223. });
  224. await expect(
  225. integration.classifyQueuedItem({
  226. sessionId: SESSION,
  227. clientRequestId: "thread-goal-followup:turn_goal",
  228. message: { origin: enqueuedOrigin() },
  229. }),
  230. ).resolves.toBe("ready");
  231. // The user Turn settling afterwards must not add a second follow-up.
  232. turnTimings.finish(SESSION, "turn_goal");
  233. await integration.settleInjectedTurn(settleInput("turn_user"));
  234. expect(enqueuePostTurnContinuation).toHaveBeenCalledOnce();
  235. });
  236. it("re-arms from the user Turn when the stale Goal Turn settles last", async () => {
  237. // The other interleaving: the user Turn reaches settlement first, so it is
  238. // the owner, and the late stale settlement must stay a no-op.
  239. const goal = await seedRunningGoal();
  240. await admitGoalTurn(goal, "turn_goal");
  241. turnTimings.finish(SESSION, "turn_goal");
  242. await admitUserTurn("turn_user");
  243. turnTimings.finish(SESSION, "turn_user");
  244. await integration.settleInjectedTurn(settleInput("turn_user"));
  245. expect(enqueuePostTurnContinuation).toHaveBeenCalledOnce();
  246. expect(enqueuedOrigin()).toMatchObject({
  247. goalId: goal.goalId,
  248. kind: "active",
  249. });
  250. await integration.settleInjectedTurn(settleInput("turn_goal"));
  251. expect(enqueuePostTurnContinuation).toHaveBeenCalledOnce();
  252. });
  253. it("rebuilds the follow-up from compensate when the user Turn never starts", async () => {
  254. // `commit` landed, so the epoch already moved, but TurnSystem failed to start
  255. // the Turn. No settlement will ever come, so compensate is the only owner.
  256. const goal = await seedRunningGoal();
  257. await admitGoalTurn(goal, "turn_goal");
  258. turnTimings.finish(SESSION, "turn_goal");
  259. const prepared = await prepareUserTurn("turn_user");
  260. if (!prepared)
  261. throw new Error("expected the breaker reset preparation to be present");
  262. await prepared.commit();
  263. await prepared.compensate?.();
  264. expect(enqueuePostTurnContinuation).toHaveBeenCalledOnce();
  265. expect(enqueuedOrigin()).toMatchObject({
  266. goalId: goal.goalId,
  267. kind: "active",
  268. });
  269. // And the marker is spent: a late settlement of the same Turn adds nothing.
  270. await integration.settleInjectedTurn(settleInput("turn_user"));
  271. expect(enqueuePostTurnContinuation).toHaveBeenCalledOnce();
  272. });
  273. it("rebuilds an unconsumed kickoff as a kickoff, not as an active continuation", async () => {
  274. // The queued kickoff carries the one-shot attachment snapshot, so an epoch
  275. // advance that strands it has to be repaired by re-issuing the kickoff.
  276. await integration.createGoal({ sessionId: SESSION, objective: OBJECTIVE });
  277. const goal = await integration.store.getBySession(SESSION);
  278. if (!goal) throw new Error("expected the seeded Goal to persist");
  279. expect(goal.kickoffState).not.toBe("consumed");
  280. expect(kickoffQueued).toBe(true);
  281. enqueueInitialContinuationTurn.mockClear();
  282. await admitUserTurn("turn_user");
  283. turnTimings.finish(SESSION, "turn_user");
  284. await integration.settleInjectedTurn(settleInput("turn_user"));
  285. expect(cancelInitialContinuation).toHaveBeenCalled();
  286. expect(enqueueInitialContinuationTurn).toHaveBeenCalledOnce();
  287. const [, message] = enqueueInitialContinuationTurn.mock.calls[0] as [
  288. string,
  289. { readonly origin?: Record<string, unknown> },
  290. ];
  291. expect(message.origin).toMatchObject({
  292. type: "thread-goal-kickoff",
  293. goalId: goal.goalId,
  294. });
  295. // The kickoff owns execution; no duplicate `active` continuation.
  296. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  297. });
  298. it("keeps the kickoff delivery responsibility when the rewrite fails mid-way", async () => {
  299. /*
  300. * The rewrite cancels the queued kickoff and then re-enqueues it. If the
  301. * re-enqueue fails, the old item is already gone while the kickoff — and
  302. * the one-shot attachment snapshot it carries — has never run. Two things
  303. * used to go wrong at once: the failure was swallowed, so the drain dropped
  304. * the marker, and the next reconcile read `enqueued` with an empty Queue as
  305. * "already delivered" and consumed it. The input was then never delivered.
  306. */
  307. await integration.createGoal({ sessionId: SESSION, objective: OBJECTIVE });
  308. const seeded = await integration.store.getBySession(SESSION);
  309. if (!seeded) throw new Error("expected the seeded Goal to persist");
  310. expect(seeded.kickoffState).not.toBe("consumed");
  311. enqueueInitialContinuationTurn.mockClear();
  312. await admitUserTurn("turn_user");
  313. turnTimings.finish(SESSION, "turn_user");
  314. // The cancel lands, the first re-enqueue does not.
  315. enqueueInitialContinuationTurn.mockRejectedValueOnce(
  316. new Error("queue unavailable"),
  317. );
  318. await expect(
  319. integration.settleInjectedTurn(settleInput("turn_user")),
  320. ).rejects.toThrow("queue unavailable");
  321. expect(cancelInitialContinuation).toHaveBeenCalled();
  322. expect(reportFailure).toHaveBeenCalledWith(
  323. SESSION,
  324. expect.stringContaining("thread_goal_kickoff_refresh_failed"),
  325. );
  326. // The undelivered kickoff must not be inferred as consumed just because the
  327. // Queue no longer holds it.
  328. const stranded = await integration.store.getBySession(SESSION);
  329. expect(stranded?.kickoffState).not.toBe("consumed");
  330. expect(kickoffQueued).toBe(false);
  331. // The retry re-delivers the original kickoff, attachments and all.
  332. await integration.settleInjectedTurn(settleInput("turn_user"));
  333. expect(enqueueInitialContinuationTurn).toHaveBeenCalledTimes(2);
  334. const [, redelivered] = enqueueInitialContinuationTurn.mock.calls[1] as [
  335. string,
  336. {
  337. readonly origin?: Record<string, unknown>;
  338. readonly attachments?: readonly unknown[];
  339. },
  340. ];
  341. expect(redelivered.origin).toMatchObject({
  342. type: "thread-goal-kickoff",
  343. goalId: seeded.goalId,
  344. });
  345. expect(kickoffQueued).toBe(true);
  346. const recovered = await integration.store.getBySession(SESSION);
  347. expect(recovered?.kickoffState).not.toBe("consumed");
  348. });
  349. it("still consumes a kickoff that was genuinely delivered and drained", async () => {
  350. // The guard above must not keep a normally delivered kickoff alive forever:
  351. // an `enqueued` Goal whose item left the Queue by being executed is still
  352. // consumed, exactly as before.
  353. await integration.createGoal({ sessionId: SESSION, objective: OBJECTIVE });
  354. const seeded = await integration.store.getBySession(SESSION);
  355. if (!seeded) throw new Error("expected the seeded Goal to persist");
  356. // The Queue delivered it: the item is gone and no rewrite is outstanding.
  357. kickoffQueued = false;
  358. await integration.recoverInitialContinuation(seeded);
  359. const current = await integration.store.getBySession(SESSION);
  360. expect(current?.kickoffState).toBe("consumed");
  361. });
  362. it("does not re-arm a Goal the user paused in the same Turn", async () => {
  363. const goal = await seedRunningGoal();
  364. await admitGoalTurn(goal, "turn_goal");
  365. turnTimings.finish(SESSION, "turn_goal");
  366. await admitUserTurn("turn_user");
  367. await integration.patchGoal(SESSION, { status: "paused" });
  368. turnTimings.finish(SESSION, "turn_user");
  369. await integration.settleInjectedTurn(settleInput("turn_user"));
  370. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  371. expect(startContinuationTurn).not.toHaveBeenCalled();
  372. });
  373. it("prepares nothing when the session has no active Goal", async () => {
  374. await expect(prepareUserTurn("turn_user")).resolves.toBeUndefined();
  375. await integration.settleInjectedTurn(settleInput("turn_user"));
  376. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  377. });
  378. it("does not re-arm when the reset CAS lost to a concurrent epoch advance", async () => {
  379. const goal = await seedRunningGoal();
  380. const prepared = await prepareUserTurn("turn_user");
  381. if (!prepared)
  382. throw new Error("expected the breaker reset preparation to be present");
  383. // Another writer advances the epoch between preparation and commit, so the
  384. // reset CAS misses and this preparation never owned a follow-up. The PATCH
  385. // path that won the race owns it instead.
  386. await integration.patchGoal(SESSION, { tokenBudget: 400_000 });
  387. for (let i = 0; i < 8; i += 1) await Promise.resolve();
  388. enqueuePostTurnContinuation.mockClear();
  389. startContinuationTurn.mockClear();
  390. await prepared.commit();
  391. const afterCommit = await integration.store.getBySession(SESSION);
  392. expect(afterCommit?.goalId).toBe(goal.goalId);
  393. await integration.settleInjectedTurn(settleInput("turn_user"));
  394. expect(enqueuePostTurnContinuation).not.toHaveBeenCalled();
  395. });
  396. it("stays armed when the Queue rejects the rebuilt follow-up", async () => {
  397. const goal = await seedRunningGoal();
  398. await admitGoalTurn(goal, "turn_goal");
  399. turnTimings.finish(SESSION, "turn_goal");
  400. await admitUserTurn("turn_user");
  401. turnTimings.finish(SESSION, "turn_user");
  402. enqueuePostTurnContinuation.mockRejectedValueOnce(
  403. new Error("queue closed"),
  404. );
  405. await expect(
  406. integration.settleInjectedTurn(settleInput("turn_user")),
  407. ).rejects.toThrow("queue closed");
  408. expect(reportFailure).toHaveBeenCalledWith(
  409. SESSION,
  410. expect.stringContaining("thread_goal_continuation_enqueue_failed"),
  411. );
  412. // The settle retry finds the marker still armed and rebuilds the follow-up.
  413. await integration.settleInjectedTurn(settleInput("turn_user"));
  414. expect(enqueuePostTurnContinuation).toHaveBeenCalledTimes(2);
  415. expect(enqueuedOrigin(1)).toMatchObject({
  416. goalId: goal.goalId,
  417. kind: "active",
  418. });
  419. });
  420. it("does not let a failed drain overwrite a newer epoch writer", async () => {
  421. // The failing drain must not restore its own (now older) claim on top of the
  422. // arm a later writer installed while the enqueue was in flight, or the newer
  423. // epoch's follow-up would be silently rebuilt from the wrong Goal.
  424. const first = await seedRunningGoal();
  425. await admitUserTurn("turn_user");
  426. turnTimings.finish(SESSION, "turn_user");
  427. let recreated: ThreadGoalState | undefined;
  428. enqueuePostTurnContinuation.mockImplementationOnce(async () => {
  429. await integration.deleteGoal(SESSION);
  430. recreated = await integration.createGoal({
  431. sessionId: SESSION,
  432. objective: "A new goal",
  433. });
  434. const seeded = await integration.store.getBySession(SESSION);
  435. if (!seeded) throw new Error("expected the recreated Goal to persist");
  436. await integration.store.transitionKickoffState(
  437. recreated.goalId,
  438. seeded.kickoffState,
  439. "consumed",
  440. );
  441. await integration
  442. .prepareTurnAdmission({
  443. sessionId: SESSION,
  444. turnId: "turn_user_2",
  445. provenance: { source: "api" },
  446. hasPendingPlan: async () => false,
  447. hasPriorityMailboxWork: async () => false,
  448. })
  449. .then((prepared) =>
  450. prepared?.status === "ready" ? prepared.commit() : undefined,
  451. );
  452. throw new Error("queue closed");
  453. });
  454. await expect(
  455. integration.settleInjectedTurn(settleInput("turn_user")),
  456. ).rejects.toThrow("queue closed");
  457. // The next settlement must rebuild the *recreated* Goal's follow-up.
  458. await integration.settleInjectedTurn(settleInput("turn_user_2"));
  459. expect(enqueuePostTurnContinuation).toHaveBeenCalledTimes(2);
  460. expect(recreated?.goalId).not.toBe(first.goalId);
  461. expect(enqueuedOrigin(1)).toMatchObject({
  462. goalId: recreated?.goalId,
  463. kind: "active",
  464. });
  465. });
  466. it("re-arms for channel-sourced user Turns too", async () => {
  467. const goal = await seedRunningGoal();
  468. await admitUserTurn("turn_channel", "channel:lark");
  469. turnTimings.finish(SESSION, "turn_channel");
  470. await integration.settleInjectedTurn(settleInput("turn_channel"));
  471. expect(enqueuePostTurnContinuation).toHaveBeenCalledOnce();
  472. expect(enqueuedOrigin()).toMatchObject({
  473. goalId: goal.goalId,
  474. kind: "active",
  475. });
  476. });
  477. it("rebuilds under an epoch-scoped key so the Queue cannot fold it onto the stale row", async () => {
  478. /*
  479. * The rebuild carries the settling Turn's id, and the Host's default
  480. * follow-up key is derived from exactly that id. Reusing it makes the Queue
  481. * replay onto the row that belongs to the epoch just invalidated, which
  482. * final recheck then cancels for being stale — so the Goal stops even though
  483. * the marker did its job. The rebuild has to name the epoch it is rebuilt at.
  484. */
  485. const goal = await seedRunningGoal();
  486. await admitGoalTurn(goal, "turn_goal");
  487. enqueuePostTurnContinuation.mockImplementationOnce(async () => {
  488. const prepared = await prepareUserTurn("turn_user");
  489. if (!prepared)
  490. throw new Error("expected the breaker reset preparation to be present");
  491. await prepared.commit();
  492. });
  493. await integration.settleInjectedTurn(settleInput("turn_goal"));
  494. expect(enqueuePostTurnContinuation).toHaveBeenCalledTimes(2);
  495. const staleSubmission = enqueuePostTurnContinuation.mock.calls[0]?.[0] as {
  496. readonly clientRequestId?: string;
  497. };
  498. const rebuiltSubmission = enqueuePostTurnContinuation.mock
  499. .calls[1]?.[0] as {
  500. readonly clientRequestId?: string;
  501. };
  502. const current = await integration.store.getBySession(SESSION);
  503. if (!current) throw new Error("expected the Goal to survive the user Turn");
  504. // Stage 10 keeps the default per-Turn key, which the Host derives from the
  505. // settling turnId; the rebuild must not reuse it.
  506. expect(staleSubmission.clientRequestId).toBeUndefined();
  507. expect(rebuiltSubmission.clientRequestId).toBe(
  508. `thread-goal-followup:rearm:${goal.goalId}:${current.updatedAt}`,
  509. );
  510. expect(rebuiltSubmission.clientRequestId).not.toBe(
  511. "thread-goal-followup:turn_goal",
  512. );
  513. });
  514. it("reuses one key when the same epoch rebuild is retried", async () => {
  515. // Retrying the same rebuild must stay idempotent: at-least-once delivery is
  516. // the contract, but it may not cost a second admissible row per attempt.
  517. const goal = await seedRunningGoal();
  518. await admitGoalTurn(goal, "turn_goal");
  519. await admitUserTurn("turn_user");
  520. turnTimings.finish(SESSION, "turn_goal");
  521. enqueuePostTurnContinuation.mockRejectedValueOnce(
  522. new Error("queue unavailable"),
  523. );
  524. await expect(
  525. integration.settleInjectedTurn(settleInput("turn_user")),
  526. ).rejects.toThrow("queue unavailable");
  527. await integration.settleInjectedTurn(settleInput("turn_user"));
  528. const keys = enqueuePostTurnContinuation.mock.calls.map(
  529. (call) =>
  530. (call[0] as { readonly clientRequestId?: string }).clientRequestId,
  531. );
  532. const current = await integration.store.getBySession(SESSION);
  533. if (!current) throw new Error("expected the Goal to survive");
  534. const expected = `thread-goal-followup:rearm:${goal.goalId}:${current.updatedAt}`;
  535. expect(keys.filter((key) => key !== undefined)).toEqual([
  536. expected,
  537. expected,
  538. ]);
  539. });
  540. it("does not let an old-epoch stage 10 submission swallow a newer arm", async () => {
  541. // Scheduling a follow-up is asynchronous: the Goal is read and a prompt is
  542. // built before the Queue submission lands. A user message admitted inside
  543. // that window resets the breaker and arms for the new epoch, while the item
  544. // this settlement is handing over still carries the old one and will be
  545. // cancelled by final recheck. Clearing the marker unconditionally afterwards
  546. // would leave the Goal with no runner at all — the exact bug this suite
  547. // exists for, reintroduced through the back door.
  548. const goal = await seedRunningGoal();
  549. await admitGoalTurn(goal, "turn_goal");
  550. enqueuePostTurnContinuation.mockImplementationOnce(async () => {
  551. const prepared = await prepareUserTurn("turn_user");
  552. if (!prepared)
  553. throw new Error("expected the breaker reset preparation to be present");
  554. await prepared.commit();
  555. });
  556. // Stage 10 continues normally and submits the (now old-epoch) follow-up,
  557. // then the same settlement's tail drain finds the surviving marker and
  558. // rebuilds a second follow-up at the current epoch.
  559. const decision = await integration.settleInjectedTurn(
  560. settleInput("turn_goal"),
  561. );
  562. expect(decision).toMatchObject({ stage: 10, action: "continued" });
  563. expect(enqueuePostTurnContinuation).toHaveBeenCalledTimes(2);
  564. // The old-epoch item is the one final recheck throws away...
  565. await expect(
  566. integration.classifyQueuedItem({
  567. sessionId: SESSION,
  568. clientRequestId: "thread-goal-followup:turn_goal",
  569. message: { origin: enqueuedOrigin(0) },
  570. }),
  571. ).resolves.toBe("cancel");
  572. // ...and the rebuilt one is what actually keeps the Goal running. Without
  573. // the generation guard the marker would have been deleted here and only the
  574. // cancelled item would exist.
  575. const current = await integration.store.getBySession(SESSION);
  576. expect(enqueuedOrigin(1)).toMatchObject({
  577. goalId: goal.goalId,
  578. goalUpdatedAt: current?.updatedAt,
  579. kind: "active",
  580. });
  581. await expect(
  582. integration.classifyQueuedItem({
  583. sessionId: SESSION,
  584. clientRequestId: "thread-goal-followup:turn_goal",
  585. message: { origin: enqueuedOrigin(1) },
  586. }),
  587. ).resolves.toBe("ready");
  588. // The debt is settled: the user Turn adds no third item.
  589. turnTimings.finish(SESSION, "turn_goal");
  590. await integration.settleInjectedTurn(settleInput("turn_user"));
  591. expect(enqueuePostTurnContinuation).toHaveBeenCalledTimes(2);
  592. });
  593. });