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