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

EffectWorker.ts

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