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

ProviderRuntimeRecoveryService.ts

1,249 lines48.4 KB

1import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
2import {
3 CommandId,
4 isProviderNativeSubagentThread,
5 type OrchestrationV2DomainEvent,
6 type ProviderThreadId,
7 type RunAttemptId,
8 type OrchestrationV2RestartCancelledBackgroundWork,
9 type OrchestrationV2Subagent,
10 type OrchestrationV2ThreadProjection,
11 isOrchestrationV2WorkActive,
12 ThreadId,
13} from "@t3tools/contracts";
14import * as Cause from "effect/Cause";
15import * as Context from "effect/Context";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Schema from "effect/Schema";
21​
22import * as EffectOutbox from "./EffectOutbox.ts";
23import * as EventSink from "./EventSink.ts";
24import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
25import * as ProjectionStore from "./ProjectionStore.ts";
26import * as ServerSettings from "../serverSettings.ts";
27import {
28 restartContinuationBlocked,
29 restartContinuationRun,
30 restartStopRequested,
31} from "./RestartContinuation.ts";
32import { isBufferedProviderNotification } from "./NotificationMailbox.ts";
33import { queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts";
34import {
35 endOrphanedNativeSubagent,
36 endRunlessRootTurns,
37} from "@t3tools/provider-core/server/subagentProjection";
38import {
39 awaitingProviderThreadId,
40 cancelledRosterTaskWork,
41 cancelledTurnItemWork,
42 mergeRestartCancelledBackgroundWork,
43 latestStartedRun,
44 neverStarted,
45} from "./RestartBackgroundNote.ts";
46​
47export class ProviderRuntimeRecoveryError extends Schema.TaggedError<ProviderRuntimeRecoveryError>()(
48 "ProviderRuntimeRecoveryError",
49 {
50 operation: Schema.Literals(["read-projections", "reconcile", "drain-outbox"]),
51 threadId: Schema.optional(ThreadId),
52 cause: Schema.Defect(),
53 },
54) {
55 override get message(): string {
56 return `Provider runtime recovery failed during ${this.operation}.`;
57 }
59​
60const isProviderRuntimeRecoveryError = Schema.is(ProviderRuntimeRecoveryError);
61​
62const MAX_RESENDS = 3;
63​
64export interface ProviderRuntimeRecoverySummary {
65 readonly terminalizedRuns: number;
66 readonly stoppedSessions: number;
67 readonly closedRequests: number;
68 readonly retiredEffects: number;
69 readonly requeuedEffects: number;
71​
72export interface ProviderRuntimeReconciliationSummary {
73 readonly terminalizedRuns: number;
74 readonly stoppedSessions: number;
75 readonly closedRequests: number;
76 readonly retiredEffects: number;
77 readonly requeuedEffects: number;
79​
80export class ProviderRuntimeRecoveryService extends Context.Service<
81 ProviderRuntimeRecoveryService,
82 {
83 readonly reconcile: (
84 trigger: "startup" | "shutdown",
85 ) => Effect.Effect<ProviderRuntimeReconciliationSummary, ProviderRuntimeRecoveryError>;
86 readonly prepareForShutdown: Effect.Effect<void, ProviderRuntimeRecoveryError>;
87 readonly recover: Effect.Effect<ProviderRuntimeRecoverySummary, ProviderRuntimeRecoveryError>;
88 }
89>()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {}
90​
91function nonterminalRuns(projection: ProjectionStore.ProjectionRuntimeRecoveryState) {
92 return projection.runs.filter((run) => {
93 const status: string = run.status;
94 return (
95 status === "preparing" ||
96 run.status === "starting" ||
97 run.status === "running" ||
98 run.status === "waiting"
99 );
100 });
102​
103function isBackgroundCapableTurnItemType(type: string): boolean {
104 return type === "command_execution" || type === "dynamic_tool" || type === "subagent";
106​
107function isNonterminalTurnItemStatus(status: string): boolean {
108 return status === "pending" || status === "running" || status === "waiting";
110​
111/**
112 * A delegate_task child. Its own thread is reconciled and continued on its own
113 * (here, or in the linked environment it runs in) and reports back through
114 * the app, so it is not provider background work.
115 */
116function isAppOwnedDelegation(task: {
117 readonly origin: OrchestrationV2Subagent["origin"];
118 readonly childThreadId: ThreadId | null;
119 readonly remoteChild?: OrchestrationV2Subagent["remoteChild"];
120}): boolean {
121 return (
122 task.origin === "app_owned" && (task.childThreadId !== null || task.remoteChild !== undefined)
123 );
125​
126function isAppOwnedDelegationItem(
127 item: OrchestrationV2ThreadProjection["turnItems"][number],
128): boolean {
129 return item.type === "subagent" && isAppOwnedDelegation(item);
131​
132function providerThreadHasPendingBackgroundTasks(
133 providerThread: OrchestrationV2ThreadProjection["providerThreads"][number],
134): boolean {
135 return (providerThread.pendingBackgroundTasks?.length ?? 0) > 0;
137​
138function resolveStaleBackgroundItemProviderInstanceId(
139 item: OrchestrationV2ThreadProjection["turnItems"][number],
140 projection: ProjectionStore.ProjectionRuntimeRecoveryState,
141): OrchestrationV2ThreadProjection["thread"]["providerInstanceId"] {
142 if (item.runId !== null) {
143 const run = projection.runs.find((candidate) => candidate.id === item.runId);
144 if (run !== undefined) {
145 return run.providerInstanceId;
146 }
147 }
148 if (item.type === "subagent") {
149 return item.providerInstanceId;
150 }
151 if (item.providerThreadId !== null && item.providerThreadId !== undefined) {
152 const providerThread = projection.providerThreads.find(
153 (candidate) => candidate.id === item.providerThreadId,
154 );
155 if (providerThread !== undefined) {
156 return providerThread.providerInstanceId;
157 }
158 }
159 return projection.providerThreads[0]?.providerInstanceId ?? projection.thread.providerInstanceId;
161​
162const cancelledItem = (
163 item: OrchestrationV2ThreadProjection["turnItems"][number],
164 now: DateTime.Utc,
165): OrchestrationV2ThreadProjection["turnItems"][number] =>
166 item.type === "secret_request" && item.secretStatus === "pending"
167 ? { ...item, status: "cancelled", secretStatus: "cancelled", completedAt: now, updatedAt: now }
168 : {
169 ...item,
170 ...("streaming" in item ? { streaming: false } : {}),
171 status: "cancelled",
172 completedAt: now,
173 updatedAt: now,
174 };
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 type RecoverySession = ProjectionStore.ProjectionRuntimeRecoveryState["providerSessions"][number];
183 /** Shared sessions stop on their first recovered thread; later threads still decide wakes from pre-recovery liveness. */
184 const sessionsLiveAtStart = (
185 projection: ProjectionStore.ProjectionRuntimeRecoveryState,
186 stoppedThisPass: ReadonlyMap<string, RecoverySession>,
187 ) => {
188 const sessions = new Map(projection.providerSessions.map((session) => [session.id, session]));
189 for (const providerThread of projection.providerThreads) {
190 const stopped =
191 providerThread.providerSessionId === null
192 ? undefined
193 : stoppedThisPass.get(providerThread.providerSessionId);
194 if (stopped !== undefined) sessions.set(stopped.id, stopped);
195 }
196 return [...sessions.values()];
197 };
198​
199 /**
200 * A run is marked running before its provider accepts the prompt, so only a provider turn of
201 * one of its attempts proves the prompt arrived. Recovery treats the others as never started.
202 */
203 const rewindUnacceptedRuns = Effect.fn("ProviderRuntimeRecoveryService.rewindUnacceptedRuns")(
204 function* (projection: ProjectionStore.ProjectionRuntimeRecoveryState) {
205 const runIdByAttempt = new Map(
206 projection.runs.flatMap((run) =>
207 (run.status === "running" || (run.status === "starting" && run.startedAt !== null)) &&
208 run.activeAttemptId !== null
209 ? [[run.activeAttemptId, run.id] as const]
210 : [],
211 ),
212 );
213 if (runIdByAttempt.size === 0) return projection;
214 const unaccepted = new Set(runIdByAttempt.values());
215 const accept = (turns: ReadonlyArray<{ readonly runAttemptId: RunAttemptId | null }>) => {
216 for (const turn of turns) {
217 const runId =
218 turn.runAttemptId === null ? undefined : runIdByAttempt.get(turn.runAttemptId);
219 if (runId !== undefined) unaccepted.delete(runId);
220 }
221 };
222 accept(projection.providerTurns);
223 if (unaccepted.size === 0) return projection;
224 for (const attempt of projection.attempts) {
225 if (unaccepted.has(attempt.runId)) runIdByAttempt.set(attempt.id, attempt.runId);
226 }
227 // The recovery projection omits ended provider turns, such as one a steer replaced.
228 accept(
229 (yield* projections
230 .getThreadRecords(projection.thread.id, ["providerTurns"], {
231 providerTurnAttemptIds: [...runIdByAttempt].flatMap(([attemptId, runId]) =>
232 unaccepted.has(runId) ? [attemptId] : [],
233 ),
234 })
235 .pipe(
236 Effect.mapError(
237 (cause) =>
238 new ProviderRuntimeRecoveryError({
239 operation: "read-projections",
240 threadId: projection.thread.id,
241 cause,
242 }),
243 ),
244 )).providerTurns,
245 );
246 return {
247 ...projection,
248 runs: projection.runs.map((run) =>
249 unaccepted.has(run.id) ? { ...run, status: "starting" as const, startedAt: null } : run,
250 ),
251 };
252 },
253 );
254​
255 const reconcileProjection = Effect.fn("ProviderRuntimeRecoveryService.reconcileProjection")(
256 function* (
257 stored: ProjectionStore.ProjectionRuntimeRecoveryState,
258 trigger: "startup" | "shutdown",
259 continueAfterRestart: boolean,
260 stoppedThisPass: ReadonlyMap<string, RecoverySession> = new Map(),
261 ) {
262 const now = yield* DateTime.now;
263 const projection = yield* rewindUnacceptedRuns(stored);
264 let runs = [] as Array<OrchestrationV2ThreadProjection["runs"][number]>;
265 for (const run of nonterminalRuns(projection)) {
266 if (run.status === "waiting") {
267 const checkpointEffects = yield* outbox
268 .listByCommandId(CommandId.make(`command:effect:checkpoint.capture:${run.id}`))
269 .pipe(
270 Effect.mapError(
271 (cause) =>
272 new ProviderRuntimeRecoveryError({
273 operation: "reconcile",
274 threadId: projection.thread.id,
275 cause,
276 }),
277 ),
278 );
279 const hasReplayableCheckpoint = checkpointEffects.some(
280 (effect) =>
281 effect.request.type === "checkpoint.capture" &&
282 effect.request.runId === run.id &&
283 (effect.status === "pending" || effect.status === "running"),
284 );
285 if (hasReplayableCheckpoint) continue;
286 }
287 runs.push(run);
288 }
289 const pendingRequests = projection.runtimeRequests.filter(
290 (request) => request.status === "pending",
291 );
292 // The lost provider callback cannot resume; persisted questions can be
293 // answered by a new user message in threads that accept messages.
294 const questions = pendingRequests.filter(
295 (request) =>
296 request.kind === "user_input" &&
297 request.responseCapability.type === "live" &&
298 projection.turnItems.some(
299 (item) =>
300 item.type === "user_input_request" &&
301 item.requestId === request.id &&
302 item.nodeId === request.nodeId &&
303 item.questions.length > 0 &&
304 item.questions.every((question) => question.question.trim().length > 0),
305 ) &&
306 !isProviderNativeSubagentThread(projection.thread),
307 );
308 const recoveredRequestIds = new Set(questions.map((request) => request.id));
309 const messageRequestNodeIds = new Set(
310 pendingRequests
311 .filter(
312 (request) =>
313 request.responseCapability.type === "message" || recoveredRequestIds.has(request.id),
314 )
315 .map((request) => request.nodeId),
316 );
317 const requests = pendingRequests.filter(
318 (request) =>
319 request.responseCapability.type !== "message" && !recoveredRequestIds.has(request.id),
320 );
321 // Delegated task rows, items and nodes stay open: the child settles them.
322 const delegatedTaskNodeIds = new Set<string>([
323 ...(projection.subagents ?? []).filter(isAppOwnedDelegation).map((subagent) => subagent.id),
324 ...(projection.turnItems ?? []).flatMap((item) =>
325 item.type === "subagent" && isAppOwnedDelegation(item) ? [item.subagentId] : [],
326 ),
327 ]);
328 const detail = `Cancelled because the server ${trigger === "startup" ? "restarted" : "shut down"} before the provider work completed.`;
329 const commandId = CommandId.make(
330 `command:runtime-reconcile:${trigger}:${projection.thread.id}:${DateTime.formatIso(now)}`,
331 );
332 const allocateEventId = () =>
333 ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
334 Effect.mapError(
335 (cause) =>
336 new ProviderRuntimeRecoveryError({
337 operation: "reconcile",
338 threadId: projection.thread.id,
339 cause,
340 }),
341 ),
342 );
343 const events: Array<OrchestrationV2DomainEvent> = [];
344 const cancelledBackgroundWork = new Map<
345 ProviderThreadId,
346 Array<OrchestrationV2RestartCancelledBackgroundWork>
347 >();
348 const cancelledBackgroundNativeIds = new Set<string>();
349 const recordCancelledBackgroundWork = (
350 providerThreadId: ProviderThreadId | null | undefined,
351 work: OrchestrationV2RestartCancelledBackgroundWork,
352 ) => {
353 if (providerThreadId == null) return;
354 const existing = cancelledBackgroundWork.get(providerThreadId);
355 if (existing === undefined) cancelledBackgroundWork.set(providerThreadId, [work]);
356 else existing.push(work);
357 };
358 const recordCancelledBackgroundItem = (
359 item: OrchestrationV2ThreadProjection["turnItems"][number],
360 ) => {
361 if (!isBackgroundCapableTurnItemType(item.type)) return;
362 const awaitingId = awaitingProviderThreadId(item, projection.runs);
363 const ownProviderThread =
364 item.providerThreadId === awaitingId
365 ? undefined
366 : (projection.providerThreads ?? []).find(
367 (candidate) => candidate.id === item.providerThreadId,
368 );
369 const work = cancelledTurnItemWork(
370 item,
371 ownProviderThread?.nativeThreadRef?.nativeId ?? undefined,
372 );
373 if (work === undefined) return;
374 recordCancelledBackgroundWork(awaitingId, work);
375 if (item.nativeItemRef?.nativeId != null) {
376 cancelledBackgroundNativeIds.add(item.nativeItemRef.nativeId);
377 }
378 };
379 const unstartedRuns = runs.filter(
380 (run) =>
381 run.status === "starting" &&
382 neverStarted(run) &&
383 !projection.providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId) &&
384 !projection.runtimeRequests.some(
385 (request) =>
386 request.status === "pending" &&
387 projection.nodes.some((node) => node.id === request.nodeId && node.runId === run.id),
388 ),
389 );
390 const queuedRuns = projection.runs.filter((run) => run.status === "queued");
391 const pendingRuns = [...unstartedRuns, ...queuedRuns];
392 const queuedMessages =
393 pendingRuns.length === 0
394 ? []
395 : [
396 ...(yield* projections
397 .getMessagesById(
398 projection.thread.id,
399 pendingRuns.map((run) => run.userMessageId),
400 )
401 .pipe(
402 Effect.mapError(
403 (cause) =>
404 new ProviderRuntimeRecoveryError({
405 operation: "read-projections",
406 threadId: projection.thread.id,
407 cause,
408 }),
409 ),
410 )).values(),
411 ];
412 const bufferedMessageIds = new Set(
413 queuedMessages.filter(isBufferedProviderNotification).map((message) => message.id),
414 );
415 const retryableMessageIds = new Set(
416 queuedMessages
417 .filter(
418 (message) =>
419 message.createdBy === "user" &&
420 message.scheduledTaskId === undefined &&
421 message.notification === undefined &&
422 message.delegatedCompletion === undefined,
423 )
424 .map((message) => message.id),
425 );
426 // A saved user message the provider never accepted stays available through the held queue.
427 const retryableRuns = unstartedRuns.filter((run) =>
428 retryableMessageIds.has(run.userMessageId),
429 );
430 // Nobody reviews a delegated, agent-sent or scheduled prompt, so it is sent again instead.
431 const unattendedRuns = continueAfterRestart
432 ? unstartedRuns.filter((run) =>
433 queuedMessages.some(
434 (message) =>
435 message.id === run.userMessageId &&
436 !retryableMessageIds.has(message.id) &&
437 message.notification === undefined &&
438 message.delegatedCompletion === undefined &&
439 (message.scheduledTaskId !== undefined || message.creationSource === "mcp"),
440 ),
441 )
442 : [];
443 const resentRuns: Array<OrchestrationV2ThreadProjection["runs"][number]> = [];
444 const resends: Array<EffectOutbox.PendingOrchestrationEffectV2> = [];
445 for (const run of unattendedRuns) {
446 if (
447 restartContinuationBlocked(projection, run, now, false) ||
448 (yield* restartStopRequested(projections.getThreadRecords, projection.thread, run).pipe(
449 Effect.mapError(
450 (cause) =>
451 new ProviderRuntimeRecoveryError({
452 operation: "read-projections",
453 threadId: projection.thread.id,
454 cause,
455 }),
456 ),
457 ))
458 )
459 continue;
460 const resendCommandId = CommandId.make(`command:restart-resend:${run.id}`);
461 const earlierResends = yield* outbox.listByCommandId(resendCommandId).pipe(
462 Effect.mapError(
463 (cause) =>
464 new ProviderRuntimeRecoveryError({
465 operation: "reconcile",
466 threadId: projection.thread.id,
467 cause,
468 }),
469 ),
470 );
471 // A prompt whose start keeps crashing the server would otherwise be sent forever.
472 if (earlierResends.filter((effect) => effect.attemptCount > 0).length >= MAX_RESENDS) {
473 yield* Effect.logWarning("Not resending a prompt that restarts cut too many times", {
474 threadId: projection.thread.id,
475 runId: run.id,
476 });
477 continue;
478 }
479 resentRuns.push(run);
480 resends.push({
481 id: `effect:restart-resend:${run.id}:${commandId}`,
482 commandId: resendCommandId,
483 threadId: projection.thread.id,
484 request: { type: "provider-turn.start", runId: run.id },
485 });
486 }
487 for (const run of resentRuns) {
488 events.push({
489 id: yield* allocateEventId(),
490 type: "run.updated",
491 threadId: projection.thread.id,
492 runId: run.id,
493 providerInstanceId: run.providerInstanceId,
494 occurredAt: now,
495 payload: run,
496 });
497 }
498 const keptRuns = [...retryableRuns, ...resentRuns];
499 for (const run of keptRuns) {
500 for (const attempt of projection.attempts.filter(
501 (candidate) => candidate.id === run.activeAttemptId && candidate.status === "running",
502 )) {
503 events.push({
504 id: yield* allocateEventId(),
505 type: "run-attempt.updated",
506 threadId: projection.thread.id,
507 runId: run.id,
508 nodeId: attempt.rootNodeId,
509 providerInstanceId: run.providerInstanceId,
510 occurredAt: now,
511 payload: { ...attempt, status: "pending", startedAt: null },
512 });
513 }
514 for (const node of projection.nodes.filter(
515 (candidate) => candidate.id === run.rootNodeId && candidate.status === "running",
516 )) {
517 events.push({
518 id: yield* allocateEventId(),
519 type: "node.updated",
520 threadId: projection.thread.id,
521 runId: run.id,
522 nodeId: node.id,
523 providerInstanceId: run.providerInstanceId,
524 occurredAt: now,
525 payload: { ...node, status: "pending", startedAt: null },
526 });
527 }
528 }
529 const retryableItems =
530 retryableRuns.length === 0
531 ? []
532 : (yield* projections
533 .getThreadRecords(projection.thread.id, ["turnItems"], {
534 turnItemTypes: ["user_message"],
535 turnItemRunIds: retryableRuns.map((run) => run.id),
536 })
537 .pipe(
538 Effect.mapError(
539 (cause) =>
540 new ProviderRuntimeRecoveryError({
541 operation: "read-projections",
542 threadId: projection.thread.id,
543 cause,
544 }),
545 ),
546 )).turnItems;
547 for (const item of retryableItems) {
548 if (item.type !== "user_message" || !retryableMessageIds.has(item.messageId)) continue;
549 events.push({
550 id: yield* allocateEventId(),
551 type: "turn-item.updated",
552 threadId: projection.thread.id,
553 ...(item.runId === null ? {} : { runId: item.runId }),
554 occurredAt: now,
555 payload: {
556 ...item,
557 inputIntent: "queued_turn",
558 status: "pending",
559 startedAt: null,
560 completedAt: null,
561 updatedAt: now,
562 },
563 });
564 }
565 runs = runs.filter((run) => !keptRuns.some((kept) => kept.id === run.id));
566 const heldRuns = [
567 ...retryableRuns,
568 ...queuedRunsInDeliveryOrder({ runs: queuedRuns, messages: queuedMessages }),
569 ];
570 for (const [index, run] of heldRuns.entries()) {
571 if (bufferedMessageIds.has(run.userMessageId)) {
572 runs.push(run);
573 continue;
574 }
575 if (run.queueHeld === true && retryableRuns.length === 0) continue;
576 events.push({
577 id: yield* allocateEventId(),
578 type: "run.updated",
579 threadId: projection.thread.id,
580 runId: run.id,
581 providerInstanceId: run.providerInstanceId,
582 occurredAt: now,
583 payload: {
584 ...run,
585 status: "queued",
586 queueHeld: true,
587 ...(retryableRuns.length === 0 ? {} : { queuePosition: index + 1 }),
588 },
589 });
590 }
591 const unsentResumeRunIds = runs.flatMap((run) =>
592 run.startedAt === null && run.usageLimitContinuationOfRunId !== undefined ? [run.id] : [],
593 );
594 const limitRecovery = projection.thread.limitRecovery;
595 // The unsent resume spent the worker's request id, so a fresh one lets it send again. An
596 // untagged resume from an older server stays cancelled: its copy couldn't be hidden.
597 if (limitRecovery?.autoResume === true && unsentResumeRunIds.length > 0) {
598 events.push({
599 id: yield* allocateEventId(),
600 type: "thread.metadata-updated",
601 threadId: projection.thread.id,
602 occurredAt: now,
603 payload: {
604 ...projection.thread,
605 limitRecovery: { ...limitRecovery, requestId: commandId },
606 updatedAt: now,
607 },
608 });
609 }
610 // The worker sends the auto-resume again, so the unsent copy leaves the transcript the way
611 // cancelled queued input does.
612 const unsentResumePrompts =
613 unsentResumeRunIds.length === 0
614 ? []
615 : (yield* projections
616 .getThreadRecords(projection.thread.id, ["turnItems"], {
617 turnItemTypes: ["user_message"],
618 turnItemRunIds: unsentResumeRunIds,
619 })
620 .pipe(
621 Effect.mapError(
622 (cause) =>
623 new ProviderRuntimeRecoveryError({
624 operation: "read-projections",
625 threadId: projection.thread.id,
626 cause,
627 }),
628 ),
629 )).turnItems;
630 const unsentResumePromptIds = new Set(unsentResumePrompts.map((item) => item.id));
631 for (const item of unsentResumePrompts) {
632 if (item.type !== "user_message") continue;
633 const active =
634 item.status === "pending" || item.status === "running" || item.status === "waiting";
635 events.push({
636 id: yield* allocateEventId(),
637 type: "turn-item.updated",
638 threadId: projection.thread.id,
639 ...(item.runId === null ? {} : { runId: item.runId }),
640 occurredAt: now,
641 payload: {
642 ...item,
643 ...(active ? { status: "cancelled", completedAt: now } : {}),
644 inputIntent: "queued_turn",
645 updatedAt: now,
646 },
647 });
648 }
649 for (const question of questions) {
650 events.push({
651 id: yield* allocateEventId(),
652 type: "runtime-request.updated",
653 threadId: projection.thread.id,
654 nodeId: question.nodeId,
655 occurredAt: now,
656 payload: { ...question, responseCapability: { type: "message" } },
657 });
658 }
659 for (const request of requests) {
660 events.push({
661 id: yield* allocateEventId(),
662 type: "runtime-request.updated",
663 threadId: projection.thread.id,
664 nodeId: request.nodeId,
665 occurredAt: now,
666 payload: {
667 ...request,
668 status: trigger === "startup" ? "expired" : "cancelled",
669 responseCapability: {
670 type: "not_resumable",
671 reason: `The server ${trigger === "startup" ? "restarted" : "shut down"} before this runtime request was resolved.`,
672 },
673 resolvedAt: now,
674 },
675 });
676 }
677 for (const run of runs) {
678 events.push({
679 id: yield* allocateEventId(),
680 type: "run.updated",
681 threadId: projection.thread.id,
682 runId: run.id,
683 providerInstanceId: run.providerInstanceId,
684 occurredAt: now,
685 payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
686 });
687 for (const attempt of projection.attempts.filter(
688 (candidate) =>
689 candidate.runId === run.id &&
690 (candidate.status === "pending" || candidate.status === "running"),
691 )) {
692 events.push({
693 id: yield* allocateEventId(),
694 type: "run-attempt.updated",
695 threadId: projection.thread.id,
696 runId: run.id,
697 nodeId: attempt.rootNodeId,
698 providerInstanceId: run.providerInstanceId,
699 occurredAt: now,
700 payload: { ...attempt, status: "cancelled", completedAt: now },
701 });
702 }
703 for (const node of projection.nodes.filter(
704 (candidate) =>
705 candidate.runId === run.id &&
706 !messageRequestNodeIds.has(candidate.id) &&
707 !delegatedTaskNodeIds.has(candidate.id) &&
708 (candidate.status === "pending" ||
709 candidate.status === "running" ||
710 candidate.status === "waiting"),
711 )) {
712 events.push({
713 id: yield* allocateEventId(),
714 type: "node.updated",
715 threadId: projection.thread.id,
716 runId: run.id,
717 nodeId: node.id,
718 providerInstanceId: run.providerInstanceId,
719 occurredAt: now,
720 payload: { ...node, status: "cancelled", completedAt: now },
721 });
722 }
723 for (const providerTurn of projection.providerTurns.filter(
724 (candidate) =>
725 candidate.runAttemptId !== null &&
726 projection.attempts.some(
727 (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id,
728 ) &&
729 (candidate.status === "pending" || candidate.status === "running"),
730 )) {
731 events.push({
732 id: yield* allocateEventId(),
733 type: "provider-turn.updated",
734 threadId: projection.thread.id,
735 runId: run.id,
736 nodeId: providerTurn.nodeId,
737 providerInstanceId: run.providerInstanceId,
738 occurredAt: now,
739 payload: { ...providerTurn, status: "cancelled", completedAt: now },
740 });
741 }
742 for (const message of projection.messages.filter(
743 (candidate) => candidate.runId === run.id && candidate.streaming,
744 )) {
745 events.push({
746 id: yield* allocateEventId(),
747 type: "message.updated",
748 threadId: projection.thread.id,
749 runId: run.id,
750 ...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
751 providerInstanceId: run.providerInstanceId,
752 occurredAt: now,
753 payload: { ...message, streaming: false, updatedAt: now },
754 });
755 }
756 for (const item of projection.turnItems.filter(
757 (candidate) =>
758 candidate.runId === run.id &&
759 !unsentResumePromptIds.has(candidate.id) &&
760 (candidate.nodeId === null || !messageRequestNodeIds.has(candidate.nodeId)) &&
761 !isAppOwnedDelegationItem(candidate) &&
762 // A link card waits on the user, not the run, and answers by message.
763 candidate.type !== "link_request" &&
764 // The orchestrator queues a steer the provider never reported reading.
765 !(
766 candidate.type === "user_message" &&
767 candidate.status === "pending" &&
768 (candidate.inputIntent === "steer" ||
769 candidate.inputIntent === "promoted_queued_to_steer")
770 ) &&
771 (candidate.status === "pending" ||
772 candidate.status === "running" ||
773 candidate.status === "waiting"),
774 )) {
775 // Cut native subagents do not resume; record them for the continuation to restart.
776 if (run.status === "waiting") recordCancelledBackgroundItem(item);
777 else if (item.type === "subagent" && item.origin === "provider_native")
778 recordCancelledBackgroundItem(item);
779 events.push({
780 id: yield* allocateEventId(),
781 type: "turn-item.updated",
782 threadId: projection.thread.id,
783 runId: run.id,
784 ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
785 providerInstanceId: run.providerInstanceId,
786 occurredAt: now,
787 payload: cancelledItem(item, now),
788 });
789 }
790 // Queued runs and unsent resumes leave no visible turn behind, so there is nothing to explain.
791 if (run.status === "queued" || unsentResumeRunIds.includes(run.id)) continue;
792 events.push({
793 id: yield* allocateEventId(),
794 type: "turn-item.updated",
795 threadId: projection.thread.id,
796 runId: run.id,
797 ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }),
798 providerInstanceId: run.providerInstanceId,
799 occurredAt: now,
800 payload: {
801 id: ids.derive.runSignalTurnItem({ runId: run.id, signal: "server-recovery" }),
802 threadId: projection.thread.id,
803 runId: run.id,
804 nodeId: run.rootNodeId,
805 providerThreadId: run.providerThreadId,
806 providerTurnId: null,
807 nativeItemRef: null,
808 parentItemId: null,
809 // EventSink allocates the real position, after the run's existing items.
810 ordinal: 0,
811 status: "completed",
812 title: trigger === "startup" ? "Server restarted" : "Server shut down",
813 startedAt: now,
814 completedAt: now,
815 updatedAt: now,
816 type: "system_notice",
817 message: detail,
818 },
819 });
820 }
821 // Blocking waits die with their turn; let child results wake the parent continuation as async tasks.
822 const cutRunIds = new Set(runs.map((run) => run.id));
823 for (const task of projection.subagents ?? []) {
824 if (
825 task.origin !== "app_owned" ||
826 task.runId === null ||
827 !cutRunIds.has(task.runId) ||
828 task.completionWake !== "settled_only" ||
829 !isOrchestrationV2WorkActive(task.status)
830 )
831 continue;
832 events.push({
833 id: yield* allocateEventId(),
834 type: "subagent.updated",
835 threadId: projection.thread.id,
836 runId: task.runId,
837 nodeId: task.id,
838 driver: task.driver,
839 providerInstanceId: task.providerInstanceId,
840 occurredAt: now,
841 payload: { ...task, completionWake: "always", updatedAt: now },
842 });
843 }
844 const recoveredNonterminalRunIds = new Set(runs.map((run) => run.id));
845 const cancelledStaleNodeIds = new Set<string>();
846 for (const item of projection.turnItems ?? []) {
847 if (item.runId !== null && recoveredNonterminalRunIds.has(item.runId)) {
848 continue;
849 }
850 if (!isBackgroundCapableTurnItemType(item.type)) {
851 continue;
852 }
853 if (!isNonterminalTurnItemStatus(item.status) || isAppOwnedDelegationItem(item)) {
854 continue;
855 }
856 const providerInstanceId = resolveStaleBackgroundItemProviderInstanceId(item, projection);
857 recordCancelledBackgroundItem(item);
858 events.push({
859 id: yield* allocateEventId(),
860 type: "turn-item.updated",
861 threadId: projection.thread.id,
862 ...(item.runId === null ? {} : { runId: item.runId }),
863 ...(item.nodeId === null || item.nodeId === undefined ? {} : { nodeId: item.nodeId }),
864 providerInstanceId,
865 occurredAt: now,
866 payload: cancelledItem(item, now),
867 });
868 if (item.nodeId !== null && item.nodeId !== undefined) {
869 const staleItemNode = projection.nodes.find(
870 (candidate) =>
871 candidate.id === item.nodeId && isNonterminalTurnItemStatus(candidate.status),
872 );
873 if (staleItemNode !== undefined && !cancelledStaleNodeIds.has(staleItemNode.id)) {
874 cancelledStaleNodeIds.add(staleItemNode.id);
875 events.push({
876 id: yield* allocateEventId(),
877 type: "node.updated",
878 threadId: projection.thread.id,
879 ...(item.runId === null ? {} : { runId: item.runId }),
880 nodeId: staleItemNode.id,
881 providerInstanceId,
882 occurredAt: now,
883 payload: { ...staleItemNode, status: "cancelled", completedAt: now },
884 });
885 }
886 }
887 }
888 // No provider process survives the server; open native subagents can never report completion.
889 for (const subagent of projection.subagents ?? []) {
890 events.push(
891 ...(yield* endOrphanedNativeSubagent({
892 projection,
893 subagentId: subagent.id,
894 status: "cancelled",
895 now,
896 emitted: events,
897 allocateEventId,
898 })),
899 );
900 }
901 // Native subagent threads have no runs to settle their runless root turns.
902 events.push(
903 ...(yield* endRunlessRootTurns({
904 threadId: projection.thread.id,
905 providerInstanceId: projection.thread.providerInstanceId,
906 projection,
907 status: "cancelled",
908 now,
909 emitted: events,
910 allocateEventId,
911 })),
912 );
913 for (const providerThread of projection.providerThreads ?? []) {
914 const needsIdle = providerThread.status === "active";
915 const needsRosterClear = providerThreadHasPendingBackgroundTasks(providerThread);
916 if (!needsIdle && !needsRosterClear) {
917 continue;
918 }
919 if (providerThread.ownerNodeId === null) {
920 for (const task of providerThread.pendingBackgroundTasks ?? []) {
921 // A subagent already recorded covers the shells it started.
922 if (
923 cancelledBackgroundNativeIds.has(task.taskId) ||
924 (task.parentTaskId !== undefined &&
925 cancelledBackgroundNativeIds.has(task.parentTaskId))
926 )
927 continue;
928 cancelledBackgroundNativeIds.add(task.taskId);
929 recordCancelledBackgroundWork(providerThread.id, cancelledRosterTaskWork(task));
930 }
931 }
932 events.push({
933 id: yield* allocateEventId(),
934 type: "provider-thread.updated",
935 threadId: projection.thread.id,
936 driver: providerThread.driver,
937 providerInstanceId: providerThread.providerInstanceId,
938 occurredAt: now,
939 payload: {
940 ...providerThread,
941 status: needsIdle ? "idle" : providerThread.status,
942 pendingBackgroundTasks: [],
943 updatedAt: now,
944 },
945 });
946 }
947 for (const session of projection.providerSessions.filter(
948 (candidate) =>
949 (candidate.status !== "stopped" && candidate.status !== "error") ||
950 (candidate.status === "error" && (candidate.extensionStatuses?.length ?? 0) > 0),
951 )) {
952 events.push({
953 id: yield* allocateEventId(),
954 type: "provider-session.updated",
955 threadId: projection.thread.id,
956 driver: session.driver,
957 providerInstanceId: session.providerInstanceId,
958 occurredAt: now,
959 payload: {
960 ...session,
961 status: session.status === "error" ? "error" : "stopped",
962 ...(session.extensionStatuses === undefined ? {} : { extensionStatuses: [] }),
963 updatedAt: now,
964 lastError: session.status === "error" ? session.lastError : null,
965 },
966 });
967 }
968 for (const [providerThreadId, work] of cancelledBackgroundWork) {
969 const noteRun = latestStartedRun(projection.runs, providerThreadId);
970 if (noteRun === undefined) continue;
971 // Use a separate event; stale run snapshots can overwrite intervening lifecycle changes.
972 events.push({
973 id: yield* allocateEventId(),
974 type: "run.background-work-cancelled",
975 threadId: projection.thread.id,
976 runId: noteRun.id,
977 providerInstanceId: noteRun.providerInstanceId,
978 occurredAt: now,
979 payload: {
980 runId: noteRun.id,
981 restartCancelledBackgroundWork: mergeRestartCancelledBackgroundWork(
982 noteRun.restartCancelledBackgroundWork ?? [],
983 work,
984 ),
985 },
986 });
987 }
988 const continuationRun =
989 continueAfterRestart && trigger === "startup"
990 ? restartContinuationRun(
991 { ...projection, providerSessions: sessionsLiveAtStart(projection, stoppedThisPass) },
992 now,
993 )
994 : undefined;
995 let processLossCount = 1;
996 // Normal upgrades must not exhaust an unfinished turn's crash allowance.
997 if (
998 continuationRun?.restartContinuationOfRunId !== undefined &&
999 continuationRun.status !== "completed" &&
1000 continuationRun.status !== "waiting"
1001 ) {
1002 const previous = yield* outbox
1003 .get(`effect:restart-continuation:${continuationRun.restartContinuationOfRunId}`)
1004 .pipe(
1005 Effect.mapError(
1006 (cause) =>
1007 new ProviderRuntimeRecoveryError({
1008 operation: "reconcile",
1009 threadId: projection.thread.id,
1010 cause,
1011 }),
1012 ),
1013 );
1014 if (Option.isSome(previous) && previous.value.request.type === "provider-runtime.continue")
1015 processLossCount += previous.value.request.processLossCount ?? 0;
1017 const effects: Array<EffectOutbox.PendingOrchestrationEffectV2> = continuationRun
1018 ? [
1020 id: `effect:restart-continuation:${continuationRun.id}`,
1021 commandId,
1022 threadId: projection.thread.id,
1023 request: {
1024 type: "provider-runtime.continue",
1025 sourceRunId: continuationRun.id,
1026 processLossCount,
1027 },
1028 },
1030 : [];
1031 const stoppedSessions = projection.providerSessions.filter(
1032 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
1033 ).length;
1034 let retiredEffects: number;
1035 let cancelledEffectIds: ReadonlyArray<string> = [];
1036 if (events.length === 0) {
1037 const retiredEffectIds = yield* outbox
1038 .cancelUnsettled({
1039 threadId: projection.thread.id,
1040 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
1041 reason: detail,
1042 })
1043 .pipe(
1044 Effect.mapError(
1045 (cause) =>
1046 new ProviderRuntimeRecoveryError({
1047 operation: "reconcile",
1048 threadId: projection.thread.id,
1049 cause: { detail, cause },
1050 }),
1051 ),
1052 );
1053 cancelledEffectIds = retiredEffectIds;
1054 retiredEffects = retiredEffectIds.length;
1055 } else {
1056 const result = yield* eventSink
1057 .commitCommand({
1058 commandId,
1059 threadId: projection.thread.id,
1060 commandType: "provider-runtime.reconcile",
1061 acceptedAt: now,
1062 events,
1063 effects,
1064 cancelUnsettledEffects: {
1065 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
1066 reason: detail,
1067 },
1068 })
1069 .pipe(
1070 Effect.mapError(
1071 (cause) =>
1072 new ProviderRuntimeRecoveryError({
1073 operation: "reconcile",
1074 threadId: projection.thread.id,
1075 cause,
1076 }),
1077 ),
1078 );
1079 retiredEffects = result.cancelledEffectCount;
1081 return {
1082 terminalizedRuns: runs.length,
1083 stoppedSessions,
1084 closedRequests: requests.length,
1085 retiredEffects,
1086 cancelledEffectIds,
1087 resends,
1088 };
1089 },
1090 );
1091​
1092 const reconcile = Effect.fn("ProviderRuntimeRecoveryService.reconcile")(function* (
1093 trigger: "startup" | "shutdown",
1094 ) {
1095 const continueAfterRestart = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
1096 const threadIds = yield* projections
1097 .getRecoveryThreadIds("runtime")
1098 .pipe(
1099 Effect.mapError(
1100 (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
1101 ),
1102 );
1103 let terminalizedRuns = 0;
1104 let stoppedSessions = 0;
1105 let closedRequests = 0;
1106 let retiredEffects = 0;
1107 const resends: Array<EffectOutbox.PendingOrchestrationEffectV2> = [];
1108 const stoppedThisPass = new Map<string, RecoverySession>();
1109 const grouped = trigger === "shutdown" && threadIds.length > 1;
1110 const groupSize = grouped ? 32 : 1;
1111 for (let offset = 0; offset < threadIds.length; offset += groupSize) {
1112 const cancelledEffectIds: string[] = [];
1113 // Read and decide on the writer so shared sessions see earlier updates in this group.
1114 const reconcileGroup = Effect.gen(function* () {
1115 for (const threadId of threadIds.slice(offset, offset + groupSize)) {
1116 const projection = yield* projections.getRuntimeRecoveryProjection(threadId).pipe(
1117 Effect.mapError(
1118 (cause) =>
1119 new ProviderRuntimeRecoveryError({
1120 operation: "read-projections",
1121 threadId,
1122 cause,
1123 }),
1124 ),
1125 );
1126 const enabled =
1127 continueAfterRestart !== null &&
1128 resolveProjectSettings(continueAfterRestart, projection.thread.projectId).settings
1129 .continueThreadsAfterServerUpdate;
1130 const result = yield* reconcileProjection(projection, trigger, enabled, stoppedThisPass);
1131 for (const session of projection.providerSessions) {
1132 if (session.status !== "stopped" && session.status !== "error") {
1133 stoppedThisPass.set(session.id, session);
1136 cancelledEffectIds.push(...result.cancelledEffectIds);
1137 resends.push(...result.resends);
1138 terminalizedRuns += result.terminalizedRuns;
1139 stoppedSessions += result.stoppedSessions;
1140 closedRequests += result.closedRequests;
1141 retiredEffects += result.retiredEffects;
1143 });
1144 yield* (grouped ? eventSink.withProviderBatch(reconcileGroup) : reconcileGroup).pipe(
1145 Effect.mapError((cause) =>
1146 isProviderRuntimeRecoveryError(cause)
1147 ? cause
1148 : new ProviderRuntimeRecoveryError({ operation: "reconcile", cause }),
1149 ),
1150 );
1151 // Eventless outbox cancellations also wait for the group's durable commit.
1152 if (cancelledEffectIds.length > 0) yield* outbox.signalCancellations(cancelledEffectIds);
1154 const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
1155 Effect.mapError(
1156 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
1157 ),
1158 );
1159 // After the drain, which cancels every unsettled provider start. A crash before this write
1160 // leaves the run unstarted, so the next recovery sends it again.
1161 if (resends.length > 0) {
1162 yield* eventSink
1163 .writeWithEffects({ events: [], effects: resends })
1164 .pipe(
1165 Effect.mapError(
1166 (cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause }),
1167 ),
1168 );
1170 return {
1171 terminalizedRuns,
1172 stoppedSessions,
1173 closedRequests,
1174 retiredEffects: retiredEffects + outboxReconciliation.cancelled,
1175 requeuedEffects: outboxReconciliation.requeued,
1176 } satisfies ProviderRuntimeReconciliationSummary;
1177 });
1178​
1179 const prepareForShutdown = Effect.gen(function* () {
1180 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
1181 if (!enabled) return;
1182 const enabledProjects = Object.entries(enabled.projectSettingsOverrides)
1183 .filter(([, overrides]) => overrides.continueThreadsAfterServerUpdate === true)
1184 .map(([id]) => id);
1185 if (!enabled.continueThreadsAfterServerUpdate && enabledProjects.length === 0) return;
1186 const disabledProjects = Object.entries(enabled.projectSettingsOverrides)
1187 .filter(([, overrides]) => overrides.continueThreadsAfterServerUpdate === false)
1188 .map(([id]) => id);
1189 const threadIds = yield* projections.getRecoveryThreadIds(
1190 "restart-continuations",
1191 enabled.continueThreadsAfterServerUpdate
1192 ? { exclude: disabledProjects }
1193 : { include: enabledProjects },
1194 );
1195 yield* Effect.forEach(
1196 threadIds,
1197 (threadId) =>
1198 Effect.gen(function* () {
1199 const projection = yield* projections.getRuntimeRecoveryProjection(threadId);
1200 if (
1201 !resolveProjectSettings(enabled, projection.thread.projectId).settings
1202 .continueThreadsAfterServerUpdate
1204 return;
1205 const run = restartContinuationRun(
1206 yield* rewindUnacceptedRuns(projection),
1207 yield* DateTime.now,
1208 );
1209 if (!run) return;
1210 const commandId = CommandId.make(`command:restart-prepare:${run.id}`);
1211 yield* eventSink.writeWithEffects({
1212 commandId,
1213 events: [],
1214 effects: [
1216 id: `effect:restart-continuation:${run.id}`,
1217 commandId,
1218 threadId,
1219 request: {
1220 type: "provider-runtime.continue",
1221 sourceRunId: run.id,
1222 processLossCount: 0,
1223 },
1224 },
1225 ],
1226 });
1227 }).pipe(
1228 Effect.catchCauseIf(
1229 (cause) => !Cause.hasInterruptsOnly(cause),
1230 (cause) =>
1231 Effect.logWarning("Failed to prepare a restart continuation", { threadId, cause }),
1232 ),
1233 ),
1234 // Leave room in the four-reader pool for other shutdown reads.
1235 { concurrency: 2, discard: true },
1236 );
1237 }).pipe(
1238 Effect.withSpan("ProviderRuntimeRecoveryService.prepareForShutdown"),
1239 Effect.mapError((cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause })),
1240 );
1241​
1242 const recover = Effect.gen(function* () {
1243 return (yield* reconcile("startup")) satisfies ProviderRuntimeRecoverySummary;
1244 });
1245​
1246 return ProviderRuntimeRecoveryService.of({ reconcile, prepareForShutdown, recover });
1247});
1248​
1249export const layer = Layer.effect(ProviderRuntimeRecoveryService, make);