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

EffectWorker.ts

902 lines37.2 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 "terminal.cleanup":
466 return resourceCleanup.cleanupTerminals(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 "preview.cleanup":
477 return resourceCleanup.cleanupPreviews(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 "attachment.cleanup":
488 return resourceCleanup.cleanupAttachments(effect.request.attachmentIds).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 "thread-title.generate":
499 return threadTitleRegeneration
500 .execute({
501 threadId: effect.threadId,
502 requestId: effect.commandId,
503 kind: effect.request.kind,
504 })
505 .pipe(
506 Effect.mapError(
507 (cause) =>
508 new OrchestrationEffectExecutionError({
509 effectId: effect.id,
510 effectType: effect.request.type,
511 cause,
512 }),
513 ),
514 );
515 case "delegated-tasks.stop":
516 return threads
517 .stopDelegatedTasks({
518 threadId: effect.threadId,
519 commandId: effect.commandId,
520 reason: effect.request.reason,
521 })
522 .pipe(
523 Effect.mapError(
524 (cause) =>
525 new OrchestrationEffectExecutionError({
526 effectId: effect.id,
527 effectType: effect.request.type,
528 cause,
529 }),
530 ),
531 );
532 }
533 },
534 });
535 }),
536);
537​
538export class OrchestrationEffectWorkerError extends Schema.TaggedError<OrchestrationEffectWorkerError>()(
539 "OrchestrationEffectWorkerError",
540 {
541 operation: Schema.String,
542 effectId: Schema.optional(Schema.String),
543 cause: Schema.optional(Schema.Defect()),
544 },
545) {}
546​
547const isOrchestrationEffectWorkerError = Schema.is(OrchestrationEffectWorkerError);
548​
549export interface OrchestrationEffectWorkerV2Shape {
550 readonly awaitWork: Effect.Effect<void>;
551 readonly runOnce: Effect.Effect<boolean, OrchestrationEffectWorkerError>;
552 readonly runRecoveryOnce: Effect.Effect<boolean, OrchestrationEffectWorkerError>;
553 readonly nextClaimableAt: Effect.Effect<
554 Option.Option<DateTime.Utc>,
555 OrchestrationEffectWorkerError
556 >;
557 readonly drain: (maxEffects?: number) => Effect.Effect<number, OrchestrationEffectWorkerError>;
559​
560export class OrchestrationEffectWorkerV2 extends Context.Service<
561 OrchestrationEffectWorkerV2,
562 OrchestrationEffectWorkerV2Shape
563>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectWorkerV2") {}
564​
565export interface OrchestrationEffectWorkerOptions {
566 readonly workerId?: string;
567 readonly leaseDurationMs?: number;
568 readonly maxAttempts?: number;
570​
571export const layerWithOptions = (
572 options: OrchestrationEffectWorkerOptions = {},
573): Layer.Layer<
574 OrchestrationEffectWorkerV2,
575 never,
576 EffectOutbox.EffectOutboxV2 | OrchestrationEffectExecutorV2
577> =>
578 Layer.effect(
579 OrchestrationEffectWorkerV2,
580 Effect.gen(function* () {
581 const outbox = yield* EffectOutbox.EffectOutboxV2;
582 const executor = yield* OrchestrationEffectExecutorV2;
583 const workerId = options.workerId ?? `orchestration-v2:${process.pid}`;
584 const leaseDurationMs = Math.max(1, options.leaseDurationMs ?? 30_000);
585 const maxAttempts = Math.max(1, options.maxAttempts ?? 5);
586 const wasCancelled = (effectId: string) =>
587 outbox.get(effectId).pipe(
588 Effect.map(
589 Option.match({
590 onNone: () => false,
591 onSome: (effect) => effect.status === "cancelled",
592 }),
593 ),
594 );
595 const requeueClaim = (
596 effect: EffectOutbox.OrchestrationEffectV2,
597 cause: Cause.Cause<unknown>,
598 ) =>
599 Cause.hasInterruptsOnly(cause)
600 ? Effect.void
601 : outbox
602 .retry({
603 effectId: effect.id,
604 workerId,
605 error: `Worker failed before settling the claimed effect: ${Cause.pretty(cause)}`,
606 delayMs: 0,
607 })
608 .pipe(
609 Effect.flatMap((requeued) =>
610 requeued
611 ? Effect.logWarning("Requeued effect after unexpected worker failure", {
612 effectId: effect.id,
613 effectType: effect.request.type,
614 })
615 : Effect.logWarning("Could not requeue effect after worker lost its lease", {
616 effectId: effect.id,
617 effectType: effect.request.type,
618 }),
619 ),
620 Effect.catchCause((requeueCause) =>
621 Effect.logError("Failed to requeue effect after unexpected worker failure", {
622 effectId: effect.id,
623 effectType: effect.request.type,
624 error: Cause.pretty(requeueCause),
625 }),
626 ),
627 );
628 const terminalizeClaim = (
629 effect: EffectOutbox.OrchestrationEffectV2,
630 cause: Cause.Cause<unknown>,
631 ) => {
632 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
633 return outbox
634 .fail({
635 effectId: effect.id,
636 workerId,
637 error: `Worker failed to settle a process-bound effect after execution started: ${Cause.pretty(cause)}`,
638 })
639 .pipe(
640 Effect.flatMap((failed) =>
641 failed
642 ? Effect.logError("Terminalized process-bound effect after settlement failure", {
643 effectId: effect.id,
644 effectType: effect.request.type,
645 })
646 : Effect.logWarning(
647 "Could not terminalize process-bound effect after worker lost its lease",
648 {
649 effectId: effect.id,
650 effectType: effect.request.type,
651 },
652 ),
653 ),
654 Effect.catchCause((failCause) =>
655 Effect.logError(
656 "Failed to terminalize process-bound effect after settlement failure",
657 {
658 effectId: effect.id,
659 effectType: effect.request.type,
660 error: Cause.pretty(failCause),
661 },
662 ),
663 ),
664 );
665 };
666 const recoverPostSuccessSettlement = (
667 effect: EffectOutbox.OrchestrationEffectV2,
668 cause: Cause.Cause<unknown>,
669 ) =>
670 EffectOutbox.REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS.some(
671 (effectType) => effectType === effect.request.type,
672 )
673 ? requeueClaim(effect, cause)
674 : terminalizeClaim(effect, cause);
675​
676 const runOnce = (excludeRestartContinuations = false) =>
677 Effect.gen(function* () {
678 const claimExit = yield* Effect.exit(
679 outbox.claimNext({ workerId, leaseDurationMs, excludeRestartContinuations }),
680 );
681 yield* increment(orchestrationEffectClaimsTotal, {
682 result: Exit.isFailure(claimExit)
683 ? "error"
684 : Option.isNone(claimExit.value)
685 ? "empty"
686 : "claimed",
687 });
688 if (Exit.isFailure(claimExit)) return yield* Effect.failCause(claimExit.cause);
689 const claimed = claimExit.value;
690 if (Option.isNone(claimed)) {
691 return false;
692 }
693 const effect = claimed.value;
694 // Arm the process-local cancellation signal before re-reading durable
695 // state. A cancellation that commits after the row read has begun can
696 // then still win the execution race instead of falling into the gap
697 // between the read and signal registration.
698 const cancellation = outbox
699 .awaitCancellation(effect.id)
700 .pipe(Effect.as("cancelled" as const));
701 const cancelledBeforeExecution = yield* Effect.gen(function* () {
702 const claimedAt = DateTime.toEpochMillis(yield* DateTime.now);
703 const eligibleAt = Math.max(
704 DateTime.toEpochMillis(DateTime.makeUnsafe(effect.createdAt)),
705 DateTime.toEpochMillis(DateTime.makeUnsafe(effect.availableAt)),
706 );
707 yield* Metric.update(
708 Metric.withAttributes(
709 orchestrationEffectQueueWait,
710 metricAttributes({ effect_type: effect.request.type }),
711 ),
712 Duration.millis(Math.max(0, claimedAt - eligibleAt)),
713 );
714 // Cancellation can commit after the durable claim but before the
715 // process-local Deferred is registered. Re-read the authoritative row
716 // once before starting external work; later cancellations use the
717 // Deferred raced below.
718 if (yield* wasCancelled(effect.id)) {
719 yield* outbox.clearCancellation(effect.id);
720 return true;
721 }
722 return false;
723 }).pipe(Effect.onError((cause) => requeueClaim(effect, cause)));
724 if (cancelledBeforeExecution) return true;
725​
726 const execution = executor
727 .execute(effect, { willRetry: effect.attemptCount < maxAttempts })
728 .pipe(Effect.as("executed" as const));
729 const exit = yield* Effect.exit(Effect.raceFirst(execution, cancellation)).pipe(
730 Effect.ensuring(outbox.clearCancellation(effect.id)),
731 );
732 if (Exit.isSuccess(exit) && exit.value === "cancelled") {
733 return true;
734 }
735 if (Exit.isSuccess(exit)) {
736 return yield* Effect.gen(function* () {
737 const completed = yield* outbox.succeed({ effectId: effect.id, workerId });
738 if (!completed) {
739 if (yield* wasCancelled(effect.id)) return true;
740 return yield* new OrchestrationEffectWorkerError({
741 operation: "complete",
742 effectId: effect.id,
743 cause: "The worker no longer owns the effect lease.",
744 });
745 }
746 return true;
747 }).pipe(Effect.onError((cause) => recoverPostSuccessSettlement(effect, cause)));
748 }
749​
750 const error = Cause.pretty(exit.cause);
751 const nonRetryable = isNonRetryableProviderTurnControlFailure(effect.request.type, error);
752 yield* Effect.logWarning("Orchestration effect execution failed", {
753 effectId: effect.id,
754 effectType: effect.request.type,
755 attemptCount: effect.attemptCount,
756 nonRetryable,
757 error,
758 });
759 const updated = nonRetryable
760 ? yield* outbox
761 .succeed({ effectId: effect.id, workerId })
762 .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause)))
763 : effect.attemptCount >= maxAttempts
764 ? yield* outbox
765 .fail({ effectId: effect.id, workerId, error })
766 .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause)))
767 : yield* outbox
768 .retry({
769 effectId: effect.id,
770 workerId,
771 error,
772 delayMs: Math.min(30_000, 100 * 2 ** Math.max(0, effect.attemptCount - 1)),
773 })
774 .pipe(Effect.onError((cause) => requeueClaim(effect, cause)));
775 if (!updated) {
776 if (yield* wasCancelled(effect.id)) return true;
777 return yield* new OrchestrationEffectWorkerError({
778 operation: "reschedule",
779 effectId: effect.id,
780 cause: "The worker no longer owns the effect lease.",
781 });
782 }
783 return true;
784 }).pipe(
785 Effect.mapError((cause) =>
786 isOrchestrationEffectWorkerError(cause)
787 ? cause
788 : new OrchestrationEffectWorkerError({ operation: "run", cause }),
789 ),
790 );
791​
792 return OrchestrationEffectWorkerV2.of({
793 awaitWork: outbox.awaitAvailable,
794 runOnce: runOnce(),
795 runRecoveryOnce: runOnce(true),
796 nextClaimableAt: outbox.nextClaimableAt.pipe(
797 Effect.mapError(
798 (cause) =>
799 new OrchestrationEffectWorkerError({
800 operation: "next-claimable",
801 cause,
802 }),
803 ),
804 ),
805 drain: (maxEffects = Number.MAX_SAFE_INTEGER) =>
806 Effect.gen(function* () {
807 let completed = 0;
808 while (completed < maxEffects && (yield* runOnce())) {
809 completed += 1;
810 }
811 return completed;
812 }),
813 });
814 }),
815 );
816​
817export const layer = layerWithOptions();
818​
819export interface OrchestrationEffectDaemonOptions {
820 readonly concurrency?: number;
821 readonly livenessPollIntervalMs?: number;
823​
824const DEFAULT_EFFECT_WORKER_CONCURRENCY = 4;
825const DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS = 30_000;
826​
827export const runDaemonWithOptions = (options: OrchestrationEffectDaemonOptions = {}) =>
828 Effect.scoped(
829 Effect.gen(function* () {
830 const worker = yield* OrchestrationEffectWorkerV2;
831 const requestedConcurrency = options.concurrency ?? DEFAULT_EFFECT_WORKER_CONCURRENCY;
832 const concurrency = Number.isFinite(requestedConcurrency)
833 ? Math.max(1, Math.floor(requestedConcurrency))
834 : DEFAULT_EFFECT_WORKER_CONCURRENCY;
835 const requestedLivenessPollIntervalMs =
836 options.livenessPollIntervalMs ?? DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
837 const livenessPollIntervalMs = Number.isFinite(requestedLivenessPollIntervalMs)
838 ? Math.max(1, Math.floor(requestedLivenessPollIntervalMs))
839 : DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
840 // Post-commit notifications are the low-latency path. `availableAt` is the
841 // durable retry schedule, and the long liveness poll only recovers from a
842 // missed in-process notification or work inserted by another process.
843 const runWorker = Effect.gen(function* () {
844 while (true) {
845 const outcome = yield* worker.runOnce.pipe(
846 Effect.map((worked) => (worked ? ("worked" as const) : ("idle" as const))),
847 Effect.catchCause((cause) =>
848 Effect.logWarning("Orchestration effect worker failed", cause).pipe(
849 Effect.as("failed" as const),
850 ),
851 ),
852 );
853 if (outcome === "worked") {
854 yield* Effect.yieldNow;
855 continue;
856 }
857 if (outcome === "failed") {
858 // A due row can remain visible when a claim UPDATE fails. Do not
859 // feed that past deadline back into the scheduler and retry at the
860 // one-millisecond floor; let transient database failures cool off.
861 yield* Effect.sleep(Duration.millis(Math.min(1_000, livenessPollIntervalMs)));
862 continue;
863 }
864​
865 const nextClaimableAt = yield* worker.nextClaimableAt.pipe(
866 Effect.catchCause((cause) =>
867 Effect.logWarning(
868 "Failed to read the next orchestration effect deadline",
869 cause,
870 ).pipe(Effect.as(Option.none<DateTime.Utc>())),
871 ),
872 );
873 const now = DateTime.toEpochMillis(yield* DateTime.now);
874 const sleepMs = Option.match(nextClaimableAt, {
875 onNone: () => livenessPollIntervalMs,
876 onSome: (availableAt) => {
877 const untilAvailable = DateTime.toEpochMillis(availableAt) - now;
878 return Math.min(livenessPollIntervalMs, untilAvailable > 0 ? untilAvailable : 25);
879 },
880 });
881 yield* Effect.raceFirst(
882 worker.awaitWork.pipe(Effect.as("notified" as const)),
883 Effect.sleep(Duration.millis(sleepMs)).pipe(Effect.as("scheduled" as const)),
884 );
885 }
886 });
887​
888 return yield* Effect.all(
889 Array.from({ length: concurrency }, () => runWorker),
890 {
891 concurrency: "unbounded",
892 discard: true,
893 },
894 );
895 }),
896 );
897​
898export const runDaemon = runDaemonWithOptions();
899​
900const layerDaemon: Layer.Layer<never, never, OrchestrationEffectWorkerV2> = Layer.effectDiscard(
901 runDaemon.pipe(Effect.forkScoped),
902);