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

ProviderRuntimeRecoveryService.ts

804 lines31.1 KB

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