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

EffectWorker.ts

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