Open History to see the last commit
1import {
2 CheckpointId,
3 CheckpointScopeId,
4 CommandId,
5 MessageId,
6 ModelSelection,
7 NodeId,
8 NonNegativeInt,
9 ProviderSessionId,
10 RunAttemptId,
11 ProviderApprovalDecision,
12 ProviderUserInputAnswers,
13 ProviderThreadId,
14 ProviderTurnId,
15 RunId,
16 RuntimeRequestId,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as Context from "effect/Context";
20import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
21import * as DateTime from "effect/DateTime";
22import * as Deferred from "effect/Deferred";
23import * as Duration from "effect/Duration";
24import * as Effect from "effect/Effect";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Queue from "effect/Queue";
28import * as Result from "effect/Result";
29import * as Schedule from "effect/Schedule";
30import * as Schema from "effect/Schema";
31import * as SqlClient from "effect/sql/SqlClient";
32
33import { forkParked } from "../serverActivation.ts";
34
35export const OrchestrationEffectRequestV2 = Schema.Union([
36 Schema.Struct({
37 type: Schema.Literal("provider-runtime.continue"),
38 sourceRunId: RunId,
39 processLossCount: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
40 /** Set when the provider process exited under a live server; absent means a server restart. */
41 cause: Schema.optional(Schema.Literal("provider_exit")),
42 }),
43 Schema.Struct({
44 type: Schema.Literal("provider-session.detach"),
45 providerSessionId: ProviderSessionId,
46 detail: Schema.optional(Schema.String),
47 revokeMcpCredential: Schema.optional(Schema.Boolean),
48 }),
49 Schema.Struct({
50 type: Schema.Literal("provider-session.apply-model-selection"),
51 providerSessionId: ProviderSessionId,
52 providerThreadId: ProviderThreadId,
53 modelSelection: ModelSelection,
54 }),
55 Schema.Struct({
56 type: Schema.Literal("provider-session.apply-thread-title"),
57 title: Schema.String,
58 }),
59 Schema.Struct({
60 type: Schema.Literal("provider-turn.start"),
61 runId: RunId,
62 }),
63 Schema.Struct({
64 type: Schema.Literal("provider-turn.interrupt"),
65 providerSessionId: ProviderSessionId,
66 providerThreadId: ProviderThreadId,
67 providerTurnId: ProviderTurnId,
68 subagent: Schema.optional(Schema.Struct({ id: NodeId, nativeTaskId: Schema.String })),
69 }),
70 Schema.Struct({
71 type: Schema.Literal("provider-turn.steer"),
72 providerSessionId: ProviderSessionId,
73 providerThreadId: ProviderThreadId,
74 providerTurnId: ProviderTurnId,
75 messageId: MessageId,
76 modelSelection: Schema.optional(ModelSelection),
77 steerFollowUpAfterRunOrdinal: Schema.optional(NonNegativeInt),
78 }),
79 Schema.Struct({
80 type: Schema.Literal("provider-turn.restart"),
81 providerSessionId: ProviderSessionId,
82 providerThreadId: ProviderThreadId,
83 providerTurnId: ProviderTurnId,
84 interruptedAttemptId: RunAttemptId,
85 runId: RunId,
86 sessionTransition: Schema.optional(
87 Schema.Union([
88 Schema.Struct({
89 type: Schema.Literal("replace"),
90 replacementProviderSessionId: ProviderSessionId,
91 }),
92 Schema.Struct({ type: Schema.Literal("detach") }),
93 ]),
94 ),
95 }),
96 Schema.Struct({
97 type: Schema.Literal("runtime-request.respond"),
98 providerSessionId: ProviderSessionId,
99 requestId: RuntimeRequestId,
100 decision: Schema.optional(ProviderApprovalDecision),
101 feedback: Schema.optional(Schema.String),
102 answers: Schema.optional(ProviderUserInputAnswers),
103 }),
104 Schema.Struct({
105 type: Schema.Literal("provider-thread.rollback"),
106 restoreFiles: Schema.optional(Schema.Boolean),
107 providerThreadId: ProviderThreadId,
108 checkpointId: CheckpointId,
109 scopeId: CheckpointScopeId,
110 }),
111 Schema.Struct({
112 type: Schema.Literal("checkpoint.capture"),
113 runId: RunId,
114 scopeId: CheckpointScopeId,
115 }),
116 Schema.Struct({
117 type: Schema.Literal("scheduled-tasks.cleanup"),
118 }),
119 Schema.Struct({
120 type: Schema.Literal("terminal.cleanup"),
121 }),
122 Schema.Struct({
123 type: Schema.Literal("preview.cleanup"),
124 }),
125 Schema.Struct({
126 type: Schema.Literal("attachment.cleanup"),
127 attachmentIds: Schema.Array(Schema.String),
128 skipReferenced: Schema.optional(Schema.Boolean),
129 }),
130 Schema.Struct({
131 type: Schema.Literal("thread-title.generate"),
132 kind: Schema.Union([
133 Schema.Struct({ type: Schema.Literal("initial"), messageId: MessageId }),
134 Schema.Struct({ type: Schema.Literal("regenerate") }),
135 ]),
136 }),
137 Schema.Struct({
138 type: Schema.Literal("delegated-tasks.stop"),
139 reason: Schema.optional(Schema.String),
140 }),
141]);
142export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type;
143
144export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [
145 "provider-runtime.continue",
146 "provider-session.detach",
147 "provider-thread.rollback",
148 "checkpoint.capture",
149 "scheduled-tasks.cleanup",
150 "terminal.cleanup",
151 "preview.cleanup",
152 "attachment.cleanup",
153 "thread-title.generate",
154 "delegated-tasks.stop",
155] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
156
157export const PROCESS_BOUND_EFFECT_TYPES = [
158 "provider-session.apply-model-selection",
159 "provider-session.apply-thread-title",
160 "provider-turn.start",
161 "provider-turn.interrupt",
162 "provider-turn.steer",
163 "provider-turn.restart",
164 "runtime-request.respond",
165] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
166
167export const OrchestrationEffectStatusV2 = Schema.Literals([
168 "pending",
169 "running",
170 "succeeded",
171 "failed",
172 "cancelled",
173]);
174export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type;
175
176/** Receipts deduplicate retries, and restart re-enqueues need far less than a week. Retain failed rows to keep deleted-thread worktrees. */
177export const SETTLED_EFFECT_RETENTION = Duration.days(7);
178const PRUNE_BATCH_SIZE = 500;
179
180export interface OrchestrationEffectV2 {
181 readonly id: string;
182 readonly commandId: CommandId;
183 readonly threadId: ThreadId;
184 readonly request: OrchestrationEffectRequestV2;
185 readonly status: OrchestrationEffectStatusV2;
186 readonly attemptCount: number;
187 readonly availableAt: string;
188 readonly leaseOwner: string | null;
189 readonly createdAt: string;
190 readonly updatedAt: string;
191 readonly completedAt: string | null;
192 readonly lastError: string | null;
193}
194
195export interface PendingOrchestrationEffectV2 {
196 readonly id: string;
197 readonly commandId: CommandId;
198 readonly threadId: ThreadId;
199 readonly request: OrchestrationEffectRequestV2;
200 readonly availableAt?: DateTime.Utc;
201}
202
203export class EffectOutboxError extends Schema.TaggedError<EffectOutboxError>()(
204 "EffectOutboxError",
205 {
206 operation: Schema.String,
207 effectId: Schema.optional(Schema.String),
208 cause: Schema.optional(Schema.Defect()),
209 },
210) {
211 override get message(): string {
212 return `Orchestration effect outbox ${this.operation} failed${this.effectId === undefined ? "" : ` for ${this.effectId}`}.`;
213 }
214}
215
216const isEffectOutboxError = Schema.is(EffectOutboxError);
217
218export interface EffectOutboxV2Shape {
219 readonly awaitAvailable: Effect.Effect<void>;
220 readonly notifyAvailable: (count?: number) => Effect.Effect<void>;
221 /** Persist rows only. Notify workers after the surrounding transaction commits. */
222 readonly enqueue: (
223 effects: ReadonlyArray<PendingOrchestrationEffectV2>,
224 ) => Effect.Effect<void, EffectOutboxError>;
225 readonly get: (
226 effectId: string,
227 ) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
228 readonly listByCommandId: (
229 commandId: CommandId,
230 ) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
231 /** A message's first steer effect: it records which runs were queued before the message. */
232 readonly firstSteer: (
233 threadId: ThreadId,
234 messageId: MessageId,
235 ) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
236 readonly cancelUnsettled: (input: {
237 readonly threadId: ThreadId;
238 readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
239 readonly reason: string;
240 }) => Effect.Effect<ReadonlyArray<string>, EffectOutboxError>;
241 readonly signalCancellations: (effectIds: ReadonlyArray<string>) => Effect.Effect<void>;
242 readonly awaitCancellation: (effectId: string) => Effect.Effect<void>;
243 readonly clearCancellation: (effectId: string) => Effect.Effect<void>;
244 /** Resolves once the effect is neither pending nor running, or right away when it does not exist. */
245 readonly awaitSettled: (effectId: string) => Effect.Effect<void, EffectOutboxError>;
246 readonly reconcileAfterProcessLoss: Effect.Effect<
247 { readonly requeued: number; readonly cancelled: number },
248 EffectOutboxError
249 >;
250 readonly claimNext: (input: {
251 readonly workerId: string;
252 readonly excludeRestartContinuations?: boolean;
253 readonly maxRunningTitleGenerations?: number;
254 }) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
255 readonly nextClaimableAt: (input?: {
256 readonly maxRunningTitleGenerations?: number;
257 }) => Effect.Effect<Option.Option<DateTime.Utc>, EffectOutboxError>;
258 readonly succeed: (input: {
259 readonly effectId: string;
260 readonly workerId: string;
261 }) => Effect.Effect<boolean, EffectOutboxError>;
262 readonly retry: (input: {
263 readonly effectId: string;
264 readonly workerId: string;
265 readonly error: string;
266 readonly delayMs: number;
267 }) => Effect.Effect<boolean, EffectOutboxError>;
268 readonly fail: (input: {
269 readonly effectId: string;
270 readonly workerId: string;
271 readonly error: string;
272 }) => Effect.Effect<boolean, EffectOutboxError>;
273 readonly pruneSettled: Effect.Effect<number, EffectOutboxError>;
274}
275
276export class EffectOutboxV2 extends Context.Service<EffectOutboxV2, EffectOutboxV2Shape>()(
277 "t3/orchestration-v2/EffectOutbox/EffectOutboxV2",
278) {}
279
280type EffectRow = {
281 readonly effect_id: string;
282 readonly command_id: string;
283 readonly thread_id: string;
284 readonly effect_type: string;
285 readonly payload_json: string;
286 readonly status: string;
287 readonly attempt_count: number;
288 readonly available_at: string;
289 readonly lease_owner: string | null;
290 readonly created_at: string;
291 readonly updated_at: string;
292 readonly completed_at: string | null;
293 readonly last_error: string | null;
294};
295
296const encodeRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
297const decodeRequest = Schema.decodeUnknownEffect(
298 Schema.fromJsonString(OrchestrationEffectRequestV2),
299);
300
301const rowToEffect = (row: EffectRow) =>
302 decodeRequest(row.payload_json).pipe(
303 Effect.map((request): OrchestrationEffectV2 => ({
304 id: row.effect_id,
305 commandId: CommandId.make(row.command_id),
306 threadId: ThreadId.make(row.thread_id),
307 request,
308 status: row.status as OrchestrationEffectStatusV2,
309 attemptCount: row.attempt_count,
310 availableAt: row.available_at,
311 leaseOwner: row.lease_owner,
312 createdAt: row.created_at,
313 updatedAt: row.updated_at,
314 completedAt: row.completed_at,
315 lastError: row.last_error,
316 })),
317 );
318
319export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = Layer.effect(
320 EffectOutboxV2,
321 Effect.gen(function* () {
322 const sql = yield* SqlClient.SqlClient;
323 const available = yield* Queue.dropping<void>(64);
324 const cancellationSignals = new Map<string, Deferred.Deferred<void>>();
325 const settledSignals = new Map<string, Deferred.Deferred<void>>();
326 const signalSettled = (effectIds: ReadonlyArray<string>) =>
327 Effect.forEach(
328 effectIds,
329 (effectId) => {
330 const signal = settledSignals.get(effectId);
331 if (signal === undefined) return Effect.void;
332 settledSignals.delete(effectId);
333 return Deferred.succeed(signal, undefined);
334 },
335 { discard: true },
336 );
337 const notifyAvailable = (count = 1) =>
338 Queue.offerAll(
339 available,
340 Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined),
341 ).pipe(Effect.asVoid);
342 // Retry backoff must block later effects so turns cannot race a pending rollback.
343 const claimableCandidatePredicate = (
344 availableBefore?: string,
345 excludeRestartContinuations = false,
346 maxRunningTitleGenerations?: number,
347 ) =>
348 sql`
349 ${
350 availableBefore === undefined
351 ? sql`1 = 1`
352 : sql`candidate.available_at <= ${availableBefore}`
353 }
354 AND candidate.status = 'pending'
355 AND NOT EXISTS (
356 SELECT 1
357 FROM orchestration_v2_effect_outbox AS active
358 WHERE active.thread_id = candidate.thread_id
359 AND (
360 active.status = 'running'
361 OR (
362 active.status = 'pending'
363 AND active.rowid < candidate.rowid
364 AND ${
365 excludeRestartContinuations
366 ? sql`active.effect_type != 'provider-runtime.continue'`
367 : sql`1 = 1`
368 }
369 )
370 )
371 AND (
372 (
373 candidate.effect_type = 'thread-title.generate'
374 AND active.effect_type = 'thread-title.generate'
375 )
376 OR
377 (
378 candidate.effect_type != 'thread-title.generate'
379 AND active.effect_type != 'thread-title.generate'
380 )
381 )
382 )
383 AND ${
384 maxRunningTitleGenerations === undefined
385 ? sql`1 = 1`
386 : sql`(
387 candidate.effect_type != 'thread-title.generate'
388 OR (
389 SELECT COUNT(*)
390 FROM orchestration_v2_effect_outbox AS running_title
391 WHERE running_title.status = 'running'
392 AND running_title.effect_type = 'thread-title.generate'
393 ) < ${maxRunningTitleGenerations}
394 )`
395 }
396 `;
397
398 const cancellationSignal = (effectId: string) => {
399 const existing = cancellationSignals.get(effectId);
400 if (existing !== undefined) return existing;
401 const created = Deferred.makeUnsafe<void>();
402 cancellationSignals.set(effectId, created);
403 return created;
404 };
405
406 const decodeRows = (operation: string, rows: ReadonlyArray<EffectRow>) =>
407 Effect.forEach(rows, rowToEffect).pipe(
408 Effect.mapError((cause) => new EffectOutboxError({ operation, cause })),
409 );
410
411 const service: EffectOutboxV2Shape = {
412 enqueue: Effect.fn("EffectOutbox.enqueue")(
413 function* (effects) {
414 const now = yield* DateTime.now;
415 const nowIso = DateTime.formatIso(now);
416 yield* Effect.forEach(
417 effects,
418 (effect) => sql`
419 INSERT INTO orchestration_v2_effect_outbox (
420 effect_id,
421 command_id,
422 thread_id,
423 effect_type,
424 payload_json,
425 status,
426 attempt_count,
427 available_at,
428 created_at,
429 updated_at
430 )
431 VALUES (
432 ${effect.id},
433 ${effect.commandId},
434 ${effect.threadId},
435 ${effect.request.type},
436 ${encodeRequest(effect.request)},
437 'pending',
438 0,
439 ${DateTime.formatIso(effect.availableAt ?? now)},
440 ${nowIso},
441 ${nowIso}
442 )
443 ON CONFLICT(effect_id) DO NOTHING
444 `,
445 { concurrency: 1, discard: true },
446 );
447 // EventSink owns the corresponding post-commit notification.
448 },
449 Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause })),
450 ),
451 get: (effectId) =>
452 sql<EffectRow>`
453 SELECT *
454 FROM orchestration_v2_effect_outbox
455 WHERE effect_id = ${effectId}
456 LIMIT 1
457 `.pipe(
458 NodeSqliteClient.readOnly,
459 Effect.flatMap((rows) => {
460 const row = rows[0];
461 return row === undefined ? Effect.succeedNone : rowToEffect(row).pipe(Effect.asSome);
462 }),
463 Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })),
464 ),
465 awaitAvailable: Queue.take(available),
466 notifyAvailable,
467 listByCommandId: (commandId) =>
468 sql<EffectRow>`
469 SELECT *
470 FROM orchestration_v2_effect_outbox
471 WHERE command_id = ${commandId}
472 ORDER BY created_at ASC, effect_id ASC
473 `.pipe(
474 NodeSqliteClient.readOnly,
475 Effect.flatMap((rows) => decodeRows("list", rows)),
476 Effect.mapError((cause) =>
477 isEffectOutboxError(cause)
478 ? cause
479 : new EffectOutboxError({ operation: "list", cause }),
480 ),
481 ),
482 firstSteer: (threadId, messageId) =>
483 sql<EffectRow>`
484 SELECT *
485 FROM orchestration_v2_effect_outbox
486 WHERE thread_id = ${threadId}
487 AND effect_type = 'provider-turn.steer'
488 AND json_extract(payload_json, '$.messageId') = ${messageId}
489 ORDER BY rowid ASC
490 LIMIT 1
491 `.pipe(
492 NodeSqliteClient.readOnly,
493 Effect.flatMap((rows) => decodeRows("first-steer", rows)),
494 Effect.map((effects) => Option.fromNullishOr(effects[0])),
495 Effect.mapError((cause) =>
496 isEffectOutboxError(cause)
497 ? cause
498 : new EffectOutboxError({ operation: "first-steer", cause }),
499 ),
500 ),
501 cancelUnsettled: Effect.fn("EffectOutbox.cancelUnsettled")(
502 function* ({ threadId, effectTypes, reason }) {
503 if (effectTypes.length === 0) return [];
504 const now = DateTime.formatIso(yield* DateTime.now);
505 const rows = yield* sql<{ readonly effect_id: string }>`
506 UPDATE orchestration_v2_effect_outbox
507 SET
508 status = 'cancelled',
509 lease_owner = NULL,
510 completed_at = ${now},
511 updated_at = ${now},
512 last_error = ${reason}
513 WHERE thread_id = ${threadId}
514 AND status IN ('pending', 'running')
515 AND effect_type IN ${sql.in(effectTypes)}
516 RETURNING effect_id
517 `;
518 return rows.map(({ effect_id }) => effect_id);
519 },
520 Effect.mapError((cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause })),
521 ),
522 signalCancellations: Effect.fn("EffectOutbox.signalCancellations")(function* (effectIds) {
523 yield* Effect.forEach(
524 effectIds,
525 (effectId) => {
526 const signal = cancellationSignals.get(effectId);
527 return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
528 },
529 { discard: true },
530 );
531 yield* signalSettled(effectIds);
532 if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);
533 }),
534 awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)),
535 clearCancellation: (effectId) =>
536 Effect.sync(() => {
537 cancellationSignals.delete(effectId);
538 }),
539 awaitSettled: Effect.fn("EffectOutbox.awaitSettled")(function* (effectId) {
540 // Registered before the read, so a settle right after it still resolves.
541 const signal = settledSignals.get(effectId) ?? Deferred.makeUnsafe<void>();
542 settledSignals.set(effectId, signal);
543 const effect = yield* service.get(effectId);
544 if (Option.exists(effect, ({ status }) => status === "pending" || status === "running")) {
545 return yield* Deferred.await(signal);
546 }
547 yield* signalSettled([effectId]);
548 }),
549 reconcileAfterProcessLoss: Effect.gen(function* () {
550 const now = DateTime.formatIso(yield* DateTime.now);
551 const cancelledRows = yield* sql<{ readonly effect_id: string }>`
552 UPDATE orchestration_v2_effect_outbox
553 SET
554 status = 'cancelled',
555 lease_owner = NULL,
556 completed_at = ${now},
557 updated_at = ${now},
558 last_error = 'Cancelled because the server process ended before the effect completed.'
559 WHERE status IN ('pending', 'running')
560 AND effect_type IN ${sql.in(PROCESS_BOUND_EFFECT_TYPES)}
561 RETURNING effect_id
562 `;
563 const requeuedRows = yield* sql<{ readonly effect_id: string }>`
564 UPDATE orchestration_v2_effect_outbox
565 SET
566 status = 'pending',
567 lease_owner = NULL,
568 available_at = ${now},
569 updated_at = ${now},
570 last_error = 'Requeued after the previous server process ended.'
571 WHERE status = 'running'
572 AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)}
573 RETURNING effect_id
574 `;
575 if (requeuedRows.length > 0) yield* notifyAvailable(requeuedRows.length);
576 return { requeued: requeuedRows.length, cancelled: cancelledRows.length };
577 }).pipe(
578 Effect.mapError(
579 (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }),
580 ),
581 ),
582 // The worker polls for the next effect even when there is no work to claim.
583 claimNext: Effect.fnUntraced(
584 function* ({ workerId, excludeRestartContinuations = false, maxRunningTitleGenerations }) {
585 const now = yield* DateTime.now;
586 const nowIso = DateTime.formatIso(now);
587 // Idle claims return empty; tracing their full SQL on every poll overwhelms useful traces.
588 const claimStatement = sql<EffectRow>`
589 UPDATE orchestration_v2_effect_outbox
590 SET
591 status = 'running',
592 attempt_count = attempt_count + 1,
593 lease_owner = ${workerId},
594 updated_at = ${nowIso},
595 last_error = NULL
596 WHERE effect_id = (
597 SELECT candidate.effect_id
598 FROM orchestration_v2_effect_outbox AS candidate
599 WHERE ${claimableCandidatePredicate(
600 nowIso,
601 excludeRestartContinuations,
602 maxRunningTitleGenerations,
603 )}
604 AND ${excludeRestartContinuations ? sql`candidate.effect_type != 'provider-runtime.continue'` : sql`1 = 1`}
605 ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC
606 LIMIT 1
607 )
608 RETURNING *
609 `;
610 while (true) {
611 const rows = yield* claimStatement.pipe(Effect.withTracerEnabled(false));
612 const row = rows[0];
613 if (row === undefined) return Option.none();
614 const decoded = yield* Effect.result(rowToEffect(row));
615 if (Result.isSuccess(decoded)) {
616 cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());
617 return Option.some(decoded.success);
618 }
619 // Left running, an unreadable row would block every later effect on its thread.
620 yield* Effect.logWarning("Failing an orchestration effect this build cannot decode", {
621 effectId: row.effect_id,
622 effectType: row.effect_type,
623 cause: decoded.failure,
624 });
625 yield* service.fail({
626 effectId: row.effect_id,
627 workerId,
628 error: `This server build cannot decode the ${row.effect_type} effect.`,
629 });
630 }
631 },
632 Effect.mapError((cause) =>
633 isEffectOutboxError(cause) ? cause : new EffectOutboxError({ operation: "claim", cause }),
634 ),
635 ),
636 nextClaimableAt: Effect.fnUntraced(
637 function* ({
638 maxRunningTitleGenerations,
639 }: { readonly maxRunningTitleGenerations?: number } = {}) {
640 const rows = yield* sql<{ readonly available_at: string | null }>`
641 SELECT MIN(candidate.available_at) AS available_at
642 FROM orchestration_v2_effect_outbox AS candidate
643 WHERE ${claimableCandidatePredicate(undefined, false, maxRunningTitleGenerations)}
644 `.pipe(NodeSqliteClient.readOnly, Effect.withTracerEnabled(false));
645 const availableAt = rows[0]?.available_at;
646 if (availableAt === undefined || availableAt === null) return Option.none();
647 const parsed = DateTime.make(availableAt);
648 if (Option.isNone(parsed)) {
649 return yield* new EffectOutboxError({
650 operation: "next-claimable",
651 cause: `Invalid available_at timestamp: ${availableAt}`,
652 });
653 }
654 return parsed;
655 },
656 Effect.mapError((cause) =>
657 isEffectOutboxError(cause)
658 ? cause
659 : new EffectOutboxError({ operation: "next-claimable", cause }),
660 ),
661 ),
662 succeed: Effect.fn("EffectOutbox.succeed")(
663 function* ({ effectId, workerId }) {
664 const now = DateTime.formatIso(yield* DateTime.now);
665 const rows = yield* sql<{ readonly effect_id: string }>`
666 UPDATE orchestration_v2_effect_outbox
667 SET
668 status = 'succeeded',
669 lease_owner = NULL,
670 completed_at = ${now},
671 updated_at = ${now},
672 last_error = NULL
673 WHERE effect_id = ${effectId}
674 AND status = 'running'
675 AND lease_owner = ${workerId}
676 RETURNING effect_id
677 `;
678 if (rows.length === 1) {
679 cancellationSignals.delete(effectId);
680 yield* signalSettled([effectId]);
681 yield* notifyAvailable();
682 }
683 return rows.length === 1;
684 },
685 (effect, { effectId }) =>
686 effect.pipe(
687 Effect.mapError(
688 (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
689 ),
690 ),
691 ),
692 retry: Effect.fn("EffectOutbox.retry")(
693 function* ({ effectId, workerId, error, delayMs }) {
694 const now = yield* DateTime.now;
695 const nowIso = DateTime.formatIso(now);
696 const availableAt = DateTime.formatIso(
697 DateTime.add(now, { milliseconds: Math.max(0, delayMs) }),
698 );
699 const rows = yield* sql<{ readonly effect_id: string }>`
700 UPDATE orchestration_v2_effect_outbox
701 SET
702 status = 'pending',
703 available_at = ${availableAt},
704 lease_owner = NULL,
705 updated_at = ${nowIso},
706 last_error = ${error}
707 WHERE effect_id = ${effectId}
708 AND status = 'running'
709 AND lease_owner = ${workerId}
710 RETURNING effect_id
711 `;
712 if (rows.length === 1) {
713 cancellationSignals.delete(effectId);
714 yield* notifyAvailable();
715 }
716 return rows.length === 1;
717 },
718 (effect, { effectId }) =>
719 effect.pipe(
720 Effect.mapError(
721 (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
722 ),
723 ),
724 ),
725 fail: Effect.fn("EffectOutbox.fail")(
726 function* ({ effectId, workerId, error }) {
727 const now = DateTime.formatIso(yield* DateTime.now);
728 const rows = yield* sql<{ readonly effect_id: string }>`
729 UPDATE orchestration_v2_effect_outbox
730 SET
731 status = 'failed',
732 lease_owner = NULL,
733 completed_at = ${now},
734 updated_at = ${now},
735 last_error = ${error}
736 WHERE effect_id = ${effectId}
737 AND status = 'running'
738 AND lease_owner = ${workerId}
739 RETURNING effect_id
740 `;
741 if (rows.length === 1) {
742 cancellationSignals.delete(effectId);
743 yield* signalSettled([effectId]);
744 yield* notifyAvailable();
745 }
746 return rows.length === 1;
747 },
748 (effect, { effectId }) =>
749 effect.pipe(
750 Effect.mapError(
751 (cause) => new EffectOutboxError({ operation: "fail", effectId, cause }),
752 ),
753 ),
754 ),
755 pruneSettled: Effect.gen(function* () {
756 const cutoff = DateTime.formatIso(
757 DateTime.subtractDuration(yield* DateTime.now, SETTLED_EFFECT_RETENTION),
758 );
759 // Live continuations retain their preceding intent's cumulative crash budget.
760 // Separate batch statements release the write lock between batches.
761 const deleteBatch = sql<{ readonly effect_id: string }>`
762 DELETE FROM orchestration_v2_effect_outbox
763 WHERE rowid IN (
764 SELECT rowid
765 FROM orchestration_v2_effect_outbox
766 WHERE status IN ('succeeded', 'cancelled')
767 AND completed_at < ${cutoff}
768 AND NOT (
769 effect_type = 'provider-runtime.continue'
770 AND EXISTS (
771 SELECT 1 FROM orchestration_v2_projection_runs AS recovery_run
772 WHERE recovery_run.thread_id = orchestration_v2_effect_outbox.thread_id
773 AND recovery_run.status IN ('queued', 'preparing', 'starting', 'running', 'waiting')
774 AND json_extract(recovery_run.payload_json, '$.restartContinuationOfRunId') =
775 json_extract(orchestration_v2_effect_outbox.payload_json, '$.sourceRunId')
776 )
777 )
778 LIMIT ${PRUNE_BATCH_SIZE}
779 )
780 RETURNING effect_id
781 `;
782 let pruned = 0;
783 while (true) {
784 const deleted = (yield* deleteBatch).length;
785 pruned += deleted;
786 if (deleted < PRUNE_BATCH_SIZE) return pruned;
787 yield* Effect.yieldNow;
788 }
789 }).pipe(
790 Effect.mapError((cause) => new EffectOutboxError({ operation: "prune-settled", cause })),
791 ),
792 };
793
794 return service;
795 }),
796);
797
798export const layerPruneWorker = Layer.effectDiscard(
799 Effect.gen(function* () {
800 const outbox = yield* EffectOutboxV2;
801 yield* forkParked(
802 outbox.pruneSettled.pipe(
803 Effect.catch((cause) => Effect.logWarning("Failed to prune settled effects", { cause })),
804 Effect.repeat(Schedule.spaced(Duration.hours(1))),
805 ),
806 );
807 }),
808);