Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

EffectWorker.ts

822 lines34.0 KB

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