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