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

ProviderRuntimeRecoveryService.ts

802 lines30.5 KB

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