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