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

ProviderRuntimeRecoveryService.ts

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