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

serverRuntimeStartup.reconcile.test.ts

297 lines11.0 KB

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