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