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

EffectWorker.ts

1,176 lines49.9 KB

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