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

ProviderRuntimeRecoveryService.ts

616 lines23.6 KB

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