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