Open History to see the last commit
1import { CommandId, type RunId } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as Fiber from "effect/Fiber";
9import * as Layer from "effect/Layer";
10import * as Metric from "effect/Metric";
11import * as Option from "effect/Option";
12import * as Schedule from "effect/Schedule";
13import * as Schema from "effect/Schema";
14import * as SqlError from "effect/sql/SqlError";
15
16import {
17 increment,
18 metricAttributes,
19 orchestrationEffectClaimsTotal,
20 orchestrationEffectQueueWait,
21} from "../observability/Metrics.ts";
22import * as RunFinalizationService from "./RunFinalizationService.ts";
23import * as ResourceCleanupService from "./ResourceCleanupService.ts";
24import * as EffectOutbox from "./EffectOutbox.ts";
25import * as ProjectionMaintenance from "./ProjectionMaintenance.ts";
26import * as ProjectionStore from "./ProjectionStore.ts";
27import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
28import * as ProviderSessionManager from "./ProviderSessionManager.ts";
29import * as ProviderTurnControlService from "./ProviderTurnControlService.ts";
30import * as ProviderTurnStartService from "./ProviderTurnStartService.ts";
31import * as RuntimeRequestService from "./RuntimeRequestService.ts";
32import * as ThreadTitleRegenerationService from "./ThreadTitleRegenerationService.ts";
33import * as ThreadManagementService from "./ThreadManagementService.ts";
34import * as ServerSettings from "../serverSettings.ts";
35import { continueRestartedRun } from "./RestartContinuation.ts";
36
37const isProviderTurnControlError = Schema.is(ProviderTurnControlService.ProviderTurnControlError);
38
39export class OrchestrationEffectExecutionError extends Schema.TaggedError<OrchestrationEffectExecutionError>()(
40 "OrchestrationEffectExecutionError",
41 {
42 effectId: Schema.String,
43 effectType: Schema.String,
44 cause: Schema.optional(Schema.Defect()),
45 },
46) {}
47
48const isOrchestrationEffectExecutionError = Schema.is(OrchestrationEffectExecutionError);
49
50/**
51 * Do not apply this to `provider-turn.restart`: that compound effect also runs
52 * detach and start. Swallowing a start failure that happens to mention
53 * "is not active" would drop the outbox item without ever starting the
54 * replacement turn.
55 */
56function isNonRetryableProviderTurnControlFailure(effectType: string, errorText: string): boolean {
57 if (effectType !== "provider-turn.interrupt") {
58 return false;
59 }
60 return (
61 /is not active/i.test(errorText) ||
62 /hard teardown is already in progress/i.test(errorText) ||
63 /treating as already interrupted/i.test(errorText) ||
64 /treating as already stopped/i.test(errorText)
65 );
66}
67
68// Keep an owner for starting runs when persistence or restart cleanup fails.
69const ownsStartingRun = (effectType: EffectOutbox.OrchestrationEffectV2["request"]["type"]) =>
70 effectType === "provider-turn.start" || effectType === "provider-turn.restart";
71
72const cannotSettleRun = (cause: Cause.Cause<unknown>) =>
73 Cause.findErrorOption(cause).pipe(
74 Option.exists(
75 (error) =>
76 isOrchestrationEffectExecutionError(error) &&
77 ProviderTurnStartService.isProviderTurnStartRunStateMissingError(error.cause),
78 ),
79 );
80
81export interface OrchestrationEffectExecutorV2Shape {
82 readonly execute: (
83 effect: EffectOutbox.OrchestrationEffectV2,
84 options?: { readonly willRetry: boolean },
85 ) => Effect.Effect<void, OrchestrationEffectExecutionError>;
86}
87
88export class OrchestrationEffectExecutorV2 extends Context.Service<
89 OrchestrationEffectExecutorV2,
90 OrchestrationEffectExecutorV2Shape
91>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectExecutorV2") {}
92
93export const layerExecutor: Layer.Layer<
94 OrchestrationEffectExecutorV2,
95 never,
96 | ProviderSessionManager.ProviderSessionManagerV2
97 | RunFinalizationService.RunFinalizationService
98 | CheckpointRollbackService.CheckpointRollbackServiceV2
99 | ProviderTurnControlService.ProviderTurnControlServiceV2
100 | ProviderTurnStartService.ProviderTurnStartServiceV2
101 | RuntimeRequestService.RuntimeRequestServiceV2
102 | ThreadTitleRegenerationService.ThreadTitleRegenerationService
103 | ThreadManagementService.ThreadManagementService
104 | ProjectionStore.ProjectionStoreV2
105 | ProjectionMaintenance.ProjectionMaintenanceV2
106 | ServerSettings.ServerSettingsService
107> = Layer.effect(
108 OrchestrationEffectExecutorV2,
109 Effect.gen(function* () {
110 const runFinalization = yield* RunFinalizationService.RunFinalizationService;
111 const resourceCleanup = yield* ResourceCleanupService.ResourceCleanupService;
112 const checkpointRollback = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
113 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
114 const providerTurnControl = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
115 const providerTurnStart = yield* ProviderTurnStartService.ProviderTurnStartServiceV2;
116 const runtimeRequests = yield* RuntimeRequestService.RuntimeRequestServiceV2;
117 const threadTitleRegeneration =
118 yield* ThreadTitleRegenerationService.ThreadTitleRegenerationService;
119 const threads = yield* ThreadManagementService.ThreadManagementService;
120 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
121 const projectionMaintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
122 const settings = yield* ServerSettings.ServerSettingsService;
123 const startRun = (
124 effect: EffectOutbox.OrchestrationEffectV2,
125 runId: RunId,
126 willRetry: boolean,
127 ) =>
128 providerTurnStart.start({ threadId: effect.threadId, runId, willRetry }).pipe(
129 Effect.catchCauseIf(
130 (cause) => !willRetry && !Cause.hasInterruptsOnly(cause),
131 (cause) =>
132 Effect.logWarning(
133 "Last run start attempt failed",
134 { effectId: effect.id, effectType: effect.request.type, runId },
135 cause,
136 ).pipe(
137 Effect.andThen(
138 Effect.suspend(() => {
139 const failure = Option.getOrUndefined(Cause.findErrorOption(cause));
140 // A failed read cannot identify the attempt. Keep retry ownership
141 // rather than settling whichever attempt happens to be current.
142 if (
143 !ProviderTurnStartService.isProviderTurnStartError(failure) ||
144 failure.attemptId === undefined ||
145 failure.rootNodeId === undefined
146 ) {
147 return Effect.failCause(cause);
148 }
149 return providerTurnStart.failStartingRun({
150 threadId: effect.threadId,
151 runId,
152 attemptId: failure.attemptId,
153 rootNodeId: failure.rootNodeId,
154 });
155 }),
156 ),
157 ),
158 ),
159 );
160 return OrchestrationEffectExecutorV2.of({
161 execute: Effect.fn("OrchestrationEffectExecutorV2.execute")(function (effect, options) {
162 const willRetry = options?.willRetry ?? false;
163 switch (effect.request.type) {
164 case "provider-runtime.continue": {
165 const sourceRunId = effect.request.sourceRunId;
166 return continueRestartedRun({
167 threadId: effect.threadId,
168 sourceRunId,
169 ...(effect.request.processLossCount === undefined
170 ? {}
171 : { processLossCount: effect.request.processLossCount }),
172 ...(effect.request.cause === undefined ? {} : { cause: effect.request.cause }),
173 }).pipe(
174 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
175 Effect.provideService(ServerSettings.ServerSettingsService, settings),
176 Effect.tapError(() =>
177 willRetry
178 ? Effect.void
179 : threads.recoverDelegatedTask(effect.threadId, { sourceRunId }),
180 ),
181 Effect.mapError(
182 (cause) =>
183 new OrchestrationEffectExecutionError({
184 effectId: effect.id,
185 effectType: effect.request.type,
186 cause,
187 }),
188 ),
189 );
190 }
191 case "provider-session.detach":
192 return providerSessions
193 .detach({
194 providerSessionId: effect.request.providerSessionId,
195 threadId: effect.threadId,
196 ...(effect.request.detail === undefined ? {} : { detail: effect.request.detail }),
197 ...(effect.request.revokeMcpCredential === undefined
198 ? {}
199 : { revokeMcpCredential: effect.request.revokeMcpCredential }),
200 })
201 .pipe(
202 Effect.mapError(
203 (cause) =>
204 new OrchestrationEffectExecutionError({
205 effectId: effect.id,
206 effectType: effect.request.type,
207 cause,
208 }),
209 ),
210 );
211 case "provider-session.apply-model-selection":
212 return providerTurnControl
213 .applyModelSelection({
214 threadId: effect.threadId,
215 providerSessionId: effect.request.providerSessionId,
216 providerThreadId: effect.request.providerThreadId,
217 modelSelection: effect.request.modelSelection,
218 })
219 .pipe(
220 Effect.mapError(
221 (cause) =>
222 new OrchestrationEffectExecutionError({
223 effectId: effect.id,
224 effectType: effect.request.type,
225 cause,
226 }),
227 ),
228 );
229 case "provider-session.apply-thread-title":
230 return providerTurnControl
231 .applyThreadTitle({ threadId: effect.threadId, title: effect.request.title })
232 .pipe(
233 Effect.mapError(
234 (cause) =>
235 new OrchestrationEffectExecutionError({
236 effectId: effect.id,
237 effectType: effect.request.type,
238 cause,
239 }),
240 ),
241 );
242 case "provider-turn.start":
243 return startRun(effect, effect.request.runId, willRetry).pipe(
244 Effect.mapError(
245 (cause) =>
246 new OrchestrationEffectExecutionError({
247 effectId: effect.id,
248 effectType: effect.request.type,
249 cause,
250 }),
251 ),
252 );
253 case "provider-turn.interrupt": {
254 const request = effect.request;
255 return providerTurnControl
256 .interrupt({
257 threadId: effect.threadId,
258 providerSessionId: request.providerSessionId,
259 providerThreadId: request.providerThreadId,
260 providerTurnId: request.providerTurnId,
261 ...(request.subagent === undefined
262 ? {}
263 : {
264 subagent: {
265 ...request.subagent,
266 requestedAt: DateTime.makeUnsafe(effect.createdAt),
267 },
268 }),
269 })
270 .pipe(
271 Effect.tapError((cause) =>
272 request.subagent === undefined
273 ? Effect.void
274 : Effect.logWarning("orchestration-v2.subagent-stop-failed", {
275 effectId: effect.id,
276 cause,
277 }),
278 ),
279 Effect.map((outcome) => ({ unresponsive: false, outcome }) as const),
280 // Settling here would end the run while the agent may still be running; the
281 // user decides with Force stop instead.
282 Effect.catchIf(
283 (cause) => request.subagent === undefined && cause.unresponsive === true,
284 () => Effect.succeed({ unresponsive: true, outcome: undefined } as const),
285 ),
286 Effect.catchIf(
287 (cause) =>
288 request.subagent === undefined &&
289 isNonRetryableProviderTurnControlFailure(
290 request.type,
291 Cause.pretty(Cause.fail(cause)),
292 ),
293 () => Effect.succeed({ unresponsive: false, outcome: undefined } as const),
294 ),
295 Effect.andThen(({ unresponsive, outcome }) =>
296 unresponsive
297 ? threads.dispatch({
298 type: "thread.interrupt.unresponsive",
299 commandId: CommandId.make(`${effect.id}:unresponsive`),
300 threadId: effect.threadId,
301 providerThreadId: request.providerThreadId,
302 providerTurnId: request.providerTurnId,
303 })
304 : request.subagent !== undefined && outcome === undefined
305 ? Effect.void
306 : threads.dispatch({
307 type: "thread.background-work.settle",
308 commandId: CommandId.make(`${effect.id}:background-work-settled`),
309 ...(request.subagent === undefined || outcome === undefined
310 ? {}
311 : {
312 subagent: {
313 id: request.subagent.id,
314 stoppedAt: DateTime.makeUnsafe(effect.createdAt),
315 outcome,
316 },
317 }),
318 threadId: effect.threadId,
319 providerThreadId: request.providerThreadId,
320 providerTurnId: request.providerTurnId,
321 }),
322 ),
323 Effect.mapError(
324 (cause) =>
325 new OrchestrationEffectExecutionError({
326 effectId: effect.id,
327 effectType: request.type,
328 cause,
329 }),
330 ),
331 );
332 }
333 case "provider-turn.steer":
334 return providerTurnControl
335 .steer({
336 threadId: effect.threadId,
337 providerSessionId: effect.request.providerSessionId,
338 providerThreadId: effect.request.providerThreadId,
339 providerTurnId: effect.request.providerTurnId,
340 messageId: effect.request.messageId,
341 ...(effect.request.modelSelection === undefined
342 ? {}
343 : { modelSelection: effect.request.modelSelection }),
344 })
345 .pipe(
346 Effect.tap(() =>
347 Effect.gen(function* () {
348 if (effect.request.type !== "provider-turn.steer") return;
349 const messageId = effect.request.messageId;
350 const projection = yield* threads.getThreadRecords(
351 effect.threadId,
352 ["messages", "runs"],
353 { messageIds: [effect.request.messageId] },
354 );
355 const message = projection.messages.find((row) => row.id === messageId);
356 if (message?.delegatedCompletion === undefined) return;
357 yield* threads.dispatch({
358 type: "notification.delivery.accept",
359 commandId: CommandId.make(`command:mailbox-accepted:${effect.id}`),
360 threadId: effect.threadId,
361 messageId: message.id,
362 });
363 }),
364 ),
365 Effect.catch((error) =>
366 Effect.gen(function* () {
367 if (
368 !isProviderTurnControlError(error) ||
369 (!error.turnCompleted && !error.steerDeclined) ||
370 effect.request.type !== "provider-turn.steer"
371 ) {
372 return yield* error;
373 }
374 const projection = yield* threads.getThreadRecords(
375 effect.threadId,
376 ["messages", "runs"],
377 { messageIds: [effect.request.messageId] },
378 );
379 const messageId = effect.request.messageId;
380 const message = projection.messages.find((item) => item.id === messageId);
381 const run = projection.runs.find((item) => item.id === message?.runId);
382 if (message === undefined || run === undefined) return yield* error;
383 // Notifications must be queued messages.
384 const queued =
385 message.delegatedCompletion !== undefined ||
386 message.notification !== undefined ||
387 error.steerDeclined === true;
388 // Reuse message ids and receipts so retries cannot duplicate messages or follow-ups.
389 yield* threads
390 .dispatch({
391 type: "message.dispatch",
392 commandId: CommandId.make(`command:steer-follow-up:${effect.id}`),
393 threadId: effect.threadId,
394 messageId: message.id,
395 ...(error.steerDeclined ? { steerFollowUpOfRunId: run.id } : {}),
396 ...(effect.request.steerFollowUpAfterRunOrdinal !== undefined
397 ? {
398 steerFollowUpAfterRunOrdinal:
399 effect.request.steerFollowUpAfterRunOrdinal,
400 }
401 : {}),
402 text: message.text,
403 ...(message.context ? { context: message.context } : {}),
404 attachments: message.attachments,
405 ...(error.steerDeclined && effect.request.modelSelection !== undefined
406 ? { modelSelection: effect.request.modelSelection }
407 : message.delegatedCompletion === undefined
408 ? {}
409 : { modelSelection: run.modelSelection }),
410 dispatchMode: {
411 type: queued ? "queue_after_active" : "start_immediately",
412 },
413 createdBy: message.createdBy,
414 creationSource: message.creationSource,
415 ...(message.delegatedCompletion === undefined
416 ? {}
417 : { delegatedCompletion: message.delegatedCompletion }),
418 ...(message.notification === undefined
419 ? {}
420 : { notification: message.notification }),
421 ...(message.scheduledTaskId === undefined
422 ? {}
423 : { scheduledTaskId: message.scheduledTaskId }),
424 ...(message.senderThreadId === undefined
425 ? {}
426 : { senderThreadId: message.senderThreadId }),
427 ...(message.linkedSender === undefined
428 ? {}
429 : { linkedSender: message.linkedSender }),
430 })
431 .pipe(
432 // A disabled instance cannot retry this completed turn; its result stands.
433 Effect.catchTags({
434 ThreadManagementProviderInstanceDisabledError: (disabledError) =>
435 Effect.logInfo(
436 "orchestration-v2.effect-worker.steer-follow-up-disabled",
437 {
438 threadId: effect.threadId,
439 messageId: message.id,
440 projectId: disabledError.projectId,
441 instanceId: disabledError.instanceId,
442 },
443 ),
444 }),
445 );
446 }),
447 ),
448 Effect.mapError(
449 (cause) =>
450 new OrchestrationEffectExecutionError({
451 effectId: effect.id,
452 effectType: effect.request.type,
453 cause,
454 }),
455 ),
456 );
457 case "provider-turn.restart":
458 return providerTurnControl
459 .interruptAndAwaitTerminal({
460 threadId: effect.threadId,
461 providerSessionId: effect.request.providerSessionId,
462 providerThreadId: effect.request.providerThreadId,
463 providerTurnId: effect.request.providerTurnId,
464 interruptedAttemptId: effect.request.interruptedAttemptId,
465 ...(effect.request.sessionTransition?.type === "replace"
466 ? {
467 replacementProviderSessionId:
468 effect.request.sessionTransition.replacementProviderSessionId,
469 }
470 : {}),
471 })
472 .pipe(
473 Effect.andThen(
474 effect.request.sessionTransition?.type === "replace"
475 ? providerSessions.detach({
476 providerSessionId: effect.request.providerSessionId,
477 threadId: effect.threadId,
478 detail: "Selection change requires a provider session restart.",
479 })
480 : effect.request.sessionTransition?.type === "detach"
481 ? providerSessions.detach({
482 providerSessionId: effect.request.providerSessionId,
483 threadId: effect.threadId,
484 detail: "Provider thread handoff replaced this session binding.",
485 })
486 : Effect.void,
487 ),
488 Effect.andThen(
489 // Failed interruption or detach must not report the old process stopped.
490 startRun(effect, effect.request.runId, willRetry),
491 ),
492 Effect.mapError(
493 (cause) =>
494 new OrchestrationEffectExecutionError({
495 effectId: effect.id,
496 effectType: effect.request.type,
497 cause,
498 }),
499 ),
500 );
501 case "runtime-request.respond": {
502 const requestId = effect.request.requestId;
503 return runtimeRequests
504 .respond({
505 threadId: effect.threadId,
506 providerSessionId: effect.request.providerSessionId,
507 requestId: effect.request.requestId,
508 ...(effect.request.decision === undefined
509 ? {}
510 : { decision: effect.request.decision }),
511 ...(effect.request.feedback === undefined
512 ? {}
513 : { feedback: effect.request.feedback }),
514 ...(effect.request.answers === undefined
515 ? {}
516 : { answers: effect.request.answers }),
517 })
518 .pipe(
519 Effect.tapCause((cause) =>
520 willRetry || Cause.hasInterruptsOnly(cause)
521 ? Effect.void
522 : threads
523 .dispatch({
524 type: "runtime-request.delivery.fail",
525 commandId: CommandId.make(`${effect.commandId}:delivery-failed`),
526 threadId: effect.threadId,
527 requestId,
528 })
529 .pipe(
530 Effect.catchCause((recordCause) =>
531 Effect.logWarning("Failed to record answer delivery failure", {
532 effectId: effect.id,
533 cause: recordCause,
534 }),
535 ),
536 ),
537 ),
538 Effect.mapError(
539 (cause) =>
540 new OrchestrationEffectExecutionError({
541 effectId: effect.id,
542 effectType: effect.request.type,
543 cause,
544 }),
545 ),
546 );
547 }
548 case "provider-thread.rollback":
549 return checkpointRollback
550 .execute({
551 threadId: effect.threadId,
552 providerThreadId: effect.request.providerThreadId,
553 checkpointId: effect.request.checkpointId,
554 scopeId: effect.request.scopeId,
555 requestId: effect.commandId,
556 ...(effect.request.restoreFiles === undefined
557 ? {}
558 : { restoreFiles: effect.request.restoreFiles }),
559 })
560 .pipe(
561 Effect.tapCause((cause) =>
562 willRetry || Cause.hasInterruptsOnly(cause)
563 ? Effect.void
564 : threads
565 .dispatch({
566 type: "checkpoint.rollback.fail",
567 commandId: CommandId.make(`${effect.commandId}:rollback-failed`),
568 threadId: effect.threadId,
569 requestId: effect.commandId,
570 message: Option.match(Cause.findErrorOption(cause), {
571 onNone: () => CheckpointRollbackService.ROLLBACK_FAILED_MESSAGE,
572 onSome: CheckpointRollbackService.rollbackFailureClientMessage,
573 }),
574 })
575 .pipe(
576 Effect.catchCause((recordCause) =>
577 Effect.logWarning("Failed to record rollback failure", {
578 effectId: effect.id,
579 cause: recordCause,
580 }),
581 ),
582 ),
583 ),
584 Effect.mapError(
585 (cause) =>
586 new OrchestrationEffectExecutionError({
587 effectId: effect.id,
588 effectType: effect.request.type,
589 cause,
590 }),
591 ),
592 );
593 case "checkpoint.capture":
594 return runFinalization
595 .finalize({
596 threadId: effect.threadId,
597 runId: effect.request.runId,
598 scopeId: effect.request.scopeId,
599 })
600 .pipe(
601 // Completion bookkeeping must survive a missed live run update, including capture retries.
602 Effect.andThen(
603 threads.recoverDelegatedTask(effect.threadId, {
604 completedRunId: effect.request.runId,
605 }),
606 ),
607 Effect.mapError(
608 (cause) =>
609 new OrchestrationEffectExecutionError({
610 effectId: effect.id,
611 effectType: effect.request.type,
612 cause,
613 }),
614 ),
615 );
616 case "scheduled-tasks.cleanup":
617 return resourceCleanup.cleanupScheduledTasks(effect.threadId).pipe(
618 Effect.mapError(
619 (cause) =>
620 new OrchestrationEffectExecutionError({
621 effectId: effect.id,
622 effectType: effect.request.type,
623 cause,
624 }),
625 ),
626 );
627 // Archive and delete queue this one per-thread teardown, so it also releases the
628 // thread's device claims; the devices stay booted for other threads.
629 case "terminal.cleanup":
630 return Effect.partition(
631 [
632 resourceCleanup.cleanupTerminals(effect.threadId),
633 resourceCleanup.cleanupDevices(effect.threadId),
634 ],
635 (cleanup) => cleanup,
636 ).pipe(
637 Effect.flatMap(([, [failure]]) =>
638 failure === undefined ? Effect.void : Effect.fail(failure),
639 ),
640 Effect.mapError(
641 (cause) =>
642 new OrchestrationEffectExecutionError({
643 effectId: effect.id,
644 effectType: effect.request.type,
645 cause,
646 }),
647 ),
648 );
649 case "preview.cleanup":
650 return resourceCleanup.cleanupPreviews(effect.threadId).pipe(
651 Effect.mapError(
652 (cause) =>
653 new OrchestrationEffectExecutionError({
654 effectId: effect.id,
655 effectType: effect.request.type,
656 cause,
657 }),
658 ),
659 );
660 case "attachment.cleanup": {
661 const request = effect.request;
662 return Effect.gen(function* () {
663 // Another message or answer may share the file, or a stale queued edit may restore it.
664 const referenced = new Set(
665 request.skipReferenced
666 ? yield* projectionStore.getThreadAttachmentIds(effect.threadId, {
667 includeShownByLiveFork: true,
668 })
669 : [],
670 );
671 yield* resourceCleanup.cleanupAttachments(
672 request.attachmentIds.filter((id) => !referenced.has(id)),
673 );
674 }).pipe(
675 Effect.mapError(
676 (cause) =>
677 new OrchestrationEffectExecutionError({
678 effectId: effect.id,
679 effectType: effect.request.type,
680 cause,
681 }),
682 ),
683 );
684 }
685 case "thread-content.purge":
686 return projectionMaintenance.purgeDeletedThread(effect.threadId).pipe(
687 Effect.asVoid,
688 Effect.mapError(
689 (cause) =>
690 new OrchestrationEffectExecutionError({
691 effectId: effect.id,
692 effectType: effect.request.type,
693 cause,
694 }),
695 ),
696 );
697 case "thread-title.generate":
698 return threadTitleRegeneration
699 .execute({
700 threadId: effect.threadId,
701 requestId: effect.commandId,
702 kind: effect.request.kind,
703 })
704 .pipe(
705 Effect.mapError(
706 (cause) =>
707 new OrchestrationEffectExecutionError({
708 effectId: effect.id,
709 effectType: effect.request.type,
710 cause,
711 }),
712 ),
713 );
714 case "delegated-tasks.stop":
715 return threads
716 .stopDelegatedTasks({
717 threadId: effect.threadId,
718 commandId: effect.commandId,
719 reason: effect.request.reason,
720 })
721 .pipe(
722 Effect.mapError(
723 (cause) =>
724 new OrchestrationEffectExecutionError({
725 effectId: effect.id,
726 effectType: effect.request.type,
727 cause,
728 }),
729 ),
730 );
731 }
732 }),
733 });
734 }),
735);
736
737// A running effect blocks later work on its thread and its lease is never reclaimed in-process,
738// so a stop that hangs must give up and fall through to the normal retry/fail path.
739const DELEGATED_TASKS_STOP_TIMEOUT = Duration.seconds(30);
740
741const boundExecution =
742 (effect: EffectOutbox.OrchestrationEffectV2) =>
743 (execution: Effect.Effect<void, OrchestrationEffectExecutionError>) =>
744 effect.request.type === "delegated-tasks.stop"
745 ? execution.pipe(
746 Effect.timeoutOrElse({
747 duration: DELEGATED_TASKS_STOP_TIMEOUT,
748 orElse: () =>
749 Effect.fail(
750 new OrchestrationEffectExecutionError({
751 effectId: effect.id,
752 effectType: effect.request.type,
753 cause: `Timed out after ${Duration.format(DELEGATED_TASKS_STOP_TIMEOUT)}.`,
754 }),
755 ),
756 }),
757 )
758 : execution;
759
760export class OrchestrationEffectWorkerError extends Schema.TaggedError<OrchestrationEffectWorkerError>()(
761 "OrchestrationEffectWorkerError",
762 {
763 operation: Schema.String,
764 effectId: Schema.optional(Schema.String),
765 cause: Schema.optional(Schema.Defect()),
766 },
767) {}
768
769const isOrchestrationEffectWorkerError = Schema.is(OrchestrationEffectWorkerError);
770
771// Only the claiming worker settles its row, and a running row blocks every later effect on its
772// thread until the server restarts. onError masks interruption, so retries must restore it.
773const isLockTimeout = (error: EffectOutbox.EffectOutboxError) =>
774 SqlError.isSqlError(error.cause) && error.cause.reason._tag === "LockTimeoutError";
775const lockRetrySchedule = Schedule.spaced(Duration.millis(100));
776const retryWhileLocked = <A>(settlement: Effect.Effect<A, EffectOutbox.EffectOutboxError>) =>
777 Effect.interruptible(
778 Effect.retry(settlement, { schedule: lockRetrySchedule, while: isLockTimeout }),
779 );
780
781type ClaimFilter = Omit<Parameters<EffectOutbox.EffectOutboxV2Shape["claimNext"]>[0], "workerId">;
782
783export interface OrchestrationEffectWorkerV2Shape {
784 readonly awaitWork: Effect.Effect<void>;
785 readonly runOnce: (input?: {
786 readonly maxRunningTitleGenerations?: number;
787 }) => Effect.Effect<boolean, OrchestrationEffectWorkerError>;
788 readonly runRecoveryOnce: Effect.Effect<boolean, OrchestrationEffectWorkerError>;
789 readonly nextClaimableAt: (input?: {
790 readonly maxRunningTitleGenerations?: number;
791 }) => Effect.Effect<Option.Option<DateTime.Utc>, OrchestrationEffectWorkerError>;
792 readonly drain: (maxEffects?: number) => Effect.Effect<number, OrchestrationEffectWorkerError>;
793}
794
795export class OrchestrationEffectWorkerV2 extends Context.Service<
796 OrchestrationEffectWorkerV2,
797 OrchestrationEffectWorkerV2Shape
798>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectWorkerV2") {}
799
800export interface OrchestrationEffectWorkerOptions {
801 readonly workerId?: string;
802 readonly maxAttempts?: number;
803}
804
805export const layerWithOptions = (
806 options: OrchestrationEffectWorkerOptions = {},
807): Layer.Layer<
808 OrchestrationEffectWorkerV2,
809 never,
810 EffectOutbox.EffectOutboxV2 | OrchestrationEffectExecutorV2
811> =>
812 Layer.effect(
813 OrchestrationEffectWorkerV2,
814 Effect.gen(function* () {
815 const outbox = yield* EffectOutbox.EffectOutboxV2;
816 const executor = yield* OrchestrationEffectExecutorV2;
817 const workerId = options.workerId ?? `orchestration-v2:${process.pid}`;
818 const maxAttempts = Math.max(1, options.maxAttempts ?? 5);
819 const wasCancelled = (effectId: string) =>
820 outbox.get(effectId).pipe(
821 Effect.map(
822 Option.match({
823 onNone: () => false,
824 onSome: (effect) => effect.status === "cancelled",
825 }),
826 ),
827 );
828 const requeueClaim = (
829 effect: EffectOutbox.OrchestrationEffectV2,
830 cause: Cause.Cause<unknown>,
831 ) =>
832 Cause.hasInterruptsOnly(cause)
833 ? Effect.void
834 : outbox
835 .retry({
836 effectId: effect.id,
837 workerId,
838 error: `Worker failed before settling the claimed effect: ${Cause.pretty(cause)}`,
839 delayMs: 0,
840 })
841 .pipe(
842 retryWhileLocked,
843 Effect.flatMap((requeued) =>
844 requeued
845 ? Effect.logWarning("Requeued effect after unexpected worker failure", {
846 effectId: effect.id,
847 effectType: effect.request.type,
848 })
849 : Effect.logWarning("Could not requeue effect after worker lost its lease", {
850 effectId: effect.id,
851 effectType: effect.request.type,
852 }),
853 ),
854 Effect.catchCause((requeueCause) =>
855 Effect.logError("Failed to requeue effect after unexpected worker failure", {
856 effectId: effect.id,
857 effectType: effect.request.type,
858 error: Cause.pretty(requeueCause),
859 }),
860 ),
861 );
862 const terminalizeClaim = (
863 effect: EffectOutbox.OrchestrationEffectV2,
864 cause: Cause.Cause<unknown>,
865 ) => {
866 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
867 return outbox
868 .fail({
869 effectId: effect.id,
870 workerId,
871 error: `Worker failed to settle a process-bound effect after execution started: ${Cause.pretty(cause)}`,
872 })
873 .pipe(
874 retryWhileLocked,
875 Effect.flatMap((failed) =>
876 failed
877 ? Effect.logError("Terminalized process-bound effect after settlement failure", {
878 effectId: effect.id,
879 effectType: effect.request.type,
880 })
881 : Effect.logWarning(
882 "Could not terminalize process-bound effect after worker lost its lease",
883 {
884 effectId: effect.id,
885 effectType: effect.request.type,
886 },
887 ),
888 ),
889 Effect.catchCause((failCause) =>
890 Effect.logError(
891 "Failed to terminalize process-bound effect after settlement failure",
892 {
893 effectId: effect.id,
894 effectType: effect.request.type,
895 error: Cause.pretty(failCause),
896 },
897 ),
898 ),
899 );
900 };
901 const recoverPostSuccessSettlement = (
902 effect: EffectOutbox.OrchestrationEffectV2,
903 cause: Cause.Cause<unknown>,
904 ) =>
905 EffectOutbox.REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS.some(
906 (effectType) => effectType === effect.request.type,
907 )
908 ? requeueClaim(effect, cause)
909 : terminalizeClaim(effect, cause);
910
911 // The worker probes for work repeatedly, including when the outbox is empty.
912 const runOnce = Effect.fnUntraced(
913 function* (filter: ClaimFilter = {}) {
914 const claimExit = yield* Effect.exit(outbox.claimNext({ workerId, ...filter }));
915 yield* increment(orchestrationEffectClaimsTotal, {
916 result: Exit.isFailure(claimExit)
917 ? "error"
918 : Option.isNone(claimExit.value)
919 ? "empty"
920 : "claimed",
921 });
922 if (Exit.isFailure(claimExit)) return yield* Effect.failCause(claimExit.cause);
923 const claimed = claimExit.value;
924 if (Option.isNone(claimed)) {
925 return false;
926 }
927 const effect = claimed.value;
928 // Arm cancellation before rereading durable state to close the read-to-registration race.
929 const cancellation = outbox
930 .awaitCancellation(effect.id)
931 .pipe(Effect.as("cancelled" as const));
932 const cancelledBeforeExecution = yield* Effect.gen(function* () {
933 const claimedAt = DateTime.toEpochMillis(yield* DateTime.now);
934 const eligibleAt = Math.max(
935 DateTime.toEpochMillis(DateTime.makeUnsafe(effect.createdAt)),
936 DateTime.toEpochMillis(DateTime.makeUnsafe(effect.availableAt)),
937 );
938 yield* Metric.update(
939 Metric.withAttributes(
940 orchestrationEffectQueueWait,
941 metricAttributes({ effect_type: effect.request.type }),
942 ),
943 Duration.millis(Math.max(0, claimedAt - eligibleAt)),
944 );
945 // Recheck durable cancellation after registering the Deferred; cancellation may have committed after claim.
946 if (yield* wasCancelled(effect.id)) {
947 yield* outbox.clearCancellation(effect.id);
948 return true;
949 }
950 return false;
951 }).pipe(Effect.onError((cause) => requeueClaim(effect, cause)));
952 if (cancelledBeforeExecution) return true;
953
954 const execution = executor
955 .execute(effect, { willRetry: effect.attemptCount < maxAttempts })
956 .pipe(boundExecution(effect), Effect.as("executed" as const));
957 const exit = yield* Effect.exit(Effect.raceFirst(execution, cancellation)).pipe(
958 Effect.ensuring(outbox.clearCancellation(effect.id)),
959 );
960 if (Exit.isSuccess(exit) && exit.value === "cancelled") {
961 return true;
962 }
963 if (Exit.isSuccess(exit)) {
964 return yield* Effect.gen(function* () {
965 const completed = yield* outbox.succeed({ effectId: effect.id, workerId });
966 if (!completed) {
967 if (yield* wasCancelled(effect.id)) return true;
968 return yield* new OrchestrationEffectWorkerError({
969 operation: "complete",
970 effectId: effect.id,
971 cause: "The worker no longer owns the effect lease.",
972 });
973 }
974 return true;
975 }).pipe(Effect.onError((cause) => recoverPostSuccessSettlement(effect, cause)));
976 }
977
978 const error = Cause.pretty(exit.cause);
979 const nonRetryable = isNonRetryableProviderTurnControlFailure(effect.request.type, error);
980 yield* Effect.logWarning("Orchestration effect execution failed", {
981 effectId: effect.id,
982 effectType: effect.request.type,
983 attemptCount: effect.attemptCount,
984 nonRetryable,
985 error,
986 });
987 const updated = nonRetryable
988 ? yield* outbox
989 .succeed({ effectId: effect.id, workerId })
990 .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause)))
991 : effect.attemptCount >= maxAttempts &&
992 (!ownsStartingRun(effect.request.type) || cannotSettleRun(exit.cause))
993 ? yield* outbox
994 .fail({ effectId: effect.id, workerId, error })
995 .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause)))
996 : yield* outbox
997 .retry({
998 effectId: effect.id,
999 workerId,
1000 error,
1001 delayMs: Math.min(30_000, 100 * 2 ** Math.max(0, effect.attemptCount - 1)),
1002 })
1003 .pipe(Effect.onError((cause) => requeueClaim(effect, cause)));
1004 if (!updated) {
1005 if (yield* wasCancelled(effect.id)) return true;
1006 return yield* new OrchestrationEffectWorkerError({
1007 operation: "reschedule",
1008 effectId: effect.id,
1009 cause: "The worker no longer owns the effect lease.",
1010 });
1011 }
1012 return true;
1013 },
1014 (effect, _filter?: ClaimFilter) =>
1015 effect.pipe(
1016 Effect.mapError((cause) =>
1017 isOrchestrationEffectWorkerError(cause)
1018 ? cause
1019 : new OrchestrationEffectWorkerError({ operation: "run", cause }),
1020 ),
1021 ),
1022 );
1023
1024 return OrchestrationEffectWorkerV2.of({
1025 awaitWork: outbox.awaitAvailable,
1026 runOnce,
1027 runRecoveryOnce: runOnce({ excludeRestartContinuations: true }),
1028 // Idle workers poll this; a span per poll would bury useful traces.
1029 nextClaimableAt: Effect.fnUntraced(
1030 function* (input) {
1031 return yield* outbox.nextClaimableAt(input);
1032 },
1033 Effect.mapError(
1034 (cause) =>
1035 new OrchestrationEffectWorkerError({
1036 operation: "next-claimable",
1037 cause,
1038 }),
1039 ),
1040 ),
1041 drain: Effect.fn("EffectWorker.drain")(function* (maxEffects = Number.MAX_SAFE_INTEGER) {
1042 let completed = 0;
1043 while (completed < maxEffects && (yield* runOnce())) {
1044 completed += 1;
1045 }
1046 return completed;
1047 }),
1048 });
1049 }),
1050 );
1051
1052export const layer = layerWithOptions();
1053
1054export interface OrchestrationEffectDaemonOptions {
1055 readonly concurrency?: number;
1056 readonly livenessPollIntervalMs?: number;
1057}
1058
1059const DEFAULT_EFFECT_WORKER_CONCURRENCY = 4;
1060const DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS = 30_000;
1061// A provider request can go unanswered indefinitely. After this wait the slot claims other work
1062// while the execution keeps its running row (which blocks its own thread) and settles it later.
1063const EFFECT_WORKER_SLOT_WAIT = Duration.seconds(30);
1064
1065export const runDaemonWithOptions = (options: OrchestrationEffectDaemonOptions = {}) =>
1066 Effect.scoped(
1067 Effect.gen(function* () {
1068 const worker = yield* OrchestrationEffectWorkerV2;
1069 const scope = yield* Effect.scope;
1070 const requestedConcurrency = options.concurrency ?? DEFAULT_EFFECT_WORKER_CONCURRENCY;
1071 const concurrency = Number.isFinite(requestedConcurrency)
1072 ? Math.max(1, Math.floor(requestedConcurrency))
1073 : DEFAULT_EFFECT_WORKER_CONCURRENCY;
1074 const requestedLivenessPollIntervalMs =
1075 options.livenessPollIntervalMs ?? DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
1076 const livenessPollIntervalMs = Number.isFinite(requestedLivenessPollIntervalMs)
1077 ? Math.max(1, Math.floor(requestedLivenessPollIntervalMs))
1078 : DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
1079 // Title generation can run for minutes; leave at least one worker free for turn work.
1080 const claimLimits = concurrency > 1 ? { maxRunningTitleGenerations: concurrency - 1 } : {};
1081 // Notifications wake promptly; availableAt persists retry timing, and liveness polling recovers missed wakeups.
1082 const runWorker = Effect.gen(function* () {
1083 while (true) {
1084 const attempt = yield* worker.runOnce(claimLimits).pipe(
1085 Effect.map((worked) => (worked ? ("worked" as const) : ("idle" as const))),
1086 Effect.catchCause((cause) =>
1087 Effect.logWarning("Orchestration effect worker failed", cause).pipe(
1088 Effect.as("failed" as const),
1089 ),
1090 ),
1091 Effect.forkIn(scope),
1092 );
1093 const outcome = yield* Fiber.join(attempt).pipe(
1094 Effect.timeoutOption(EFFECT_WORKER_SLOT_WAIT),
1095 Effect.map(Option.getOrElse(() => "worked" as const)),
1096 );
1097 if (outcome === "worked") {
1098 yield* Effect.yieldNow;
1099 continue;
1100 }
1101 if (outcome === "failed") {
1102 // Failed claims can leave overdue rows; cool off instead of rescheduling at the one-millisecond floor.
1103 yield* Effect.sleep(Duration.millis(Math.min(1_000, livenessPollIntervalMs)));
1104 continue;
1105 }
1106
1107 const nextClaimableAt = yield* worker
1108 .nextClaimableAt(claimLimits)
1109 .pipe(
1110 Effect.catchCause((cause) =>
1111 Effect.logWarning(
1112 "Failed to read the next orchestration effect deadline",
1113 cause,
1114 ).pipe(Effect.as(Option.none<DateTime.Utc>())),
1115 ),
1116 );
1117 const now = DateTime.toEpochMillis(yield* DateTime.now);
1118 const sleepMs = Option.match(nextClaimableAt, {
1119 onNone: () => livenessPollIntervalMs,
1120 onSome: (availableAt) => {
1121 const untilAvailable = DateTime.toEpochMillis(availableAt) - now;
1122 return Math.min(livenessPollIntervalMs, untilAvailable > 0 ? untilAvailable : 25);
1123 },
1124 });
1125 yield* Effect.raceFirst(
1126 worker.awaitWork.pipe(Effect.as("notified" as const)),
1127 Effect.sleep(Duration.millis(sleepMs)).pipe(Effect.as("scheduled" as const)),
1128 );
1129 }
1130 });
1131
1132 return yield* Effect.all(
1133 Array.from({ length: concurrency }, () => runWorker),
1134 {
1135 concurrency: "unbounded",
1136 discard: true,
1137 },
1138 );
1139 }),
1140 );
1141
1142export const runDaemon = runDaemonWithOptions();