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 ...(error.steerDeclined &&
394 effect.request.steerFollowUpAfterRunOrdinal !== undefined
395 ? {
396 steerFollowUpAfterRunOrdinal:
397 effect.request.steerFollowUpAfterRunOrdinal,
398 }
399 : {}),
400 text: message.text,
401 ...(message.context ? { context: message.context } : {}),
402 attachments: message.attachments,
403 ...(error.steerDeclined && effect.request.modelSelection !== undefined
404 ? { modelSelection: effect.request.modelSelection }
405 : message.delegatedCompletion === undefined
406 ? {}
407 : { modelSelection: run.modelSelection }),
408 dispatchMode: {
409 type: queued ? "queue_after_active" : "start_immediately",
410 },
411 createdBy: message.createdBy,
412 creationSource: message.creationSource,
413 ...(message.delegatedCompletion === undefined
414 ? {}
415 : { delegatedCompletion: message.delegatedCompletion }),
416 ...(message.notification === undefined
417 ? {}
418 : { notification: message.notification }),
419 ...(message.scheduledTaskId === undefined
420 ? {}
421 : { scheduledTaskId: message.scheduledTaskId }),
422 ...(message.senderThreadId === undefined
423 ? {}
424 : { senderThreadId: message.senderThreadId }),
425 ...(message.linkedSender === undefined
426 ? {}
427 : { linkedSender: message.linkedSender }),
428 })
429 .pipe(
430 // A disabled instance cannot retry this completed turn; its result stands.
431 Effect.catchTags({
432 ThreadManagementProviderInstanceDisabledError: (disabledError) =>
433 Effect.logInfo(
434 "orchestration-v2.effect-worker.steer-follow-up-disabled",
435 {
436 threadId: effect.threadId,
437 messageId: message.id,
438 projectId: disabledError.projectId,
439 instanceId: disabledError.instanceId,
440 },
441 ),
442 }),
443 );
444 }),
445 ),
446 Effect.mapError(
447 (cause) =>
448 new OrchestrationEffectExecutionError({
449 effectId: effect.id,
450 effectType: effect.request.type,
451 cause,
452 }),
453 ),
454 );
455 case "provider-turn.restart":
456 return providerTurnControl
457 .interruptAndAwaitTerminal({
458 threadId: effect.threadId,
459 providerSessionId: effect.request.providerSessionId,
460 providerThreadId: effect.request.providerThreadId,
461 providerTurnId: effect.request.providerTurnId,
462 interruptedAttemptId: effect.request.interruptedAttemptId,
463 ...(effect.request.sessionTransition?.type === "replace"
464 ? {
465 replacementProviderSessionId:
466 effect.request.sessionTransition.replacementProviderSessionId,
467 }
468 : {}),
469 })
470 .pipe(
471 Effect.andThen(
472 effect.request.sessionTransition?.type === "replace"
473 ? providerSessions.detach({
474 providerSessionId: effect.request.providerSessionId,
475 threadId: effect.threadId,
476 detail: "Selection change requires a provider session restart.",
477 })
478 : effect.request.sessionTransition?.type === "detach"
479 ? providerSessions.detach({
480 providerSessionId: effect.request.providerSessionId,
481 threadId: effect.threadId,
482 detail: "Provider thread handoff replaced this session binding.",
483 })
484 : Effect.void,
485 ),
486 Effect.andThen(
487 // Failed interruption or detach must not report the old process stopped.
488 startRun(effect, effect.request.runId, willRetry),
489 ),
490 Effect.mapError(
491 (cause) =>
492 new OrchestrationEffectExecutionError({
493 effectId: effect.id,
494 effectType: effect.request.type,
495 cause,
496 }),
497 ),
498 );
499 case "runtime-request.respond": {
500 const requestId = effect.request.requestId;
501 return runtimeRequests
502 .respond({
503 threadId: effect.threadId,
504 providerSessionId: effect.request.providerSessionId,
505 requestId: effect.request.requestId,
506 ...(effect.request.decision === undefined
507 ? {}
508 : { decision: effect.request.decision }),
509 ...(effect.request.feedback === undefined
510 ? {}
511 : { feedback: effect.request.feedback }),
512 ...(effect.request.answers === undefined
513 ? {}
514 : { answers: effect.request.answers }),
515 })
516 .pipe(
517 Effect.tapCause((cause) =>
518 willRetry || Cause.hasInterruptsOnly(cause)
519 ? Effect.void
520 : threads
521 .dispatch({
522 type: "runtime-request.delivery.fail",
523 commandId: CommandId.make(`${effect.commandId}:delivery-failed`),
524 threadId: effect.threadId,
525 requestId,
526 })
527 .pipe(
528 Effect.catchCause((recordCause) =>
529 Effect.logWarning("Failed to record answer delivery failure", {
530 effectId: effect.id,
531 cause: recordCause,
532 }),
533 ),
534 ),
535 ),
536 Effect.mapError(
537 (cause) =>
538 new OrchestrationEffectExecutionError({
539 effectId: effect.id,
540 effectType: effect.request.type,
541 cause,
542 }),
543 ),
544 );
545 }
546 case "provider-thread.rollback":
547 return checkpointRollback
548 .execute({
549 threadId: effect.threadId,
550 providerThreadId: effect.request.providerThreadId,
551 checkpointId: effect.request.checkpointId,
552 scopeId: effect.request.scopeId,
553 requestId: effect.commandId,
554 ...(effect.request.restoreFiles === undefined
555 ? {}
556 : { restoreFiles: effect.request.restoreFiles }),
557 })
558 .pipe(
559 Effect.tapCause((cause) =>
560 willRetry || Cause.hasInterruptsOnly(cause)
561 ? Effect.void
562 : threads
563 .dispatch({
564 type: "checkpoint.rollback.fail",
565 commandId: CommandId.make(`${effect.commandId}:rollback-failed`),
566 threadId: effect.threadId,
567 requestId: effect.commandId,
568 message: Option.match(Cause.findErrorOption(cause), {
569 onNone: () => CheckpointRollbackService.ROLLBACK_FAILED_MESSAGE,
570 onSome: CheckpointRollbackService.rollbackFailureClientMessage,
571 }),
572 })
573 .pipe(
574 Effect.catchCause((recordCause) =>
575 Effect.logWarning("Failed to record rollback failure", {
576 effectId: effect.id,
577 cause: recordCause,
578 }),
579 ),
580 ),
581 ),
582 Effect.mapError(
583 (cause) =>
584 new OrchestrationEffectExecutionError({
585 effectId: effect.id,
586 effectType: effect.request.type,
587 cause,
588 }),
589 ),
590 );
591 case "checkpoint.capture":
592 return runFinalization
593 .finalize({
594 threadId: effect.threadId,
595 runId: effect.request.runId,
596 scopeId: effect.request.scopeId,
597 })
598 .pipe(
599 // Completion bookkeeping must survive a missed live run update, including capture retries.
600 Effect.andThen(
601 threads.recoverDelegatedTask(effect.threadId, {
602 completedRunId: effect.request.runId,
603 }),
604 ),
605 Effect.mapError(
606 (cause) =>
607 new OrchestrationEffectExecutionError({
608 effectId: effect.id,
609 effectType: effect.request.type,
610 cause,
611 }),
612 ),
613 );
614 case "scheduled-tasks.cleanup":
615 return resourceCleanup.cleanupScheduledTasks(effect.threadId).pipe(
616 Effect.mapError(
617 (cause) =>
618 new OrchestrationEffectExecutionError({
619 effectId: effect.id,
620 effectType: effect.request.type,
621 cause,
622 }),
623 ),
624 );
625 // Archive and delete queue this one per-thread teardown, so it also releases the
626 // thread's device claims; the devices stay booted for other threads.
627 case "terminal.cleanup":
628 return Effect.partition(
629 [
630 resourceCleanup.cleanupTerminals(effect.threadId),
631 resourceCleanup.cleanupDevices(effect.threadId),
632 ],
633 (cleanup) => cleanup,
634 ).pipe(
635 Effect.flatMap(([, [failure]]) =>
636 failure === undefined ? Effect.void : Effect.fail(failure),
637 ),
638 Effect.mapError(
639 (cause) =>
640 new OrchestrationEffectExecutionError({
641 effectId: effect.id,
642 effectType: effect.request.type,
643 cause,
644 }),
645 ),
646 );
647 case "preview.cleanup":
648 return resourceCleanup.cleanupPreviews(effect.threadId).pipe(
649 Effect.mapError(
650 (cause) =>
651 new OrchestrationEffectExecutionError({
652 effectId: effect.id,
653 effectType: effect.request.type,
654 cause,
655 }),
656 ),
657 );
658 case "attachment.cleanup": {
659 const request = effect.request;
660 return Effect.gen(function* () {
661 // Another message or answer may share the file, or a stale queued edit may restore it.
662 const referenced = new Set(
663 request.skipReferenced
664 ? yield* projectionStore.getThreadAttachmentIds(effect.threadId, {
665 includeShownByLiveFork: true,
666 })
667 : [],
668 );
669 yield* resourceCleanup.cleanupAttachments(
670 request.attachmentIds.filter((id) => !referenced.has(id)),
671 );
672 }).pipe(
673 Effect.mapError(
674 (cause) =>
675 new OrchestrationEffectExecutionError({
676 effectId: effect.id,
677 effectType: effect.request.type,
678 cause,
679 }),
680 ),
681 );
682 }
683 case "thread-title.generate":
684 return threadTitleRegeneration
685 .execute({
686 threadId: effect.threadId,
687 requestId: effect.commandId,
688 kind: effect.request.kind,
689 })
690 .pipe(
691 Effect.mapError(
692 (cause) =>
693 new OrchestrationEffectExecutionError({
694 effectId: effect.id,
695 effectType: effect.request.type,
696 cause,
697 }),
698 ),
699 );
700 case "delegated-tasks.stop":
701 return threads
702 .stopDelegatedTasks({
703 threadId: effect.threadId,
704 commandId: effect.commandId,
705 reason: effect.request.reason,
706 })
707 .pipe(
708 Effect.mapError(
709 (cause) =>
710 new OrchestrationEffectExecutionError({
711 effectId: effect.id,
712 effectType: effect.request.type,
713 cause,
714 }),
715 ),
716 );
717 }
718 }),
719 });
720 }),
721);
722
723// A running effect blocks later work on its thread and its lease is never reclaimed in-process,
724// so a stop that hangs must give up and fall through to the normal retry/fail path.
725const DELEGATED_TASKS_STOP_TIMEOUT = Duration.seconds(30);
726
727const boundExecution =
728 (effect: EffectOutbox.OrchestrationEffectV2) =>
729 (execution: Effect.Effect<void, OrchestrationEffectExecutionError>) =>
730 effect.request.type === "delegated-tasks.stop"
731 ? execution.pipe(
732 Effect.timeoutOrElse({
733 duration: DELEGATED_TASKS_STOP_TIMEOUT,
734 orElse: () =>
735 Effect.fail(
736 new OrchestrationEffectExecutionError({
737 effectId: effect.id,
738 effectType: effect.request.type,
739 cause: `Timed out after ${Duration.format(DELEGATED_TASKS_STOP_TIMEOUT)}.`,
740 }),
741 ),
742 }),
743 )
744 : execution;
745
746export class OrchestrationEffectWorkerError extends Schema.TaggedError<OrchestrationEffectWorkerError>()(
747 "OrchestrationEffectWorkerError",
748 {
749 operation: Schema.String,
750 effectId: Schema.optional(Schema.String),
751 cause: Schema.optional(Schema.Defect()),
752 },
753) {}
754
755const isOrchestrationEffectWorkerError = Schema.is(OrchestrationEffectWorkerError);
756
757// Only the claiming worker settles its row, and a running row blocks every later effect on its
758// thread until the server restarts. onError masks interruption, so retries must restore it.
759const isLockTimeout = (error: EffectOutbox.EffectOutboxError) =>
760 SqlError.isSqlError(error.cause) && error.cause.reason._tag === "LockTimeoutError";
761const lockRetrySchedule = Schedule.spaced(Duration.millis(100));
762const retryWhileLocked = <A>(settlement: Effect.Effect<A, EffectOutbox.EffectOutboxError>) =>
763 Effect.interruptible(
764 Effect.retry(settlement, { schedule: lockRetrySchedule, while: isLockTimeout }),
765 );
766
767type ClaimFilter = Omit<Parameters<EffectOutbox.EffectOutboxV2Shape["claimNext"]>[0], "workerId">;
768
769export interface OrchestrationEffectWorkerV2Shape {
770 readonly awaitWork: Effect.Effect<void>;
771 readonly runOnce: (input?: {
772 readonly maxRunningTitleGenerations?: number;
773 }) => Effect.Effect<boolean, OrchestrationEffectWorkerError>;
774 readonly runRecoveryOnce: Effect.Effect<boolean, OrchestrationEffectWorkerError>;
775 readonly nextClaimableAt: (input?: {
776 readonly maxRunningTitleGenerations?: number;
777 }) => Effect.Effect<Option.Option<DateTime.Utc>, OrchestrationEffectWorkerError>;
778 readonly drain: (maxEffects?: number) => Effect.Effect<number, OrchestrationEffectWorkerError>;
779}
780
781export class OrchestrationEffectWorkerV2 extends Context.Service<
782 OrchestrationEffectWorkerV2,
783 OrchestrationEffectWorkerV2Shape
784>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectWorkerV2") {}
785
786export interface OrchestrationEffectWorkerOptions {
787 readonly workerId?: string;
788 readonly maxAttempts?: number;
789}
790
791export const layerWithOptions = (
792 options: OrchestrationEffectWorkerOptions = {},
793): Layer.Layer<
794 OrchestrationEffectWorkerV2,
795 never,
796 EffectOutbox.EffectOutboxV2 | OrchestrationEffectExecutorV2
797> =>
798 Layer.effect(
799 OrchestrationEffectWorkerV2,
800 Effect.gen(function* () {
801 const outbox = yield* EffectOutbox.EffectOutboxV2;
802 const executor = yield* OrchestrationEffectExecutorV2;
803 const workerId = options.workerId ?? `orchestration-v2:${process.pid}`;
804 const maxAttempts = Math.max(1, options.maxAttempts ?? 5);
805 const wasCancelled = (effectId: string) =>
806 outbox.get(effectId).pipe(
807 Effect.map(
808 Option.match({
809 onNone: () => false,
810 onSome: (effect) => effect.status === "cancelled",
811 }),
812 ),
813 );
814 const requeueClaim = (
815 effect: EffectOutbox.OrchestrationEffectV2,
816 cause: Cause.Cause<unknown>,
817 ) =>
818 Cause.hasInterruptsOnly(cause)
819 ? Effect.void
820 : outbox
821 .retry({
822 effectId: effect.id,
823 workerId,
824 error: `Worker failed before settling the claimed effect: ${Cause.pretty(cause)}`,
825 delayMs: 0,
826 })
827 .pipe(
828 retryWhileLocked,
829 Effect.flatMap((requeued) =>
830 requeued
831 ? Effect.logWarning("Requeued effect after unexpected worker failure", {
832 effectId: effect.id,
833 effectType: effect.request.type,
834 })
835 : Effect.logWarning("Could not requeue effect after worker lost its lease", {
836 effectId: effect.id,
837 effectType: effect.request.type,
838 }),
839 ),
840 Effect.catchCause((requeueCause) =>
841 Effect.logError("Failed to requeue effect after unexpected worker failure", {
842 effectId: effect.id,
843 effectType: effect.request.type,
844 error: Cause.pretty(requeueCause),
845 }),
846 ),
847 );
848 const terminalizeClaim = (
849 effect: EffectOutbox.OrchestrationEffectV2,
850 cause: Cause.Cause<unknown>,
851 ) => {
852 if (Cause.hasInterruptsOnly(cause)) return Effect.void;
853 return outbox
854 .fail({
855 effectId: effect.id,
856 workerId,
857 error: `Worker failed to settle a process-bound effect after execution started: ${Cause.pretty(cause)}`,
858 })
859 .pipe(
860 retryWhileLocked,
861 Effect.flatMap((failed) =>
862 failed
863 ? Effect.logError("Terminalized process-bound effect after settlement failure", {
864 effectId: effect.id,
865 effectType: effect.request.type,
866 })
867 : Effect.logWarning(
868 "Could not terminalize process-bound effect after worker lost its lease",
869 {
870 effectId: effect.id,
871 effectType: effect.request.type,
872 },
873 ),
874 ),
875 Effect.catchCause((failCause) =>
876 Effect.logError(
877 "Failed to terminalize process-bound effect after settlement failure",
878 {
879 effectId: effect.id,
880 effectType: effect.request.type,
881 error: Cause.pretty(failCause),
882 },
883 ),
884 ),
885 );
886 };
887 const recoverPostSuccessSettlement = (
888 effect: EffectOutbox.OrchestrationEffectV2,
889 cause: Cause.Cause<unknown>,
890 ) =>
891 EffectOutbox.REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS.some(
892 (effectType) => effectType === effect.request.type,
893 )
894 ? requeueClaim(effect, cause)
895 : terminalizeClaim(effect, cause);
896
897 // The worker probes for work repeatedly, including when the outbox is empty.
898 const runOnce = Effect.fnUntraced(
899 function* (filter: ClaimFilter = {}) {
900 const claimExit = yield* Effect.exit(outbox.claimNext({ workerId, ...filter }));
901 yield* increment(orchestrationEffectClaimsTotal, {
902 result: Exit.isFailure(claimExit)
903 ? "error"
904 : Option.isNone(claimExit.value)
905 ? "empty"
906 : "claimed",
907 });
908 if (Exit.isFailure(claimExit)) return yield* Effect.failCause(claimExit.cause);
909 const claimed = claimExit.value;
910 if (Option.isNone(claimed)) {
911 return false;
912 }
913 const effect = claimed.value;
914 // Arm cancellation before rereading durable state to close the read-to-registration race.
915 const cancellation = outbox
916 .awaitCancellation(effect.id)
917 .pipe(Effect.as("cancelled" as const));
918 const cancelledBeforeExecution = yield* Effect.gen(function* () {
919 const claimedAt = DateTime.toEpochMillis(yield* DateTime.now);
920 const eligibleAt = Math.max(
921 DateTime.toEpochMillis(DateTime.makeUnsafe(effect.createdAt)),
922 DateTime.toEpochMillis(DateTime.makeUnsafe(effect.availableAt)),
923 );
924 yield* Metric.update(
925 Metric.withAttributes(
926 orchestrationEffectQueueWait,
927 metricAttributes({ effect_type: effect.request.type }),
928 ),
929 Duration.millis(Math.max(0, claimedAt - eligibleAt)),
930 );
931 // Recheck durable cancellation after registering the Deferred; cancellation may have committed after claim.
932 if (yield* wasCancelled(effect.id)) {
933 yield* outbox.clearCancellation(effect.id);
934 return true;
935 }
936 return false;
937 }).pipe(Effect.onError((cause) => requeueClaim(effect, cause)));
938 if (cancelledBeforeExecution) return true;
939
940 const execution = executor
941 .execute(effect, { willRetry: effect.attemptCount < maxAttempts })
942 .pipe(boundExecution(effect), Effect.as("executed" as const));
943 const exit = yield* Effect.exit(Effect.raceFirst(execution, cancellation)).pipe(
944 Effect.ensuring(outbox.clearCancellation(effect.id)),
945 );
946 if (Exit.isSuccess(exit) && exit.value === "cancelled") {
947 return true;
948 }
949 if (Exit.isSuccess(exit)) {
950 return yield* Effect.gen(function* () {
951 const completed = yield* outbox.succeed({ effectId: effect.id, workerId });
952 if (!completed) {
953 if (yield* wasCancelled(effect.id)) return true;
954 return yield* new OrchestrationEffectWorkerError({
955 operation: "complete",
956 effectId: effect.id,
957 cause: "The worker no longer owns the effect lease.",
958 });
959 }
960 return true;
961 }).pipe(Effect.onError((cause) => recoverPostSuccessSettlement(effect, cause)));
962 }
963
964 const error = Cause.pretty(exit.cause);
965 const nonRetryable = isNonRetryableProviderTurnControlFailure(effect.request.type, error);
966 yield* Effect.logWarning("Orchestration effect execution failed", {
967 effectId: effect.id,
968 effectType: effect.request.type,
969 attemptCount: effect.attemptCount,
970 nonRetryable,
971 error,
972 });
973 const updated = nonRetryable
974 ? yield* outbox
975 .succeed({ effectId: effect.id, workerId })
976 .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause)))
977 : effect.attemptCount >= maxAttempts &&
978 (!ownsStartingRun(effect.request.type) || cannotSettleRun(exit.cause))
979 ? yield* outbox
980 .fail({ effectId: effect.id, workerId, error })
981 .pipe(Effect.onError((cause) => terminalizeClaim(effect, cause)))
982 : yield* outbox
983 .retry({
984 effectId: effect.id,
985 workerId,
986 error,
987 delayMs: Math.min(30_000, 100 * 2 ** Math.max(0, effect.attemptCount - 1)),
988 })
989 .pipe(Effect.onError((cause) => requeueClaim(effect, cause)));
990 if (!updated) {
991 if (yield* wasCancelled(effect.id)) return true;
992 return yield* new OrchestrationEffectWorkerError({
993 operation: "reschedule",
994 effectId: effect.id,
995 cause: "The worker no longer owns the effect lease.",
996 });
997 }
998 return true;
999 },
1000 (effect, _filter?: ClaimFilter) =>
1001 effect.pipe(
1002 Effect.mapError((cause) =>
1003 isOrchestrationEffectWorkerError(cause)
1004 ? cause
1005 : new OrchestrationEffectWorkerError({ operation: "run", cause }),
1006 ),
1007 ),
1008 );
1009
1010 return OrchestrationEffectWorkerV2.of({
1011 awaitWork: outbox.awaitAvailable,
1012 runOnce,
1013 runRecoveryOnce: runOnce({ excludeRestartContinuations: true }),
1014 // Idle workers poll this; a span per poll would bury useful traces.
1015 nextClaimableAt: Effect.fnUntraced(
1016 function* (input) {
1017 return yield* outbox.nextClaimableAt(input);
1018 },
1019 Effect.mapError(
1020 (cause) =>
1021 new OrchestrationEffectWorkerError({
1022 operation: "next-claimable",
1023 cause,
1024 }),
1025 ),
1026 ),
1027 drain: Effect.fn("EffectWorker.drain")(function* (maxEffects = Number.MAX_SAFE_INTEGER) {
1028 let completed = 0;
1029 while (completed < maxEffects && (yield* runOnce())) {
1030 completed += 1;
1031 }
1032 return completed;
1033 }),
1034 });
1035 }),
1036 );
1037
1038export const layer = layerWithOptions();
1039
1040export interface OrchestrationEffectDaemonOptions {
1041 readonly concurrency?: number;
1042 readonly livenessPollIntervalMs?: number;
1043}
1044
1045const DEFAULT_EFFECT_WORKER_CONCURRENCY = 4;
1046const DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS = 30_000;
1047// A provider request can go unanswered indefinitely. After this wait the slot claims other work
1048// while the execution keeps its running row (which blocks its own thread) and settles it later.
1049const EFFECT_WORKER_SLOT_WAIT = Duration.seconds(30);
1050
1051export const runDaemonWithOptions = (options: OrchestrationEffectDaemonOptions = {}) =>
1052 Effect.scoped(
1053 Effect.gen(function* () {
1054 const worker = yield* OrchestrationEffectWorkerV2;
1055 const scope = yield* Effect.scope;
1056 const requestedConcurrency = options.concurrency ?? DEFAULT_EFFECT_WORKER_CONCURRENCY;
1057 const concurrency = Number.isFinite(requestedConcurrency)
1058 ? Math.max(1, Math.floor(requestedConcurrency))
1059 : DEFAULT_EFFECT_WORKER_CONCURRENCY;
1060 const requestedLivenessPollIntervalMs =
1061 options.livenessPollIntervalMs ?? DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
1062 const livenessPollIntervalMs = Number.isFinite(requestedLivenessPollIntervalMs)
1063 ? Math.max(1, Math.floor(requestedLivenessPollIntervalMs))
1064 : DEFAULT_EFFECT_WORKER_LIVENESS_POLL_INTERVAL_MS;
1065 // Title generation can run for minutes; leave at least one worker free for turn work.
1066 const claimLimits = concurrency > 1 ? { maxRunningTitleGenerations: concurrency - 1 } : {};
1067 // Notifications wake promptly; availableAt persists retry timing, and liveness polling recovers missed wakeups.
1068 const runWorker = Effect.gen(function* () {
1069 while (true) {
1070 const attempt = yield* worker.runOnce(claimLimits).pipe(
1071 Effect.map((worked) => (worked ? ("worked" as const) : ("idle" as const))),
1072 Effect.catchCause((cause) =>
1073 Effect.logWarning("Orchestration effect worker failed", cause).pipe(
1074 Effect.as("failed" as const),
1075 ),
1076 ),
1077 Effect.forkIn(scope),
1078 );
1079 const outcome = yield* Fiber.join(attempt).pipe(
1080 Effect.timeoutOption(EFFECT_WORKER_SLOT_WAIT),
1081 Effect.map(Option.getOrElse(() => "worked" as const)),
1082 );
1083 if (outcome === "worked") {
1084 yield* Effect.yieldNow;
1085 continue;
1086 }
1087 if (outcome === "failed") {
1088 // Failed claims can leave overdue rows; cool off instead of rescheduling at the one-millisecond floor.
1089 yield* Effect.sleep(Duration.millis(Math.min(1_000, livenessPollIntervalMs)));
1090 continue;
1091 }
1092
1093 const nextClaimableAt = yield* worker
1094 .nextClaimableAt(claimLimits)
1095 .pipe(
1096 Effect.catchCause((cause) =>
1097 Effect.logWarning(
1098 "Failed to read the next orchestration effect deadline",
1099 cause,
1100 ).pipe(Effect.as(Option.none<DateTime.Utc>())),
1101 ),
1102 );
1103 const now = DateTime.toEpochMillis(yield* DateTime.now);
1104 const sleepMs = Option.match(nextClaimableAt, {
1105 onNone: () => livenessPollIntervalMs,
1106 onSome: (availableAt) => {
1107 const untilAvailable = DateTime.toEpochMillis(availableAt) - now;
1108 return Math.min(livenessPollIntervalMs, untilAvailable > 0 ? untilAvailable : 25);
1109 },
1110 });
1111 yield* Effect.raceFirst(
1112 worker.awaitWork.pipe(Effect.as("notified" as const)),
1113 Effect.sleep(Duration.millis(sleepMs)).pipe(Effect.as("scheduled" as const)),
1114 );
1115 }
1116 });
1117
1118 return yield* Effect.all(
1119 Array.from({ length: concurrency }, () => runWorker),
1120 {
1121 concurrency: "unbounded",
1122 discard: true,
1123 },
1124 );
1125 }),
1126 );
1127
1128export const runDaemon = runDaemonWithOptions();