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 uploadFeedback: () => Effect.die("unused"),
59 streamEvents: Stream.empty,
60 }) satisfies ProviderService.ProviderService["Service"];
61
62const queryWithThreads = (threads: ReadonlyArray<ReturnType<typeof makeThread>>) =>
63 ({
64 getCommandReadModel: () => Effect.succeed({ threads } as never),
65 }) as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"];
66
67const runReconciliation = (input: {
68 readonly threads: ReadonlyArray<ReturnType<typeof makeThread>>;
69 readonly liveThreadIds?: ReadonlyArray<ThreadId>;
70 readonly directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"];
71 readonly dispatch: OrchestrationEngine.OrchestrationEngineService["Service"]["dispatch"];
72}) =>
73 ServerRuntimeStartup.reconcileProviderSessions.pipe(
74 Effect.provideService(
75 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
76 queryWithThreads(input.threads),
77 ),
78 Effect.provideService(
79 ProviderService.ProviderService,
80 makeProviderService(input.liveThreadIds),
81 ),
82 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, input.directory),
83 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
84 readEvents: () => Stream.empty,
85 dispatch: input.dispatch,
86 streamDomainEvents: Stream.empty,
87 subscribeDomainEvents: Effect.succeed(Stream.empty),
88 latestSequence: Effect.succeed(0),
89 }),
90 Effect.provide(NodeServices.layer),
91 );
92
93it.effect("reconciles multiple active and archived orphans but skips live sessions", () => {
94 const starting = makeThread("thread-starting", "starting");
95 const running = makeThread("thread-running", "running", TurnId.make("turn-running"));
96 const staleActiveTurn = makeThread(
97 "thread-stale-active-turn",
98 "ready",
99 TurnId.make("turn-stale-active"),
100 );
101 const archived = makeThread(
102 "thread-archived",
103 "running",
104 TurnId.make("turn-archived"),
105 updatedAt,
106 );
107 const live = makeThread("thread-live", "running", TurnId.make("turn-live"));
108 const settled = makeThread("thread-ready", "ready");
109 const dispatched: OrchestrationCommand[] = [];
110 const bindingReads: ThreadId[] = [];
111 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
112
113 return runReconciliation({
114 threads: [starting, running, staleActiveTurn, archived, live, settled],
115 liveThreadIds: [live.id],
116 directory: {
117 getBinding: (candidate) =>
118 Effect.sync(() => bindingReads.push(candidate)).pipe(
119 Effect.as(
120 Option.some({
121 threadId: candidate,
122 provider: ProviderDriverKind.make("codex"),
123 providerInstanceId,
124 status: "running" as const,
125 resumeCursor: { cursor: candidate },
126 runtimePayload: { activeTurnId: "stale", unrelated: candidate },
127 }),
128 ),
129 ),
130 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
131 getProvider: () => Effect.die("unused"),
132 listThreadIds: () => Effect.die("unused"),
133 listBindings: () => Effect.die("unused"),
134 },
135 dispatch: (command) =>
136 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
137 }).pipe(
138 Effect.tap(() =>
139 Effect.sync(() => {
140 const orphanIds = [starting.id, running.id, staleActiveTurn.id, archived.id];
141 assert.deepStrictEqual(bindingReads, orphanIds);
142 assert.deepStrictEqual(
143 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
144 orphanIds,
145 );
146 assert.deepStrictEqual(
147 dispatched.map((command) =>
148 command.type === "thread.session.set"
149 ? {
150 status: command.session.status,
151 activeTurnId: command.session.activeTurnId,
152 }
153 : null,
154 ),
155 orphanIds.map(() => ({ status: "error" as const, activeTurnId: null })),
156 );
157 assert.equal(upserts.length, orphanIds.length);
158 for (const binding of upserts) {
159 assert.equal(binding.status, "stopped");
160 assert.deepStrictEqual(binding.runtimePayload, { activeTurnId: null });
161 assert.deepStrictEqual(binding.resumeCursor, { cursor: binding.threadId });
162 }
163 }),
164 ),
165 );
166});
167
168it.effect(
169 "settles projections when directory bindings are absent, corrupt, or fail to upsert",
170 () => {
171 const absent = makeThread("thread-binding-absent", "starting");
172 const corrupt = makeThread("thread-binding-corrupt", "running");
173 const upsertFailure = makeThread("thread-binding-upsert-failure", "running");
174 const dispatched: OrchestrationCommand[] = [];
175 const corruptFailure = new ProviderSessionDirectoryPersistenceError({
176 operation: "ProviderSessionDirectory.getBinding",
177 detail: "corrupt persisted binding",
178 });
179 const writeFailure = new ProviderSessionDirectoryPersistenceError({
180 operation: "ProviderSessionDirectory.upsert",
181 detail: "failed binding write",
182 });
183
184 return runReconciliation({
185 threads: [absent, corrupt, upsertFailure],
186 directory: {
187 getBinding: (candidate) =>
188 candidate === absent.id
189 ? Effect.succeed(Option.none())
190 : candidate === corrupt.id
191 ? Effect.fail(corruptFailure)
192 : Effect.succeed(
193 Option.some({
194 threadId: candidate,
195 provider: ProviderDriverKind.make("codex"),
196 providerInstanceId,
197 }),
198 ),
199 upsert: () => Effect.fail(writeFailure),
200 getProvider: () => Effect.die("unused"),
201 listThreadIds: () => Effect.die("unused"),
202 listBindings: () => Effect.die("unused"),
203 },
204 dispatch: (command) =>
205 Effect.sync(() => dispatched.push(command)).pipe(
206 Effect.as({ sequence: dispatched.length }),
207 ),
208 }).pipe(
209 Effect.tap(() =>
210 Effect.sync(() => {
211 assert.deepStrictEqual(
212 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
213 [absent.id, corrupt.id, upsertFailure.id],
214 );
215 }),
216 ),
217 );
218 },
219);
220
221it.effect("retries failed projections and continues after a persistent failure", () => {
222 const transient = makeThread("thread-dispatch-transient-failure", "running");
223 const persistent = makeThread("thread-dispatch-persistent-failure", "running");
224 const later = makeThread("thread-dispatch-success", "running");
225 const attempted: ThreadId[] = [];
226 let transientAttempts = 0;
227 const failure = new OrchestrationCommandInvariantError({
228 commandType: "thread.session.set",
229 detail: "simulated startup reconciliation failure",
230 });
231
232 return runReconciliation({
233 threads: [transient, persistent, later],
234 directory: {
235 getBinding: () => Effect.succeed(Option.none()),
236 upsert: () => Effect.void,
237 getProvider: () => Effect.die("unused"),
238 listThreadIds: () => Effect.die("unused"),
239 listBindings: () => Effect.die("unused"),
240 },
241 dispatch: (command) => {
242 if (command.type !== "thread.session.set") {
243 return Effect.die("unexpected command");
244 }
245 attempted.push(command.threadId);
246 if (command.threadId === transient.id && transientAttempts++ === 0) {
247 return Effect.fail(failure);
248 }
249 return command.threadId === persistent.id
250 ? Effect.fail(failure)
251 : Effect.succeed({ sequence: attempted.length });
252 },
253 }).pipe(
254 Effect.tap(() =>
255 Effect.sync(() =>
256 assert.deepStrictEqual(attempted, [
257 transient.id,
258 transient.id,
259 persistent.id,
260 persistent.id,
261 later.id,
262 ]),
263 ),
264 ),
265 );
266});
267
268it.effect("does not fail startup when the live provider session inventory cannot be read", () => {
269 let queried = false;
270 return ServerRuntimeStartup.reconcileProviderSessions.pipe(
271 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
272 getCommandReadModel: () =>
273 Effect.sync(() => {
274 queried = true;
275 return { threads: [] } as never;
276 }),
277 } as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]),
278 Effect.provideService(ProviderService.ProviderService, {
279 ...makeProviderService(),
280 listSessions: () => Effect.die("provider inventory unavailable"),
281 }),
282 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
283 getBinding: () => Effect.die("unused"),
284 upsert: () => Effect.die("unused"),
285 getProvider: () => Effect.die("unused"),
286 listThreadIds: () => Effect.die("unused"),
287 listBindings: () => Effect.die("unused"),
288 }),
289 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
290 readEvents: () => Stream.empty,
291 dispatch: () => Effect.die("unused"),
292 streamDomainEvents: Stream.empty,
293 subscribeDomainEvents: Effect.succeed(Stream.empty),
294 latestSequence: Effect.succeed(0),
295 }),
296 Effect.provide(NodeServices.layer),
297 Effect.tap(() => Effect.sync(() => assert.equal(queried, false))),
298 );
299});