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