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

EffectWorker.ts

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