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

ProviderRuntimeRecoveryService.ts

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