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