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