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

EffectWorker.ts

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