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

serverRuntimeStartup.reconcile.test.ts

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