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