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

serverRuntimeStartup.reconcile.test.ts

660 lines23.0 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 type OrchestrationCommand,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 type ProviderSendTurnInput,
7 ThreadId,
8 TurnId,
9} from "@t3tools/contracts";
10import { assert, it } from "@effect/vitest";
11import * as Deferred from "effect/Deferred";
12import * as Effect from "effect/Effect";
13import * as Option from "effect/Option";
14import * as Stream from "effect/Stream";
15​
16import { OrchestrationCommandInvariantError } from "./orchestration/Errors.ts";
17import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
18import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
19import { ProviderSessionDirectoryPersistenceError } from "./provider/Errors.ts";
20import * as ProviderService from "./provider/Services/ProviderService.ts";
21import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
22import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
23​
24const providerInstanceId = ProviderInstanceId.make("codex");
25const updatedAt = "2026-08-20T12:00:00.000Z";
26​
27const makeThread = (
28 id: string,
29 status: "starting" | "running" | "ready" | "stopped" | "error",
30 activeTurnId: TurnId | null = null,
31 archivedAt: string | null = null,
32 deletedAt: string | null = null,
33) => ({
34 id: ThreadId.make(id),
35 archivedAt,
36 deletedAt,
37 interactionMode: "default" as const,
38 session: {
39 threadId: ThreadId.make(id),
40 status,
41 providerName: "codex" as const,
42 providerInstanceId,
43 runtimeMode: "full-access" as const,
44 activeTurnId,
45 lastError: null,
46 updatedAt,
47 },
48});
49​
50const makeProviderService = (liveThreadIds: ReadonlyArray<ThreadId> = []) =>
51 ({
52 startSession: () => Effect.die("unused"),
53 sendTurn: () => Effect.die("unused"),
54 interruptTurn: () => Effect.die("unused"),
55 respondToRequest: () => Effect.die("unused"),
56 respondToUserInput: () => Effect.die("unused"),
57 stopSession: () => Effect.die("unused"),
58 listSessions: () => Effect.succeed(liveThreadIds.map((threadId) => ({ threadId }) as never)),
59 getCapabilities: () => Effect.die("unused"),
60 getInstanceInfo: () => Effect.die("unused"),
61 rollbackConversation: () => Effect.die("unused"),
62 uploadFeedback: () => Effect.die("unused"),
63 streamEvents: Stream.empty,
64 }) satisfies ProviderService.ProviderService["Service"];
65​
66const queryWithThreads = (threads: ReadonlyArray<ReturnType<typeof makeThread>>) =>
67 ({
68 getCommandReadModel: () => Effect.succeed({ threads } as never),
69 }) as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"];
70​
71const runReconciliation = (input: {
72 readonly threads: ReadonlyArray<ReturnType<typeof makeThread>>;
73 readonly liveThreadIds?: ReadonlyArray<ThreadId>;
74 readonly providerService?: ProviderService.ProviderService["Service"];
75 readonly directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"];
76 readonly dispatch: OrchestrationEngine.OrchestrationEngineService["Service"]["dispatch"];
77}) =>
78 ServerRuntimeStartup.reconcileProviderSessions.pipe(
79 Effect.provideService(
80 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
81 queryWithThreads(input.threads),
82 ),
83 Effect.provideService(
84 ProviderService.ProviderService,
85 input.providerService ?? makeProviderService(input.liveThreadIds),
86 ),
87 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, input.directory),
88 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
89 readEvents: () => Stream.empty,
90 dispatch: input.dispatch,
91 streamDomainEvents: Stream.empty,
92 subscribeDomainEvents: Effect.succeed(Stream.empty),
93 latestSequence: Effect.succeed(0),
94 }),
95 Effect.provide(NodeServices.layer),
96 );
97​
98it.effect("marks active running sessions that have persisted resume state", () => {
99 const active = makeThread("thread-mark-active", "running", TurnId.make("turn-mark-active"));
100 const archived = makeThread(
101 "thread-mark-archived",
102 "running",
103 TurnId.make("turn-mark-archived"),
104 updatedAt,
105 );
106 const ready = makeThread("thread-mark-ready", "ready");
107 const missingResumeState = makeThread(
108 "thread-mark-missing-resume-state",
109 "running",
110 TurnId.make("turn-mark-missing-resume-state"),
111 );
112 const bindingReads: ThreadId[] = [];
113 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
114​
115 return ServerRuntimeStartup.markRunningProviderSessionsForContinuation.pipe(
116 Effect.provideService(
117 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
118 queryWithThreads([active, archived, ready, missingResumeState]),
119 ),
120 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
121 getBinding: (threadId) =>
122 Effect.sync(() => bindingReads.push(threadId)).pipe(
123 Effect.as(
124 Option.some({
125 threadId,
126 provider: ProviderDriverKind.make("codex"),
127 providerInstanceId,
128 ...(threadId === active.id ? { resumeCursor: { threadId } } : {}),
129 runtimePayload: { activeTurnId: "turn-mark-active" },
130 }),
131 ),
132 ),
133 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
134 getProvider: () => Effect.die("unused"),
135 listThreadIds: () => Effect.die("unused"),
136 listBindings: () => Effect.die("unused"),
137 }),
138 Effect.tap((marked) =>
139 Effect.sync(() => {
140 assert.deepStrictEqual(bindingReads, [active.id, missingResumeState.id]);
141 assert.deepStrictEqual(marked, [active.id]);
142 assert.deepStrictEqual(upserts[0]?.runtimePayload, {
143 activeTurnId: "turn-mark-active",
144 continueAfterServerUpdate: active.session.activeTurnId,
145 });
146 }),
147 ),
148 );
149});
150​
151it.effect("continues marked sessions after activation with provider-specific input", () =>
152 Effect.gen(function* () {
153 const codex = makeThread(
154 "thread-continue-codex",
155 "running",
156 TurnId.make("turn-continue-codex"),
157 );
158 const fallback = makeThread("thread-continue-fallback", "starting");
159 const fallbackContinuationTurnId = TurnId.make("turn-continue-fallback");
160 const fallbackProviderInstanceId = ProviderInstanceId.make("claudeAgent");
161 const continuationSent = yield* Deferred.make<void>();
162 const continuationCleared = yield* Deferred.make<void>();
163 const sends: ProviderSendTurnInput[] = [];
164 const dispatched: OrchestrationCommand[] = [];
165 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
166 const bindings = new Map<ThreadId, ProviderSessionDirectory.ProviderRuntimeBinding>(
167 [codex, fallback].map((thread) => [
168 thread.id,
169 {
170 threadId: thread.id,
171 provider:
172 thread.id === codex.id
173 ? ProviderDriverKind.make("codex")
174 : ProviderDriverKind.make("claudeAgent"),
175 providerInstanceId:
176 thread.id === codex.id ? providerInstanceId : fallbackProviderInstanceId,
177 status: "running" as const,
178 runtimePayload: {
179 continueAfterServerUpdate:
180 thread.id === codex.id ? codex.session.activeTurnId : fallbackContinuationTurnId,
181 },
182 },
183 ]),
184 );
185 const providerService: ProviderService.ProviderService["Service"] = {
186 ...makeProviderService(),
187 getCapabilities: (instanceId) =>
188 Effect.succeed({
189 sessionModelSwitch: "in-session",
190 ...(instanceId === providerInstanceId ? { promptlessTurnContinuation: true } : {}),
191 }),
192 sendTurn: (input) =>
193 Effect.gen(function* () {
194 sends.push(input);
195 if (sends.length === 2) {
196 yield* Deferred.succeed(continuationSent, undefined);
197 }
198 return {
199 threadId: input.threadId,
200 turnId: TurnId.make(`continued-${String(input.threadId)}`),
201 };
202 }),
203 };
204​
205 yield* runReconciliation({
206 threads: [codex, fallback],
207 providerService,
208 directory: {
209 getBinding: (threadId) =>
210 Effect.sync(() => {
211 const binding = bindings.get(threadId);
212 return binding === undefined ? Option.none() : Option.some(binding);
213 }),
214 upsert: (binding) =>
215 Effect.sync(() => {
216 bindings.set(binding.threadId, binding);
217 upserts.push(binding);
218 const clearedCount = upserts.filter((candidate) => {
219 const payload = candidate.runtimePayload;
220 return (
221 payload !== null &&
222 typeof payload === "object" &&
223 !Array.isArray(payload) &&
224 "continueAfterServerUpdate" in payload &&
225 payload.continueAfterServerUpdate === null
226 );
227 }).length;
228 return clearedCount === 1;
229 }).pipe(
230 Effect.flatMap((firstMarkerCleared) =>
231 firstMarkerCleared ? Deferred.succeed(continuationCleared, undefined) : Effect.void,
232 ),
233 ),
234 getProvider: () => Effect.die("unused"),
235 listThreadIds: () => Effect.die("unused"),
236 listBindings: () => Effect.die("unused"),
237 },
238 dispatch: (command) =>
239 Effect.sync(() => dispatched.push(command)).pipe(
240 Effect.as({ sequence: dispatched.length }),
241 ),
242 });
243 yield* Deferred.await(continuationSent);
244 yield* Deferred.await(continuationCleared);
245​
246 assert.deepStrictEqual(
247 sends.toSorted((left, right) => String(left.threadId).localeCompare(String(right.threadId))),
248 [
249 { threadId: codex.id, continuation: true, interactionMode: "default" },
250 {
251 threadId: fallback.id,
252 input: "Continue where you left off.",
253 interactionMode: "default",
254 },
255 ],
256 );
257 assert.deepStrictEqual(
258 dispatched.map((command) =>
259 command.type === "thread.session.set"
260 ? {
261 threadId: command.threadId,
262 status: command.session.status,
263 activeTurnId: command.session.activeTurnId,
264 }
265 : null,
266 ),
267 [
268 {
269 threadId: codex.id,
270 status: "starting",
271 activeTurnId: null,
272 },
273 {
274 threadId: fallback.id,
275 status: "starting",
276 activeTurnId: fallback.session.activeTurnId,
277 },
278 ],
279 );
280 for (const [thread, continuationTurnId] of [
281 [codex, codex.session.activeTurnId],
282 [fallback, fallbackContinuationTurnId],
283 ] as const) {
284 assert.deepStrictEqual(
285 upserts
286 .filter((binding) => binding.threadId === thread.id)
287 .map((binding) => binding.runtimePayload)[0],
288 {
289 continueAfterServerUpdate: continuationTurnId,
290 activeTurnId: null,
291 },
292 );
293 }
294 assert.equal(
295 upserts.some((binding) => {
296 const payload = binding.runtimePayload;
297 return (
298 payload !== null &&
299 typeof payload === "object" &&
300 !Array.isArray(payload) &&
301 "continueAfterServerUpdate" in payload &&
302 payload.continueAfterServerUpdate === null
303 );
304 }),
305 true,
306 );
307 }),
308);
309​
310it.effect("does not continue archived or deleted marked sessions", () => {
311 const archived = makeThread(
312 "thread-continue-archived",
313 "running",
314 TurnId.make("turn-continue-archived"),
315 updatedAt,
316 );
317 const deleted = makeThread(
318 "thread-continue-deleted",
319 "running",
320 TurnId.make("turn-continue-deleted"),
321 null,
322 updatedAt,
323 );
324 const sends: ProviderSendTurnInput[] = [];
325 const dispatched: OrchestrationCommand[] = [];
326​
327 return runReconciliation({
328 threads: [archived, deleted],
329 providerService: {
330 ...makeProviderService(),
331 sendTurn: (input) =>
332 Effect.sync(() => {
333 sends.push(input);
334 return {
335 threadId: input.threadId,
336 turnId: TurnId.make("unexpected-archived-turn"),
337 };
338 }),
339 },
340 directory: {
341 getBinding: (threadId) => {
342 const thread = threadId === archived.id ? archived : deleted;
343 return Effect.succeed(
344 Option.some({
345 threadId,
346 provider: ProviderDriverKind.make("codex"),
347 providerInstanceId,
348 status: "running" as const,
349 resumeCursor: { cursor: threadId },
350 runtimePayload: {
351 continueAfterServerUpdate: thread.session.activeTurnId,
352 },
353 }),
354 );
355 },
356 upsert: () => Effect.void,
357 getProvider: () => Effect.die("unused"),
358 listThreadIds: () => Effect.die("unused"),
359 listBindings: () => Effect.die("unused"),
360 },
361 dispatch: (command) =>
362 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
363 }).pipe(
364 Effect.tap(() =>
365 Effect.sync(() => {
366 assert.deepStrictEqual(sends, []);
367 assert.deepStrictEqual(
368 dispatched.map((command) =>
369 command.type === "thread.session.set"
370 ? { threadId: command.threadId, status: command.session.status }
371 : null,
372 ),
373 [
374 { threadId: archived.id, status: "error" },
375 { threadId: deleted.id, status: "error" },
376 ],
377 );
378 }),
379 ),
380 );
381});
382​
383it.effect("retries continuation preparation before settling a persistent failure", () => {
384 const thread = makeThread(
385 "thread-continuation-preparation-failure",
386 "running",
387 TurnId.make("turn-continuation-preparation-failure"),
388 );
389 const dispatched: OrchestrationCommand[] = [];
390 const failure = new OrchestrationCommandInvariantError({
391 commandType: "thread.session.set",
392 detail: "simulated continuation preparation failure",
393 });
394​
395 return runReconciliation({
396 threads: [thread],
397 directory: {
398 getBinding: () =>
399 Effect.succeed(
400 Option.some({
401 threadId: thread.id,
402 provider: ProviderDriverKind.make("codex"),
403 providerInstanceId,
404 status: "running" as const,
405 resumeCursor: { cursor: thread.id },
406 runtimePayload: {
407 continueAfterServerUpdate: thread.session.activeTurnId,
408 },
409 }),
410 ),
411 upsert: () => Effect.void,
412 getProvider: () => Effect.die("unused"),
413 listThreadIds: () => Effect.die("unused"),
414 listBindings: () => Effect.die("unused"),
415 },
416 dispatch: (command) => {
417 if (command.type !== "thread.session.set") {
418 return Effect.die("unexpected command");
419 }
420 dispatched.push(command);
421 return command.session.status === "starting"
422 ? Effect.fail(failure)
423 : Effect.succeed({ sequence: dispatched.length });
424 },
425 }).pipe(
426 Effect.tap(() =>
427 Effect.sync(() =>
428 assert.deepStrictEqual(
429 dispatched.map(
430 (command) => command.type === "thread.session.set" && command.session.status,
431 ),
432 ["starting", "starting", "error"],
433 ),
434 ),
435 ),
436 );
437});
438​
439it.effect("reconciles multiple active and archived orphans but skips live sessions", () => {
440 const starting = makeThread("thread-starting", "starting");
441 const running = makeThread("thread-running", "running", TurnId.make("turn-running"));
442 const staleActiveTurn = makeThread(
443 "thread-stale-active-turn",
444 "ready",
445 TurnId.make("turn-stale-active"),
446 );
447 const archived = makeThread(
448 "thread-archived",
449 "running",
450 TurnId.make("turn-archived"),
451 updatedAt,
452 );
453 const live = makeThread("thread-live", "running", TurnId.make("turn-live"));
454 const settled = makeThread("thread-ready", "ready");
455 const dispatched: OrchestrationCommand[] = [];
456 const bindingReads: ThreadId[] = [];
457 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
458​
459 return runReconciliation({
460 threads: [starting, running, staleActiveTurn, archived, live, settled],
461 liveThreadIds: [live.id],
462 directory: {
463 getBinding: (candidate) =>
464 Effect.sync(() => bindingReads.push(candidate)).pipe(
465 Effect.as(
466 Option.some({
467 threadId: candidate,
468 provider: ProviderDriverKind.make("codex"),
469 providerInstanceId,
470 status: "running" as const,
471 resumeCursor: { cursor: candidate },
472 runtimePayload: {
473 activeTurnId: "stale",
474 unrelated: candidate,
475 ...(candidate === staleActiveTurn.id
476 ? { continueAfterServerUpdate: "turn-from-an-earlier-update" }
477 : {}),
478 },
479 }),
480 ),
481 ),
482 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
483 getProvider: () => Effect.die("unused"),
484 listThreadIds: () => Effect.die("unused"),
485 listBindings: () => Effect.die("unused"),
486 },
487 dispatch: (command) =>
488 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
489 }).pipe(
490 Effect.tap(() =>
491 Effect.sync(() => {
492 const orphanIds = [starting.id, running.id, staleActiveTurn.id, archived.id];
493 assert.deepStrictEqual(bindingReads, orphanIds);
494 assert.deepStrictEqual(
495 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
496 orphanIds,
497 );
498 assert.deepStrictEqual(
499 dispatched.map((command) =>
500 command.type === "thread.session.set"
501 ? {
502 status: command.session.status,
503 activeTurnId: command.session.activeTurnId,
504 }
505 : null,
506 ),
507 orphanIds.map(() => ({ status: "error" as const, activeTurnId: null })),
508 );
509 assert.equal(upserts.length, orphanIds.length);
510 for (const binding of upserts) {
511 assert.equal(binding.status, "stopped");
512 assert.deepStrictEqual(
513 binding.runtimePayload,
514 binding.threadId === staleActiveTurn.id
515 ? {
516 activeTurnId: null,
517 unrelated: binding.threadId,
518 continueAfterServerUpdate: null,
519 }
520 : { activeTurnId: null, unrelated: binding.threadId },
521 );
522 assert.deepStrictEqual(binding.resumeCursor, { cursor: binding.threadId });
523 }
524 }),
525 ),
526 );
527});
528​
529it.effect(
530 "settles projections when directory bindings are absent, corrupt, or fail to upsert",
531 () => {
532 const absent = makeThread("thread-binding-absent", "starting");
533 const corrupt = makeThread("thread-binding-corrupt", "running");
534 const upsertFailure = makeThread("thread-binding-upsert-failure", "running");
535 const dispatched: OrchestrationCommand[] = [];
536 const corruptFailure = new ProviderSessionDirectoryPersistenceError({
537 operation: "ProviderSessionDirectory.getBinding",
538 detail: "corrupt persisted binding",
539 });
540 const writeFailure = new ProviderSessionDirectoryPersistenceError({
541 operation: "ProviderSessionDirectory.upsert",
542 detail: "failed binding write",
543 });
544​
545 return runReconciliation({
546 threads: [absent, corrupt, upsertFailure],
547 directory: {
548 getBinding: (candidate) =>
549 candidate === absent.id
550 ? Effect.succeed(Option.none())
551 : candidate === corrupt.id
552 ? Effect.fail(corruptFailure)
553 : Effect.succeed(
554 Option.some({
555 threadId: candidate,
556 provider: ProviderDriverKind.make("codex"),
557 providerInstanceId,
558 }),
559 ),
560 upsert: () => Effect.fail(writeFailure),
561 getProvider: () => Effect.die("unused"),
562 listThreadIds: () => Effect.die("unused"),
563 listBindings: () => Effect.die("unused"),
564 },
565 dispatch: (command) =>
566 Effect.sync(() => dispatched.push(command)).pipe(
567 Effect.as({ sequence: dispatched.length }),
568 ),
569 }).pipe(
570 Effect.tap(() =>
571 Effect.sync(() => {
572 assert.deepStrictEqual(
573 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
574 [absent.id, corrupt.id, upsertFailure.id],
575 );
576 }),
577 ),
578 );
579 },
580);
581​
582it.effect("retries failed projections and continues after a persistent failure", () => {
583 const transient = makeThread("thread-dispatch-transient-failure", "running");
584 const persistent = makeThread("thread-dispatch-persistent-failure", "running");
585 const later = makeThread("thread-dispatch-success", "running");
586 const attempted: ThreadId[] = [];
587 let transientAttempts = 0;
588 const failure = new OrchestrationCommandInvariantError({
589 commandType: "thread.session.set",
590 detail: "simulated startup reconciliation failure",
591 });
592​
593 return runReconciliation({
594 threads: [transient, persistent, later],
595 directory: {
596 getBinding: () => Effect.succeed(Option.none()),
597 upsert: () => Effect.void,
598 getProvider: () => Effect.die("unused"),
599 listThreadIds: () => Effect.die("unused"),
600 listBindings: () => Effect.die("unused"),
601 },
602 dispatch: (command) => {
603 if (command.type !== "thread.session.set") {
604 return Effect.die("unexpected command");
605 }
606 attempted.push(command.threadId);
607 if (command.threadId === transient.id && transientAttempts++ === 0) {
608 return Effect.fail(failure);
609 }
610 return command.threadId === persistent.id
611 ? Effect.fail(failure)
612 : Effect.succeed({ sequence: attempted.length });
613 },
614 }).pipe(
615 Effect.tap(() =>
616 Effect.sync(() =>
617 assert.deepStrictEqual(attempted, [
618 transient.id,
619 transient.id,
620 persistent.id,
621 persistent.id,
622 later.id,
623 ]),
624 ),
625 ),
626 );
627});
628​
629it.effect("does not fail startup when the live provider session inventory cannot be read", () => {
630 let queried = false;
631 return ServerRuntimeStartup.reconcileProviderSessions.pipe(
632 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
633 getCommandReadModel: () =>
634 Effect.sync(() => {
635 queried = true;
636 return { threads: [] } as never;
637 }),
638 } as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]),
639 Effect.provideService(ProviderService.ProviderService, {
640 ...makeProviderService(),
641 listSessions: () => Effect.die("provider inventory unavailable"),
642 }),
643 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
644 getBinding: () => Effect.die("unused"),
645 upsert: () => Effect.die("unused"),
646 getProvider: () => Effect.die("unused"),
647 listThreadIds: () => Effect.die("unused"),
648 listBindings: () => Effect.die("unused"),
649 }),
650 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
651 readEvents: () => Stream.empty,
652 dispatch: () => Effect.die("unused"),
653 streamDomainEvents: Stream.empty,
654 subscribeDomainEvents: Effect.succeed(Stream.empty),
655 latestSequence: Effect.succeed(0),
656 }),
657 Effect.provide(NodeServices.layer),
658 Effect.tap(() => Effect.sync(() => assert.equal(queried, false))),
659 );
660});