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

ProviderRuntimeRecoveryService.ts

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