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

ProviderRuntimeRecoveryService.ts

610 lines23.3 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 EffectOutbox from "./EffectOutbox.ts";
14import * as EventSink from "./EventSink.ts";
15import * as IdAllocator from "./IdAllocator.ts";
16import * as ProjectionStore from "./ProjectionStore.ts";
17import type { ProjectionRuntimeRecoveryState } from "./ProjectionStore.ts";
18import { ServerSettingsService } from "../serverSettings.ts";
19import { restartContinuationRun } from "./RestartContinuation.ts";
20​
21export class ProviderRuntimeRecoveryError extends Schema.TaggedError<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;
41​
42export interface ProviderRuntimeReconciliationSummary {
43 readonly terminalizedRuns: number;
44 readonly stoppedSessions: number;
45 readonly closedRequests: number;
46 readonly retiredEffects: number;
47 readonly requeuedEffects: number;
49​
50export class ProviderRuntimeRecoveryService extends Context.Service<
51 ProviderRuntimeRecoveryService,
52 {
53 readonly reconcile: (
54 trigger: "startup" | "shutdown",
55 ) => Effect.Effect<ProviderRuntimeReconciliationSummary, ProviderRuntimeRecoveryError>;
56 readonly prepareForShutdown: Effect.Effect<void, ProviderRuntimeRecoveryError>;
57 readonly recover: Effect.Effect<ProviderRuntimeRecoverySummary, ProviderRuntimeRecoveryError>;
58 }
59>()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {}
60​
61function nonterminalRuns(projection: ProjectionRuntimeRecoveryState) {
62 return projection.runs.filter((run) => {
63 const status: string = run.status;
64 return (
65 run.status === "queued" ||
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 for (const request of requests) {
206 events.push({
207 id: yield* allocateEventId(),
208 type: "runtime-request.updated",
209 threadId: projection.thread.id,
210 nodeId: request.nodeId,
211 occurredAt: now,
212 payload: {
213 ...request,
214 status: trigger === "startup" ? "expired" : "cancelled",
215 responseCapability: {
216 type: "not_resumable",
217 reason: `The server ${trigger === "startup" ? "restarted" : "shut down"} before this runtime request was resolved.`,
218 },
219 resolvedAt: now,
220 },
221 });
222 }
223 for (const run of runs) {
224 events.push({
225 id: yield* allocateEventId(),
226 type: "run.updated",
227 threadId: projection.thread.id,
228 runId: run.id,
229 providerInstanceId: run.providerInstanceId,
230 occurredAt: now,
231 payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
232 });
233 for (const attempt of projection.attempts.filter(
234 (candidate) =>
235 candidate.runId === run.id &&
236 (candidate.status === "pending" || candidate.status === "running"),
237 )) {
238 events.push({
239 id: yield* allocateEventId(),
240 type: "run-attempt.updated",
241 threadId: projection.thread.id,
242 runId: run.id,
243 nodeId: attempt.rootNodeId,
244 providerInstanceId: run.providerInstanceId,
245 occurredAt: now,
246 payload: { ...attempt, status: "cancelled", completedAt: now },
247 });
248 }
249 for (const node of projection.nodes.filter(
250 (candidate) =>
251 candidate.runId === run.id &&
252 !messageRequestNodeIds.has(candidate.id) &&
253 (candidate.status === "pending" ||
254 candidate.status === "running" ||
255 candidate.status === "waiting"),
256 )) {
257 events.push({
258 id: yield* allocateEventId(),
259 type: "node.updated",
260 threadId: projection.thread.id,
261 runId: run.id,
262 nodeId: node.id,
263 providerInstanceId: run.providerInstanceId,
264 occurredAt: now,
265 payload: { ...node, status: "cancelled", completedAt: now },
266 });
267 }
268 for (const subagent of projection.subagents.filter(
269 (candidate) =>
270 candidate.runId === run.id &&
271 (candidate.status === "pending" ||
272 candidate.status === "running" ||
273 candidate.status === "waiting"),
274 )) {
275 events.push({
276 id: yield* allocateEventId(),
277 type: "subagent.updated",
278 threadId: projection.thread.id,
279 runId: run.id,
280 nodeId: subagent.id,
281 driver: subagent.driver,
282 providerInstanceId: subagent.providerInstanceId,
283 occurredAt: now,
284 payload: { ...subagent, status: "cancelled", completedAt: now, updatedAt: now },
285 });
286 }
287 for (const providerTurn of projection.providerTurns.filter(
288 (candidate) =>
289 candidate.runAttemptId !== null &&
290 projection.attempts.some(
291 (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id,
292 ) &&
293 (candidate.status === "pending" || candidate.status === "running"),
294 )) {
295 events.push({
296 id: yield* allocateEventId(),
297 type: "provider-turn.updated",
298 threadId: projection.thread.id,
299 runId: run.id,
300 nodeId: providerTurn.nodeId,
301 providerInstanceId: run.providerInstanceId,
302 occurredAt: now,
303 payload: { ...providerTurn, status: "cancelled", completedAt: now },
304 });
305 }
306 for (const message of projection.messages.filter(
307 (candidate) => candidate.runId === run.id && candidate.streaming,
308 )) {
309 events.push({
310 id: yield* allocateEventId(),
311 type: "message.updated",
312 threadId: projection.thread.id,
313 runId: run.id,
314 ...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
315 providerInstanceId: run.providerInstanceId,
316 occurredAt: now,
317 payload: { ...message, streaming: false, updatedAt: now },
318 });
319 }
320 for (const item of projection.turnItems.filter(
321 (candidate) =>
322 candidate.runId === run.id &&
323 (candidate.nodeId === null || !messageRequestNodeIds.has(candidate.nodeId)) &&
324 (candidate.status === "pending" ||
325 candidate.status === "running" ||
326 candidate.status === "waiting"),
327 )) {
328 events.push({
329 id: yield* allocateEventId(),
330 type: "turn-item.updated",
331 threadId: projection.thread.id,
332 runId: run.id,
333 ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
334 providerInstanceId: run.providerInstanceId,
335 occurredAt: now,
336 payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
337 });
338 }
339 }
340 // Process loss also orphans background-capable turn items on already-
341 // settled runs (e.g. post-settle Waiting work). Skip items already
342 // cancelled above for recovered nonterminal runs to avoid duplicate
343 // cancellation events.
344 const recoveredNonterminalRunIds = new Set(runs.map((run) => run.id));
345 const cancelledStaleNodeIds = new Set<string>();
346 for (const item of projection.turnItems ?? []) {
347 if (item.runId !== null && recoveredNonterminalRunIds.has(item.runId)) {
348 continue;
349 }
350 if (!isBackgroundCapableTurnItemType(item.type)) {
351 continue;
352 }
353 if (!isNonterminalTurnItemStatus(item.status)) {
354 continue;
355 }
356 const providerInstanceId = resolveStaleBackgroundItemProviderInstanceId(item, projection);
357 events.push({
358 id: yield* allocateEventId(),
359 type: "turn-item.updated",
360 threadId: projection.thread.id,
361 ...(item.runId === null ? {} : { runId: item.runId }),
362 ...(item.nodeId === null || item.nodeId === undefined ? {} : { nodeId: item.nodeId }),
363 providerInstanceId,
364 occurredAt: now,
365 payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
366 });
367 if (item.nodeId !== null && item.nodeId !== undefined) {
368 const staleItemNode = projection.nodes.find(
369 (candidate) =>
370 candidate.id === item.nodeId && isNonterminalNodeStatus(candidate.status),
371 );
372 if (staleItemNode !== undefined && !cancelledStaleNodeIds.has(staleItemNode.id)) {
373 cancelledStaleNodeIds.add(staleItemNode.id);
374 events.push({
375 id: yield* allocateEventId(),
376 type: "node.updated",
377 threadId: projection.thread.id,
378 ...(item.runId === null ? {} : { runId: item.runId }),
379 nodeId: staleItemNode.id,
380 providerInstanceId,
381 occurredAt: now,
382 payload: { ...staleItemNode, status: "cancelled", completedAt: now },
383 });
384 }
385 }
386 if (item.type !== "subagent") {
387 continue;
388 }
389 // Cancelling only the turn item would leave the linked subagent entity
390 // non-terminal forever, since the dead provider process can no longer
391 // emit its terminal event. Match the exact linked id so a subagent
392 // that already finished is never overwritten.
393 const staleSubagent = projection.subagents.find(
394 (candidate) =>
395 candidate.id === item.subagentId && isNonterminalSubagentStatus(candidate.status),
396 );
397 if (staleSubagent !== undefined) {
398 events.push({
399 id: yield* allocateEventId(),
400 type: "subagent.updated",
401 threadId: projection.thread.id,
402 ...(item.runId === null ? {} : { runId: item.runId }),
403 nodeId: staleSubagent.id,
404 driver: staleSubagent.driver,
405 providerInstanceId: staleSubagent.providerInstanceId,
406 occurredAt: now,
407 payload: { ...staleSubagent, status: "cancelled", completedAt: now, updatedAt: now },
408 });
409 }
410 const staleSubagentNode = projection.nodes.find(
411 (candidate) =>
412 candidate.id === item.subagentId && isNonterminalNodeStatus(candidate.status),
413 );
414 if (staleSubagentNode !== undefined && !cancelledStaleNodeIds.has(staleSubagentNode.id)) {
415 cancelledStaleNodeIds.add(staleSubagentNode.id);
416 events.push({
417 id: yield* allocateEventId(),
418 type: "node.updated",
419 threadId: projection.thread.id,
420 ...(item.runId === null ? {} : { runId: item.runId }),
421 nodeId: staleSubagentNode.id,
422 providerInstanceId,
423 occurredAt: now,
424 payload: { ...staleSubagentNode, status: "cancelled", completedAt: now },
425 });
426 }
427 }
428 // All provider processes are gone on startup/shutdown: clear any
429 // persisted Waiting roster (including idle threads from settled roots)
430 // and idle active threads without resurrecting active status.
431 for (const providerThread of projection.providerThreads ?? []) {
432 const needsIdle = providerThread.status === "active";
433 const needsRosterClear = providerThreadHasPendingBackgroundTasks(providerThread);
434 if (!needsIdle && !needsRosterClear) {
435 continue;
436 }
437 events.push({
438 id: yield* allocateEventId(),
439 type: "provider-thread.updated",
440 threadId: projection.thread.id,
441 driver: providerThread.driver,
442 providerInstanceId: providerThread.providerInstanceId,
443 occurredAt: now,
444 payload: {
445 ...providerThread,
446 status: needsIdle ? "idle" : providerThread.status,
447 pendingBackgroundTasks: [],
448 updatedAt: now,
449 },
450 });
451 }
452 for (const session of projection.providerSessions.filter(
453 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
454 )) {
455 events.push({
456 id: yield* allocateEventId(),
457 type: "provider-session.updated",
458 threadId: projection.thread.id,
459 driver: session.driver,
460 providerInstanceId: session.providerInstanceId,
461 occurredAt: now,
462 payload: { ...session, status: "stopped", updatedAt: now, lastError: null },
463 });
464 }
465 const stoppedSessions = projection.providerSessions.filter(
466 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
467 ).length;
468 let retiredEffects: number;
469 if (events.length === 0) {
470 const retiredEffectIds = yield* outbox
471 .cancelUnsettled({
472 threadId: projection.thread.id,
473 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
474 reason: detail,
475 })
476 .pipe(
477 Effect.mapError(
478 (cause) =>
479 new ProviderRuntimeRecoveryError({
480 operation: "reconcile",
481 threadId: projection.thread.id,
482 cause: { detail, cause },
483 }),
484 ),
485 );
486 yield* outbox.signalCancellations(retiredEffectIds);
487 retiredEffects = retiredEffectIds.length;
488 } else {
489 const result = yield* eventSink
490 .commitCommand({
491 commandId,
492 threadId: projection.thread.id,
493 commandType: "provider-runtime.reconcile",
494 acceptedAt: now,
495 events,
496 effects,
497 cancelUnsettledEffects: {
498 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
499 reason: detail,
500 },
501 })
502 .pipe(
503 Effect.mapError(
504 (cause) =>
505 new ProviderRuntimeRecoveryError({
506 operation: "reconcile",
507 threadId: projection.thread.id,
508 cause,
509 }),
510 ),
511 );
512 retiredEffects = result.cancelledEffectCount;
513 }
514 return {
515 terminalizedRuns: runs.length,
516 stoppedSessions,
517 closedRequests: requests.length,
518 retiredEffects,
519 };
520 },
521 );
522​
523 const reconcile = (trigger: "startup" | "shutdown") =>
524 Effect.gen(function* () {
525 const continueAfterRestart = yield* settings.getSettings.pipe(
526 Effect.map((value) => value.continueThreadsAfterServerUpdate),
527 Effect.orElseSucceed(() => false),
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 result = yield* reconcileProjection(projection, trigger, continueAfterRestart);
552 terminalizedRuns += result.terminalizedRuns;
553 stoppedSessions += result.stoppedSessions;
554 closedRequests += result.closedRequests;
555 retiredEffects += result.retiredEffects;
556 }
557 const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
558 Effect.mapError(
559 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
560 ),
561 );
562 return {
563 terminalizedRuns,
564 stoppedSessions,
565 closedRequests,
566 retiredEffects: retiredEffects + outboxReconciliation.cancelled,
567 requeuedEffects: outboxReconciliation.requeued,
568 } satisfies ProviderRuntimeReconciliationSummary;
569 });
570​
571 // Snapshot intent only while providers are live. A provider may finish while
572 // this commits; reconciliation reads fresh state after shutdown, and delivery
573 // rejects any source run that actually completed.
574 const prepareForShutdown = Effect.gen(function* () {
575 const enabled = yield* settings.getSettings.pipe(
576 Effect.map((value) => value.continueThreadsAfterServerUpdate),
577 Effect.orElseSucceed(() => false),
578 );
579 if (!enabled) return;
580 const threadIds = yield* projections.getRecoveryThreadIds("runtime");
581 for (const threadId of threadIds) {
582 const projection = yield* projections.getRuntimeRecoveryProjection(threadId);
583 const run = restartContinuationRun(projection);
584 if (!run) continue;
585 const commandId = CommandId.make(`command:restart-prepare:${run.id}`);
586 yield* eventSink.writeWithEffects({
587 commandId,
588 events: [],
589 effects: [
590 {
591 id: `effect:restart-continuation:${run.id}`,
592 commandId,
593 threadId,
594 request: { type: "provider-runtime.continue", sourceRunId: run.id },
595 },
596 ],
597 });
598 }
599 }).pipe(
600 Effect.mapError((cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause })),
601 );
602​
603 const recover = Effect.gen(function* () {
604 return (yield* reconcile("startup")) satisfies ProviderRuntimeRecoverySummary;
605 });
606​
607 return ProviderRuntimeRecoveryService.of({ reconcile, prepareForShutdown, recover });
608});
609​
610export const layer = Layer.effect(ProviderRuntimeRecoveryService, make);