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

ProviderRuntimeRecoveryService.ts

402 lines14.6 KB

1import {
2 CommandId,
3 type OrchestrationV2DomainEvent,
4 type OrchestrationV2ThreadProjection,
5 ThreadId,
6} from "@t3tools/contracts";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Schema from "effect/Schema";
12​
13import * as EffectWorker from "./EffectWorker.ts";
14import * as EffectOutbox from "./EffectOutbox.ts";
15import * as EventSink from "./EventSink.ts";
16import * as IdAllocator from "./IdAllocator.ts";
17import * as ProjectionStore from "./ProjectionStore.ts";
18​
19export class ProviderRuntimeRecoveryError extends Schema.TaggedErrorClass<ProviderRuntimeRecoveryError>()(
20 "ProviderRuntimeRecoveryError",
21 {
22 operation: Schema.Literals(["read-projections", "reconcile", "drain-outbox"]),
23 threadId: Schema.optional(ThreadId),
24 cause: Schema.Defect(),
25 },
26) {
27 override get message(): string {
28 return `Provider runtime recovery failed during ${this.operation}.`;
29 }
31​
32export interface ProviderRuntimeRecoverySummary {
33 readonly terminalizedRuns: number;
34 readonly stoppedSessions: number;
35 readonly closedRequests: number;
36 readonly retiredEffects: number;
37 readonly requeuedEffects: number;
38 readonly executedEffects: number;
40​
41export interface ProviderRuntimeReconciliationSummary {
42 readonly terminalizedRuns: number;
43 readonly stoppedSessions: number;
44 readonly closedRequests: number;
45 readonly retiredEffects: number;
46 readonly requeuedEffects: number;
48​
49export class ProviderRuntimeRecoveryService extends Context.Service<
50 ProviderRuntimeRecoveryService,
51 {
52 readonly reconcile: (
53 trigger: "startup" | "shutdown",
54 ) => Effect.Effect<ProviderRuntimeReconciliationSummary, ProviderRuntimeRecoveryError>;
55 readonly recover: Effect.Effect<ProviderRuntimeRecoverySummary, ProviderRuntimeRecoveryError>;
56 }
57>()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {}
58​
59function nonterminalRuns(projection: OrchestrationV2ThreadProjection) {
60 return projection.runs.filter((run) => {
61 const status: string = run.status;
62 return (
63 run.status === "queued" ||
64 status === "preparing" ||
65 run.status === "starting" ||
66 run.status === "running" ||
67 run.status === "waiting"
68 );
69 });
71​
72export const make = Effect.gen(function* () {
73 const projections = yield* ProjectionStore.ProjectionStoreV2;
74 const eventSink = yield* EventSink.EventSinkV2;
75 const ids = yield* IdAllocator.IdAllocatorV2;
76 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
77 const outbox = yield* EffectOutbox.EffectOutboxV2;
78 const reconcileProjection = Effect.fn("ProviderRuntimeRecoveryService.reconcileProjection")(
79 function* (projection: OrchestrationV2ThreadProjection, trigger: "startup" | "shutdown") {
80 const now = yield* DateTime.now;
81 const runs = [] as Array<OrchestrationV2ThreadProjection["runs"][number]>;
82 for (const run of nonterminalRuns(projection)) {
83 if (run.status === "waiting") {
84 const checkpointEffects = yield* outbox
85 .listByCommandId(CommandId.make(`command:effect:checkpoint.capture:${run.id}`))
86 .pipe(
87 Effect.mapError(
88 (cause) =>
89 new ProviderRuntimeRecoveryError({
90 operation: "reconcile",
91 threadId: projection.thread.id,
92 cause,
93 }),
94 ),
95 );
96 const hasReplayableCheckpoint = checkpointEffects.some(
97 (effect) =>
98 effect.request.type === "checkpoint.capture" &&
99 effect.request.runId === run.id &&
100 (effect.status === "pending" || effect.status === "running"),
101 );
102 if (hasReplayableCheckpoint) continue;
103 }
104 runs.push(run);
105 }
106 const requests = projection.runtimeRequests.filter((request) => request.status === "pending");
107 const detail = `Cancelled because the server ${trigger === "startup" ? "restarted" : "shut down"} before the provider work completed.`;
108 const commandId = CommandId.make(
109 `command:runtime-reconcile:${trigger}:${projection.thread.id}:${DateTime.formatIso(now)}`,
110 );
111 const allocateEventId = () =>
112 ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
113 Effect.mapError(
114 (cause) =>
115 new ProviderRuntimeRecoveryError({
116 operation: "reconcile",
117 threadId: projection.thread.id,
118 cause,
119 }),
120 ),
121 );
122 const events: Array<OrchestrationV2DomainEvent> = [];
123 for (const request of requests) {
124 events.push({
125 id: yield* allocateEventId(),
126 type: "runtime-request.updated",
127 threadId: projection.thread.id,
128 nodeId: request.nodeId,
129 occurredAt: now,
130 payload: {
131 ...request,
132 status: trigger === "startup" ? "expired" : "cancelled",
133 responseCapability: {
134 type: "not_resumable",
135 reason: `The server ${trigger === "startup" ? "restarted" : "shut down"} before this runtime request was resolved.`,
136 },
137 resolvedAt: now,
138 },
139 });
140 }
141 for (const run of runs) {
142 events.push({
143 id: yield* allocateEventId(),
144 type: "run.updated",
145 threadId: projection.thread.id,
146 runId: run.id,
147 providerInstanceId: run.providerInstanceId,
148 occurredAt: now,
149 payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
150 });
151 for (const attempt of projection.attempts.filter(
152 (candidate) =>
153 candidate.runId === run.id &&
154 (candidate.status === "pending" || candidate.status === "running"),
155 )) {
156 events.push({
157 id: yield* allocateEventId(),
158 type: "run-attempt.updated",
159 threadId: projection.thread.id,
160 runId: run.id,
161 nodeId: attempt.rootNodeId,
162 providerInstanceId: run.providerInstanceId,
163 occurredAt: now,
164 payload: { ...attempt, status: "cancelled", completedAt: now },
165 });
166 }
167 for (const node of projection.nodes.filter(
168 (candidate) =>
169 candidate.runId === run.id &&
170 (candidate.status === "pending" ||
171 candidate.status === "running" ||
172 candidate.status === "waiting"),
173 )) {
174 events.push({
175 id: yield* allocateEventId(),
176 type: "node.updated",
177 threadId: projection.thread.id,
178 runId: run.id,
179 nodeId: node.id,
180 providerInstanceId: run.providerInstanceId,
181 occurredAt: now,
182 payload: { ...node, status: "cancelled", completedAt: now },
183 });
184 }
185 for (const subagent of projection.subagents.filter(
186 (candidate) =>
187 candidate.runId === run.id &&
188 (candidate.status === "pending" ||
189 candidate.status === "running" ||
190 candidate.status === "waiting"),
191 )) {
192 events.push({
193 id: yield* allocateEventId(),
194 type: "subagent.updated",
195 threadId: projection.thread.id,
196 runId: run.id,
197 nodeId: subagent.id,
198 driver: subagent.driver,
199 providerInstanceId: subagent.providerInstanceId,
200 occurredAt: now,
201 payload: { ...subagent, status: "cancelled", completedAt: now, updatedAt: now },
202 });
203 }
204 for (const providerTurn of projection.providerTurns.filter(
205 (candidate) =>
206 candidate.runAttemptId !== null &&
207 projection.attempts.some(
208 (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id,
209 ) &&
210 (candidate.status === "pending" || candidate.status === "running"),
211 )) {
212 events.push({
213 id: yield* allocateEventId(),
214 type: "provider-turn.updated",
215 threadId: projection.thread.id,
216 runId: run.id,
217 nodeId: providerTurn.nodeId,
218 providerInstanceId: run.providerInstanceId,
219 occurredAt: now,
220 payload: { ...providerTurn, status: "cancelled", completedAt: now },
221 });
222 }
223 for (const message of projection.messages.filter(
224 (candidate) => candidate.runId === run.id && candidate.streaming,
225 )) {
226 events.push({
227 id: yield* allocateEventId(),
228 type: "message.updated",
229 threadId: projection.thread.id,
230 runId: run.id,
231 ...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
232 providerInstanceId: run.providerInstanceId,
233 occurredAt: now,
234 payload: { ...message, streaming: false, updatedAt: now },
235 });
236 }
237 for (const item of projection.turnItems.filter(
238 (candidate) =>
239 candidate.runId === run.id &&
240 (candidate.status === "pending" ||
241 candidate.status === "running" ||
242 candidate.status === "waiting"),
243 )) {
244 events.push({
245 id: yield* allocateEventId(),
246 type: "turn-item.updated",
247 threadId: projection.thread.id,
248 runId: run.id,
249 ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
250 providerInstanceId: run.providerInstanceId,
251 occurredAt: now,
252 payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
253 });
254 }
255 }
256 for (const providerThread of projection.providerThreads.filter(
257 (candidate) => candidate.status === "active",
258 )) {
259 events.push({
260 id: yield* allocateEventId(),
261 type: "provider-thread.updated",
262 threadId: projection.thread.id,
263 driver: providerThread.driver,
264 providerInstanceId: providerThread.providerInstanceId,
265 occurredAt: now,
266 payload: { ...providerThread, status: "idle", updatedAt: now },
267 });
268 }
269 for (const session of projection.providerSessions.filter(
270 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
271 )) {
272 events.push({
273 id: yield* allocateEventId(),
274 type: "provider-session.updated",
275 threadId: projection.thread.id,
276 driver: session.driver,
277 providerInstanceId: session.providerInstanceId,
278 occurredAt: now,
279 payload: { ...session, status: "stopped", updatedAt: now, lastError: null },
280 });
281 }
282 const stoppedSessions = projection.providerSessions.filter(
283 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
284 ).length;
285 let retiredEffects: number;
286 if (events.length === 0) {
287 const retiredEffectIds = yield* outbox
288 .cancelUnsettled({
289 threadId: projection.thread.id,
290 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
291 reason: detail,
292 })
293 .pipe(
294 Effect.mapError(
295 (cause) =>
296 new ProviderRuntimeRecoveryError({
297 operation: "reconcile",
298 threadId: projection.thread.id,
299 cause: { detail, cause },
300 }),
301 ),
302 );
303 yield* outbox.signalCancellations(retiredEffectIds);
304 retiredEffects = retiredEffectIds.length;
305 } else {
306 const result = yield* eventSink
307 .commitCommand({
308 commandId,
309 threadId: projection.thread.id,
310 commandType: "provider-runtime.reconcile",
311 acceptedAt: now,
312 events,
313 effects: [],
314 cancelUnsettledEffects: {
315 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
316 reason: detail,
317 },
318 })
319 .pipe(
320 Effect.mapError(
321 (cause) =>
322 new ProviderRuntimeRecoveryError({
323 operation: "reconcile",
324 threadId: projection.thread.id,
325 cause,
326 }),
327 ),
328 );
329 retiredEffects = result.cancelledEffectCount;
330 }
331 return {
332 terminalizedRuns: runs.length,
333 stoppedSessions,
334 closedRequests: requests.length,
335 retiredEffects,
336 };
337 },
338 );
339​
340 const reconcile = (trigger: "startup" | "shutdown") =>
341 Effect.gen(function* () {
342 const shell = yield* projections
343 .getShellSnapshot()
344 .pipe(
345 Effect.mapError(
346 (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
347 ),
348 );
349 let terminalizedRuns = 0;
350 let stoppedSessions = 0;
351 let closedRequests = 0;
352 let retiredEffects = 0;
353 for (const thread of [...shell.threads, ...shell.archivedThreads]) {
354 const projection = yield* projections.getThreadProjection(thread.id).pipe(
355 Effect.mapError(
356 (cause) =>
357 new ProviderRuntimeRecoveryError({
358 operation: "read-projections",
359 threadId: thread.id,
360 cause,
361 }),
362 ),
363 );
364 const result = yield* reconcileProjection(projection, trigger);
365 terminalizedRuns += result.terminalizedRuns;
366 stoppedSessions += result.stoppedSessions;
367 closedRequests += result.closedRequests;
368 retiredEffects += result.retiredEffects;
369 }
370 const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
371 Effect.mapError(
372 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
373 ),
374 );
375 return {
376 terminalizedRuns,
377 stoppedSessions,
378 closedRequests,
379 retiredEffects: retiredEffects + outboxReconciliation.cancelled,
380 requeuedEffects: outboxReconciliation.requeued,
381 } satisfies ProviderRuntimeReconciliationSummary;
382 });
383​
384 const recover = Effect.gen(function* () {
385 const reconciliation = yield* reconcile("startup");
386 let executedEffects = 0;
387 while (
388 yield* worker.runOnce.pipe(
389 Effect.mapError(
390 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
391 ),
392 )
393 ) {
394 executedEffects += 1;
395 }
396 return { ...reconciliation, executedEffects } satisfies ProviderRuntimeRecoverySummary;
397 });
398​
399 return ProviderRuntimeRecoveryService.of({ reconcile, recover });
400});
401​
402export const layer = Layer.effect(ProviderRuntimeRecoveryService, make);