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