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

ProviderRuntimeRecoveryService.ts

735 lines28.5 KB

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