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

ProviderRuntimeRecoveryService.ts

623 lines23.7 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";
18import { ServerSettingsService } from "../serverSettings.ts";
19import { restartContinuationRun } from "./RestartContinuation.ts";
20​
21export class ProviderRuntimeRecoveryError extends Schema.TaggedErrorClass<ProviderRuntimeRecoveryError>()(
22 "ProviderRuntimeRecoveryError",
23 {
24 operation: Schema.Literals(["read-projections", "reconcile", "drain-outbox"]),
25 threadId: Schema.optional(ThreadId),
26 cause: Schema.Defect(),
27 },
28) {
29 override get message(): string {
30 return `Provider runtime recovery failed during ${this.operation}.`;
31 }
33​
34export interface ProviderRuntimeRecoverySummary {
35 readonly terminalizedRuns: number;
36 readonly stoppedSessions: number;
37 readonly closedRequests: number;
38 readonly retiredEffects: number;
39 readonly requeuedEffects: number;
40 readonly executedEffects: number;
42​
43export interface ProviderRuntimeReconciliationSummary {
44 readonly terminalizedRuns: number;
45 readonly stoppedSessions: number;
46 readonly closedRequests: number;
47 readonly retiredEffects: number;
48 readonly requeuedEffects: number;
50​
51export class ProviderRuntimeRecoveryService extends Context.Service<
52 ProviderRuntimeRecoveryService,
53 {
54 readonly reconcile: (
55 trigger: "startup" | "shutdown",
56 ) => Effect.Effect<ProviderRuntimeReconciliationSummary, ProviderRuntimeRecoveryError>;
57 readonly prepareForShutdown: Effect.Effect<void, ProviderRuntimeRecoveryError>;
58 readonly recover: Effect.Effect<ProviderRuntimeRecoverySummary, ProviderRuntimeRecoveryError>;
59 }
60>()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {}
61​
62function nonterminalRuns(projection: OrchestrationV2ThreadProjection) {
63 return projection.runs.filter((run) => {
64 const status: string = run.status;
65 return (
66 run.status === "queued" ||
67 status === "preparing" ||
68 run.status === "starting" ||
69 run.status === "running" ||
70 run.status === "waiting"
71 );
72 });
74​
75function isBackgroundCapableTurnItemType(type: string): boolean {
76 return type === "command_execution" || type === "dynamic_tool" || type === "subagent";
78​
79function isNonterminalTurnItemStatus(status: string): boolean {
80 return status === "pending" || status === "running" || status === "waiting";
82​
83function isNonterminalSubagentStatus(status: string): boolean {
84 return status === "pending" || status === "running" || status === "waiting";
86​
87function isNonterminalNodeStatus(status: string): boolean {
88 return status === "pending" || status === "running" || status === "waiting";
90​
91function providerThreadHasPendingBackgroundTasks(
92 providerThread: OrchestrationV2ThreadProjection["providerThreads"][number],
93): boolean {
94 return (providerThread.pendingBackgroundTasks?.length ?? 0) > 0;
96​
97/**
98 * Resolve providerInstanceId for a stale background-capable turn item whose
99 * run is missing/null (or not found). Prefer an existing run, then a subagent
100 * item's own instance id, then the item's provider thread, then a last-resort
101 * first provider thread, then the thread's selected provider.
102 */
103function resolveStaleBackgroundItemProviderInstanceId(
104 item: OrchestrationV2ThreadProjection["turnItems"][number],
105 projection: OrchestrationV2ThreadProjection,
106): OrchestrationV2ThreadProjection["thread"]["providerInstanceId"] {
107 if (item.runId !== null) {
108 const run = projection.runs.find((candidate) => candidate.id === item.runId);
109 if (run !== undefined) {
110 return run.providerInstanceId;
111 }
112 }
113 if (item.type === "subagent") {
114 return item.providerInstanceId;
115 }
116 if (item.providerThreadId !== null && item.providerThreadId !== undefined) {
117 const providerThread = projection.providerThreads.find(
118 (candidate) => candidate.id === item.providerThreadId,
119 );
120 if (providerThread !== undefined) {
121 return providerThread.providerInstanceId;
122 }
123 }
124 return projection.providerThreads[0]?.providerInstanceId ?? projection.thread.providerInstanceId;
126​
127export const make = Effect.gen(function* () {
128 const settings = yield* ServerSettingsService;
129 const projections = yield* ProjectionStore.ProjectionStoreV2;
130 const eventSink = yield* EventSink.EventSinkV2;
131 const ids = yield* IdAllocator.IdAllocatorV2;
132 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
133 const outbox = yield* EffectOutbox.EffectOutboxV2;
134 const reconcileProjection = Effect.fn("ProviderRuntimeRecoveryService.reconcileProjection")(
135 function* (
136 projection: OrchestrationV2ThreadProjection,
137 trigger: "startup" | "shutdown",
138 continueAfterRestart: boolean,
139 ) {
140 const now = yield* DateTime.now;
141 const runs = [] as Array<OrchestrationV2ThreadProjection["runs"][number]>;
142 for (const run of nonterminalRuns(projection)) {
143 if (run.status === "waiting") {
144 const checkpointEffects = yield* outbox
145 .listByCommandId(CommandId.make(`command:effect:checkpoint.capture:${run.id}`))
146 .pipe(
147 Effect.mapError(
148 (cause) =>
149 new ProviderRuntimeRecoveryError({
150 operation: "reconcile",
151 threadId: projection.thread.id,
152 cause,
153 }),
154 ),
155 );
156 const hasReplayableCheckpoint = checkpointEffects.some(
157 (effect) =>
158 effect.request.type === "checkpoint.capture" &&
159 effect.request.runId === run.id &&
160 (effect.status === "pending" || effect.status === "running"),
161 );
162 if (hasReplayableCheckpoint) continue;
163 }
164 runs.push(run);
165 }
166 const messageRequestNodeIds = new Set(
167 projection.runtimeRequests
168 .filter(
169 (request) =>
170 request.status === "pending" && request.responseCapability.type === "message",
171 )
172 .map((request) => request.nodeId),
173 );
174 const requests = projection.runtimeRequests.filter(
175 (request) => request.status === "pending" && request.responseCapability.type !== "message",
176 );
177 const detail = `Cancelled because the server ${trigger === "startup" ? "restarted" : "shut down"} before the provider work completed.`;
178 const commandId = CommandId.make(
179 `command:runtime-reconcile:${trigger}:${projection.thread.id}:${DateTime.formatIso(now)}`,
180 );
181 const allocateEventId = () =>
182 ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
183 Effect.mapError(
184 (cause) =>
185 new ProviderRuntimeRecoveryError({
186 operation: "reconcile",
187 threadId: projection.thread.id,
188 cause,
189 }),
190 ),
191 );
192 const continuationRun =
193 continueAfterRestart && trigger === "startup"
194 ? restartContinuationRun(projection)
195 : undefined;
196 const effects: Array<EffectOutbox.PendingOrchestrationEffectV2> = continuationRun
197 ? [
198 {
199 id: `effect:restart-continuation:${continuationRun.id}`,
200 commandId,
201 threadId: projection.thread.id,
202 request: { type: "provider-runtime.continue", sourceRunId: continuationRun.id },
203 },
204 ]
205 : [];
206 const events: Array<OrchestrationV2DomainEvent> = [];
207 for (const request of requests) {
208 events.push({
209 id: yield* allocateEventId(),
210 type: "runtime-request.updated",
211 threadId: projection.thread.id,
212 nodeId: request.nodeId,
213 occurredAt: now,
214 payload: {
215 ...request,
216 status: trigger === "startup" ? "expired" : "cancelled",
217 responseCapability: {
218 type: "not_resumable",
219 reason: `The server ${trigger === "startup" ? "restarted" : "shut down"} before this runtime request was resolved.`,
220 },
221 resolvedAt: now,
222 },
223 });
224 }
225 for (const run of runs) {
226 events.push({
227 id: yield* allocateEventId(),
228 type: "run.updated",
229 threadId: projection.thread.id,
230 runId: run.id,
231 providerInstanceId: run.providerInstanceId,
232 occurredAt: now,
233 payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
234 });
235 for (const attempt of projection.attempts.filter(
236 (candidate) =>
237 candidate.runId === run.id &&
238 (candidate.status === "pending" || candidate.status === "running"),
239 )) {
240 events.push({
241 id: yield* allocateEventId(),
242 type: "run-attempt.updated",
243 threadId: projection.thread.id,
244 runId: run.id,
245 nodeId: attempt.rootNodeId,
246 providerInstanceId: run.providerInstanceId,
247 occurredAt: now,
248 payload: { ...attempt, status: "cancelled", completedAt: now },
249 });
250 }
251 for (const node of projection.nodes.filter(
252 (candidate) =>
253 candidate.runId === run.id &&
254 !messageRequestNodeIds.has(candidate.id) &&
255 (candidate.status === "pending" ||
256 candidate.status === "running" ||
257 candidate.status === "waiting"),
258 )) {
259 events.push({
260 id: yield* allocateEventId(),
261 type: "node.updated",
262 threadId: projection.thread.id,
263 runId: run.id,
264 nodeId: node.id,
265 providerInstanceId: run.providerInstanceId,
266 occurredAt: now,
267 payload: { ...node, status: "cancelled", completedAt: now },
268 });
269 }
270 for (const subagent of projection.subagents.filter(
271 (candidate) =>
272 candidate.runId === run.id &&
273 (candidate.status === "pending" ||
274 candidate.status === "running" ||
275 candidate.status === "waiting"),
276 )) {
277 events.push({
278 id: yield* allocateEventId(),
279 type: "subagent.updated",
280 threadId: projection.thread.id,
281 runId: run.id,
282 nodeId: subagent.id,
283 driver: subagent.driver,
284 providerInstanceId: subagent.providerInstanceId,
285 occurredAt: now,
286 payload: { ...subagent, status: "cancelled", completedAt: now, updatedAt: now },
287 });
288 }
289 for (const providerTurn of projection.providerTurns.filter(
290 (candidate) =>
291 candidate.runAttemptId !== null &&
292 projection.attempts.some(
293 (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id,
294 ) &&
295 (candidate.status === "pending" || candidate.status === "running"),
296 )) {
297 events.push({
298 id: yield* allocateEventId(),
299 type: "provider-turn.updated",
300 threadId: projection.thread.id,
301 runId: run.id,
302 nodeId: providerTurn.nodeId,
303 providerInstanceId: run.providerInstanceId,
304 occurredAt: now,
305 payload: { ...providerTurn, status: "cancelled", completedAt: now },
306 });
307 }
308 for (const message of projection.messages.filter(
309 (candidate) => candidate.runId === run.id && candidate.streaming,
310 )) {
311 events.push({
312 id: yield* allocateEventId(),
313 type: "message.updated",
314 threadId: projection.thread.id,
315 runId: run.id,
316 ...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
317 providerInstanceId: run.providerInstanceId,
318 occurredAt: now,
319 payload: { ...message, streaming: false, updatedAt: now },
320 });
321 }
322 for (const item of projection.turnItems.filter(
323 (candidate) =>
324 candidate.runId === run.id &&
325 (candidate.nodeId === null || !messageRequestNodeIds.has(candidate.nodeId)) &&
326 (candidate.status === "pending" ||
327 candidate.status === "running" ||
328 candidate.status === "waiting"),
329 )) {
330 events.push({
331 id: yield* allocateEventId(),
332 type: "turn-item.updated",
333 threadId: projection.thread.id,
334 runId: run.id,
335 ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
336 providerInstanceId: run.providerInstanceId,
337 occurredAt: now,
338 payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
339 });
340 }
341 }
342 // Process loss also orphans background-capable turn items on already-
343 // settled runs (e.g. post-settle Waiting work). Skip items already
344 // cancelled above for recovered nonterminal runs to avoid duplicate
345 // cancellation events.
346 const recoveredNonterminalRunIds = new Set(runs.map((run) => run.id));
347 const cancelledStaleNodeIds = new Set<string>();
348 for (const item of projection.turnItems ?? []) {
349 if (item.runId !== null && recoveredNonterminalRunIds.has(item.runId)) {
350 continue;
351 }
352 if (!isBackgroundCapableTurnItemType(item.type)) {
353 continue;
354 }
355 if (!isNonterminalTurnItemStatus(item.status)) {
356 continue;
357 }
358 const providerInstanceId = resolveStaleBackgroundItemProviderInstanceId(item, projection);
359 events.push({
360 id: yield* allocateEventId(),
361 type: "turn-item.updated",
362 threadId: projection.thread.id,
363 ...(item.runId === null ? {} : { runId: item.runId }),
364 ...(item.nodeId === null || item.nodeId === undefined ? {} : { nodeId: item.nodeId }),
365 providerInstanceId,
366 occurredAt: now,
367 payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
368 });
369 if (item.nodeId !== null && item.nodeId !== undefined) {
370 const staleItemNode = projection.nodes.find(
371 (candidate) =>
372 candidate.id === item.nodeId && isNonterminalNodeStatus(candidate.status),
373 );
374 if (staleItemNode !== undefined && !cancelledStaleNodeIds.has(staleItemNode.id)) {
375 cancelledStaleNodeIds.add(staleItemNode.id);
376 events.push({
377 id: yield* allocateEventId(),
378 type: "node.updated",
379 threadId: projection.thread.id,
380 ...(item.runId === null ? {} : { runId: item.runId }),
381 nodeId: staleItemNode.id,
382 providerInstanceId,
383 occurredAt: now,
384 payload: { ...staleItemNode, status: "cancelled", completedAt: now },
385 });
386 }
387 }
388 if (item.type !== "subagent") {
389 continue;
390 }
391 // Cancelling only the turn item would leave the linked subagent entity
392 // non-terminal forever, since the dead provider process can no longer
393 // emit its terminal event. Match the exact linked id so a subagent
394 // that already finished is never overwritten.
395 const staleSubagent = projection.subagents.find(
396 (candidate) =>
397 candidate.id === item.subagentId && isNonterminalSubagentStatus(candidate.status),
398 );
399 if (staleSubagent !== undefined) {
400 events.push({
401 id: yield* allocateEventId(),
402 type: "subagent.updated",
403 threadId: projection.thread.id,
404 ...(item.runId === null ? {} : { runId: item.runId }),
405 nodeId: staleSubagent.id,
406 driver: staleSubagent.driver,
407 providerInstanceId: staleSubagent.providerInstanceId,
408 occurredAt: now,
409 payload: { ...staleSubagent, status: "cancelled", completedAt: now, updatedAt: now },
410 });
411 }
412 const staleSubagentNode = projection.nodes.find(
413 (candidate) =>
414 candidate.id === item.subagentId && isNonterminalNodeStatus(candidate.status),
415 );
416 if (staleSubagentNode !== undefined && !cancelledStaleNodeIds.has(staleSubagentNode.id)) {
417 cancelledStaleNodeIds.add(staleSubagentNode.id);
418 events.push({
419 id: yield* allocateEventId(),
420 type: "node.updated",
421 threadId: projection.thread.id,
422 ...(item.runId === null ? {} : { runId: item.runId }),
423 nodeId: staleSubagentNode.id,
424 providerInstanceId,
425 occurredAt: now,
426 payload: { ...staleSubagentNode, status: "cancelled", completedAt: now },
427 });
428 }
429 }
430 // All provider processes are gone on startup/shutdown: clear any
431 // persisted Waiting roster (including idle threads from settled roots)
432 // and idle active threads without resurrecting active status.
433 for (const providerThread of projection.providerThreads ?? []) {
434 const needsIdle = providerThread.status === "active";
435 const needsRosterClear = providerThreadHasPendingBackgroundTasks(providerThread);
436 if (!needsIdle && !needsRosterClear) {
437 continue;
438 }
439 events.push({
440 id: yield* allocateEventId(),
441 type: "provider-thread.updated",
442 threadId: projection.thread.id,
443 driver: providerThread.driver,
444 providerInstanceId: providerThread.providerInstanceId,
445 occurredAt: now,
446 payload: {
447 ...providerThread,
448 status: needsIdle ? "idle" : providerThread.status,
449 pendingBackgroundTasks: [],
450 updatedAt: now,
451 },
452 });
453 }
454 for (const session of projection.providerSessions.filter(
455 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
456 )) {
457 events.push({
458 id: yield* allocateEventId(),
459 type: "provider-session.updated",
460 threadId: projection.thread.id,
461 driver: session.driver,
462 providerInstanceId: session.providerInstanceId,
463 occurredAt: now,
464 payload: { ...session, status: "stopped", updatedAt: now, lastError: null },
465 });
466 }
467 const stoppedSessions = projection.providerSessions.filter(
468 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
469 ).length;
470 let retiredEffects: number;
471 if (events.length === 0) {
472 const retiredEffectIds = yield* outbox
473 .cancelUnsettled({
474 threadId: projection.thread.id,
475 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
476 reason: detail,
477 })
478 .pipe(
479 Effect.mapError(
480 (cause) =>
481 new ProviderRuntimeRecoveryError({
482 operation: "reconcile",
483 threadId: projection.thread.id,
484 cause: { detail, cause },
485 }),
486 ),
487 );
488 yield* outbox.signalCancellations(retiredEffectIds);
489 retiredEffects = retiredEffectIds.length;
490 } else {
491 const result = yield* eventSink
492 .commitCommand({
493 commandId,
494 threadId: projection.thread.id,
495 commandType: "provider-runtime.reconcile",
496 acceptedAt: now,
497 events,
498 effects,
499 cancelUnsettledEffects: {
500 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
501 reason: detail,
502 },
503 })
504 .pipe(
505 Effect.mapError(
506 (cause) =>
507 new ProviderRuntimeRecoveryError({
508 operation: "reconcile",
509 threadId: projection.thread.id,
510 cause,
511 }),
512 ),
513 );
514 retiredEffects = result.cancelledEffectCount;
515 }
516 return {
517 terminalizedRuns: runs.length,
518 stoppedSessions,
519 closedRequests: requests.length,
520 retiredEffects,
521 };
522 },
523 );
524​
525 const reconcile = (trigger: "startup" | "shutdown") =>
526 Effect.gen(function* () {
527 const continueAfterRestart = yield* settings.getSettings.pipe(
528 Effect.map((value) => value.continueThreadsAfterServerUpdate),
529 Effect.orElseSucceed(() => false),
530 );
531 const threadIds = yield* projections
532 .getRecoveryThreadIds("runtime")
533 .pipe(
534 Effect.mapError(
535 (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
536 ),
537 );
538 let terminalizedRuns = 0;
539 let stoppedSessions = 0;
540 let closedRequests = 0;
541 let retiredEffects = 0;
542 for (const threadId of threadIds) {
543 const projection = yield* projections.getThreadProjection(threadId).pipe(
544 Effect.mapError(
545 (cause) =>
546 new ProviderRuntimeRecoveryError({
547 operation: "read-projections",
548 threadId,
549 cause,
550 }),
551 ),
552 );
553 const result = yield* reconcileProjection(projection, trigger, continueAfterRestart);
554 terminalizedRuns += result.terminalizedRuns;
555 stoppedSessions += result.stoppedSessions;
556 closedRequests += result.closedRequests;
557 retiredEffects += result.retiredEffects;
558 }
559 const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
560 Effect.mapError(
561 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
562 ),
563 );
564 return {
565 terminalizedRuns,
566 stoppedSessions,
567 closedRequests,
568 retiredEffects: retiredEffects + outboxReconciliation.cancelled,
569 requeuedEffects: outboxReconciliation.requeued,
570 } satisfies ProviderRuntimeReconciliationSummary;
571 });
572​
573 // Snapshot intent only while providers are live. A provider may finish while
574 // this commits; reconciliation reads fresh state after shutdown, and delivery
575 // rejects any source run that actually completed.
576 const prepareForShutdown = Effect.gen(function* () {
577 const enabled = yield* settings.getSettings.pipe(
578 Effect.map((value) => value.continueThreadsAfterServerUpdate),
579 Effect.orElseSucceed(() => false),
580 );
581 if (!enabled) return;
582 const threadIds = yield* projections.getRecoveryThreadIds("runtime");
583 for (const threadId of threadIds) {
584 const projection = yield* projections.getThreadProjection(threadId);
585 const run = restartContinuationRun(projection);
586 if (!run) continue;
587 const commandId = CommandId.make(`command:restart-prepare:${run.id}`);
588 yield* eventSink.writeWithEffects({
589 commandId,
590 events: [],
591 effects: [
592 {
593 id: `effect:restart-continuation:${run.id}`,
594 commandId,
595 threadId,
596 request: { type: "provider-runtime.continue", sourceRunId: run.id },
597 },
598 ],
599 });
600 }
601 }).pipe(
602 Effect.mapError((cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause })),
603 );
604​
605 const recover = Effect.gen(function* () {
606 const reconciliation = yield* reconcile("startup");
607 let executedEffects = 0;
608 while (
609 yield* worker.runRecoveryOnce.pipe(
610 Effect.mapError(
611 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
612 ),
613 )
614 ) {
615 executedEffects += 1;
616 }
617 return { ...reconciliation, executedEffects } satisfies ProviderRuntimeRecoverySummary;
618 });
619​
620 return ProviderRuntimeRecoveryService.of({ reconcile, prepareForShutdown, recover });
621});
622​
623export const layer = Layer.effect(ProviderRuntimeRecoveryService, make);