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