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