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