Open History to see the last commit
1import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
2import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
3import {
4 CommandId,
5 type OrchestrationV2DomainEvent,
6 type ProviderThreadId,
7 type OrchestrationV2RestartCancelledBackgroundWork,
8 type OrchestrationV2Subagent,
9 type OrchestrationV2ThreadProjection,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as Cause from "effect/Cause";
13import * as Context from "effect/Context";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Schema from "effect/Schema";
18
19import * as EffectOutbox from "./EffectOutbox.ts";
20import * as EventSink from "./EventSink.ts";
21import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
22import * as ProjectionStore from "./ProjectionStore.ts";
23import * as ServerSettings from "../serverSettings.ts";
24import { restartContinuationRun } from "./RestartContinuation.ts";
25import { isBufferedProviderNotification } from "./NotificationMailbox.ts";
26import {
27 endOrphanedNativeSubagent,
28 endRunlessRootTurns,
29} from "@t3tools/provider-core/server/subagentProjection";
30import {
31 cancelledRosterTaskWork,
32 cancelledTurnItemWork,
33 mergeRestartCancelledBackgroundWork,
34} from "./RestartBackgroundNote.ts";
35
36export class ProviderRuntimeRecoveryError extends Schema.TaggedError<ProviderRuntimeRecoveryError>()(
37 "ProviderRuntimeRecoveryError",
38 {
39 operation: Schema.Literals(["read-projections", "reconcile", "drain-outbox"]),
40 threadId: Schema.optional(ThreadId),
41 cause: Schema.Defect(),
42 },
43) {
44 override get message(): string {
45 return `Provider runtime recovery failed during ${this.operation}.`;
46 }
47}
48
49export interface ProviderRuntimeRecoverySummary {
50 readonly terminalizedRuns: number;
51 readonly stoppedSessions: number;
52 readonly closedRequests: number;
53 readonly retiredEffects: number;
54 readonly requeuedEffects: number;
55}
56
57export interface ProviderRuntimeReconciliationSummary {
58 readonly terminalizedRuns: number;
59 readonly stoppedSessions: number;
60 readonly closedRequests: number;
61 readonly retiredEffects: number;
62 readonly requeuedEffects: number;
63}
64
65export class ProviderRuntimeRecoveryService extends Context.Service<
66 ProviderRuntimeRecoveryService,
67 {
68 readonly reconcile: (
69 trigger: "startup" | "shutdown",
70 ) => Effect.Effect<ProviderRuntimeReconciliationSummary, ProviderRuntimeRecoveryError>;
71 readonly prepareForShutdown: Effect.Effect<void, ProviderRuntimeRecoveryError>;
72 readonly recover: Effect.Effect<ProviderRuntimeRecoverySummary, ProviderRuntimeRecoveryError>;
73 }
74>()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {}
75
76function nonterminalRuns(projection: ProjectionStore.ProjectionRuntimeRecoveryState) {
77 return projection.runs.filter((run) => {
78 const status: string = run.status;
79 return (
80 status === "preparing" ||
81 run.status === "starting" ||
82 run.status === "running" ||
83 run.status === "waiting"
84 );
85 });
86}
87
88function isBackgroundCapableTurnItemType(type: string): boolean {
89 return type === "command_execution" || type === "dynamic_tool" || type === "subagent";
90}
91
92function isNonterminalTurnItemStatus(status: string): boolean {
93 return status === "pending" || status === "running" || status === "waiting";
94}
95
96function isNonterminalNodeStatus(status: string): boolean {
97 return status === "pending" || status === "running" || status === "waiting";
98}
99
100/**
101 * A delegate_task child. Its own thread is reconciled and continued on its own
102 * and reports back through the app, so it is not provider background work.
103 */
104function isAppOwnedDelegation(task: {
105 readonly origin: OrchestrationV2Subagent["origin"];
106 readonly childThreadId: ThreadId | null;
107}): boolean {
108 return task.origin === "app_owned" && task.childThreadId !== null;
109}
110
111function isAppOwnedDelegationItem(
112 item: OrchestrationV2ThreadProjection["turnItems"][number],
113): boolean {
114 return item.type === "subagent" && isAppOwnedDelegation(item);
115}
116
117function providerThreadHasPendingBackgroundTasks(
118 providerThread: OrchestrationV2ThreadProjection["providerThreads"][number],
119): boolean {
120 return (providerThread.pendingBackgroundTasks?.length ?? 0) > 0;
121}
122
123/**
124 * Resolve providerInstanceId for a stale background-capable turn item whose
125 * run is missing/null (or not found). Prefer an existing run, then a subagent
126 * item's own instance id, then the item's provider thread, then a last-resort
127 * first provider thread, then the thread's selected provider.
128 */
129function resolveStaleBackgroundItemProviderInstanceId(
130 item: OrchestrationV2ThreadProjection["turnItems"][number],
131 projection: ProjectionStore.ProjectionRuntimeRecoveryState,
132): OrchestrationV2ThreadProjection["thread"]["providerInstanceId"] {
133 if (item.runId !== null) {
134 const run = projection.runs.find((candidate) => candidate.id === item.runId);
135 if (run !== undefined) {
136 return run.providerInstanceId;
137 }
138 }
139 if (item.type === "subagent") {
140 return item.providerInstanceId;
141 }
142 if (item.providerThreadId !== null && item.providerThreadId !== undefined) {
143 const providerThread = projection.providerThreads.find(
144 (candidate) => candidate.id === item.providerThreadId,
145 );
146 if (providerThread !== undefined) {
147 return providerThread.providerInstanceId;
148 }
149 }
150 return projection.providerThreads[0]?.providerInstanceId ?? projection.thread.providerInstanceId;
151}
152
153/** An open item closed by recovery. A secret card also closes its form, so it takes no answer. */
154const cancelledItem = (
155 item: OrchestrationV2ThreadProjection["turnItems"][number],
156 now: DateTime.Utc,
157): OrchestrationV2ThreadProjection["turnItems"][number] =>
158 item.type === "secret_request" && item.secretStatus === "pending"
159 ? { ...item, status: "cancelled", secretStatus: "cancelled", completedAt: now, updatedAt: now }
160 : { ...item, status: "cancelled", completedAt: now, updatedAt: now };
161
162/**
163 * A provider thread's latest started run: the last turn that provider saw.
164 * Restart recovery records the thread's cancelled background work on it, and
165 * the next run on the same provider thread delivers it with its input.
166 */
167function latestStartedRun(
168 projection: ProjectionStore.ProjectionRuntimeRecoveryState,
169 providerThreadId: ProviderThreadId,
170) {
171 return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | undefined>(
172 (latest, run) =>
173 run.providerThreadId === providerThreadId &&
174 run.status !== "queued" &&
175 run.status !== "rolled_back" &&
176 (latest === undefined || runRanAfter(run, latest))
177 ? run
178 : latest,
179 undefined,
180 );
181}
182
183export const make = Effect.gen(function* () {
184 const settings = yield* ServerSettings.ServerSettingsService;
185 const projections = yield* ProjectionStore.ProjectionStoreV2;
186 const eventSink = yield* EventSink.EventSinkV2;
187 const ids = yield* IdAllocator.IdAllocatorV2;
188 const outbox = yield* EffectOutbox.EffectOutboxV2;
189 const reconcileProjection = Effect.fn("ProviderRuntimeRecoveryService.reconcileProjection")(
190 function* (
191 projection: ProjectionStore.ProjectionRuntimeRecoveryState,
192 trigger: "startup" | "shutdown",
193 continueAfterRestart: boolean,
194 ) {
195 const now = yield* DateTime.now;
196 const runs = [] as Array<OrchestrationV2ThreadProjection["runs"][number]>;
197 for (const run of nonterminalRuns(projection)) {
198 if (run.status === "waiting") {
199 const checkpointEffects = yield* outbox
200 .listByCommandId(CommandId.make(`command:effect:checkpoint.capture:${run.id}`))
201 .pipe(
202 Effect.mapError(
203 (cause) =>
204 new ProviderRuntimeRecoveryError({
205 operation: "reconcile",
206 threadId: projection.thread.id,
207 cause,
208 }),
209 ),
210 );
211 const hasReplayableCheckpoint = checkpointEffects.some(
212 (effect) =>
213 effect.request.type === "checkpoint.capture" &&
214 effect.request.runId === run.id &&
215 (effect.status === "pending" || effect.status === "running"),
216 );
217 if (hasReplayableCheckpoint) continue;
218 }
219 runs.push(run);
220 }
221 const messageRequestNodeIds = new Set(
222 projection.runtimeRequests
223 .filter(
224 (request) =>
225 request.status === "pending" && request.responseCapability.type === "message",
226 )
227 .map((request) => request.nodeId),
228 );
229 const requests = projection.runtimeRequests.filter(
230 (request) => request.status === "pending" && request.responseCapability.type !== "message",
231 );
232 // Delegated task rows, items and nodes stay open: the child settles them.
233 const delegatedTaskNodeIds = new Set<string>([
234 ...(projection.subagents ?? []).filter(isAppOwnedDelegation).map((subagent) => subagent.id),
235 ...(projection.turnItems ?? []).flatMap((item) =>
236 item.type === "subagent" && isAppOwnedDelegation(item) ? [item.subagentId] : [],
237 ),
238 ]);
239 const detail = `Cancelled because the server ${trigger === "startup" ? "restarted" : "shut down"} before the provider work completed.`;
240 const commandId = CommandId.make(
241 `command:runtime-reconcile:${trigger}:${projection.thread.id}:${DateTime.formatIso(now)}`,
242 );
243 const allocateEventId = () =>
244 ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
245 Effect.mapError(
246 (cause) =>
247 new ProviderRuntimeRecoveryError({
248 operation: "reconcile",
249 threadId: projection.thread.id,
250 cause,
251 }),
252 ),
253 );
254 const events: Array<OrchestrationV2DomainEvent> = [];
255 // Background work that outlived its settled turn. The provider transcript
256 // cannot record its death, so the next provider turn is told instead.
257 // Shutdown records it too: a graceful restart cancels it there first.
258 // Keyed by the provider thread that lost the work: only its turns are told.
259 const cancelledBackgroundWork = new Map<
260 ProviderThreadId,
261 Array<OrchestrationV2RestartCancelledBackgroundWork>
262 >();
263 const cancelledBackgroundNativeIds = new Set<string>();
264 const recordCancelledBackgroundWork = (
265 providerThreadId: ProviderThreadId | null | undefined,
266 work: OrchestrationV2RestartCancelledBackgroundWork,
267 ) => {
268 if (providerThreadId == null) return;
269 const existing = cancelledBackgroundWork.get(providerThreadId);
270 if (existing === undefined) cancelledBackgroundWork.set(providerThreadId, [work]);
271 else existing.push(work);
272 };
273 const recordCancelledBackgroundItem = (
274 item: OrchestrationV2ThreadProjection["turnItems"][number],
275 ) => {
276 if (!isBackgroundCapableTurnItemType(item.type)) return;
277 const work = cancelledTurnItemWork(item);
278 if (work === undefined) return;
279 recordCancelledBackgroundWork(
280 item.providerThreadId ??
281 projection.runs.find((run) => run.id === item.runId)?.providerThreadId,
282 work,
283 );
284 if (item.nativeItemRef?.nativeId != null) {
285 cancelledBackgroundNativeIds.add(item.nativeItemRef.nativeId);
286 }
287 };
288 const queuedRuns = projection.runs.filter((run) => run.status === "queued");
289 const queuedMessages =
290 queuedRuns.length === 0
291 ? []
292 : (yield* projections
293 .getThreadRecords(projection.thread.id, ["messages"], {
294 messageIds: queuedRuns.map((run) => run.userMessageId),
295 })
296 .pipe(
297 Effect.mapError(
298 (cause) =>
299 new ProviderRuntimeRecoveryError({
300 operation: "read-projections",
301 threadId: projection.thread.id,
302 cause,
303 }),
304 ),
305 )).messages;
306 const bufferedMessageIds = new Set(
307 queuedMessages.filter(isBufferedProviderNotification).map((message) => message.id),
308 );
309 // Buffered wakes lost their output with the process. Durable queued messages
310 // keep their execution identities and order until the user resumes them.
311 for (const run of queuedRuns) {
312 if (bufferedMessageIds.has(run.userMessageId)) {
313 runs.push(run);
314 continue;
315 }
316 if (run.queueHeld === true) continue;
317 events.push({
318 id: yield* allocateEventId(),
319 type: "run.updated",
320 threadId: projection.thread.id,
321 runId: run.id,
322 providerInstanceId: run.providerInstanceId,
323 occurredAt: now,
324 payload: { ...run, queueHeld: true },
325 });
326 }
327 for (const request of requests) {
328 events.push({
329 id: yield* allocateEventId(),
330 type: "runtime-request.updated",
331 threadId: projection.thread.id,
332 nodeId: request.nodeId,
333 occurredAt: now,
334 payload: {
335 ...request,
336 status: trigger === "startup" ? "expired" : "cancelled",
337 responseCapability: {
338 type: "not_resumable",
339 reason: `The server ${trigger === "startup" ? "restarted" : "shut down"} before this runtime request was resolved.`,
340 },
341 resolvedAt: now,
342 },
343 });
344 }
345 for (const run of runs) {
346 events.push({
347 id: yield* allocateEventId(),
348 type: "run.updated",
349 threadId: projection.thread.id,
350 runId: run.id,
351 providerInstanceId: run.providerInstanceId,
352 occurredAt: now,
353 payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
354 });
355 for (const attempt of projection.attempts.filter(
356 (candidate) =>
357 candidate.runId === run.id &&
358 (candidate.status === "pending" || candidate.status === "running"),
359 )) {
360 events.push({
361 id: yield* allocateEventId(),
362 type: "run-attempt.updated",
363 threadId: projection.thread.id,
364 runId: run.id,
365 nodeId: attempt.rootNodeId,
366 providerInstanceId: run.providerInstanceId,
367 occurredAt: now,
368 payload: { ...attempt, status: "cancelled", completedAt: now },
369 });
370 }
371 for (const node of projection.nodes.filter(
372 (candidate) =>
373 candidate.runId === run.id &&
374 !messageRequestNodeIds.has(candidate.id) &&
375 !delegatedTaskNodeIds.has(candidate.id) &&
376 (candidate.status === "pending" ||
377 candidate.status === "running" ||
378 candidate.status === "waiting"),
379 )) {
380 events.push({
381 id: yield* allocateEventId(),
382 type: "node.updated",
383 threadId: projection.thread.id,
384 runId: run.id,
385 nodeId: node.id,
386 providerInstanceId: run.providerInstanceId,
387 occurredAt: now,
388 payload: { ...node, status: "cancelled", completedAt: now },
389 });
390 }
391 for (const providerTurn of projection.providerTurns.filter(
392 (candidate) =>
393 candidate.runAttemptId !== null &&
394 projection.attempts.some(
395 (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id,
396 ) &&
397 (candidate.status === "pending" || candidate.status === "running"),
398 )) {
399 events.push({
400 id: yield* allocateEventId(),
401 type: "provider-turn.updated",
402 threadId: projection.thread.id,
403 runId: run.id,
404 nodeId: providerTurn.nodeId,
405 providerInstanceId: run.providerInstanceId,
406 occurredAt: now,
407 payload: { ...providerTurn, status: "cancelled", completedAt: now },
408 });
409 }
410 for (const message of projection.messages.filter(
411 (candidate) => candidate.runId === run.id && candidate.streaming,
412 )) {
413 events.push({
414 id: yield* allocateEventId(),
415 type: "message.updated",
416 threadId: projection.thread.id,
417 runId: run.id,
418 ...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
419 providerInstanceId: run.providerInstanceId,
420 occurredAt: now,
421 payload: { ...message, streaming: false, updatedAt: now },
422 });
423 }
424 for (const item of projection.turnItems.filter(
425 (candidate) =>
426 candidate.runId === run.id &&
427 (candidate.nodeId === null || !messageRequestNodeIds.has(candidate.nodeId)) &&
428 !isAppOwnedDelegationItem(candidate) &&
429 (candidate.status === "pending" ||
430 candidate.status === "running" ||
431 candidate.status === "waiting"),
432 )) {
433 // A waiting run's provider turn already settled; its open items are
434 // background work. A running run's items die with its turn.
435 if (run.status === "waiting") recordCancelledBackgroundItem(item);
436 events.push({
437 id: yield* allocateEventId(),
438 type: "turn-item.updated",
439 threadId: projection.thread.id,
440 runId: run.id,
441 ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
442 providerInstanceId: run.providerInstanceId,
443 occurredAt: now,
444 payload: cancelledItem(item, now),
445 });
446 }
447 }
448 // Process loss also orphans background-capable turn items on already-
449 // settled runs (e.g. post-settle Waiting work). Skip items already
450 // cancelled above for recovered nonterminal runs to avoid duplicate
451 // cancellation events.
452 const recoveredNonterminalRunIds = new Set(runs.map((run) => run.id));
453 const cancelledStaleNodeIds = new Set<string>();
454 for (const item of projection.turnItems ?? []) {
455 if (item.runId !== null && recoveredNonterminalRunIds.has(item.runId)) {
456 continue;
457 }
458 if (!isBackgroundCapableTurnItemType(item.type)) {
459 continue;
460 }
461 if (!isNonterminalTurnItemStatus(item.status) || isAppOwnedDelegationItem(item)) {
462 continue;
463 }
464 const providerInstanceId = resolveStaleBackgroundItemProviderInstanceId(item, projection);
465 recordCancelledBackgroundItem(item);
466 events.push({
467 id: yield* allocateEventId(),
468 type: "turn-item.updated",
469 threadId: projection.thread.id,
470 ...(item.runId === null ? {} : { runId: item.runId }),
471 ...(item.nodeId === null || item.nodeId === undefined ? {} : { nodeId: item.nodeId }),
472 providerInstanceId,
473 occurredAt: now,
474 payload: cancelledItem(item, now),
475 });
476 if (item.nodeId !== null && item.nodeId !== undefined) {
477 const staleItemNode = projection.nodes.find(
478 (candidate) =>
479 candidate.id === item.nodeId && isNonterminalNodeStatus(candidate.status),
480 );
481 if (staleItemNode !== undefined && !cancelledStaleNodeIds.has(staleItemNode.id)) {
482 cancelledStaleNodeIds.add(staleItemNode.id);
483 events.push({
484 id: yield* allocateEventId(),
485 type: "node.updated",
486 threadId: projection.thread.id,
487 ...(item.runId === null ? {} : { runId: item.runId }),
488 nodeId: staleItemNode.id,
489 providerInstanceId,
490 occurredAt: now,
491 payload: { ...staleItemNode, status: "cancelled", completedAt: now },
492 });
493 }
494 }
495 }
496 // No provider process outlives the server, so a native subagent still open
497 // here never reports its end, whatever state its run and item are in.
498 for (const subagent of projection.subagents ?? []) {
499 events.push(
500 ...(yield* endOrphanedNativeSubagent({
501 projection,
502 subagentId: subagent.id,
503 status: "cancelled",
504 now,
505 emitted: events,
506 allocateEventId,
507 })),
508 );
509 }
510 // A provider-native subagent thread has no runs; left running, the child
511 // would show as working forever.
512 events.push(
513 ...(yield* endRunlessRootTurns({
514 threadId: projection.thread.id,
515 providerInstanceId: projection.thread.providerInstanceId,
516 projection,
517 status: "cancelled",
518 now,
519 emitted: events,
520 allocateEventId,
521 })),
522 );
523 // All provider processes are gone on startup/shutdown: clear any
524 // persisted Waiting roster (including idle threads from settled roots)
525 // and idle active threads without resurrecting active status.
526 for (const providerThread of projection.providerThreads ?? []) {
527 const needsIdle = providerThread.status === "active";
528 const needsRosterClear = providerThreadHasPendingBackgroundTasks(providerThread);
529 if (!needsIdle && !needsRosterClear) {
530 continue;
531 }
532 if (providerThread.ownerNodeId === null) {
533 for (const task of providerThread.pendingBackgroundTasks ?? []) {
534 if (cancelledBackgroundNativeIds.has(task.taskId)) continue;
535 cancelledBackgroundNativeIds.add(task.taskId);
536 recordCancelledBackgroundWork(providerThread.id, cancelledRosterTaskWork(task));
537 }
538 }
539 events.push({
540 id: yield* allocateEventId(),
541 type: "provider-thread.updated",
542 threadId: projection.thread.id,
543 driver: providerThread.driver,
544 providerInstanceId: providerThread.providerInstanceId,
545 occurredAt: now,
546 payload: {
547 ...providerThread,
548 status: needsIdle ? "idle" : providerThread.status,
549 pendingBackgroundTasks: [],
550 updatedAt: now,
551 },
552 });
553 }
554 for (const session of projection.providerSessions.filter(
555 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
556 )) {
557 events.push({
558 id: yield* allocateEventId(),
559 type: "provider-session.updated",
560 threadId: projection.thread.id,
561 driver: session.driver,
562 providerInstanceId: session.providerInstanceId,
563 occurredAt: now,
564 payload: { ...session, status: "stopped", updatedAt: now, lastError: null },
565 });
566 }
567 for (const [providerThreadId, work] of cancelledBackgroundWork) {
568 const noteRun = latestStartedRun(projection, providerThreadId);
569 if (noteRun === undefined) continue;
570 // Its own event: a run snapshot read before this commit could regress
571 // a lifecycle change (e.g. a checkpoint completing the run) made since.
572 events.push({
573 id: yield* allocateEventId(),
574 type: "run.background-work-cancelled",
575 threadId: projection.thread.id,
576 runId: noteRun.id,
577 providerInstanceId: noteRun.providerInstanceId,
578 occurredAt: now,
579 payload: {
580 runId: noteRun.id,
581 restartCancelledBackgroundWork: mergeRestartCancelledBackgroundWork(
582 noteRun.restartCancelledBackgroundWork ?? [],
583 work,
584 ),
585 },
586 });
587 }
588 const continuationRun =
589 continueAfterRestart && trigger === "startup"
590 ? restartContinuationRun(projection, now)
591 : undefined;
592 const effects: Array<EffectOutbox.PendingOrchestrationEffectV2> = continuationRun
593 ? [
594 {
595 id: `effect:restart-continuation:${continuationRun.id}`,
596 commandId,
597 threadId: projection.thread.id,
598 request: { type: "provider-runtime.continue", sourceRunId: continuationRun.id },
599 },
600 ]
601 : [];
602 const stoppedSessions = projection.providerSessions.filter(
603 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
604 ).length;
605 let retiredEffects: number;
606 if (events.length === 0) {
607 const retiredEffectIds = yield* outbox
608 .cancelUnsettled({
609 threadId: projection.thread.id,
610 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
611 reason: detail,
612 })
613 .pipe(
614 Effect.mapError(
615 (cause) =>
616 new ProviderRuntimeRecoveryError({
617 operation: "reconcile",
618 threadId: projection.thread.id,
619 cause: { detail, cause },
620 }),
621 ),
622 );
623 yield* outbox.signalCancellations(retiredEffectIds);
624 retiredEffects = retiredEffectIds.length;
625 } else {
626 const result = yield* eventSink
627 .commitCommand({
628 commandId,
629 threadId: projection.thread.id,
630 commandType: "provider-runtime.reconcile",
631 acceptedAt: now,
632 events,
633 effects,
634 cancelUnsettledEffects: {
635 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
636 reason: detail,
637 },
638 })
639 .pipe(
640 Effect.mapError(
641 (cause) =>
642 new ProviderRuntimeRecoveryError({
643 operation: "reconcile",
644 threadId: projection.thread.id,
645 cause,
646 }),
647 ),
648 );
649 retiredEffects = result.cancelledEffectCount;
650 }
651 return {
652 terminalizedRuns: runs.length,
653 stoppedSessions,
654 closedRequests: requests.length,
655 retiredEffects,
656 };
657 },
658 );
659
660 const reconcile = (trigger: "startup" | "shutdown") =>
661 Effect.gen(function* () {
662 const continueAfterRestart = yield* settings.getSettings.pipe(
663 Effect.orElseSucceed(() => null),
664 );
665 const threadIds = yield* projections
666 .getRecoveryThreadIds("runtime")
667 .pipe(
668 Effect.mapError(
669 (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
670 ),
671 );
672 let terminalizedRuns = 0;
673 let stoppedSessions = 0;
674 let closedRequests = 0;
675 let retiredEffects = 0;
676 for (const threadId of threadIds) {
677 const projection = yield* projections.getRuntimeRecoveryProjection(threadId).pipe(
678 Effect.mapError(
679 (cause) =>
680 new ProviderRuntimeRecoveryError({
681 operation: "read-projections",
682 threadId,
683 cause,
684 }),
685 ),
686 );
687 const enabled =
688 continueAfterRestart !== null &&
689 resolveProjectSettings(continueAfterRestart, projection.thread.projectId).settings
690 .continueThreadsAfterServerUpdate;
691 const result = yield* reconcileProjection(projection, trigger, enabled);
692 terminalizedRuns += result.terminalizedRuns;
693 stoppedSessions += result.stoppedSessions;
694 closedRequests += result.closedRequests;
695 retiredEffects += result.retiredEffects;
696 }
697 const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
698 Effect.mapError(
699 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
700 ),
701 );
702 return {
703 terminalizedRuns,
704 stoppedSessions,
705 closedRequests,
706 retiredEffects: retiredEffects + outboxReconciliation.cancelled,
707 requeuedEffects: outboxReconciliation.requeued,
708 } satisfies ProviderRuntimeReconciliationSummary;
709 });
710
711 // Snapshot intent only while providers are live. A provider may finish while
712 // this commits; reconciliation reads fresh state after shutdown, and delivery
713 // rejects any source run that actually completed.
714 const prepareForShutdown = Effect.gen(function* () {
715 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
716 if (!enabled) return;
717 const threadIds = yield* projections.getRecoveryThreadIds("runtime");
718 for (const threadId of threadIds) {
719 yield* Effect.gen(function* () {
720 const projection = yield* projections.getRuntimeRecoveryProjection(threadId);
721 if (
722 !resolveProjectSettings(enabled, projection.thread.projectId).settings
723 .continueThreadsAfterServerUpdate
724 )
725 return;
726 const run = restartContinuationRun(projection, yield* DateTime.now);
727 if (!run) return;
728 const commandId = CommandId.make(`command:restart-prepare:${run.id}`);
729 yield* eventSink.writeWithEffects({
730 commandId,
731 events: [],
732 effects: [
733 {
734 id: `effect:restart-continuation:${run.id}`,
735 commandId,
736 threadId,
737 request: { type: "provider-runtime.continue", sourceRunId: run.id },
738 },
739 ],
740 });
741 }).pipe(
742 // One failing thread must not cost the threads after it their continuation.
743 Effect.catchCauseIf(
744 (cause) => !Cause.hasInterruptsOnly(cause),
745 (cause) =>
746 Effect.logWarning("Failed to prepare a restart continuation", { threadId, cause }),
747 ),
748 );
749 }
750 }).pipe(
751 Effect.mapError((cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause })),
752 );
753
754 const recover = Effect.gen(function* () {
755 return (yield* reconcile("startup")) satisfies ProviderRuntimeRecoverySummary;
756 });
757
758 return ProviderRuntimeRecoveryService.of({ reconcile, prepareForShutdown, recover });
759});
760
761export const layer = Layer.effect(ProviderRuntimeRecoveryService, make);