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

EffectWorker.ts

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