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