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