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

serverRuntimeStartup.reconcile.test.ts

1,168 lines41.3 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 type OrchestrationCommand,
4 type OrchestrationSessionStatus,
5 MessageId,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 type ProviderSendTurnInput,
9 ThreadId,
10 TurnId,
11} from "@t3tools/contracts";
12import { assert, it } from "@effect/vitest";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Stream from "effect/Stream";
18​
19import { OrchestrationCommandInvariantError } from "./orchestration/Errors.ts";
20import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
21import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
22import {
23 ProviderSessionDirectoryPersistenceError,
24 ProviderSessionNotFoundError,
25} from "./provider/Errors.ts";
26import * as ProviderService from "./provider/Services/ProviderService.ts";
27import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
28import { ServerActivation } from "./serverActivation.ts";
29import * as ServerSettings from "./serverSettings.ts";
30import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
31​
32const providerInstanceId = ProviderInstanceId.make("codex");
33const updatedAt = "2026-08-20T12:00:00.000Z";
34​
35const makeThread = (
36 id: string,
37 status: OrchestrationSessionStatus,
38 activeTurnId: TurnId | null = null,
39 archivedAt: string | null = null,
40 deletedAt: string | null = null,
41) => ({
42 id: ThreadId.make(id),
43 archivedAt,
44 deletedAt,
45 interactionMode: "default" as const,
46 session: {
47 threadId: ThreadId.make(id),
48 status,
49 providerName: "codex" as const,
50 providerInstanceId,
51 runtimeMode: "full-access" as const,
52 activeTurnId,
53 lastError: null,
54 updatedAt,
55 },
56});
57​
58const makeProviderService = (liveThreadIds: ReadonlyArray<ThreadId> = []) =>
59 ({
60 startSession: () => Effect.die("unused"),
61 sendTurn: () => Effect.die("unused"),
62 compactThread: () => Effect.die("unused"),
63 interruptTurn: () => Effect.die("unused"),
64 respondToRequest: () => Effect.die("unused"),
65 respondToUserInput: () => Effect.die("unused"),
66 stopSession: () => Effect.die("unused"),
67 listSessions: () => Effect.succeed(liveThreadIds.map((threadId) => ({ threadId }) as never)),
68 getCapabilities: () => Effect.die("unused"),
69 assertConversationRollbackSupported: () => Effect.die("unused"),
70 getInstanceInfo: () => Effect.die("unused"),
71 rollbackConversation: () => Effect.die("unused"),
72 uploadFeedback: () => 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.succeed(
404 Option.some({
405 threadId,
406 provider: ProviderDriverKind.make("codex"),
407 providerInstanceId,
408 status: "running" as const,
409 resumeCursor: { cursor: threadId },
410 runtimePayload: {
411 continueAfterServerUpdate: thread.session.activeTurnId,
412 },
413 }),
414 );
415 },
416 upsert: () => Effect.void,
417 recordImportedTranscript: () => Effect.die("unused"),
418 getProvider: () => Effect.die("unused"),
419 listThreadIds: () => Effect.die("unused"),
420 listBindings: () => Effect.succeed([]),
421 },
422 dispatch: (command) =>
423 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
424 }).pipe(
425 Effect.tap(() =>
426 Effect.sync(() => {
427 assert.deepStrictEqual(sends, []);
428 assert.deepStrictEqual(
429 dispatched.map((command) =>
430 command.type === "thread.session.set"
431 ? { threadId: command.threadId, status: command.session.status }
432 : null,
433 ),
434 [
435 { threadId: archived.id, status: "error" },
436 { threadId: deleted.id, status: "error" },
437 ],
438 );
439 }),
440 ),
441 );
442});
443​
444it.effect("retries continuation preparation before settling a persistent failure", () => {
445 const thread = makeThread(
446 "thread-continuation-preparation-failure",
447 "running",
448 TurnId.make("turn-continuation-preparation-failure"),
449 );
450 const dispatched: OrchestrationCommand[] = [];
451 const failure = new OrchestrationCommandInvariantError({
452 commandType: "thread.session.set",
453 detail: "simulated continuation preparation failure",
454 });
455​
456 return runReconciliation({
457 threads: [thread],
458 directory: {
459 getBinding: () =>
460 Effect.succeed(
461 Option.some({
462 threadId: thread.id,
463 provider: ProviderDriverKind.make("codex"),
464 providerInstanceId,
465 status: "running" as const,
466 resumeCursor: { cursor: thread.id },
467 runtimePayload: {
468 continueAfterServerUpdate: thread.session.activeTurnId,
469 },
470 }),
471 ),
472 upsert: () => Effect.void,
473 recordImportedTranscript: () => Effect.die("unused"),
474 getProvider: () => Effect.die("unused"),
475 listThreadIds: () => Effect.die("unused"),
476 listBindings: () => Effect.succeed([]),
477 },
478 dispatch: (command) => {
479 if (command.type !== "thread.session.set") {
480 return Effect.die("unexpected command");
481 }
482 dispatched.push(command);
483 return command.session.status === "starting"
484 ? Effect.fail(failure)
485 : Effect.succeed({ sequence: dispatched.length });
486 },
487 }).pipe(
488 Effect.tap(() =>
489 Effect.sync(() =>
490 assert.deepStrictEqual(
491 dispatched.map(
492 (command) => command.type === "thread.session.set" && command.session.status,
493 ),
494 ["starting", "starting", "error"],
495 ),
496 ),
497 ),
498 );
499});
500​
501it.effect("reconciles multiple active and archived orphans but skips live sessions", () => {
502 const starting = makeThread("thread-starting", "starting");
503 const running = makeThread("thread-running", "running", TurnId.make("turn-running"));
504 const staleActiveTurn = makeThread(
505 "thread-stale-active-turn",
506 "ready",
507 TurnId.make("turn-stale-active"),
508 );
509 const archived = makeThread(
510 "thread-archived",
511 "running",
512 TurnId.make("turn-archived"),
513 updatedAt,
514 );
515 const live = makeThread("thread-live", "running", TurnId.make("turn-live"));
516 const settled = makeThread("thread-ready", "ready");
517 const dispatched: OrchestrationCommand[] = [];
518 const bindingReads: ThreadId[] = [];
519 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
520​
521 return runReconciliation({
522 threads: [starting, running, staleActiveTurn, archived, live, settled],
523 liveThreadIds: [live.id],
524 directory: {
525 getBinding: (candidate) =>
526 Effect.sync(() => bindingReads.push(candidate)).pipe(
527 Effect.as(
528 Option.some({
529 threadId: candidate,
530 provider: ProviderDriverKind.make("codex"),
531 providerInstanceId,
532 status: "running" as const,
533 resumeCursor: { cursor: candidate },
534 runtimePayload: {
535 activeTurnId: "stale",
536 unrelated: candidate,
537 ...(candidate === staleActiveTurn.id
538 ? { continueAfterServerUpdate: "turn-from-an-earlier-update" }
539 : {}),
540 },
541 }),
542 ),
543 ),
544 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
545 recordImportedTranscript: () => Effect.die("unused"),
546 getProvider: () => Effect.die("unused"),
547 listThreadIds: () => Effect.die("unused"),
548 listBindings: () => Effect.succeed([]),
549 },
550 dispatch: (command) =>
551 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
552 }).pipe(
553 Effect.tap(() =>
554 Effect.sync(() => {
555 const orphanIds = [starting.id, running.id, staleActiveTurn.id, archived.id];
556 assert.deepStrictEqual(bindingReads, orphanIds);
557 assert.deepStrictEqual(
558 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
559 orphanIds,
560 );
561 assert.deepStrictEqual(
562 dispatched.map((command) =>
563 command.type === "thread.session.set"
564 ? {
565 status: command.session.status,
566 activeTurnId: command.session.activeTurnId,
567 }
568 : null,
569 ),
570 orphanIds.map(() => ({ status: "error" as const, activeTurnId: null })),
571 );
572 assert.equal(upserts.length, orphanIds.length);
573 for (const binding of upserts) {
574 assert.equal(binding.status, "stopped");
575 assert.deepStrictEqual(
576 binding.runtimePayload,
577 binding.threadId === staleActiveTurn.id
578 ? {
579 activeTurnId: null,
580 unrelated: binding.threadId,
581 continueAfterServerUpdate: null,
582 continueAfterServerUpdatePrepared: null,
583 }
584 : { activeTurnId: null, unrelated: binding.threadId },
585 );
586 assert.deepStrictEqual(binding.resumeCursor, { cursor: binding.threadId });
587 }
588 }),
589 ),
590 );
591});
592​
593it.effect("clears acknowledged starts when orphan reconciliation abandons the session", () => {
594 const messageId = MessageId.make("message-acknowledged-before-restart");
595 const turnId = TurnId.make("turn-acknowledged-before-restart");
596 const thread = {
597 ...makeThread("thread-acknowledged-before-restart", "starting"),
598 submittedTurnStarts: [{ messageId, turnId }],
599 };
600 const dispatched: OrchestrationCommand[] = [];
601​
602 return runReconciliation({
603 threads: [thread],
604 directory: {
605 getBinding: () => Effect.succeed(Option.none()),
606 upsert: () => Effect.void,
607 recordImportedTranscript: () => Effect.die("unused"),
608 getProvider: () => Effect.die("unused"),
609 listThreadIds: () => Effect.die("unused"),
610 listBindings: () => Effect.succeed([]),
611 },
612 dispatch: (command) =>
613 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
614 }).pipe(
615 Effect.tap(() =>
616 Effect.sync(() => {
617 assert.deepStrictEqual(
618 dispatched.map((command) =>
619 command.type === "thread.session.set"
620 ? { type: command.type, status: command.session.status }
621 : command.type === "thread.activity.append"
622 ? {
623 type: command.type,
624 kind: command.activity.kind,
625 requestId:
626 typeof command.activity.payload === "object" &&
627 command.activity.payload !== null &&
628 "requestId" in command.activity.payload
629 ? command.activity.payload.requestId
630 : null,
631 }
632 : { type: command.type },
633 ),
634 [
635 {
636 type: "thread.activity.append",
637 kind: "provider.turn.start.failed",
638 requestId: messageId,
639 },
640 { type: "thread.session.set", status: "error" },
641 ],
642 );
643 }),
644 ),
645 );
646});
647​
648it.effect("clears acknowledged starts on dead sessions that are not otherwise orphaned", () => {
649 const messageId = MessageId.make("message-acknowledged-errored-session");
650 const turnId = TurnId.make("turn-acknowledged-errored-session");
651 const thread = {
652 ...makeThread("thread-acknowledged-errored-session", "error"),
653 submittedTurnStarts: [{ messageId, turnId }],
654 };
655 const dispatched: OrchestrationCommand[] = [];
656​
657 return runReconciliation({
658 threads: [thread],
659 directory: {
660 getBinding: () => Effect.succeed(Option.none()),
661 upsert: () => Effect.void,
662 recordImportedTranscript: () => Effect.die("unused"),
663 getProvider: () => Effect.die("unused"),
664 listThreadIds: () => Effect.die("unused"),
665 listBindings: () => Effect.succeed([]),
666 },
667 dispatch: (command) =>
668 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
669 }).pipe(
670 Effect.tap(() =>
671 Effect.sync(() => {
672 assert.deepStrictEqual(
673 dispatched.map((command) =>
674 command.type === "thread.activity.append" &&
675 command.activity.payload !== null &&
676 typeof command.activity.payload === "object" &&
677 "requestId" in command.activity.payload
678 ? {
679 type: command.type,
680 kind: command.activity.kind,
681 requestId: command.activity.payload.requestId,
682 }
683 : { type: command.type },
684 ),
685 [
686 {
687 type: "thread.activity.append",
688 kind: "provider.turn.start.failed",
689 requestId: messageId,
690 },
691 ],
692 );
693 }),
694 ),
695 );
696});
697​
698it.effect("clears later orphaned starts while keeping a failed cleanup retryable", () => {
699 const failedMessageId = MessageId.make("message-cleanup-fails");
700 const clearedMessageId = MessageId.make("message-cleanup-succeeds");
701 const thread = {
702 ...makeThread("thread-cleanup-fails", "starting"),
703 submittedTurnStarts: [
704 { messageId: failedMessageId, turnId: TurnId.make("turn-cleanup-fails") },
705 { messageId: clearedMessageId, turnId: TurnId.make("turn-cleanup-succeeds") },
706 ],
707 };
708 const dispatched: OrchestrationCommand[] = [];
709​
710 return runReconciliation({
711 threads: [thread],
712 directory: {
713 getBinding: () => Effect.succeed(Option.none()),
714 upsert: () => Effect.void,
715 recordImportedTranscript: () => Effect.die("unused"),
716 getProvider: () => Effect.die("unused"),
717 listThreadIds: () => Effect.die("unused"),
718 listBindings: () => Effect.succeed([]),
719 },
720 dispatch: (command) =>
721 Effect.sync(() => dispatched.push(command)).pipe(
722 Effect.flatMap(() =>
723 command.type === "thread.activity.append" &&
724 command.activity.payload !== null &&
725 typeof command.activity.payload === "object" &&
726 "requestId" in command.activity.payload &&
727 command.activity.payload.requestId === failedMessageId
728 ? Effect.fail(
729 new OrchestrationCommandInvariantError({
730 commandType: command.type,
731 detail: "cleanup failed",
732 }),
733 )
734 : Effect.succeed({ sequence: dispatched.length }),
735 ),
736 ),
737 }).pipe(
738 Effect.tap(() =>
739 Effect.sync(() => {
740 assert.deepStrictEqual(
741 dispatched.map((command) =>
742 command.type === "thread.activity.append" &&
743 command.activity.payload !== null &&
744 typeof command.activity.payload === "object" &&
745 "requestId" in command.activity.payload
746 ? { type: command.type, requestId: command.activity.payload.requestId }
747 : { type: command.type },
748 ),
749 [
750 { type: "thread.activity.append", requestId: failedMessageId },
751 { type: "thread.activity.append", requestId: clearedMessageId },
752 ],
753 );
754 }),
755 ),
756 );
757});
758​
759it.effect(
760 "settles projections when directory bindings are absent, corrupt, or fail to upsert",
761 () => {
762 const absent = makeThread("thread-binding-absent", "starting");
763 const corrupt = makeThread("thread-binding-corrupt", "running");
764 const upsertFailure = makeThread("thread-binding-upsert-failure", "running");
765 const dispatched: OrchestrationCommand[] = [];
766 const corruptFailure = new ProviderSessionDirectoryPersistenceError({
767 operation: "ProviderSessionDirectory.getBinding",
768 detail: "corrupt persisted binding",
769 });
770 const writeFailure = new ProviderSessionDirectoryPersistenceError({
771 operation: "ProviderSessionDirectory.upsert",
772 detail: "failed binding write",
773 });
774​
775 return runReconciliation({
776 threads: [absent, corrupt, upsertFailure],
777 directory: {
778 getBinding: (candidate) =>
779 candidate === absent.id
780 ? Effect.succeed(Option.none())
781 : candidate === corrupt.id
782 ? Effect.fail(corruptFailure)
783 : Effect.succeed(
784 Option.some({
785 threadId: candidate,
786 provider: ProviderDriverKind.make("codex"),
787 providerInstanceId,
788 }),
789 ),
790 upsert: () => Effect.fail(writeFailure),
791 recordImportedTranscript: () => Effect.die("unused"),
792 getProvider: () => Effect.die("unused"),
793 listThreadIds: () => Effect.die("unused"),
794 listBindings: () => Effect.succeed([]),
795 },
796 dispatch: (command) =>
797 Effect.sync(() => dispatched.push(command)).pipe(
798 Effect.as({ sequence: dispatched.length }),
799 ),
800 }).pipe(
801 Effect.tap(() =>
802 Effect.sync(() => {
803 assert.deepStrictEqual(
804 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
805 [absent.id, corrupt.id, upsertFailure.id],
806 );
807 }),
808 ),
809 );
810 },
811);
812​
813it.effect("retries failed projections and continues after a persistent failure", () => {
814 const transient = makeThread("thread-dispatch-transient-failure", "running");
815 const persistent = makeThread("thread-dispatch-persistent-failure", "running");
816 const later = makeThread("thread-dispatch-success", "running");
817 const attempted: ThreadId[] = [];
818 let transientAttempts = 0;
819 const failure = new OrchestrationCommandInvariantError({
820 commandType: "thread.session.set",
821 detail: "simulated startup reconciliation failure",
822 });
823​
824 return runReconciliation({
825 threads: [transient, persistent, later],
826 directory: {
827 getBinding: () => Effect.succeed(Option.none()),
828 upsert: () => Effect.void,
829 recordImportedTranscript: () => Effect.die("unused"),
830 getProvider: () => Effect.die("unused"),
831 listThreadIds: () => Effect.die("unused"),
832 listBindings: () => Effect.succeed([]),
833 },
834 dispatch: (command) => {
835 if (command.type !== "thread.session.set") {
836 return Effect.die("unexpected command");
837 }
838 attempted.push(command.threadId);
839 if (command.threadId === transient.id && transientAttempts++ === 0) {
840 return Effect.fail(failure);
841 }
842 return command.threadId === persistent.id
843 ? Effect.fail(failure)
844 : Effect.succeed({ sequence: attempted.length });
845 },
846 }).pipe(
847 Effect.tap(() =>
848 Effect.sync(() =>
849 assert.deepStrictEqual(attempted, [
850 transient.id,
851 transient.id,
852 persistent.id,
853 persistent.id,
854 later.id,
855 ]),
856 ),
857 ),
858 );
859});
860​
861it.effect("does not fail startup when the live provider session inventory cannot be read", () => {
862 let queried = false;
863 return ServerRuntimeStartup.reconcileProviderSessions.pipe(
864 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
865 getUserInputActivity: () => Effect.die("unused"),
866 getCommandReadModel: () =>
867 Effect.sync(() => {
868 queried = true;
869 return { threads: [] } as never;
870 }),
871 } as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]),
872 Effect.provideService(ProviderService.ProviderService, {
873 ...makeProviderService(),
874 listSessions: () => Effect.die("provider inventory unavailable"),
875 }),
876 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
877 getBinding: () => Effect.die("unused"),
878 upsert: () => Effect.die("unused"),
879 recordImportedTranscript: () => Effect.die("unused"),
880 getProvider: () => Effect.die("unused"),
881 listThreadIds: () => Effect.die("unused"),
882 listBindings: () => Effect.succeed([]),
883 }),
884 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
885 readEvents: () => Stream.empty,
886 readThreadEvents: () => Stream.empty,
887 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
888 dispatch: () => Effect.die("unused"),
889 streamDomainEvents: Stream.empty,
890 subscribeDomainEvents: Effect.succeed(Stream.empty),
891 latestSequence: Effect.succeed(0),
892 }),
893 Effect.provide(Layer.mergeAll(NodeServices.layer, ServerSettings.layerTest())),
894 Effect.tap(() => Effect.sync(() => assert.equal(queried, false))),
895 );
896});
897​
898for (const scenario of [
899 "disabled",
900 "stopped projection",
901 "finished projection",
902 "stopped binding",
903 "missing cursor",
904 "marked without cursor",
905 "marked stopped projection",
906 "marked superseded turn",
907] as const) {
908 it.effect(`does not recover an interrupted session with ${scenario}`, () => {
909 const turnId = TurnId.make("turn-excluded-recovery");
910 const thread = makeThread(
911 "thread-excluded-recovery",
912 scenario.includes("stopped projection")
913 ? "stopped"
914 : scenario === "finished projection"
915 ? "ready"
916 : scenario === "marked superseded turn"
917 ? "starting"
918 : "running",
919 scenario === "marked superseded turn" ? null : turnId,
920 );
921 const dispatched: OrchestrationCommand[] = [];
922 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
923 return runReconciliation({
924 threads: [thread],
925 continueAfterRestart: scenario !== "disabled",
926 directory: {
927 getBinding: () =>
928 Effect.succeed(
929 Option.some({
930 threadId: thread.id,
931 provider: ProviderDriverKind.make("codex"),
932 providerInstanceId,
933 status: scenario === "stopped binding" ? "stopped" : "running",
934 ...(scenario.includes("cursor") ? {} : { resumeCursor: { threadId: thread.id } }),
935 runtimePayload: {
936 activeTurnId: scenario === "marked superseded turn" ? "another-turn" : turnId,
937 ...(scenario.startsWith("marked") ? { continueAfterServerUpdate: turnId } : {}),
938 },
939 }),
940 ),
941 upsert: (binding) =>
942 Effect.sync(() => {
943 upserts.push(binding);
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.sync(() => {
952 dispatched.push(command);
953 return { sequence: dispatched.length };
954 }),
955 }).pipe(
956 Effect.tap(() =>
957 Effect.sync(() => {
958 assert.deepStrictEqual(
959 dispatched.map(
960 (command) => command.type === "thread.session.set" && command.session.status,
961 ),
962 ["error"],
963 );
964 assert.deepStrictEqual(
965 upserts.map((binding) => binding.status),
966 ["stopped"],
967 );
968 }),
969 ),
970 );
971 });
973​
974for (const preparedStatus of [
975 "starting",
976 "ready",
977 "ready with failed scan",
978 "completed after update marking",
979] as const) {
980 it.effect(`recovers again if startup exits with a prepared ${preparedStatus} session`, () =>
981 Effect.gen(function* () {
982 const turnId = TurnId.make("turn-interrupted-startup");
983 const thread = makeThread("thread-interrupted-startup", "running", turnId);
984 const activation = yield* Deferred.make<void>();
985 const cleared = yield* Deferred.make<void>();
986 const sends: ProviderSendTurnInput[] = [];
987 let binding: ProviderSessionDirectory.ProviderRuntimeBinding = {
988 threadId: thread.id,
989 provider: ProviderDriverKind.make("codex"),
990 providerInstanceId,
991 status: "running",
992 resumeCursor: { threadId: thread.id },
993 runtimePayload: { activeTurnId: turnId },
994 };
995 const input = {
996 threads: [thread],
997 continueAfterRestart: true,
998 providerService: {
999 ...makeProviderService(),
1000 getCapabilities: () =>
1001 Effect.succeed({
1002 sessionModelSwitch: "in-session" as const,
1003 promptlessTurnContinuation: true,
1004 }),
1005 sendTurn: (input: ProviderSendTurnInput) =>
1006 Effect.sync(() => {
1007 sends.push(input);
1008 return { threadId: input.threadId, turnId: TurnId.make("turn-recovered") };
1009 }),
1010 },
1011 directory: {
1012 getBinding: () => Effect.sync(() => Option.some(binding)),
1013 upsert: (next: ProviderSessionDirectory.ProviderRuntimeBinding) =>
1014 Effect.gen(function* () {
1015 binding = next;
1016 if (binding.status !== "starting" || sends.length === 0) return;
1017 yield* Deferred.succeed(cleared, undefined);
1018 }),
1019 recordImportedTranscript: () => Effect.die("unused"),
1020 getProvider: () => Effect.die("unused"),
1021 listThreadIds: () => Effect.die("unused"),
1022 listBindings: () =>
1023 preparedStatus === "ready with failed scan"
1024 ? Effect.fail(
1025 new ProviderSessionDirectoryPersistenceError({
1026 operation: "listBindings",
1027 detail: "unreadable unrelated binding",
1028 }),
1030 : Effect.sync(() => [{ ...binding, lastSeenAt: "2026-01-01T00:00:00.000Z" }]),
1031 },
1032 dispatch: (command: OrchestrationCommand) =>
1033 Effect.sync(() => {
1034 if (command.type === "thread.session.set") {
1035 thread.session.status = command.session.status;
1036 thread.session.activeTurnId = command.session.activeTurnId;
1038 return { sequence: 1 };
1039 }),
1040 };
1041​
1042 yield* runReconciliation(input).pipe(
1043 Effect.provideService(ServerActivation, Deferred.await(activation)),
1044 Effect.scoped,
1045 );
1046 assert.deepStrictEqual(sends, []);
1047 assert.equal(thread.session.status, "starting");
1048 assert.equal(thread.session.activeTurnId, null);
1049 assert.deepStrictEqual(binding.runtimePayload, {
1050 activeTurnId: null,
1051 continueAfterServerUpdate: turnId,
1052 continueAfterServerUpdatePrepared: true,
1053 });
1054​
1055 if (preparedStatus === "completed after update marking") {
1056 thread.session.status = "ready";
1057 binding = {
1058 ...binding,
1059 status: "stopped",
1060 runtimePayload: {
1061 activeTurnId: null,
1062 continueAfterServerUpdate: turnId,
1063 continueAfterServerUpdatePrepared: null,
1064 },
1065 };
1066 yield* runReconciliation(input);
1067 assert.deepStrictEqual(sends, []);
1068 assert.equal(thread.session.status, "ready");
1069 return;
1071 thread.session.status =
1072 preparedStatus === "ready with failed scan" ? "ready" : preparedStatus;
1073 yield* runReconciliation(input);
1074 yield* Deferred.await(cleared);
1075 assert.deepStrictEqual(sends, [
1076 { threadId: thread.id, continuation: true, interactionMode: "default" },
1077 ]);
1078 assert.deepStrictEqual(binding.runtimePayload, {
1079 activeTurnId: null,
1080 continueAfterServerUpdate: null,
1081 continueAfterServerUpdatePrepared: null,
1082 });
1083 }),
1084 );
1086​
1087it.effect("settles failed opt-in recovery without retrying the provider turn", () =>
1088 Effect.gen(function* () {
1089 const turnId = TurnId.make("turn-failed-recovery");
1090 const thread = makeThread("thread-failed-recovery", "running", turnId);
1091 const settled = yield* Deferred.make<void>();
1092 const sends: ProviderSendTurnInput[] = [];
1093 const dispatched: OrchestrationCommand[] = [];
1094 const preparedPayloads: unknown[] = [];
1095 let binding: ProviderSessionDirectory.ProviderRuntimeBinding = {
1096 threadId: thread.id,
1097 provider: ProviderDriverKind.make("codex"),
1098 providerInstanceId,
1099 status: "running",
1100 resumeCursor: { threadId: thread.id },
1101 runtimePayload: { activeTurnId: turnId },
1102 };
1103 yield* runReconciliation({
1104 threads: [thread],
1105 continueAfterRestart: true,
1106 providerService: {
1107 ...makeProviderService(),
1108 getCapabilities: () =>
1109 Effect.succeed({ sessionModelSwitch: "in-session", promptlessTurnContinuation: true }),
1110 sendTurn: (input) =>
1111 Effect.gen(function* () {
1112 sends.push(input);
1113 preparedPayloads.push(binding.runtimePayload);
1114 return yield* Effect.fail(
1115 new ProviderSessionNotFoundError({ threadId: input.threadId }),
1116 );
1117 }),
1118 },
1119 directory: {
1120 getBinding: () => Effect.sync(() => Option.some(binding)),
1121 upsert: (next) =>
1122 Effect.sync(() => {
1123 binding = next;
1124 }),
1125 recordImportedTranscript: () => Effect.die("unused"),
1126 getProvider: () => Effect.die("unused"),
1127 listThreadIds: () => Effect.die("unused"),
1128 listBindings: () => Effect.succeed([]),
1129 },
1130 dispatch: (command) =>
1131 Effect.gen(function* () {
1132 dispatched.push(command);
1133 if (command.type === "thread.session.set" && command.session.status === "error") {
1134 yield* Deferred.succeed(settled, undefined);
1136 return { sequence: dispatched.length };
1137 }),
1138 });
1139 yield* Deferred.await(settled);
1140 assert.equal(sends.length, 1);
1141 assert.deepStrictEqual(preparedPayloads, [
1143 activeTurnId: null,
1144 continueAfterServerUpdate: turnId,
1145 continueAfterServerUpdatePrepared: true,
1146 },
1147 ]);
1148 assert.deepStrictEqual(
1149 dispatched.map(
1150 (command) =>
1151 command.type === "thread.session.set" && {
1152 status: command.session.status,
1153 activeTurnId: command.session.activeTurnId,
1154 },
1155 ),
1157 { status: "starting", activeTurnId: null },
1158 { status: "error", activeTurnId: null },
1159 ],
1160 );
1161 assert.equal(binding.status, "stopped");
1162 assert.deepStrictEqual(binding.runtimePayload, {
1163 activeTurnId: null,
1164 continueAfterServerUpdate: null,
1165 continueAfterServerUpdatePrepared: null,
1166 });
1167 }),