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

serverRuntimeStartup.reconcile.test.ts

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