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

EffectWorker.ts

918 lines37.8 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, 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.catch((cause) =>
181 request.subagent === undefined &&
182 isNonRetryableProviderTurnControlFailure(
183 request.type,
184 Cause.pretty(Cause.fail(cause)),
185 )
186 ? Effect.void
187 : Effect.fail(cause),
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​
565export class OrchestrationEffectWorkerError extends Schema.TaggedError<OrchestrationEffectWorkerError>()(
566 "OrchestrationEffectWorkerError",
567 {
568 operation: Schema.String,
569 effectId: Schema.optional(Schema.String),
570 cause: Schema.optional(Schema.Defect()),
571 },
572) {}
573​
574const isOrchestrationEffectWorkerError = Schema.is(OrchestrationEffectWorkerError);
575​
576export interface OrchestrationEffectWorkerV2Shape {
577 readonly awaitWork: Effect.Effect<void>;
578 readonly runOnce: Effect.Effect<boolean, OrchestrationEffectWorkerError>;
579 readonly runRecoveryOnce: Effect.Effect<boolean, OrchestrationEffectWorkerError>;
580 readonly nextClaimableAt: Effect.Effect<
581 Option.Option<DateTime.Utc>,
582 OrchestrationEffectWorkerError
583 >;
584 readonly drain: (maxEffects?: number) => Effect.Effect<number, OrchestrationEffectWorkerError>;
586​
587export class OrchestrationEffectWorkerV2 extends Context.Service<
588 OrchestrationEffectWorkerV2,
589 OrchestrationEffectWorkerV2Shape
590>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectWorkerV2") {}
591​
592export interface OrchestrationEffectWorkerOptions {
593 readonly workerId?: string;
594 readonly leaseDurationMs?: number;
595 readonly maxAttempts?: number;
597​
598export const layerWithOptions = (
599 options: OrchestrationEffectWorkerOptions = {},
600): Layer.Layer<
601 OrchestrationEffectWorkerV2,
602 never,
603 EffectOutbox.EffectOutboxV2 | OrchestrationEffectExecutorV2
604> =>
605 Layer.effect(
606 OrchestrationEffectWorkerV2,
607 Effect.gen(function* () {
608 const outbox = yield* EffectOutbox.EffectOutboxV2;
609 const executor = yield* OrchestrationEffectExecutorV2;
610 const workerId = options.workerId ?? `orchestration-v2:${process.pid}`;
611 const leaseDurationMs = Math.max(1, options.leaseDurationMs ?? 30_000);
612 const maxAttempts = Math.max(1, options.maxAttempts ?? 5);
613 const wasCancelled = (effectId: string) =>
614 outbox.get(effectId).pipe(
615 Effect.map(
616 Option.match({
617 onNone: () => false,
618 onSome: (effect) => effect.status === "cancelled",
619 }),
620 ),
621 );
622 const requeueClaim = (
623 effect: EffectOutbox.OrchestrationEffectV2,
624 cause: Cause.Cause<unknown>,
625 ) =>
626 Cause.hasInterruptsOnly(cause)
627 ? Effect.void
628 : outbox
629 .retry({
630 effectId: effect.id,
631 workerId,
632 error: `Worker failed before settling the claimed effect: ${Cause.pretty(cause)}`,
633 delayMs: 0,
634 })
635 .pipe(
636 Effect.flatMap((requeued) =>
637 requeued
638 ? Effect.logWarning("Requeued effect after unexpected worker failure", {
639 effectId: effect.id,
640 effectType: effect.request.type,
641 })
642 : Effect.logWarning("Could not requeue effect after worker lost its lease", {
643 effectId: effect.id,
644 effectType: effect.request.type,
645 }),
646 ),
647 Effect.catchCause((requeueCause) =>
648 Effect.logError("Failed to requeue effect after unexpected worker failure", {
649 effectId: effect.id,
650 effectType: effect.request.type,
651 error: Cause.pretty(requeueCause),
652 }),
653 ),
654 );
655 const terminalizeClaim = (
656 effect: EffectOutbox.OrchestrationEffectV2,
657 cause: Cause.Cause<unknown>,
658 ) => {
659 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
660 return outbox
661 .fail({
662 effectId: effect.id,
663 workerId,
664 error: `Worker failed to settle a process-bound effect after execution started: ${Cause.pretty(cause)}`,
665 })
666 .pipe(
667 Effect.flatMap((failed) =>
668 failed
669 ? Effect.logError("Terminalized process-bound effect after settlement failure", {
670 effectId: effect.id,
671 effectType: effect.request.type,
672 })
673 : Effect.logWarning(
674 "Could not terminalize process-bound effect after worker lost its lease",
675 {
676 effectId: effect.id,
677 effectType: effect.request.type,
678 },
679 ),
680 ),
681 Effect.catchCause((failCause) =>
682 Effect.logError(
683 "Failed to terminalize process-bound effect after settlement failure",
684 {
685 effectId: effect.id,
686 effectType: effect.request.type,
687 error: Cause.pretty(failCause),
688 },
689 ),
690 ),
691 );
692 };
693 const recoverPostSuccessSettlement = (
694 effect: EffectOutbox.OrchestrationEffectV2,
695 cause: Cause.Cause<unknown>,
696 ) =>
697 EffectOutbox.REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS.some(
698 (effectType) => effectType === effect.request.type,
699 )
700 ? requeueClaim(effect, cause)
701 : terminalizeClaim(effect, cause);
702​
703 // The worker probes for work repeatedly, including when the outbox is empty.
704 const runOnce = Effect.fnUntraced(
705 function* (excludeRestartContinuations = false) {
706 const claimExit = yield* Effect.exit(
707 outbox.claimNext({ workerId, leaseDurationMs, excludeRestartContinuations }),
708 );
709 yield* increment(orchestrationEffectClaimsTotal, {
710 result: Exit.isFailure(claimExit)
711 ? "error"
712 : Option.isNone(claimExit.value)
713 ? "empty"
714 : "claimed",
715 });
716 if (Exit.isFailure(claimExit)) return yield* Effect.failCause(claimExit.cause);
717 const claimed = claimExit.value;
718 if (Option.isNone(claimed)) {
719 return false;
720 }
721 const effect = claimed.value;
722 // Arm cancellation before rereading durable state to close the read-to-registration race.
723 const cancellation = outbox
724 .awaitCancellation(effect.id)
725 .pipe(Effect.as("cancelled" as const));
726 const cancelledBeforeExecution = yield* Effect.gen(function* () {
727 const claimedAt = DateTime.toEpochMillis(yield* DateTime.now);
728 const eligibleAt = Math.max(
729 DateTime.toEpochMillis(DateTime.makeUnsafe(effect.createdAt)),
730 DateTime.toEpochMillis(DateTime.makeUnsafe(effect.availableAt)),
731 );
732 yield* Metric.update(
733 Metric.withAttributes(
734 orchestrationEffectQueueWait,
735 metricAttributes({ effect_type: effect.request.type }),
736 ),
737 Duration.millis(Math.max(0, claimedAt - eligibleAt)),
738 );
739 // Recheck durable cancellation after registering the Deferred; cancellation may have committed after claim.
740 if (yield* wasCancelled(effect.id)) {
741 yield* outbox.clearCancellation(effect.id);
742 return true;
743 }
744 return false;
745 }).pipe(Effect.onError((cause) => requeueClaim(effect, cause)));
746 if (cancelledBeforeExecution) return true;
747​
748 const execution = executor
749 .execute(effect, { willRetry: effect.attemptCount < maxAttempts })
750 .pipe(Effect.as("executed" as const));
751 const exit = yield* Effect.exit(Effect.raceFirst(execution, cancellation)).pipe(
752 Effect.ensuring(outbox.clearCancellation(effect.id)),
753 );
754 if (Exit.isSuccess(exit) && exit.value === "cancelled") {
755 return true;
756 }
757 if (Exit.isSuccess(exit)) {
758 return yield* Effect.gen(function* () {
759 const completed = yield* outbox.succeed({ effectId: effect.id, workerId });
760 if (!completed) {
761 if (yield* wasCancelled(effect.id)) return true;
762 return yield* new OrchestrationEffectWorkerError({
763 operation: "complete",
764 effectId: effect.id,
765 cause: "The worker no longer owns the effect lease.",
766 });
767 }
768 return true;
769 }).pipe(Effect.onError((cause) => recoverPostSuccessSettlement(effect, cause)));
770 }
771​
772 const error = Cause.pretty(exit.cause);
773 const nonRetryable = isNonRetryableProviderTurnControlFailure(effect.request.type, error);
774 yield* Effect.logWarning("Orchestration effect execution failed", {
775 effectId: effect.id,
776 effectType: effect.request.type,
777 attemptCount: effect.attemptCount,
778 nonRetryable,
779 error,
780 });
781 const updated = nonRetryable
782 ? yield* outbox
783 .succeed({ effectId: effect.id, workerId })
784 .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause)))
785 : effect.attemptCount >= maxAttempts
786 ? yield* outbox
787 .fail({ effectId: effect.id, workerId, error })
788 .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause)))
789 : yield* outbox
790 .retry({
791 effectId: effect.id,
792 workerId,
793 error,
794 delayMs: Math.min(30_000, 100 * 2 ** Math.max(0, effect.attemptCount - 1)),
795 })
796 .pipe(Effect.onError((cause) => requeueClaim(effect, cause)));
797 if (!updated) {
798 if (yield* wasCancelled(effect.id)) return true;
799 return yield* new OrchestrationEffectWorkerError({
800 operation: "reschedule",
801 effectId: effect.id,
802 cause: "The worker no longer owns the effect lease.",
803 });
804 }
805 return true;
806 },
807 (effect, _excludeRestartContinuations?: boolean) =>
808 effect.pipe(
809 Effect.mapError((cause) =>
810 isOrchestrationEffectWorkerError(cause)
811 ? cause
812 : new OrchestrationEffectWorkerError({ operation: "run", cause }),
813 ),
814 ),
815 );
816​
817 return OrchestrationEffectWorkerV2.of({
818 awaitWork: outbox.awaitAvailable,
819 runOnce: runOnce(),
820 runRecoveryOnce: runOnce(true),
821 nextClaimableAt: outbox.nextClaimableAt.pipe(
822 Effect.mapError(
823 (cause) =>
824 new OrchestrationEffectWorkerError({
825 operation: "next-claimable",
826 cause,
827 }),
828 ),
829 ),
830 drain: Effect.fn("EffectWorker.drain")(function* (maxEffects = Number.MAX_SAFE_INTEGER) {
831 let completed = 0;
832 while (completed < maxEffects && (yield* runOnce())) {
833 completed += 1;
834 }
835 return completed;
836 }),
837 });
838 }),
839 );
840​
841export const layer = layerWithOptions();
842​
843export interface OrchestrationEffectDaemonOptions {
844 readonly concurrency?: number;
845 readonly livenessPollIntervalMs?: number;
847​
848const DEFAULT_EFFECT_WORKER_CONCURRENCY = 4;
849const DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS = 30_000;
850​
851export const runDaemonWithOptions = (options: OrchestrationEffectDaemonOptions = {}) =>
852 Effect.scoped(
853 Effect.gen(function* () {
854 const worker = yield* OrchestrationEffectWorkerV2;
855 const requestedConcurrency = options.concurrency ?? DEFAULT_EFFECT_WORKER_CONCURRENCY;
856 const concurrency = Number.isFinite(requestedConcurrency)
857 ? Math.max(1, Math.floor(requestedConcurrency))
858 : DEFAULT_EFFECT_WORKER_CONCURRENCY;
859 const requestedLivenessPollIntervalMs =
860 options.livenessPollIntervalMs ?? DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
861 const livenessPollIntervalMs = Number.isFinite(requestedLivenessPollIntervalMs)
862 ? Math.max(1, Math.floor(requestedLivenessPollIntervalMs))
863 : DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
864 // Notifications wake promptly; availableAt persists retry timing, and liveness polling recovers missed wakeups.
865 const runWorker = Effect.gen(function* () {
866 while (true) {
867 const outcome = yield* worker.runOnce.pipe(
868 Effect.map((worked) => (worked ? ("worked" as const) : ("idle" as const))),
869 Effect.catchCause((cause) =>
870 Effect.logWarning("Orchestration effect worker failed", cause).pipe(
871 Effect.as("failed" as const),
872 ),
873 ),
874 );
875 if (outcome === "worked") {
876 yield* Effect.yieldNow;
877 continue;
878 }
879 if (outcome === "failed") {
880 // Failed claims can leave overdue rows; cool off instead of rescheduling at the one-millisecond floor.
881 yield* Effect.sleep(Duration.millis(Math.min(1_000, livenessPollIntervalMs)));
882 continue;
883 }
884​
885 const nextClaimableAt = yield* worker.nextClaimableAt.pipe(
886 Effect.catchCause((cause) =>
887 Effect.logWarning(
888 "Failed to read the next orchestration effect deadline",
889 cause,
890 ).pipe(Effect.as(Option.none<DateTime.Utc>())),
891 ),
892 );
893 const now = DateTime.toEpochMillis(yield* DateTime.now);
894 const sleepMs = Option.match(nextClaimableAt, {
895 onNone: () => livenessPollIntervalMs,
896 onSome: (availableAt) => {
897 const untilAvailable = DateTime.toEpochMillis(availableAt) - now;
898 return Math.min(livenessPollIntervalMs, untilAvailable > 0 ? untilAvailable : 25);
899 },
900 });
901 yield* Effect.raceFirst(
902 worker.awaitWork.pipe(Effect.as("notified" as const)),
903 Effect.sleep(Duration.millis(sleepMs)).pipe(Effect.as("scheduled" as const)),
904 );
905 }
906 });
907​
908 return yield* Effect.all(
909 Array.from({ length: concurrency }, () => runWorker),
910 {
911 concurrency: "unbounded",
912 discard: true,
913 },
914 );
915 }),
916 );
917​
918export const runDaemon = runDaemonWithOptions();