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

ProviderRuntimeRecoveryService.ts

532 lines20.0 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​
72function isBackgroundCapableTurnItemType(type: string): boolean {
73 return type === "command_execution" || type === "dynamic_tool" || type === "subagent";
75​
76function isNonterminalTurnItemStatus(status: string): boolean {
77 return status === "pending" || status === "running" || status === "waiting";
79​
80function isNonterminalSubagentStatus(status: string): boolean {
81 return status === "pending" || status === "running" || status === "waiting";
83​
84function isNonterminalNodeStatus(status: string): boolean {
85 return status === "pending" || status === "running" || status === "waiting";
87​
88function providerThreadHasPendingBackgroundTasks(
89 providerThread: OrchestrationV2ThreadProjection["providerThreads"][number],
90): boolean {
91 return (providerThread.pendingBackgroundTasks?.length ?? 0) > 0;
93​
94/**
95 * Resolve providerInstanceId for a stale background-capable turn item whose
96 * run is missing/null (or not found). Prefer an existing run, then a subagent
97 * item's own instance id, then the item's provider thread, then a last-resort
98 * first provider thread, then the thread's selected provider.
99 */
100function resolveStaleBackgroundItemProviderInstanceId(
101 item: OrchestrationV2ThreadProjection["turnItems"][number],
102 projection: OrchestrationV2ThreadProjection,
103): OrchestrationV2ThreadProjection["thread"]["providerInstanceId"] {
104 if (item.runId !== null) {
105 const run = projection.runs.find((candidate) => candidate.id === item.runId);
106 if (run !== undefined) {
107 return run.providerInstanceId;
108 }
109 }
110 if (item.type === "subagent") {
111 return item.providerInstanceId;
112 }
113 if (item.providerThreadId !== null && item.providerThreadId !== undefined) {
114 const providerThread = projection.providerThreads.find(
115 (candidate) => candidate.id === item.providerThreadId,
116 );
117 if (providerThread !== undefined) {
118 return providerThread.providerInstanceId;
119 }
120 }
121 return projection.providerThreads[0]?.providerInstanceId ?? projection.thread.providerInstanceId;
123​
124export const make = Effect.gen(function* () {
125 const projections = yield* ProjectionStore.ProjectionStoreV2;
126 const eventSink = yield* EventSink.EventSinkV2;
127 const ids = yield* IdAllocator.IdAllocatorV2;
128 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
129 const outbox = yield* EffectOutbox.EffectOutboxV2;
130 const reconcileProjection = Effect.fn("ProviderRuntimeRecoveryService.reconcileProjection")(
131 function* (projection: OrchestrationV2ThreadProjection, trigger: "startup" | "shutdown") {
132 const now = yield* DateTime.now;
133 const runs = [] as Array<OrchestrationV2ThreadProjection["runs"][number]>;
134 for (const run of nonterminalRuns(projection)) {
135 if (run.status === "waiting") {
136 const checkpointEffects = yield* outbox
137 .listByCommandId(CommandId.make(`command:effect:checkpoint.capture:${run.id}`))
138 .pipe(
139 Effect.mapError(
140 (cause) =>
141 new ProviderRuntimeRecoveryError({
142 operation: "reconcile",
143 threadId: projection.thread.id,
144 cause,
145 }),
146 ),
147 );
148 const hasReplayableCheckpoint = checkpointEffects.some(
149 (effect) =>
150 effect.request.type === "checkpoint.capture" &&
151 effect.request.runId === run.id &&
152 (effect.status === "pending" || effect.status === "running"),
153 );
154 if (hasReplayableCheckpoint) continue;
155 }
156 runs.push(run);
157 }
158 const requests = projection.runtimeRequests.filter((request) => request.status === "pending");
159 const detail = `Cancelled because the server ${trigger === "startup" ? "restarted" : "shut down"} before the provider work completed.`;
160 const commandId = CommandId.make(
161 `command:runtime-reconcile:${trigger}:${projection.thread.id}:${DateTime.formatIso(now)}`,
162 );
163 const allocateEventId = () =>
164 ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
165 Effect.mapError(
166 (cause) =>
167 new ProviderRuntimeRecoveryError({
168 operation: "reconcile",
169 threadId: projection.thread.id,
170 cause,
171 }),
172 ),
173 );
174 const events: Array<OrchestrationV2DomainEvent> = [];
175 for (const request of requests) {
176 events.push({
177 id: yield* allocateEventId(),
178 type: "runtime-request.updated",
179 threadId: projection.thread.id,
180 nodeId: request.nodeId,
181 occurredAt: now,
182 payload: {
183 ...request,
184 status: trigger === "startup" ? "expired" : "cancelled",
185 responseCapability: {
186 type: "not_resumable",
187 reason: `The server ${trigger === "startup" ? "restarted" : "shut down"} before this runtime request was resolved.`,
188 },
189 resolvedAt: now,
190 },
191 });
192 }
193 for (const run of runs) {
194 events.push({
195 id: yield* allocateEventId(),
196 type: "run.updated",
197 threadId: projection.thread.id,
198 runId: run.id,
199 providerInstanceId: run.providerInstanceId,
200 occurredAt: now,
201 payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
202 });
203 for (const attempt of projection.attempts.filter(
204 (candidate) =>
205 candidate.runId === run.id &&
206 (candidate.status === "pending" || candidate.status === "running"),
207 )) {
208 events.push({
209 id: yield* allocateEventId(),
210 type: "run-attempt.updated",
211 threadId: projection.thread.id,
212 runId: run.id,
213 nodeId: attempt.rootNodeId,
214 providerInstanceId: run.providerInstanceId,
215 occurredAt: now,
216 payload: { ...attempt, status: "cancelled", completedAt: now },
217 });
218 }
219 for (const node of projection.nodes.filter(
220 (candidate) =>
221 candidate.runId === run.id &&
222 (candidate.status === "pending" ||
223 candidate.status === "running" ||
224 candidate.status === "waiting"),
225 )) {
226 events.push({
227 id: yield* allocateEventId(),
228 type: "node.updated",
229 threadId: projection.thread.id,
230 runId: run.id,
231 nodeId: node.id,
232 providerInstanceId: run.providerInstanceId,
233 occurredAt: now,
234 payload: { ...node, status: "cancelled", completedAt: now },
235 });
236 }
237 for (const subagent of projection.subagents.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: "subagent.updated",
247 threadId: projection.thread.id,
248 runId: run.id,
249 nodeId: subagent.id,
250 driver: subagent.driver,
251 providerInstanceId: subagent.providerInstanceId,
252 occurredAt: now,
253 payload: { ...subagent, status: "cancelled", completedAt: now, updatedAt: now },
254 });
255 }
256 for (const providerTurn of projection.providerTurns.filter(
257 (candidate) =>
258 candidate.runAttemptId !== null &&
259 projection.attempts.some(
260 (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id,
261 ) &&
262 (candidate.status === "pending" || candidate.status === "running"),
263 )) {
264 events.push({
265 id: yield* allocateEventId(),
266 type: "provider-turn.updated",
267 threadId: projection.thread.id,
268 runId: run.id,
269 nodeId: providerTurn.nodeId,
270 providerInstanceId: run.providerInstanceId,
271 occurredAt: now,
272 payload: { ...providerTurn, status: "cancelled", completedAt: now },
273 });
274 }
275 for (const message of projection.messages.filter(
276 (candidate) => candidate.runId === run.id && candidate.streaming,
277 )) {
278 events.push({
279 id: yield* allocateEventId(),
280 type: "message.updated",
281 threadId: projection.thread.id,
282 runId: run.id,
283 ...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
284 providerInstanceId: run.providerInstanceId,
285 occurredAt: now,
286 payload: { ...message, streaming: false, updatedAt: now },
287 });
288 }
289 for (const item of projection.turnItems.filter(
290 (candidate) =>
291 candidate.runId === run.id &&
292 (candidate.status === "pending" ||
293 candidate.status === "running" ||
294 candidate.status === "waiting"),
295 )) {
296 events.push({
297 id: yield* allocateEventId(),
298 type: "turn-item.updated",
299 threadId: projection.thread.id,
300 runId: run.id,
301 ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
302 providerInstanceId: run.providerInstanceId,
303 occurredAt: now,
304 payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
305 });
306 }
307 }
308 // Process loss also orphans background-capable turn items on already-
309 // settled runs (e.g. post-settle Waiting work). Skip items already
310 // cancelled above for recovered nonterminal runs to avoid duplicate
311 // cancellation events.
312 const recoveredNonterminalRunIds = new Set(runs.map((run) => run.id));
313 for (const item of projection.turnItems ?? []) {
314 if (item.runId !== null && recoveredNonterminalRunIds.has(item.runId)) {
315 continue;
316 }
317 if (!isBackgroundCapableTurnItemType(item.type)) {
318 continue;
319 }
320 if (!isNonterminalTurnItemStatus(item.status)) {
321 continue;
322 }
323 const providerInstanceId = resolveStaleBackgroundItemProviderInstanceId(item, projection);
324 events.push({
325 id: yield* allocateEventId(),
326 type: "turn-item.updated",
327 threadId: projection.thread.id,
328 ...(item.runId === null ? {} : { runId: item.runId }),
329 ...(item.nodeId === null || item.nodeId === undefined ? {} : { nodeId: item.nodeId }),
330 providerInstanceId,
331 occurredAt: now,
332 payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
333 });
334 if (item.type !== "subagent") {
335 continue;
336 }
337 // Cancelling only the turn item would leave the linked subagent entity
338 // and its execution node non-terminal forever, since the dead provider
339 // process can no longer emit their terminal events. Match the exact
340 // linked ids so a subagent that already finished is never overwritten.
341 const staleSubagent = projection.subagents.find(
342 (candidate) =>
343 candidate.id === item.subagentId && isNonterminalSubagentStatus(candidate.status),
344 );
345 if (staleSubagent !== undefined) {
346 events.push({
347 id: yield* allocateEventId(),
348 type: "subagent.updated",
349 threadId: projection.thread.id,
350 ...(item.runId === null ? {} : { runId: item.runId }),
351 nodeId: staleSubagent.id,
352 driver: staleSubagent.driver,
353 providerInstanceId: staleSubagent.providerInstanceId,
354 occurredAt: now,
355 payload: { ...staleSubagent, status: "cancelled", completedAt: now, updatedAt: now },
356 });
357 }
358 const staleSubagentNode = projection.nodes.find(
359 (candidate) =>
360 candidate.id === item.subagentId && isNonterminalNodeStatus(candidate.status),
361 );
362 if (staleSubagentNode !== undefined) {
363 events.push({
364 id: yield* allocateEventId(),
365 type: "node.updated",
366 threadId: projection.thread.id,
367 ...(item.runId === null ? {} : { runId: item.runId }),
368 nodeId: staleSubagentNode.id,
369 providerInstanceId,
370 occurredAt: now,
371 payload: { ...staleSubagentNode, status: "cancelled", completedAt: now },
372 });
373 }
374 }
375 // All provider processes are gone on startup/shutdown: clear any
376 // persisted Waiting roster (including idle threads from settled roots)
377 // and idle active threads without resurrecting active status.
378 for (const providerThread of projection.providerThreads ?? []) {
379 const needsIdle = providerThread.status === "active";
380 const needsRosterClear = providerThreadHasPendingBackgroundTasks(providerThread);
381 if (!needsIdle && !needsRosterClear) {
382 continue;
383 }
384 events.push({
385 id: yield* allocateEventId(),
386 type: "provider-thread.updated",
387 threadId: projection.thread.id,
388 driver: providerThread.driver,
389 providerInstanceId: providerThread.providerInstanceId,
390 occurredAt: now,
391 payload: {
392 ...providerThread,
393 status: needsIdle ? "idle" : providerThread.status,
394 pendingBackgroundTasks: [],
395 updatedAt: now,
396 },
397 });
398 }
399 for (const session of projection.providerSessions.filter(
400 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
401 )) {
402 events.push({
403 id: yield* allocateEventId(),
404 type: "provider-session.updated",
405 threadId: projection.thread.id,
406 driver: session.driver,
407 providerInstanceId: session.providerInstanceId,
408 occurredAt: now,
409 payload: { ...session, status: "stopped", updatedAt: now, lastError: null },
410 });
411 }
412 const stoppedSessions = projection.providerSessions.filter(
413 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
414 ).length;
415 let retiredEffects: number;
416 if (events.length === 0) {
417 const retiredEffectIds = yield* outbox
418 .cancelUnsettled({
419 threadId: projection.thread.id,
420 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
421 reason: detail,
422 })
423 .pipe(
424 Effect.mapError(
425 (cause) =>
426 new ProviderRuntimeRecoveryError({
427 operation: "reconcile",
428 threadId: projection.thread.id,
429 cause: { detail, cause },
430 }),
431 ),
432 );
433 yield* outbox.signalCancellations(retiredEffectIds);
434 retiredEffects = retiredEffectIds.length;
435 } else {
436 const result = yield* eventSink
437 .commitCommand({
438 commandId,
439 threadId: projection.thread.id,
440 commandType: "provider-runtime.reconcile",
441 acceptedAt: now,
442 events,
443 effects: [],
444 cancelUnsettledEffects: {
445 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
446 reason: detail,
447 },
448 })
449 .pipe(
450 Effect.mapError(
451 (cause) =>
452 new ProviderRuntimeRecoveryError({
453 operation: "reconcile",
454 threadId: projection.thread.id,
455 cause,
456 }),
457 ),
458 );
459 retiredEffects = result.cancelledEffectCount;
460 }
461 return {
462 terminalizedRuns: runs.length,
463 stoppedSessions,
464 closedRequests: requests.length,
465 retiredEffects,
466 };
467 },
468 );
469​
470 const reconcile = (trigger: "startup" | "shutdown") =>
471 Effect.gen(function* () {
472 const shell = yield* projections
473 .getShellSnapshot()
474 .pipe(
475 Effect.mapError(
476 (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
477 ),
478 );
479 let terminalizedRuns = 0;
480 let stoppedSessions = 0;
481 let closedRequests = 0;
482 let retiredEffects = 0;
483 for (const thread of [...shell.threads, ...shell.archivedThreads]) {
484 const projection = yield* projections.getThreadProjection(thread.id).pipe(
485 Effect.mapError(
486 (cause) =>
487 new ProviderRuntimeRecoveryError({
488 operation: "read-projections",
489 threadId: thread.id,
490 cause,
491 }),
492 ),
493 );
494 const result = yield* reconcileProjection(projection, trigger);
495 terminalizedRuns += result.terminalizedRuns;
496 stoppedSessions += result.stoppedSessions;
497 closedRequests += result.closedRequests;
498 retiredEffects += result.retiredEffects;
499 }
500 const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
501 Effect.mapError(
502 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
503 ),
504 );
505 return {
506 terminalizedRuns,
507 stoppedSessions,
508 closedRequests,
509 retiredEffects: retiredEffects + outboxReconciliation.cancelled,
510 requeuedEffects: outboxReconciliation.requeued,
511 } satisfies ProviderRuntimeReconciliationSummary;
512 });
513​
514 const recover = Effect.gen(function* () {
515 const reconciliation = yield* reconcile("startup");
516 let executedEffects = 0;
517 while (
518 yield* worker.runOnce.pipe(
519 Effect.mapError(
520 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
521 ),
522 )
523 ) {
524 executedEffects += 1;
525 }
526 return { ...reconciliation, executedEffects } satisfies ProviderRuntimeRecoverySummary;
527 });
528​
529 return ProviderRuntimeRecoveryService.of({ reconcile, recover });
530});
531​
532export const layer = Layer.effect(ProviderRuntimeRecoveryService, make);