Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

serverRuntimeStartup.reconcile.test.ts

977 lines34.4 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 type OrchestrationCommand,
4 type OrchestrationSessionStatus,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 type ProviderSendTurnInput,
8 ThreadId,
9 TurnId,
10} from "@t3tools/contracts";
11import { assert, it } from "@effect/vitest";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Stream from "effect/Stream";
17​
18import { OrchestrationCommandInvariantError } from "./orchestration/Errors.ts";
19import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
20import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
21import {
22 ProviderSessionDirectoryPersistenceError,
23 ProviderSessionNotFoundError,
24} from "./provider/Errors.ts";
25import * as ProviderService from "./provider/Services/ProviderService.ts";
26import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
27import { ServerActivation } from "./serverActivation.ts";
28import * as ServerSettings from "./serverSettings.ts";
29import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
30​
31const providerInstanceId = ProviderInstanceId.make("codex");
32const updatedAt = "2026-08-20T12:00:00.000Z";
33​
34const makeThread = (
35 id: string,
36 status: OrchestrationSessionStatus,
37 activeTurnId: TurnId | null = null,
38 archivedAt: string | null = null,
39 deletedAt: string | null = null,
40) => ({
41 id: ThreadId.make(id),
42 archivedAt,
43 deletedAt,
44 interactionMode: "default" as const,
45 session: {
46 threadId: ThreadId.make(id),
47 status,
48 providerName: "codex" as const,
49 providerInstanceId,
50 runtimeMode: "full-access" as const,
51 activeTurnId,
52 lastError: null,
53 updatedAt,
54 },
55});
56​
57const makeProviderService = (liveThreadIds: ReadonlyArray<ThreadId> = []) =>
58 ({
59 startSession: () => Effect.die("unused"),
60 sendTurn: () => Effect.die("unused"),
61 compactThread: () => Effect.die("unused"),
62 interruptTurn: () => Effect.die("unused"),
63 respondToRequest: () => Effect.die("unused"),
64 respondToUserInput: () => Effect.die("unused"),
65 stopSession: () => Effect.die("unused"),
66 listSessions: () => Effect.succeed(liveThreadIds.map((threadId) => ({ threadId }) as never)),
67 getCapabilities: () => Effect.die("unused"),
68 assertConversationRollbackSupported: () => Effect.die("unused"),
69 getInstanceInfo: () => Effect.die("unused"),
70 rollbackConversation: () => Effect.die("unused"),
71 uploadFeedback: () => Effect.die("unused"),
72 streamEvents: Stream.empty,
73 }) satisfies ProviderService.ProviderService["Service"];
74​
75const queryWithThreads = (threads: ReadonlyArray<ReturnType<typeof makeThread>>) =>
76 ({
77 getUserInputActivity: () => Effect.die("unused"),
78 getCommandReadModel: () => Effect.succeed({ threads } as never),
79 }) as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"];
80​
81const runReconciliation = (input: {
82 readonly threads: ReadonlyArray<ReturnType<typeof makeThread>>;
83 readonly continueAfterRestart?: boolean;
84 readonly liveThreadIds?: ReadonlyArray<ThreadId>;
85 readonly providerService?: ProviderService.ProviderService["Service"];
86 readonly directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"];
87 readonly dispatch: OrchestrationEngine.OrchestrationEngineService["Service"]["dispatch"];
88}) =>
89 ServerRuntimeStartup.reconcileProviderSessions.pipe(
90 Effect.provideService(
91 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
92 queryWithThreads(input.threads),
93 ),
94 Effect.provideService(
95 ProviderService.ProviderService,
96 input.providerService ?? makeProviderService(input.liveThreadIds),
97 ),
98 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, input.directory),
99 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
100 readEvents: () => Stream.empty,
101 readThreadEvents: () => Stream.empty,
102 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
103 dispatch: input.dispatch,
104 streamDomainEvents: Stream.empty,
105 subscribeDomainEvents: Effect.succeed(Stream.empty),
106 latestSequence: Effect.succeed(0),
107 }),
108 Effect.provide(
109 Layer.mergeAll(
110 ServerSettings.layerTest({
111 continueThreadsAfterServerUpdate: input.continueAfterRestart ?? false,
112 }),
113 NodeServices.layer,
114 ),
115 ),
116 );
117​
118it.effect("marks active running sessions that have persisted resume state", () => {
119 const active = makeThread("thread-mark-active", "running", TurnId.make("turn-mark-active"));
120 const archived = makeThread(
121 "thread-mark-archived",
122 "running",
123 TurnId.make("turn-mark-archived"),
124 updatedAt,
125 );
126 const ready = makeThread("thread-mark-ready", "ready");
127 const missingResumeState = makeThread(
128 "thread-mark-missing-resume-state",
129 "running",
130 TurnId.make("turn-mark-missing-resume-state"),
131 );
132 const bindingReads: ThreadId[] = [];
133 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
134​
135 return ServerRuntimeStartup.markRunningProviderSessionsForContinuation.pipe(
136 Effect.provideService(
137 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
138 queryWithThreads([active, archived, ready, missingResumeState]),
139 ),
140 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
141 getBinding: (threadId) =>
142 Effect.sync(() => bindingReads.push(threadId)).pipe(
143 Effect.as(
144 Option.some({
145 threadId,
146 provider: ProviderDriverKind.make("codex"),
147 providerInstanceId,
148 ...(threadId === active.id ? { resumeCursor: { threadId } } : {}),
149 runtimePayload: { activeTurnId: "turn-mark-active" },
150 }),
151 ),
152 ),
153 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
154 getProvider: () => Effect.die("unused"),
155 listThreadIds: () => Effect.die("unused"),
156 listBindings: () => Effect.succeed([]),
157 }),
158 Effect.tap((marked) =>
159 Effect.sync(() => {
160 assert.deepStrictEqual(bindingReads, [active.id, missingResumeState.id]);
161 assert.deepStrictEqual(marked, [active.id]);
162 assert.deepStrictEqual(upserts[0]?.runtimePayload, {
163 activeTurnId: "turn-mark-active",
164 continueAfterServerUpdate: active.session.activeTurnId,
165 continueAfterServerUpdatePrepared: null,
166 });
167 }),
168 ),
169 );
170});
171​
172it.effect.each(["marked update", "opt-in restart"] as const)(
173 "continues %s sessions after activation with provider-specific input",
174 (recovery) =>
175 Effect.gen(function* () {
176 const codex = makeThread(
177 "thread-continue-codex",
178 "running",
179 TurnId.make("turn-continue-codex"),
180 );
181 const fallbackContinuationTurnId = TurnId.make("turn-continue-fallback");
182 const fallback = makeThread(
183 "thread-continue-fallback",
184 recovery === "marked update" ? "starting" : "running",
185 recovery === "marked update" ? null : fallbackContinuationTurnId,
186 );
187 const fallbackProviderInstanceId = ProviderInstanceId.make("claudeAgent");
188 const continuationSent = yield* Deferred.make<void>();
189 const continuationCleared = yield* Deferred.make<void>();
190 const sends: ProviderSendTurnInput[] = [];
191 const dispatched: OrchestrationCommand[] = [];
192 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
193 const bindings = new Map<ThreadId, ProviderSessionDirectory.ProviderRuntimeBinding>(
194 [codex, fallback].map((thread) => [
195 thread.id,
196 {
197 threadId: thread.id,
198 provider:
199 thread.id === codex.id
200 ? ProviderDriverKind.make("codex")
201 : ProviderDriverKind.make("claudeAgent"),
202 providerInstanceId:
203 thread.id === codex.id ? providerInstanceId : fallbackProviderInstanceId,
204 status: "running" as const,
205 resumeCursor: { threadId: thread.id },
206 runtimePayload:
207 recovery === "marked update"
208 ? {
209 continueAfterServerUpdate:
210 thread.id === codex.id
211 ? codex.session.activeTurnId
212 : fallbackContinuationTurnId,
213 }
214 : { activeTurnId: thread.session.activeTurnId },
215 },
216 ]),
217 );
218 const providerService: ProviderService.ProviderService["Service"] = {
219 ...makeProviderService(),
220 getCapabilities: (instanceId) =>
221 Effect.succeed({
222 sessionModelSwitch: "in-session",
223 ...(instanceId === providerInstanceId ? { promptlessTurnContinuation: true } : {}),
224 }),
225 sendTurn: (input) =>
226 Effect.gen(function* () {
227 sends.push(input);
228 if (sends.length === 2) {
229 yield* Deferred.succeed(continuationSent, undefined);
230 }
231 return {
232 threadId: input.threadId,
233 turnId: TurnId.make(`continued-${String(input.threadId)}`),
234 };
235 }),
236 };
237​
238 yield* runReconciliation({
239 threads: [codex, fallback],
240 continueAfterRestart: recovery === "opt-in restart",
241 providerService,
242 directory: {
243 getBinding: (threadId) =>
244 Effect.sync(() => {
245 const binding = bindings.get(threadId);
246 return binding === undefined ? Option.none() : Option.some(binding);
247 }),
248 upsert: (binding) =>
249 Effect.sync(() => {
250 bindings.set(binding.threadId, binding);
251 upserts.push(binding);
252 const clearedCount = upserts.filter((candidate) => {
253 const payload = candidate.runtimePayload;
254 return (
255 payload !== null &&
256 typeof payload === "object" &&
257 !Array.isArray(payload) &&
258 "continueAfterServerUpdate" in payload &&
259 payload.continueAfterServerUpdate === null
260 );
261 }).length;
262 return clearedCount === 1;
263 }).pipe(
264 Effect.flatMap((firstMarkerCleared) =>
265 firstMarkerCleared ? Deferred.succeed(continuationCleared, undefined) : Effect.void,
266 ),
267 ),
268 getProvider: () => Effect.die("unused"),
269 listThreadIds: () => Effect.die("unused"),
270 listBindings: () => Effect.succeed([]),
271 },
272 dispatch: (command) =>
273 Effect.sync(() => dispatched.push(command)).pipe(
274 Effect.as({ sequence: dispatched.length }),
275 ),
276 });
277 yield* Deferred.await(continuationSent);
278 yield* Deferred.await(continuationCleared);
279​
280 assert.deepStrictEqual(
281 sends.toSorted((left, right) =>
282 String(left.threadId).localeCompare(String(right.threadId)),
283 ),
284 [
285 { threadId: codex.id, continuation: true, interactionMode: "default" },
286 {
287 threadId: fallback.id,
288 input: "Continue where you left off.",
289 interactionMode: "default",
290 },
291 ],
292 );
293 assert.deepStrictEqual(
294 dispatched.map((command) =>
295 command.type === "thread.session.set"
296 ? {
297 threadId: command.threadId,
298 status: command.session.status,
299 activeTurnId: command.session.activeTurnId,
300 }
301 : null,
302 ),
303 [
304 {
305 threadId: codex.id,
306 status: "starting",
307 activeTurnId: null,
308 },
309 {
310 threadId: fallback.id,
311 status: "starting",
312 activeTurnId: null,
313 },
314 ],
315 );
316 for (const [thread, continuationTurnId] of [
317 [codex, codex.session.activeTurnId],
318 [fallback, fallbackContinuationTurnId],
319 ] as const) {
320 assert.deepStrictEqual(
321 upserts
322 .filter((binding) => binding.threadId === thread.id)
323 .map((binding) => binding.runtimePayload)[0],
324 {
325 continueAfterServerUpdate: continuationTurnId,
326 continueAfterServerUpdatePrepared: true,
327 activeTurnId: null,
328 },
329 );
330 }
331 assert.equal(
332 upserts.some((binding) => {
333 const payload = binding.runtimePayload;
334 return (
335 payload !== null &&
336 typeof payload === "object" &&
337 !Array.isArray(payload) &&
338 "continueAfterServerUpdate" in payload &&
339 payload.continueAfterServerUpdate === null
340 );
341 }),
342 true,
343 );
344 }),
345);
346​
347it.effect("does not continue archived or deleted marked sessions", () => {
348 const archived = makeThread(
349 "thread-continue-archived",
350 "running",
351 TurnId.make("turn-continue-archived"),
352 updatedAt,
353 );
354 const deleted = makeThread(
355 "thread-continue-deleted",
356 "running",
357 TurnId.make("turn-continue-deleted"),
358 null,
359 updatedAt,
360 );
361 const sends: ProviderSendTurnInput[] = [];
362 const dispatched: OrchestrationCommand[] = [];
363​
364 return runReconciliation({
365 threads: [archived, deleted],
366 providerService: {
367 ...makeProviderService(),
368 sendTurn: (input) =>
369 Effect.sync(() => {
370 sends.push(input);
371 return {
372 threadId: input.threadId,
373 turnId: TurnId.make("unexpected-archived-turn"),
374 };
375 }),
376 },
377 directory: {
378 getBinding: (threadId) => {
379 const thread = threadId === archived.id ? archived : deleted;
380 return Effect.succeed(
381 Option.some({
382 threadId,
383 provider: ProviderDriverKind.make("codex"),
384 providerInstanceId,
385 status: "running" as const,
386 resumeCursor: { cursor: threadId },
387 runtimePayload: {
388 continueAfterServerUpdate: thread.session.activeTurnId,
389 },
390 }),
391 );
392 },
393 upsert: () => Effect.void,
394 getProvider: () => Effect.die("unused"),
395 listThreadIds: () => Effect.die("unused"),
396 listBindings: () => Effect.succeed([]),
397 },
398 dispatch: (command) =>
399 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
400 }).pipe(
401 Effect.tap(() =>
402 Effect.sync(() => {
403 assert.deepStrictEqual(sends, []);
404 assert.deepStrictEqual(
405 dispatched.map((command) =>
406 command.type === "thread.session.set"
407 ? { threadId: command.threadId, status: command.session.status }
408 : null,
409 ),
410 [
411 { threadId: archived.id, status: "error" },
412 { threadId: deleted.id, status: "error" },
413 ],
414 );
415 }),
416 ),
417 );
418});
419​
420it.effect("retries continuation preparation before settling a persistent failure", () => {
421 const thread = makeThread(
422 "thread-continuation-preparation-failure",
423 "running",
424 TurnId.make("turn-continuation-preparation-failure"),
425 );
426 const dispatched: OrchestrationCommand[] = [];
427 const failure = new OrchestrationCommandInvariantError({
428 commandType: "thread.session.set",
429 detail: "simulated continuation preparation failure",
430 });
431​
432 return runReconciliation({
433 threads: [thread],
434 directory: {
435 getBinding: () =>
436 Effect.succeed(
437 Option.some({
438 threadId: thread.id,
439 provider: ProviderDriverKind.make("codex"),
440 providerInstanceId,
441 status: "running" as const,
442 resumeCursor: { cursor: thread.id },
443 runtimePayload: {
444 continueAfterServerUpdate: thread.session.activeTurnId,
445 },
446 }),
447 ),
448 upsert: () => Effect.void,
449 getProvider: () => Effect.die("unused"),
450 listThreadIds: () => Effect.die("unused"),
451 listBindings: () => Effect.succeed([]),
452 },
453 dispatch: (command) => {
454 if (command.type !== "thread.session.set") {
455 return Effect.die("unexpected command");
456 }
457 dispatched.push(command);
458 return command.session.status === "starting"
459 ? Effect.fail(failure)
460 : Effect.succeed({ sequence: dispatched.length });
461 },
462 }).pipe(
463 Effect.tap(() =>
464 Effect.sync(() =>
465 assert.deepStrictEqual(
466 dispatched.map(
467 (command) => command.type === "thread.session.set" && command.session.status,
468 ),
469 ["starting", "starting", "error"],
470 ),
471 ),
472 ),
473 );
474});
475​
476it.effect("reconciles multiple active and archived orphans but skips live sessions", () => {
477 const starting = makeThread("thread-starting", "starting");
478 const running = makeThread("thread-running", "running", TurnId.make("turn-running"));
479 const staleActiveTurn = makeThread(
480 "thread-stale-active-turn",
481 "ready",
482 TurnId.make("turn-stale-active"),
483 );
484 const archived = makeThread(
485 "thread-archived",
486 "running",
487 TurnId.make("turn-archived"),
488 updatedAt,
489 );
490 const live = makeThread("thread-live", "running", TurnId.make("turn-live"));
491 const settled = makeThread("thread-ready", "ready");
492 const dispatched: OrchestrationCommand[] = [];
493 const bindingReads: ThreadId[] = [];
494 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
495​
496 return runReconciliation({
497 threads: [starting, running, staleActiveTurn, archived, live, settled],
498 liveThreadIds: [live.id],
499 directory: {
500 getBinding: (candidate) =>
501 Effect.sync(() => bindingReads.push(candidate)).pipe(
502 Effect.as(
503 Option.some({
504 threadId: candidate,
505 provider: ProviderDriverKind.make("codex"),
506 providerInstanceId,
507 status: "running" as const,
508 resumeCursor: { cursor: candidate },
509 runtimePayload: {
510 activeTurnId: "stale",
511 unrelated: candidate,
512 ...(candidate === staleActiveTurn.id
513 ? { continueAfterServerUpdate: "turn-from-an-earlier-update" }
514 : {}),
515 },
516 }),
517 ),
518 ),
519 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
520 getProvider: () => Effect.die("unused"),
521 listThreadIds: () => Effect.die("unused"),
522 listBindings: () => Effect.succeed([]),
523 },
524 dispatch: (command) =>
525 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
526 }).pipe(
527 Effect.tap(() =>
528 Effect.sync(() => {
529 const orphanIds = [starting.id, running.id, staleActiveTurn.id, archived.id];
530 assert.deepStrictEqual(bindingReads, orphanIds);
531 assert.deepStrictEqual(
532 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
533 orphanIds,
534 );
535 assert.deepStrictEqual(
536 dispatched.map((command) =>
537 command.type === "thread.session.set"
538 ? {
539 status: command.session.status,
540 activeTurnId: command.session.activeTurnId,
541 }
542 : null,
543 ),
544 orphanIds.map(() => ({ status: "error" as const, activeTurnId: null })),
545 );
546 assert.equal(upserts.length, orphanIds.length);
547 for (const binding of upserts) {
548 assert.equal(binding.status, "stopped");
549 assert.deepStrictEqual(
550 binding.runtimePayload,
551 binding.threadId === staleActiveTurn.id
552 ? {
553 activeTurnId: null,
554 unrelated: binding.threadId,
555 continueAfterServerUpdate: null,
556 continueAfterServerUpdatePrepared: null,
557 }
558 : { activeTurnId: null, unrelated: binding.threadId },
559 );
560 assert.deepStrictEqual(binding.resumeCursor, { cursor: binding.threadId });
561 }
562 }),
563 ),
564 );
565});
566​
567it.effect(
568 "settles projections when directory bindings are absent, corrupt, or fail to upsert",
569 () => {
570 const absent = makeThread("thread-binding-absent", "starting");
571 const corrupt = makeThread("thread-binding-corrupt", "running");
572 const upsertFailure = makeThread("thread-binding-upsert-failure", "running");
573 const dispatched: OrchestrationCommand[] = [];
574 const corruptFailure = new ProviderSessionDirectoryPersistenceError({
575 operation: "ProviderSessionDirectory.getBinding",
576 detail: "corrupt persisted binding",
577 });
578 const writeFailure = new ProviderSessionDirectoryPersistenceError({
579 operation: "ProviderSessionDirectory.upsert",
580 detail: "failed binding write",
581 });
582​
583 return runReconciliation({
584 threads: [absent, corrupt, upsertFailure],
585 directory: {
586 getBinding: (candidate) =>
587 candidate === absent.id
588 ? Effect.succeed(Option.none())
589 : candidate === corrupt.id
590 ? Effect.fail(corruptFailure)
591 : Effect.succeed(
592 Option.some({
593 threadId: candidate,
594 provider: ProviderDriverKind.make("codex"),
595 providerInstanceId,
596 }),
597 ),
598 upsert: () => Effect.fail(writeFailure),
599 getProvider: () => Effect.die("unused"),
600 listThreadIds: () => Effect.die("unused"),
601 listBindings: () => Effect.succeed([]),
602 },
603 dispatch: (command) =>
604 Effect.sync(() => dispatched.push(command)).pipe(
605 Effect.as({ sequence: dispatched.length }),
606 ),
607 }).pipe(
608 Effect.tap(() =>
609 Effect.sync(() => {
610 assert.deepStrictEqual(
611 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
612 [absent.id, corrupt.id, upsertFailure.id],
613 );
614 }),
615 ),
616 );
617 },
618);
619​
620it.effect("retries failed projections and continues after a persistent failure", () => {
621 const transient = makeThread("thread-dispatch-transient-failure", "running");
622 const persistent = makeThread("thread-dispatch-persistent-failure", "running");
623 const later = makeThread("thread-dispatch-success", "running");
624 const attempted: ThreadId[] = [];
625 let transientAttempts = 0;
626 const failure = new OrchestrationCommandInvariantError({
627 commandType: "thread.session.set",
628 detail: "simulated startup reconciliation failure",
629 });
630​
631 return runReconciliation({
632 threads: [transient, persistent, later],
633 directory: {
634 getBinding: () => Effect.succeed(Option.none()),
635 upsert: () => Effect.void,
636 getProvider: () => Effect.die("unused"),
637 listThreadIds: () => Effect.die("unused"),
638 listBindings: () => Effect.succeed([]),
639 },
640 dispatch: (command) => {
641 if (command.type !== "thread.session.set") {
642 return Effect.die("unexpected command");
643 }
644 attempted.push(command.threadId);
645 if (command.threadId === transient.id && transientAttempts++ === 0) {
646 return Effect.fail(failure);
647 }
648 return command.threadId === persistent.id
649 ? Effect.fail(failure)
650 : Effect.succeed({ sequence: attempted.length });
651 },
652 }).pipe(
653 Effect.tap(() =>
654 Effect.sync(() =>
655 assert.deepStrictEqual(attempted, [
656 transient.id,
657 transient.id,
658 persistent.id,
659 persistent.id,
660 later.id,
661 ]),
662 ),
663 ),
664 );
665});
666​
667it.effect("does not fail startup when the live provider session inventory cannot be read", () => {
668 let queried = false;
669 return ServerRuntimeStartup.reconcileProviderSessions.pipe(
670 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
671 getUserInputActivity: () => Effect.die("unused"),
672 getCommandReadModel: () =>
673 Effect.sync(() => {
674 queried = true;
675 return { threads: [] } as never;
676 }),
677 } as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]),
678 Effect.provideService(ProviderService.ProviderService, {
679 ...makeProviderService(),
680 listSessions: () => Effect.die("provider inventory unavailable"),
681 }),
682 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
683 getBinding: () => Effect.die("unused"),
684 upsert: () => Effect.die("unused"),
685 getProvider: () => Effect.die("unused"),
686 listThreadIds: () => Effect.die("unused"),
687 listBindings: () => Effect.succeed([]),
688 }),
689 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
690 readEvents: () => Stream.empty,
691 readThreadEvents: () => Stream.empty,
692 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
693 dispatch: () => Effect.die("unused"),
694 streamDomainEvents: Stream.empty,
695 subscribeDomainEvents: Effect.succeed(Stream.empty),
696 latestSequence: Effect.succeed(0),
697 }),
698 Effect.provide(Layer.mergeAll(NodeServices.layer, ServerSettings.layerTest())),
699 Effect.tap(() => Effect.sync(() => assert.equal(queried, false))),
700 );
701});
702​
703for (const scenario of [
704 "disabled",
705 "stopped projection",
706 "finished projection",
707 "stopped binding",
708 "finished binding",
709 "missing cursor",
710 "mismatched turn",
711 "marked without cursor",
712 "marked stopped projection",
713 "marked superseded turn",
714] as const) {
715 it.effect(`does not recover an interrupted session with ${scenario}`, () => {
716 const turnId = TurnId.make("turn-excluded-recovery");
717 const thread = makeThread(
718 "thread-excluded-recovery",
719 scenario.includes("stopped projection")
720 ? "stopped"
721 : scenario === "finished projection"
722 ? "ready"
723 : scenario === "marked superseded turn"
724 ? "starting"
725 : "running",
726 scenario === "marked superseded turn" ? null : turnId,
727 );
728 const dispatched: OrchestrationCommand[] = [];
729 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
730 return runReconciliation({
731 threads: [thread],
732 continueAfterRestart: scenario !== "disabled",
733 directory: {
734 getBinding: () =>
735 Effect.succeed(
736 Option.some({
737 threadId: thread.id,
738 provider: ProviderDriverKind.make("codex"),
739 providerInstanceId,
740 status: scenario === "stopped binding" ? "stopped" : "running",
741 ...(scenario.includes("cursor") ? {} : { resumeCursor: { threadId: thread.id } }),
742 runtimePayload: {
743 activeTurnId:
744 scenario === "finished binding"
745 ? null
746 : scenario === "mismatched turn" || scenario === "marked superseded turn"
747 ? "another-turn"
748 : turnId,
749 ...(scenario.startsWith("marked") ? { continueAfterServerUpdate: turnId } : {}),
750 },
751 }),
752 ),
753 upsert: (binding) =>
754 Effect.sync(() => {
755 upserts.push(binding);
756 }),
757 getProvider: () => Effect.die("unused"),
758 listThreadIds: () => Effect.die("unused"),
759 listBindings: () => Effect.succeed([]),
760 },
761 dispatch: (command) =>
762 Effect.sync(() => {
763 dispatched.push(command);
764 return { sequence: dispatched.length };
765 }),
766 }).pipe(
767 Effect.tap(() =>
768 Effect.sync(() => {
769 assert.deepStrictEqual(
770 dispatched.map(
771 (command) => command.type === "thread.session.set" && command.session.status,
772 ),
773 ["error"],
774 );
775 assert.deepStrictEqual(
776 upserts.map((binding) => binding.status),
777 ["stopped"],
778 );
779 }),
780 ),
781 );
782 });
784​
785for (const preparedStatus of [
786 "starting",
787 "ready",
788 "ready with failed scan",
789 "completed after update marking",
790] as const) {
791 it.effect(`recovers again if startup exits with a prepared ${preparedStatus} session`, () =>
792 Effect.gen(function* () {
793 const turnId = TurnId.make("turn-interrupted-startup");
794 const thread = makeThread("thread-interrupted-startup", "running", turnId);
795 const activation = yield* Deferred.make<void>();
796 const cleared = yield* Deferred.make<void>();
797 const sends: ProviderSendTurnInput[] = [];
798 let binding: ProviderSessionDirectory.ProviderRuntimeBinding = {
799 threadId: thread.id,
800 provider: ProviderDriverKind.make("codex"),
801 providerInstanceId,
802 status: "running",
803 resumeCursor: { threadId: thread.id },
804 runtimePayload: { activeTurnId: turnId },
805 };
806 const input = {
807 threads: [thread],
808 continueAfterRestart: true,
809 providerService: {
810 ...makeProviderService(),
811 getCapabilities: () =>
812 Effect.succeed({
813 sessionModelSwitch: "in-session" as const,
814 promptlessTurnContinuation: true,
815 }),
816 sendTurn: (input: ProviderSendTurnInput) =>
817 Effect.sync(() => {
818 sends.push(input);
819 return { threadId: input.threadId, turnId: TurnId.make("turn-recovered") };
820 }),
821 },
822 directory: {
823 getBinding: () => Effect.sync(() => Option.some(binding)),
824 upsert: (next: ProviderSessionDirectory.ProviderRuntimeBinding) =>
825 Effect.gen(function* () {
826 binding = next;
827 if (binding.status !== "starting" || sends.length === 0) return;
828 yield* Deferred.succeed(cleared, undefined);
829 }),
830 getProvider: () => Effect.die("unused"),
831 listThreadIds: () => Effect.die("unused"),
832 listBindings: () =>
833 preparedStatus === "ready with failed scan"
834 ? Effect.fail(
835 new ProviderSessionDirectoryPersistenceError({
836 operation: "listBindings",
837 detail: "unreadable unrelated binding",
838 }),
839 )
840 : Effect.sync(() => [{ ...binding, lastSeenAt: "2026-01-01T00:00:00.000Z" }]),
841 },
842 dispatch: (command: OrchestrationCommand) =>
843 Effect.sync(() => {
844 if (command.type === "thread.session.set") {
845 thread.session.status = command.session.status;
846 thread.session.activeTurnId = command.session.activeTurnId;
847 }
848 return { sequence: 1 };
849 }),
850 };
851​
852 yield* runReconciliation(input).pipe(
853 Effect.provideService(ServerActivation, Deferred.await(activation)),
854 Effect.scoped,
855 );
856 assert.deepStrictEqual(sends, []);
857 assert.equal(thread.session.status, "starting");
858 assert.equal(thread.session.activeTurnId, null);
859 assert.deepStrictEqual(binding.runtimePayload, {
860 activeTurnId: null,
861 continueAfterServerUpdate: turnId,
862 continueAfterServerUpdatePrepared: true,
863 });
864​
865 if (preparedStatus === "completed after update marking") {
866 thread.session.status = "ready";
867 binding = {
868 ...binding,
869 status: "stopped",
870 runtimePayload: {
871 activeTurnId: null,
872 continueAfterServerUpdate: turnId,
873 continueAfterServerUpdatePrepared: null,
874 },
875 };
876 yield* runReconciliation(input);
877 assert.deepStrictEqual(sends, []);
878 assert.equal(thread.session.status, "ready");
879 return;
880 }
881 thread.session.status =
882 preparedStatus === "ready with failed scan" ? "ready" : preparedStatus;
883 yield* runReconciliation(input);
884 yield* Deferred.await(cleared);
885 assert.deepStrictEqual(sends, [
886 { threadId: thread.id, continuation: true, interactionMode: "default" },
887 ]);
888 assert.deepStrictEqual(binding.runtimePayload, {
889 activeTurnId: null,
890 continueAfterServerUpdate: null,
891 continueAfterServerUpdatePrepared: null,
892 });
893 }),
894 );
896​
897it.effect("settles failed opt-in recovery without retrying the provider turn", () =>
898 Effect.gen(function* () {
899 const turnId = TurnId.make("turn-failed-recovery");
900 const thread = makeThread("thread-failed-recovery", "running", turnId);
901 const settled = yield* Deferred.make<void>();
902 const sends: ProviderSendTurnInput[] = [];
903 const dispatched: OrchestrationCommand[] = [];
904 const preparedPayloads: unknown[] = [];
905 let binding: ProviderSessionDirectory.ProviderRuntimeBinding = {
906 threadId: thread.id,
907 provider: ProviderDriverKind.make("codex"),
908 providerInstanceId,
909 status: "running",
910 resumeCursor: { threadId: thread.id },
911 runtimePayload: { activeTurnId: turnId },
912 };
913 yield* runReconciliation({
914 threads: [thread],
915 continueAfterRestart: true,
916 providerService: {
917 ...makeProviderService(),
918 getCapabilities: () =>
919 Effect.succeed({ sessionModelSwitch: "in-session", promptlessTurnContinuation: true }),
920 sendTurn: (input) =>
921 Effect.gen(function* () {
922 sends.push(input);
923 preparedPayloads.push(binding.runtimePayload);
924 return yield* Effect.fail(
925 new ProviderSessionNotFoundError({ threadId: input.threadId }),
926 );
927 }),
928 },
929 directory: {
930 getBinding: () => Effect.sync(() => Option.some(binding)),
931 upsert: (next) =>
932 Effect.sync(() => {
933 binding = next;
934 }),
935 getProvider: () => Effect.die("unused"),
936 listThreadIds: () => Effect.die("unused"),
937 listBindings: () => Effect.succeed([]),
938 },
939 dispatch: (command) =>
940 Effect.gen(function* () {
941 dispatched.push(command);
942 if (command.type === "thread.session.set" && command.session.status === "error") {
943 yield* Deferred.succeed(settled, undefined);
944 }
945 return { sequence: dispatched.length };
946 }),
947 });
948 yield* Deferred.await(settled);
949 assert.equal(sends.length, 1);
950 assert.deepStrictEqual(preparedPayloads, [
951 {
952 activeTurnId: null,
953 continueAfterServerUpdate: turnId,
954 continueAfterServerUpdatePrepared: true,
955 },
956 ]);
957 assert.deepStrictEqual(
958 dispatched.map(
959 (command) =>
960 command.type === "thread.session.set" && {
961 status: command.session.status,
962 activeTurnId: command.session.activeTurnId,
963 },
964 ),
965 [
966 { status: "starting", activeTurnId: null },
967 { status: "error", activeTurnId: null },
968 ],
969 );
970 assert.equal(binding.status, "stopped");
971 assert.deepStrictEqual(binding.runtimePayload, {
972 activeTurnId: null,
973 continueAfterServerUpdate: null,
974 continueAfterServerUpdatePrepared: null,
975 });
976 }),
977);