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

ProviderRuntimeRecoveryService.ts

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