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

EffectWorker.ts

916 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 */
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 );
61​
62export interface OrchestrationEffectExecutorV2Shape {
63 readonly execute: (
64 effect: EffectOutbox.OrchestrationEffectV2,
65 options?: { readonly willRetry: boolean },
66 ) => Effect.Effect<void, OrchestrationEffectExecutionError>;
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: 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>;
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;
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;
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);