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