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

EffectWorker.ts

941 lines38.7 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 * Do not apply this to `provider-turn.restart`: that compound effect also runs
43 * detach and start. Swallowing a start failure that happens to mention
44 * "is not active" would drop the outbox item without ever starting the
45 * replacement turn.
46 */
47function isNonRetryableProviderTurnControlFailure(effectType: string, errorText: string): boolean {
48 if (effectType !== "provider-turn.interrupt") {
49 return false;
50 }
51 return (
52 /is not active/i.test(errorText) ||
53 /hard teardown is already in progress/i.test(errorText) ||
54 /treating as already interrupted/i.test(errorText) ||
55 /treating as already stopped/i.test(errorText)
56 );
58​
59export interface OrchestrationEffectExecutorV2Shape {
60 readonly execute: (
61 effect: EffectOutbox.OrchestrationEffectV2,
62 options?: { readonly willRetry: boolean },
63 ) => Effect.Effect<void, OrchestrationEffectExecutionError>;
65​
66export class OrchestrationEffectExecutorV2 extends Context.Service<
67 OrchestrationEffectExecutorV2,
68 OrchestrationEffectExecutorV2Shape
69>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectExecutorV2") {}
70​
71export const layerExecutor: Layer.Layer<
72 OrchestrationEffectExecutorV2,
73 never,
74 | ProviderSessionManager.ProviderSessionManagerV2
75 | RunFinalizationService.RunFinalizationService
76 | CheckpointRollbackService.CheckpointRollbackServiceV2
77 | ProviderTurnControlService.ProviderTurnControlServiceV2
78 | ProviderTurnStartService.ProviderTurnStartServiceV2
79 | RuntimeRequestService.RuntimeRequestServiceV2
80 | ThreadTitleRegenerationService.ThreadTitleRegenerationService
81 | ThreadManagementService.ThreadManagementService
82 | ServerSettings.ServerSettingsService
83> = Layer.effect(
84 OrchestrationEffectExecutorV2,
85 Effect.gen(function* () {
86 const runFinalization = yield* RunFinalizationService.RunFinalizationService;
87 const resourceCleanup = yield* ResourceCleanupService.ResourceCleanupService;
88 const checkpointRollback = yield* CheckpointRollbackService.CheckpointRollbackServiceV2;
89 const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
90 const providerTurnControl = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
91 const providerTurnStart = yield* ProviderTurnStartService.ProviderTurnStartServiceV2;
92 const runtimeRequests = yield* RuntimeRequestService.RuntimeRequestServiceV2;
93 const threadTitleRegeneration =
94 yield* ThreadTitleRegenerationService.ThreadTitleRegenerationService;
95 const threads = yield* ThreadManagementService.ThreadManagementService;
96 const settings = yield* ServerSettings.ServerSettingsService;
97 return OrchestrationEffectExecutorV2.of({
98 execute: Effect.fn("OrchestrationEffectExecutorV2.execute")(function (effect, options) {
99 const willRetry = options?.willRetry ?? false;
100 switch (effect.request.type) {
101 case "provider-runtime.continue": {
102 const sourceRunId = effect.request.sourceRunId;
103 return continueRestartedRun({ threadId: effect.threadId, sourceRunId }).pipe(
104 Effect.provideService(ThreadManagementService.ThreadManagementService, threads),
105 Effect.provideService(ServerSettings.ServerSettingsService, settings),
106 Effect.tapError(() =>
107 willRetry
108 ? Effect.void
109 : threads.recoverDelegatedTask(effect.threadId, sourceRunId),
110 ),
111 Effect.mapError(
112 (cause) =>
113 new OrchestrationEffectExecutionError({
114 effectId: effect.id,
115 effectType: effect.request.type,
116 cause,
117 }),
118 ),
119 );
120 }
121 case "provider-session.detach":
122 return providerSessions
123 .detach({
124 providerSessionId: effect.request.providerSessionId,
125 threadId: effect.threadId,
126 ...(effect.request.detail === undefined ? {} : { detail: effect.request.detail }),
127 ...(effect.request.revokeMcpCredential === undefined
128 ? {}
129 : { revokeMcpCredential: effect.request.revokeMcpCredential }),
130 })
131 .pipe(
132 Effect.mapError(
133 (cause) =>
134 new OrchestrationEffectExecutionError({
135 effectId: effect.id,
136 effectType: effect.request.type,
137 cause,
138 }),
139 ),
140 );
141 case "provider-turn.start":
142 return providerTurnStart
143 .start({ threadId: effect.threadId, runId: effect.request.runId, willRetry })
144 .pipe(
145 Effect.mapError(
146 (cause) =>
147 new OrchestrationEffectExecutionError({
148 effectId: effect.id,
149 effectType: effect.request.type,
150 cause,
151 }),
152 ),
153 );
154 case "provider-turn.interrupt": {
155 const request = effect.request;
156 return providerTurnControl
157 .interrupt({
158 threadId: effect.threadId,
159 providerSessionId: request.providerSessionId,
160 providerThreadId: request.providerThreadId,
161 providerTurnId: request.providerTurnId,
162 ...(request.subagent === undefined
163 ? {}
164 : {
165 subagent: {
166 ...request.subagent,
167 requestedAt: DateTime.makeUnsafe(effect.createdAt),
168 },
169 }),
170 })
171 .pipe(
172 Effect.tapError((cause) =>
173 request.subagent === undefined
174 ? Effect.void
175 : Effect.logWarning("orchestration-v2.subagent-stop-failed", {
176 effectId: effect.id,
177 cause,
178 }),
179 ),
180 Effect.catchIf(
181 (cause) =>
182 request.subagent === undefined &&
183 isNonRetryableProviderTurnControlFailure(
184 request.type,
185 Cause.pretty(Cause.fail(cause)),
186 ),
187 () => Effect.void,
188 ),
189 Effect.andThen((outcome) =>
190 request.subagent !== undefined && outcome === undefined
191 ? Effect.void
192 : threads.dispatch({
193 type: "thread.background-work.settle",
194 commandId: CommandId.make(`${effect.id}:background-work-settled`),
195 ...(request.subagent === undefined || outcome === undefined
196 ? {}
197 : {
198 subagent: {
199 id: request.subagent.id,
200 stoppedAt: DateTime.makeUnsafe(effect.createdAt),
201 outcome,
202 },
203 }),
204 threadId: effect.threadId,
205 providerThreadId: request.providerThreadId,
206 providerTurnId: request.providerTurnId,
207 }),
208 ),
209 Effect.mapError(
210 (cause) =>
211 new OrchestrationEffectExecutionError({
212 effectId: effect.id,
213 effectType: request.type,
214 cause,
215 }),
216 ),
217 );
218 }
219 case "provider-turn.steer":
220 return providerTurnControl
221 .steer({
222 threadId: effect.threadId,
223 providerSessionId: effect.request.providerSessionId,
224 providerThreadId: effect.request.providerThreadId,
225 providerTurnId: effect.request.providerTurnId,
226 messageId: effect.request.messageId,
227 })
228 .pipe(
229 Effect.tap(() =>
230 Effect.gen(function* () {
231 if (effect.request.type !== "provider-turn.steer") return;
232 const messageId = effect.request.messageId;
233 const projection = yield* threads.getThreadRecords(
234 effect.threadId,
235 ["messages", "runs"],
236 { messageIds: [effect.request.messageId] },
237 );
238 const message = projection.messages.find((row) => row.id === messageId);
239 if (message?.delegatedCompletion === undefined) return;
240 yield* threads.dispatch({
241 type: "notification.delivery.accept",
242 commandId: CommandId.make(`command:mailbox-accepted:${effect.id}`),
243 threadId: effect.threadId,
244 messageId: message.id,
245 });
246 }),
247 ),
248 Effect.catch((error) =>
249 Effect.gen(function* () {
250 if (
251 !("turnCompleted" in error) ||
252 !error.turnCompleted ||
253 effect.request.type !== "provider-turn.steer"
254 ) {
255 return yield* error;
256 }
257 const projection = yield* threads.getThreadRecords(
258 effect.threadId,
259 ["messages", "runs"],
260 { messageIds: [effect.request.messageId] },
261 );
262 const messageId = effect.request.messageId;
263 const message = projection.messages.find((item) => item.id === messageId);
264 const run = projection.runs.find((item) => item.id === message?.runId);
265 if (message === undefined || run === undefined) return yield* error;
266 // Reuse message ids and receipts so retries cannot duplicate messages or follow-ups.
267 yield* threads
268 .dispatch({
269 type: "message.dispatch",
270 commandId: CommandId.make(`command:steer-follow-up:${effect.id}`),
271 threadId: effect.threadId,
272 messageId: message.id,
273 text: message.text,
274 ...(message.context ? { context: message.context } : {}),
275 attachments: message.attachments,
276 ...(message.delegatedCompletion === undefined
277 ? {}
278 : { modelSelection: run.modelSelection }),
279 dispatchMode: {
280 type:
281 message.delegatedCompletion === undefined
282 ? "start_immediately"
283 : "queue_after_active",
284 },
285 createdBy: message.createdBy,
286 creationSource: message.creationSource,
287 ...(message.delegatedCompletion === undefined
288 ? {}
289 : { delegatedCompletion: message.delegatedCompletion }),
290 ...(message.notification === undefined
291 ? {}
292 : { notification: message.notification }),
293 ...(message.scheduledTaskId === undefined
294 ? {}
295 : { scheduledTaskId: message.scheduledTaskId }),
296 ...(message.senderThreadId === undefined
297 ? {}
298 : { senderThreadId: message.senderThreadId }),
299 })
300 .pipe(
301 // A disabled instance cannot retry this completed turn; its result stands.
302 Effect.catchTags({
303 ThreadManagementProviderInstanceDisabledError: (disabledError) =>
304 Effect.logInfo(
305 "orchestration-v2.effect-worker.steer-follow-up-disabled",
306 {
307 threadId: effect.threadId,
308 messageId: message.id,
309 projectId: disabledError.projectId,
310 instanceId: disabledError.instanceId,
311 },
312 ),
313 }),
314 );
315 }),
316 ),
317 Effect.mapError(
318 (cause) =>
319 new OrchestrationEffectExecutionError({
320 effectId: effect.id,
321 effectType: effect.request.type,
322 cause,
323 }),
324 ),
325 );
326 case "provider-turn.restart":
327 return providerTurnControl
328 .interruptAndAwaitTerminal({
329 threadId: effect.threadId,
330 providerSessionId: effect.request.providerSessionId,
331 providerThreadId: effect.request.providerThreadId,
332 providerTurnId: effect.request.providerTurnId,
333 interruptedAttemptId: effect.request.interruptedAttemptId,
334 ...(effect.request.sessionTransition?.type === "replace"
335 ? {
336 replacementProviderSessionId:
337 effect.request.sessionTransition.replacementProviderSessionId,
338 }
339 : {}),
340 })
341 .pipe(
342 Effect.andThen(
343 effect.request.sessionTransition?.type === "replace"
344 ? providerSessions.detach({
345 providerSessionId: effect.request.providerSessionId,
346 threadId: effect.threadId,
347 detail: "Selection change requires a provider session restart.",
348 })
349 : effect.request.sessionTransition?.type === "detach"
350 ? providerSessions.detach({
351 providerSessionId: effect.request.providerSessionId,
352 threadId: effect.threadId,
353 detail: "Provider thread handoff replaced this session binding.",
354 })
355 : Effect.void,
356 ),
357 Effect.andThen(
358 providerTurnStart.start({
359 threadId: effect.threadId,
360 runId: effect.request.runId,
361 willRetry,
362 }),
363 ),
364 Effect.mapError(
365 (cause) =>
366 new OrchestrationEffectExecutionError({
367 effectId: effect.id,
368 effectType: effect.request.type,
369 cause,
370 }),
371 ),
372 );
373 case "runtime-request.respond": {
374 const requestId = effect.request.requestId;
375 return runtimeRequests
376 .respond({
377 threadId: effect.threadId,
378 providerSessionId: effect.request.providerSessionId,
379 requestId: effect.request.requestId,
380 ...(effect.request.decision === undefined
381 ? {}
382 : { decision: effect.request.decision }),
383 ...(effect.request.feedback === undefined
384 ? {}
385 : { feedback: effect.request.feedback }),
386 ...(effect.request.answers === undefined
387 ? {}
388 : { answers: effect.request.answers }),
389 })
390 .pipe(
391 Effect.tapCause((cause) =>
392 willRetry || Cause.hasInterruptsOnly(cause)
393 ? Effect.void
394 : threads
395 .dispatch({
396 type: "runtime-request.delivery.fail",
397 commandId: CommandId.make(`${effect.commandId}:delivery-failed`),
398 threadId: effect.threadId,
399 requestId,
400 })
401 .pipe(
402 Effect.catchCause((recordCause) =>
403 Effect.logWarning("Failed to record answer delivery failure", {
404 effectId: effect.id,
405 cause: recordCause,
406 }),
407 ),
408 ),
409 ),
410 Effect.mapError(
411 (cause) =>
412 new OrchestrationEffectExecutionError({
413 effectId: effect.id,
414 effectType: effect.request.type,
415 cause,
416 }),
417 ),
418 );
419 }
420 case "provider-thread.rollback":
421 return checkpointRollback
422 .execute({
423 threadId: effect.threadId,
424 providerThreadId: effect.request.providerThreadId,
425 checkpointId: effect.request.checkpointId,
426 scopeId: effect.request.scopeId,
427 ...(effect.request.restoreFiles === undefined
428 ? {}
429 : { restoreFiles: effect.request.restoreFiles }),
430 })
431 .pipe(
432 Effect.tapCause((cause) =>
433 willRetry || Cause.hasInterruptsOnly(cause)
434 ? Effect.void
435 : threads
436 .dispatch({
437 type: "checkpoint.rollback.fail",
438 commandId: CommandId.make(`${effect.commandId}:rollback-failed`),
439 threadId: effect.threadId,
440 requestId: effect.commandId,
441 message: Option.match(Cause.findErrorOption(cause), {
442 onNone: () => CheckpointRollbackService.ROLLBACK_FAILED_MESSAGE,
443 onSome: CheckpointRollbackService.rollbackFailureClientMessage,
444 }),
445 })
446 .pipe(
447 Effect.catchCause((recordCause) =>
448 Effect.logWarning("Failed to record rollback failure", {
449 effectId: effect.id,
450 cause: recordCause,
451 }),
452 ),
453 ),
454 ),
455 Effect.mapError(
456 (cause) =>
457 new OrchestrationEffectExecutionError({
458 effectId: effect.id,
459 effectType: effect.request.type,
460 cause,
461 }),
462 ),
463 );
464 case "checkpoint.capture":
465 return runFinalization
466 .finalize({
467 threadId: effect.threadId,
468 runId: effect.request.runId,
469 scopeId: effect.request.scopeId,
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 "scheduled-tasks.cleanup":
482 return resourceCleanup.cleanupScheduledTasks(effect.threadId).pipe(
483 Effect.mapError(
484 (cause) =>
485 new OrchestrationEffectExecutionError({
486 effectId: effect.id,
487 effectType: effect.request.type,
488 cause,
489 }),
490 ),
491 );
492 case "terminal.cleanup":
493 return resourceCleanup.cleanupTerminals(effect.threadId).pipe(
494 Effect.mapError(
495 (cause) =>
496 new OrchestrationEffectExecutionError({
497 effectId: effect.id,
498 effectType: effect.request.type,
499 cause,
500 }),
501 ),
502 );
503 case "preview.cleanup":
504 return resourceCleanup.cleanupPreviews(effect.threadId).pipe(
505 Effect.mapError(
506 (cause) =>
507 new OrchestrationEffectExecutionError({
508 effectId: effect.id,
509 effectType: effect.request.type,
510 cause,
511 }),
512 ),
513 );
514 case "attachment.cleanup":
515 return resourceCleanup.cleanupAttachments(effect.request.attachmentIds).pipe(
516 Effect.mapError(
517 (cause) =>
518 new OrchestrationEffectExecutionError({
519 effectId: effect.id,
520 effectType: effect.request.type,
521 cause,
522 }),
523 ),
524 );
525 case "thread-title.generate":
526 return threadTitleRegeneration
527 .execute({
528 threadId: effect.threadId,
529 requestId: effect.commandId,
530 kind: effect.request.kind,
531 })
532 .pipe(
533 Effect.mapError(
534 (cause) =>
535 new OrchestrationEffectExecutionError({
536 effectId: effect.id,
537 effectType: effect.request.type,
538 cause,
539 }),
540 ),
541 );
542 case "delegated-tasks.stop":
543 return threads
544 .stopDelegatedTasks({
545 threadId: effect.threadId,
546 commandId: effect.commandId,
547 reason: effect.request.reason,
548 })
549 .pipe(
550 Effect.mapError(
551 (cause) =>
552 new OrchestrationEffectExecutionError({
553 effectId: effect.id,
554 effectType: effect.request.type,
555 cause,
556 }),
557 ),
558 );
559 }
560 }),
561 });
562 }),
563);
564​
565// A running effect blocks later work on its thread and its lease is never reclaimed in-process,
566// so a stop that hangs must give up and fall through to the normal retry/fail path.
567const DELEGATED_TASKS_STOP_TIMEOUT = Duration.seconds(30);
568​
569const boundExecution =
570 (effect: EffectOutbox.OrchestrationEffectV2) =>
571 (execution: Effect.Effect<void, OrchestrationEffectExecutionError>) =>
572 effect.request.type === "delegated-tasks.stop"
573 ? execution.pipe(
574 Effect.timeoutOrElse({
575 duration: DELEGATED_TASKS_STOP_TIMEOUT,
576 orElse: () =>
577 Effect.fail(
578 new OrchestrationEffectExecutionError({
579 effectId: effect.id,
580 effectType: effect.request.type,
581 cause: `Timed out after ${Duration.format(DELEGATED_TASKS_STOP_TIMEOUT)}.`,
582 }),
583 ),
584 }),
585 )
586 : execution;
587​
588export class OrchestrationEffectWorkerError extends Schema.TaggedError<OrchestrationEffectWorkerError>()(
589 "OrchestrationEffectWorkerError",
590 {
591 operation: Schema.String,
592 effectId: Schema.optional(Schema.String),
593 cause: Schema.optional(Schema.Defect()),
594 },
595) {}
596​
597const isOrchestrationEffectWorkerError = Schema.is(OrchestrationEffectWorkerError);
598​
599export interface OrchestrationEffectWorkerV2Shape {
600 readonly awaitWork: Effect.Effect<void>;
601 readonly runOnce: Effect.Effect<boolean, OrchestrationEffectWorkerError>;
602 readonly runRecoveryOnce: Effect.Effect<boolean, OrchestrationEffectWorkerError>;
603 readonly nextClaimableAt: Effect.Effect<
604 Option.Option<DateTime.Utc>,
605 OrchestrationEffectWorkerError
606 >;
607 readonly drain: (maxEffects?: number) => Effect.Effect<number, OrchestrationEffectWorkerError>;
609​
610export class OrchestrationEffectWorkerV2 extends Context.Service<
611 OrchestrationEffectWorkerV2,
612 OrchestrationEffectWorkerV2Shape
613>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectWorkerV2") {}
614​
615export interface OrchestrationEffectWorkerOptions {
616 readonly workerId?: string;
617 readonly leaseDurationMs?: number;
618 readonly maxAttempts?: number;
620​
621export const layerWithOptions = (
622 options: OrchestrationEffectWorkerOptions = {},
623): Layer.Layer<
624 OrchestrationEffectWorkerV2,
625 never,
626 EffectOutbox.EffectOutboxV2 | OrchestrationEffectExecutorV2
627> =>
628 Layer.effect(
629 OrchestrationEffectWorkerV2,
630 Effect.gen(function* () {
631 const outbox = yield* EffectOutbox.EffectOutboxV2;
632 const executor = yield* OrchestrationEffectExecutorV2;
633 const workerId = options.workerId ?? `orchestration-v2:${process.pid}`;
634 const leaseDurationMs = Math.max(1, options.leaseDurationMs ?? 30_000);
635 const maxAttempts = Math.max(1, options.maxAttempts ?? 5);
636 const wasCancelled = (effectId: string) =>
637 outbox.get(effectId).pipe(
638 Effect.map(
639 Option.match({
640 onNone: () => false,
641 onSome: (effect) => effect.status === "cancelled",
642 }),
643 ),
644 );
645 const requeueClaim = (
646 effect: EffectOutbox.OrchestrationEffectV2,
647 cause: Cause.Cause<unknown>,
648 ) =>
649 Cause.hasInterruptsOnly(cause)
650 ? Effect.void
651 : outbox
652 .retry({
653 effectId: effect.id,
654 workerId,
655 error: `Worker failed before settling the claimed effect: ${Cause.pretty(cause)}`,
656 delayMs: 0,
657 })
658 .pipe(
659 Effect.flatMap((requeued) =>
660 requeued
661 ? Effect.logWarning("Requeued effect after unexpected worker failure", {
662 effectId: effect.id,
663 effectType: effect.request.type,
664 })
665 : Effect.logWarning("Could not requeue effect after worker lost its lease", {
666 effectId: effect.id,
667 effectType: effect.request.type,
668 }),
669 ),
670 Effect.catchCause((requeueCause) =>
671 Effect.logError("Failed to requeue effect after unexpected worker failure", {
672 effectId: effect.id,
673 effectType: effect.request.type,
674 error: Cause.pretty(requeueCause),
675 }),
676 ),
677 );
678 const terminalizeClaim = (
679 effect: EffectOutbox.OrchestrationEffectV2,
680 cause: Cause.Cause<unknown>,
681 ) => {
682 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
683 return outbox
684 .fail({
685 effectId: effect.id,
686 workerId,
687 error: `Worker failed to settle a process-bound effect after execution started: ${Cause.pretty(cause)}`,
688 })
689 .pipe(
690 Effect.flatMap((failed) =>
691 failed
692 ? Effect.logError("Terminalized process-bound effect after settlement failure", {
693 effectId: effect.id,
694 effectType: effect.request.type,
695 })
696 : Effect.logWarning(
697 "Could not terminalize process-bound effect after worker lost its lease",
698 {
699 effectId: effect.id,
700 effectType: effect.request.type,
701 },
702 ),
703 ),
704 Effect.catchCause((failCause) =>
705 Effect.logError(
706 "Failed to terminalize process-bound effect after settlement failure",
707 {
708 effectId: effect.id,
709 effectType: effect.request.type,
710 error: Cause.pretty(failCause),
711 },
712 ),
713 ),
714 );
715 };
716 const recoverPostSuccessSettlement = (
717 effect: EffectOutbox.OrchestrationEffectV2,
718 cause: Cause.Cause<unknown>,
719 ) =>
720 EffectOutbox.REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS.some(
721 (effectType) => effectType === effect.request.type,
722 )
723 ? requeueClaim(effect, cause)
724 : terminalizeClaim(effect, cause);
725​
726 // The worker probes for work repeatedly, including when the outbox is empty.
727 const runOnce = Effect.fnUntraced(
728 function* (excludeRestartContinuations = false) {
729 const claimExit = yield* Effect.exit(
730 outbox.claimNext({ workerId, leaseDurationMs, excludeRestartContinuations }),
731 );
732 yield* increment(orchestrationEffectClaimsTotal, {
733 result: Exit.isFailure(claimExit)
734 ? "error"
735 : Option.isNone(claimExit.value)
736 ? "empty"
737 : "claimed",
738 });
739 if (Exit.isFailure(claimExit)) return yield* Effect.failCause(claimExit.cause);
740 const claimed = claimExit.value;
741 if (Option.isNone(claimed)) {
742 return false;
743 }
744 const effect = claimed.value;
745 // Arm cancellation before rereading durable state to close the read-to-registration race.
746 const cancellation = outbox
747 .awaitCancellation(effect.id)
748 .pipe(Effect.as("cancelled" as const));
749 const cancelledBeforeExecution = yield* Effect.gen(function* () {
750 const claimedAt = DateTime.toEpochMillis(yield* DateTime.now);
751 const eligibleAt = Math.max(
752 DateTime.toEpochMillis(DateTime.makeUnsafe(effect.createdAt)),
753 DateTime.toEpochMillis(DateTime.makeUnsafe(effect.availableAt)),
754 );
755 yield* Metric.update(
756 Metric.withAttributes(
757 orchestrationEffectQueueWait,
758 metricAttributes({ effect_type: effect.request.type }),
759 ),
760 Duration.millis(Math.max(0, claimedAt - eligibleAt)),
761 );
762 // Recheck durable cancellation after registering the Deferred; cancellation may have committed after claim.
763 if (yield* wasCancelled(effect.id)) {
764 yield* outbox.clearCancellation(effect.id);
765 return true;
766 }
767 return false;
768 }).pipe(Effect.onError((cause) => requeueClaim(effect, cause)));
769 if (cancelledBeforeExecution) return true;
770​
771 const execution = executor
772 .execute(effect, { willRetry: effect.attemptCount < maxAttempts })
773 .pipe(boundExecution(effect), Effect.as("executed" as const));
774 const exit = yield* Effect.exit(Effect.raceFirst(execution, cancellation)).pipe(
775 Effect.ensuring(outbox.clearCancellation(effect.id)),
776 );
777 if (Exit.isSuccess(exit) && exit.value === "cancelled") {
778 return true;
779 }
780 if (Exit.isSuccess(exit)) {
781 return yield* Effect.gen(function* () {
782 const completed = yield* outbox.succeed({ effectId: effect.id, workerId });
783 if (!completed) {
784 if (yield* wasCancelled(effect.id)) return true;
785 return yield* new OrchestrationEffectWorkerError({
786 operation: "complete",
787 effectId: effect.id,
788 cause: "The worker no longer owns the effect lease.",
789 });
790 }
791 return true;
792 }).pipe(Effect.onError((cause) => recoverPostSuccessSettlement(effect, cause)));
793 }
794​
795 const error = Cause.pretty(exit.cause);
796 const nonRetryable = isNonRetryableProviderTurnControlFailure(effect.request.type, error);
797 yield* Effect.logWarning("Orchestration effect execution failed", {
798 effectId: effect.id,
799 effectType: effect.request.type,
800 attemptCount: effect.attemptCount,
801 nonRetryable,
802 error,
803 });
804 const updated = nonRetryable
805 ? yield* outbox
806 .succeed({ effectId: effect.id, workerId })
807 .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause)))
808 : effect.attemptCount >= maxAttempts
809 ? yield* outbox
810 .fail({ effectId: effect.id, workerId, error })
811 .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause)))
812 : yield* outbox
813 .retry({
814 effectId: effect.id,
815 workerId,
816 error,
817 delayMs: Math.min(30_000, 100 * 2 ** Math.max(0, effect.attemptCount - 1)),
818 })
819 .pipe(Effect.onError((cause) => requeueClaim(effect, cause)));
820 if (!updated) {
821 if (yield* wasCancelled(effect.id)) return true;
822 return yield* new OrchestrationEffectWorkerError({
823 operation: "reschedule",
824 effectId: effect.id,
825 cause: "The worker no longer owns the effect lease.",
826 });
827 }
828 return true;
829 },
830 (effect, _excludeRestartContinuations?: boolean) =>
831 effect.pipe(
832 Effect.mapError((cause) =>
833 isOrchestrationEffectWorkerError(cause)
834 ? cause
835 : new OrchestrationEffectWorkerError({ operation: "run", cause }),
836 ),
837 ),
838 );
839​
840 return OrchestrationEffectWorkerV2.of({
841 awaitWork: outbox.awaitAvailable,
842 runOnce: runOnce(),
843 runRecoveryOnce: runOnce(true),
844 nextClaimableAt: outbox.nextClaimableAt.pipe(
845 Effect.mapError(
846 (cause) =>
847 new OrchestrationEffectWorkerError({
848 operation: "next-claimable",
849 cause,
850 }),
851 ),
852 ),
853 drain: Effect.fn("EffectWorker.drain")(function* (maxEffects = Number.MAX_SAFE_INTEGER) {
854 let completed = 0;
855 while (completed < maxEffects && (yield* runOnce())) {
856 completed += 1;
857 }
858 return completed;
859 }),
860 });
861 }),
862 );
863​
864export const layer = layerWithOptions();
865​
866export interface OrchestrationEffectDaemonOptions {
867 readonly concurrency?: number;
868 readonly livenessPollIntervalMs?: number;
870​
871const DEFAULT_EFFECT_WORKER_CONCURRENCY = 4;
872const DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS = 30_000;
873​
874export const runDaemonWithOptions = (options: OrchestrationEffectDaemonOptions = {}) =>
875 Effect.scoped(
876 Effect.gen(function* () {
877 const worker = yield* OrchestrationEffectWorkerV2;
878 const requestedConcurrency = options.concurrency ?? DEFAULT_EFFECT_WORKER_CONCURRENCY;
879 const concurrency = Number.isFinite(requestedConcurrency)
880 ? Math.max(1, Math.floor(requestedConcurrency))
881 : DEFAULT_EFFECT_WORKER_CONCURRENCY;
882 const requestedLivenessPollIntervalMs =
883 options.livenessPollIntervalMs ?? DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
884 const livenessPollIntervalMs = Number.isFinite(requestedLivenessPollIntervalMs)
885 ? Math.max(1, Math.floor(requestedLivenessPollIntervalMs))
886 : DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
887 // Notifications wake promptly; availableAt persists retry timing, and liveness polling recovers missed wakeups.
888 const runWorker = Effect.gen(function* () {
889 while (true) {
890 const outcome = yield* worker.runOnce.pipe(
891 Effect.map((worked) => (worked ? ("worked" as const) : ("idle" as const))),
892 Effect.catchCause((cause) =>
893 Effect.logWarning("Orchestration effect worker failed", cause).pipe(
894 Effect.as("failed" as const),
895 ),
896 ),
897 );
898 if (outcome === "worked") {
899 yield* Effect.yieldNow;
900 continue;
901 }
902 if (outcome === "failed") {
903 // Failed claims can leave overdue rows; cool off instead of rescheduling at the one-millisecond floor.
904 yield* Effect.sleep(Duration.millis(Math.min(1_000, livenessPollIntervalMs)));
905 continue;
906 }
907​
908 const nextClaimableAt = yield* worker.nextClaimableAt.pipe(
909 Effect.catchCause((cause) =>
910 Effect.logWarning(
911 "Failed to read the next orchestration effect deadline",
912 cause,
913 ).pipe(Effect.as(Option.none<DateTime.Utc>())),
914 ),
915 );
916 const now = DateTime.toEpochMillis(yield* DateTime.now);
917 const sleepMs = Option.match(nextClaimableAt, {
918 onNone: () => livenessPollIntervalMs,
919 onSome: (availableAt) => {
920 const untilAvailable = DateTime.toEpochMillis(availableAt) - now;
921 return Math.min(livenessPollIntervalMs, untilAvailable > 0 ? untilAvailable : 25);
922 },
923 });
924 yield* Effect.raceFirst(
925 worker.awaitWork.pipe(Effect.as("notified" as const)),
926 Effect.sleep(Duration.millis(sleepMs)).pipe(Effect.as("scheduled" as const)),
927 );
928 }
929 });
930​
931 return yield* Effect.all(
932 Array.from({ length: concurrency }, () => runWorker),
933 {
934 concurrency: "unbounded",
935 discard: true,
936 },
937 );
938 }),
939 );
940​
941export const runDaemon = runDaemonWithOptions();