Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 type OrchestrationCommand,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 ThreadId,
7 TurnId,
8} from "@t3tools/contracts";
9import { assert, it } from "@effect/vitest";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12import * as Stream from "effect/Stream";
13
14import { OrchestrationCommandInvariantError } from "./orchestration/Errors.ts";
15import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
16import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
17import { ProviderSessionDirectoryPersistenceError } from "./provider/Errors.ts";
18import * as ProviderService from "./provider/Services/ProviderService.ts";
19import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
20import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
21
22const providerInstanceId = ProviderInstanceId.make("codex");
23const updatedAt = "2026-08-20T12:00:00.000Z";
24
25const makeThread = (
26 id: string,
27 status: "starting" | "running" | "ready" | "stopped" | "error",
28 activeTurnId: TurnId | null = null,
29 archivedAt: string | null = null,
30) => ({
31 id: ThreadId.make(id),
32 archivedAt,
33 deletedAt: null,
34 session: {
35 threadId: ThreadId.make(id),
36 status,
37 providerName: "codex" as const,
38 providerInstanceId,
39 runtimeMode: "full-access" as const,
40 activeTurnId,
41 lastError: null,
42 updatedAt,
43 },
44});
45
46const makeProviderService = (liveThreadIds: ReadonlyArray<ThreadId> = []) =>
47 ({
48 startSession: () => Effect.die("unused"),
49 sendTurn: () => Effect.die("unused"),
50 interruptTurn: () => Effect.die("unused"),
51 respondToRequest: () => Effect.die("unused"),
52 respondToUserInput: () => Effect.die("unused"),
53 stopSession: () => Effect.die("unused"),
54 listSessions: () => Effect.succeed(liveThreadIds.map((threadId) => ({ threadId }) as never)),
55 getCapabilities: () => Effect.die("unused"),
56 getInstanceInfo: () => Effect.die("unused"),
57 rollbackConversation: () => Effect.die("unused"),
58 streamEvents: Stream.empty,
59 }) satisfies ProviderService.ProviderService["Service"];
60
61const queryWithThreads = (threads: ReadonlyArray<ReturnType<typeof makeThread>>) =>
62 ({
63 getCommandReadModel: () => Effect.succeed({ threads } as never),
64 }) as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"];
65
66const runReconciliation = (input: {
67 readonly threads: ReadonlyArray<ReturnType<typeof makeThread>>;
68 readonly liveThreadIds?: ReadonlyArray<ThreadId>;
69 readonly directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"];
70 readonly dispatch: OrchestrationEngine.OrchestrationEngineService["Service"]["dispatch"];
71}) =>
72 ServerRuntimeStartup.reconcileProviderSessions.pipe(
73 Effect.provideService(
74 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
75 queryWithThreads(input.threads),
76 ),
77 Effect.provideService(
78 ProviderService.ProviderService,
79 makeProviderService(input.liveThreadIds),
80 ),
81 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, input.directory),
82 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
83 readEvents: () => Stream.empty,
84 dispatch: input.dispatch,
85 streamDomainEvents: Stream.empty,
86 latestSequence: Effect.succeed(0),
87 }),
88 Effect.provide(NodeServices.layer),
89 );
90
91it.effect("reconciles multiple active and archived orphans but skips live sessions", () => {
92 const starting = makeThread("thread-starting", "starting");
93 const running = makeThread("thread-running", "running", TurnId.make("turn-running"));
94 const staleActiveTurn = makeThread(
95 "thread-stale-active-turn",
96 "ready",
97 TurnId.make("turn-stale-active"),
98 );
99 const archived = makeThread(
100 "thread-archived",
101 "running",
102 TurnId.make("turn-archived"),
103 updatedAt,
104 );
105 const live = makeThread("thread-live", "running", TurnId.make("turn-live"));
106 const settled = makeThread("thread-ready", "ready");
107 const dispatched: OrchestrationCommand[] = [];
108 const bindingReads: ThreadId[] = [];
109 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
110
111 return runReconciliation({
112 threads: [starting, running, staleActiveTurn, archived, live, settled],
113 liveThreadIds: [live.id],
114 directory: {
115 getBinding: (candidate) =>
116 Effect.sync(() => bindingReads.push(candidate)).pipe(
117 Effect.as(
118 Option.some({
119 threadId: candidate,
120 provider: ProviderDriverKind.make("codex"),
121 providerInstanceId,
122 status: "running" as const,
123 resumeCursor: { cursor: candidate },
124 runtimePayload: { activeTurnId: "stale", unrelated: candidate },
125 }),
126 ),
127 ),
128 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
129 getProvider: () => Effect.die("unused"),
130 listThreadIds: () => Effect.die("unused"),
131 listBindings: () => Effect.die("unused"),
132 },
133 dispatch: (command) =>
134 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
135 }).pipe(
136 Effect.tap(() =>
137 Effect.sync(() => {
138 const orphanIds = [starting.id, running.id, staleActiveTurn.id, archived.id];
139 assert.deepStrictEqual(bindingReads, orphanIds);
140 assert.deepStrictEqual(
141 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
142 orphanIds,
143 );
144 assert.deepStrictEqual(
145 dispatched.map((command) =>
146 command.type === "thread.session.set"
147 ? {
148 status: command.session.status,
149 activeTurnId: command.session.activeTurnId,
150 }
151 : null,
152 ),
153 orphanIds.map(() => ({ status: "error" as const, activeTurnId: null })),
154 );
155 assert.equal(upserts.length, orphanIds.length);
156 for (const binding of upserts) {
157 assert.equal(binding.status, "stopped");
158 assert.deepStrictEqual(binding.runtimePayload, { activeTurnId: null });
159 assert.deepStrictEqual(binding.resumeCursor, { cursor: binding.threadId });
160 }
161 }),
162 ),
163 );
164});
165
166it.effect(
167 "settles projections when directory bindings are absent, corrupt, or fail to upsert",
168 () => {
169 const absent = makeThread("thread-binding-absent", "starting");
170 const corrupt = makeThread("thread-binding-corrupt", "running");
171 const upsertFailure = makeThread("thread-binding-upsert-failure", "running");
172 const dispatched: OrchestrationCommand[] = [];
173 const corruptFailure = new ProviderSessionDirectoryPersistenceError({
174 operation: "ProviderSessionDirectory.getBinding",
175 detail: "corrupt persisted binding",
176 });
177 const writeFailure = new ProviderSessionDirectoryPersistenceError({
178 operation: "ProviderSessionDirectory.upsert",
179 detail: "failed binding write",
180 });
181
182 return runReconciliation({
183 threads: [absent, corrupt, upsertFailure],
184 directory: {
185 getBinding: (candidate) =>
186 candidate === absent.id
187 ? Effect.succeed(Option.none())
188 : candidate === corrupt.id
189 ? Effect.fail(corruptFailure)
190 : Effect.succeed(
191 Option.some({
192 threadId: candidate,
193 provider: ProviderDriverKind.make("codex"),
194 providerInstanceId,
195 }),
196 ),
197 upsert: () => Effect.fail(writeFailure),
198 getProvider: () => Effect.die("unused"),
199 listThreadIds: () => Effect.die("unused"),
200 listBindings: () => Effect.die("unused"),
201 },
202 dispatch: (command) =>
203 Effect.sync(() => dispatched.push(command)).pipe(
204 Effect.as({ sequence: dispatched.length }),
205 ),
206 }).pipe(
207 Effect.tap(() =>
208 Effect.sync(() => {
209 assert.deepStrictEqual(
210 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
211 [absent.id, corrupt.id, upsertFailure.id],
212 );
213 }),
214 ),
215 );
216 },
217);
218
219it.effect("retries failed projections and continues after a persistent failure", () => {
220 const transient = makeThread("thread-dispatch-transient-failure", "running");
221 const persistent = makeThread("thread-dispatch-persistent-failure", "running");
222 const later = makeThread("thread-dispatch-success", "running");
223 const attempted: ThreadId[] = [];
224 let transientAttempts = 0;
225 const failure = new OrchestrationCommandInvariantError({
226 commandType: "thread.session.set",
227 detail: "simulated startup reconciliation failure",
228 });
229
230 return runReconciliation({
231 threads: [transient, persistent, later],
232 directory: {
233 getBinding: () => Effect.succeed(Option.none()),
234 upsert: () => Effect.void,
235 getProvider: () => Effect.die("unused"),
236 listThreadIds: () => Effect.die("unused"),
237 listBindings: () => Effect.die("unused"),
238 },
239 dispatch: (command) => {
240 if (command.type !== "thread.session.set") {
241 return Effect.die("unexpected command");
242 }
243 attempted.push(command.threadId);
244 if (command.threadId === transient.id && transientAttempts++ === 0) {
245 return Effect.fail(failure);
246 }
247 return command.threadId === persistent.id
248 ? Effect.fail(failure)
249 : Effect.succeed({ sequence: attempted.length });
250 },
251 }).pipe(
252 Effect.tap(() =>
253 Effect.sync(() =>
254 assert.deepStrictEqual(attempted, [
255 transient.id,
256 transient.id,
257 persistent.id,
258 persistent.id,
259 later.id,
260 ]),
261 ),
262 ),
263 );
264});
265
266it.effect("does not fail startup when the live provider session inventory cannot be read", () => {
267 let queried = false;
268 return ServerRuntimeStartup.reconcileProviderSessions.pipe(
269 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
270 getCommandReadModel: () =>
271 Effect.sync(() => {
272 queried = true;
273 return { threads: [] } as never;
274 }),
275 } as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]),
276 Effect.provideService(ProviderService.ProviderService, {
277 ...makeProviderService(),
278 listSessions: () => Effect.die("provider inventory unavailable"),
279 }),
280 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
281 getBinding: () => Effect.die("unused"),
282 upsert: () => Effect.die("unused"),
283 getProvider: () => Effect.die("unused"),
284 listThreadIds: () => Effect.die("unused"),
285 listBindings: () => Effect.die("unused"),
286 }),
287 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
288 readEvents: () => Stream.empty,
289 dispatch: () => Effect.die("unused"),
290 streamDomainEvents: Stream.empty,
291 latestSequence: Effect.succeed(0),
292 }),
293 Effect.provide(NodeServices.layer),
294 Effect.tap(() => Effect.sync(() => assert.equal(queried, false))),
295 );
296});