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

EffectWorker.ts

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