Open History to see the last commit
1import {
2 CheckpointId,
3 CheckpointScopeId,
4 CommandId,
5 MessageId,
6 ProviderSessionId,
7 RunAttemptId,
8 ProviderApprovalDecision,
9 ProviderUserInputAnswers,
10 ProviderThreadId,
11 ProviderTurnId,
12 RunId,
13 RuntimeRequestId,
14 ThreadId,
15} from "@t3tools/contracts";
16import * as Context from "effect/Context";
17import * as DateTime from "effect/DateTime";
18import * as Deferred from "effect/Deferred";
19import * as Duration from "effect/Duration";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as Queue from "effect/Queue";
24import * as Schedule from "effect/Schedule";
25import * as Schema from "effect/Schema";
26import * as SqlClient from "effect/sql/SqlClient";
27
28import { forkParked } from "../serverActivation.ts";
29
30export const OrchestrationEffectRequestV2 = Schema.Union([
31 Schema.Struct({
32 type: Schema.Literal("provider-runtime.continue"),
33 sourceRunId: RunId,
34 }),
35 Schema.Struct({
36 type: Schema.Literal("provider-session.detach"),
37 providerSessionId: ProviderSessionId,
38 detail: Schema.optional(Schema.String),
39 /** Set on terminal detaches (thread archive/delete): revoke the thread's MCP credentials. */
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 }),
52 Schema.Struct({
53 type: Schema.Literal("provider-turn.steer"),
54 providerSessionId: ProviderSessionId,
55 providerThreadId: ProviderThreadId,
56 providerTurnId: ProviderTurnId,
57 messageId: MessageId,
58 }),
59 Schema.Struct({
60 type: Schema.Literal("provider-turn.restart"),
61 providerSessionId: ProviderSessionId,
62 providerThreadId: ProviderThreadId,
63 providerTurnId: ProviderTurnId,
64 interruptedAttemptId: RunAttemptId,
65 runId: RunId,
66 sessionTransition: Schema.optional(
67 Schema.Union([
68 Schema.Struct({
69 type: Schema.Literal("replace"),
70 replacementProviderSessionId: ProviderSessionId,
71 }),
72 Schema.Struct({ type: Schema.Literal("detach") }),
73 ]),
74 ),
75 }),
76 Schema.Struct({
77 type: Schema.Literal("runtime-request.respond"),
78 providerSessionId: ProviderSessionId,
79 requestId: RuntimeRequestId,
80 decision: Schema.optional(ProviderApprovalDecision),
81 answers: Schema.optional(ProviderUserInputAnswers),
82 }),
83 Schema.Struct({
84 type: Schema.Literal("provider-thread.rollback"),
85 restoreFiles: Schema.optional(Schema.Boolean),
86 providerThreadId: ProviderThreadId,
87 checkpointId: CheckpointId,
88 scopeId: CheckpointScopeId,
89 }),
90 Schema.Struct({
91 type: Schema.Literal("checkpoint.capture"),
92 runId: RunId,
93 scopeId: CheckpointScopeId,
94 }),
95 Schema.Struct({
96 type: Schema.Literal("terminal.cleanup"),
97 }),
98 Schema.Struct({
99 type: Schema.Literal("attachment.cleanup"),
100 attachmentIds: Schema.Array(Schema.String),
101 }),
102 Schema.Struct({
103 type: Schema.Literal("thread-title.generate"),
104 kind: Schema.Union([
105 Schema.Struct({ type: Schema.Literal("initial"), messageId: MessageId }),
106 Schema.Struct({ type: Schema.Literal("regenerate") }),
107 ]),
108 }),
109 /** Follows a Stop: sends `thread.stop` to every delegated task under the stopped thread. */
110 Schema.Struct({
111 type: Schema.Literal("delegated-tasks.stop"),
112 reason: Schema.optional(Schema.String),
113 }),
114]);
115export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type;
116
117export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [
118 "provider-runtime.continue",
119 "provider-session.detach",
120 "provider-thread.rollback",
121 "checkpoint.capture",
122 "terminal.cleanup",
123 "attachment.cleanup",
124 "thread-title.generate",
125 "delegated-tasks.stop",
126] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
127
128export const PROCESS_BOUND_EFFECT_TYPES = [
129 "provider-turn.start",
130 "provider-turn.interrupt",
131 "provider-turn.steer",
132 "provider-turn.restart",
133 "runtime-request.respond",
134] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
135
136export const OrchestrationEffectStatusV2 = Schema.Literals([
137 "pending",
138 "running",
139 "succeeded",
140 "failed",
141 "cancelled",
142]);
143export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type;
144
145/**
146 * How long a succeeded or cancelled effect row is kept after it completes.
147 * Claiming, recovery, the orchestrator and storage cleanup only ask whether a
148 * row is pending, running or failed, so a missing succeeded or cancelled row
149 * reads the same as a present one. Its one other use is deduplication: `enqueue`
150 * ignores an id that already exists, and ids are deterministic per command or
151 * run. Command retries are deduplicated by their receipts first, and a run's
152 * effects are re-enqueued only around one server restart, so a week is far
153 * longer than either and leaves recent history for debugging.
154 * Failed rows are kept: storage cleanup keeps a deleted thread's worktree while
155 * any of its effects failed.
156 */
157export const SETTLED_EFFECT_RETENTION = Duration.days(7);
158const PRUNE_BATCH_SIZE = 500;
159
160export interface OrchestrationEffectV2 {
161 readonly id: string;
162 readonly commandId: CommandId;
163 readonly threadId: ThreadId;
164 readonly request: OrchestrationEffectRequestV2;
165 readonly status: OrchestrationEffectStatusV2;
166 readonly attemptCount: number;
167 readonly availableAt: string;
168 readonly leaseOwner: string | null;
169 readonly leaseExpiresAt: string | null;
170 readonly createdAt: string;
171 readonly updatedAt: string;
172 readonly completedAt: string | null;
173 readonly lastError: string | null;
174}
175
176export interface PendingOrchestrationEffectV2 {
177 readonly id: string;
178 readonly commandId: CommandId;
179 readonly threadId: ThreadId;
180 readonly request: OrchestrationEffectRequestV2;
181 readonly availableAt?: DateTime.Utc;
182}
183
184export class EffectOutboxError extends Schema.TaggedError<EffectOutboxError>()(
185 "EffectOutboxError",
186 {
187 operation: Schema.String,
188 effectId: Schema.optional(Schema.String),
189 cause: Schema.optional(Schema.Defect()),
190 },
191) {
192 override get message(): string {
193 return `Orchestration effect outbox ${this.operation} failed${this.effectId === undefined ? "" : ` for ${this.effectId}`}.`;
194 }
195}
196
197const isEffectOutboxError = Schema.is(EffectOutboxError);
198
199export interface EffectOutboxV2Shape {
200 readonly awaitAvailable: Effect.Effect<void>;
201 readonly notifyAvailable: (count?: number) => Effect.Effect<void>;
202 /** Persist rows only. Notify workers after the surrounding transaction commits. */
203 readonly enqueue: (
204 effects: ReadonlyArray<PendingOrchestrationEffectV2>,
205 ) => Effect.Effect<void, EffectOutboxError>;
206 readonly get: (
207 effectId: string,
208 ) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
209 readonly listByCommandId: (
210 commandId: CommandId,
211 ) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
212 readonly cancelUnsettled: (input: {
213 readonly threadId: ThreadId;
214 readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
215 readonly reason: string;
216 }) => Effect.Effect<ReadonlyArray<string>, EffectOutboxError>;
217 readonly signalCancellations: (effectIds: ReadonlyArray<string>) => Effect.Effect<void>;
218 readonly awaitCancellation: (effectId: string) => Effect.Effect<void>;
219 readonly clearCancellation: (effectId: string) => Effect.Effect<void>;
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 /** Deletes succeeded and cancelled rows older than `SETTLED_EFFECT_RETENTION`. Returns the count. */
246 readonly pruneSettled: Effect.Effect<number, EffectOutboxError>;
247}
248
249export class EffectOutboxV2 extends Context.Service<EffectOutboxV2, EffectOutboxV2Shape>()(
250 "t3/orchestration-v2/EffectOutbox/EffectOutboxV2",
251) {}
252
253type EffectRow = {
254 readonly effect_id: string;
255 readonly command_id: string;
256 readonly thread_id: string;
257 readonly effect_type: string;
258 readonly payload_json: string;
259 readonly status: string;
260 readonly attempt_count: number;
261 readonly available_at: string;
262 readonly lease_owner: string | null;
263 readonly lease_expires_at: string | null;
264 readonly created_at: string;
265 readonly updated_at: string;
266 readonly completed_at: string | null;
267 readonly last_error: string | null;
268};
269
270const encodeRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
271const decodeRequest = Schema.decodeUnknownEffect(
272 Schema.fromJsonString(OrchestrationEffectRequestV2),
273);
274
275const rowToEffect = (row: EffectRow) =>
276 decodeRequest(row.payload_json).pipe(
277 Effect.map((request): OrchestrationEffectV2 => ({
278 id: row.effect_id,
279 commandId: CommandId.make(row.command_id),
280 threadId: ThreadId.make(row.thread_id),
281 request,
282 status: row.status as OrchestrationEffectStatusV2,
283 attemptCount: row.attempt_count,
284 availableAt: row.available_at,
285 leaseOwner: row.lease_owner,
286 leaseExpiresAt: row.lease_expires_at,
287 createdAt: row.created_at,
288 updatedAt: row.updated_at,
289 completedAt: row.completed_at,
290 lastError: row.last_error,
291 })),
292 );
293
294export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = Layer.effect(
295 EffectOutboxV2,
296 Effect.gen(function* () {
297 const sql = yield* SqlClient.SqlClient;
298 // Availability is only a bounded latency hint; durable rows remain
299 // authoritative. Retaining a small burst lets multiple worker slots wake
300 // for distinct threads without allowing notifications to grow unbounded.
301 const available = yield* Queue.dropping<void>(64);
302 const cancellationSignals = new Map<string, Deferred.Deferred<void>>();
303 const notifyAvailable = (count = 1) =>
304 Queue.offerAll(
305 available,
306 Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined),
307 ).pipe(Effect.asVoid);
308 // Each thread runs its effects one at a time, in enqueue (rowid) order. An earlier
309 // effect waiting out a retry backoff still blocks later ones, so a turn
310 // cannot start while a failed rollback is about to restore files. A claim
311 // that skips restart continuations is not blocked by them either.
312 // Title generation is correlated metadata work, so it has its own
313 // per-thread lane and cannot delay provider lifecycle effects.
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: (effects) =>
370 Effect.gen(function* () {
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 // Do not signal here: callers enqueue inside a larger transaction,
405 // and workers must only observe availability after that transaction
406 // commits. EventSink owns the corresponding post-commit notification.
407 }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause }))),
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 Effect.flatMap((rows) => {
416 const row = rows[0];
417 return row === undefined
418 ? Effect.succeed(Option.none())
419 : rowToEffect(row).pipe(Effect.map(Option.some));
420 }),
421 Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })),
422 ),
423 awaitAvailable: Queue.take(available),
424 notifyAvailable,
425 listByCommandId: (commandId) =>
426 sql<EffectRow>`
427 SELECT *
428 FROM orchestration_v2_effect_outbox
429 WHERE command_id = ${commandId}
430 ORDER BY created_at ASC, effect_id ASC
431 `.pipe(
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: ({ threadId, effectTypes, reason }) =>
440 Effect.gen(function* () {
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 lease_expires_at = NULL,
449 completed_at = ${now},
450 updated_at = ${now},
451 last_error = ${reason}
452 WHERE thread_id = ${threadId}
453 AND status IN ('pending', 'running')
454 AND effect_type IN ${sql.in(effectTypes)}
455 RETURNING effect_id
456 `;
457 return rows.map(({ effect_id }) => effect_id);
458 }).pipe(
459 Effect.mapError(
460 (cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause }),
461 ),
462 ),
463 signalCancellations: (effectIds) =>
464 Effect.gen(function* () {
465 yield* Effect.forEach(
466 effectIds,
467 (effectId) => {
468 const signal = cancellationSignals.get(effectId);
469 return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
470 },
471 { discard: true },
472 );
473 // Cancellation can unblock other pending work on the same thread.
474 // This method is deliberately post-commit, so it is also the safe
475 // place to wake claimers after the durable status change.
476 if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);
477 }),
478 awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)),
479 clearCancellation: (effectId) =>
480 Effect.sync(() => {
481 cancellationSignals.delete(effectId);
482 }),
483 reconcileAfterProcessLoss: Effect.gen(function* () {
484 const now = DateTime.formatIso(yield* DateTime.now);
485 const cancelledRows = yield* sql<{ readonly effect_id: string }>`
486 UPDATE orchestration_v2_effect_outbox
487 SET
488 status = 'cancelled',
489 lease_owner = NULL,
490 lease_expires_at = NULL,
491 completed_at = ${now},
492 updated_at = ${now},
493 last_error = 'Cancelled because the server process ended before the effect completed.'
494 WHERE status IN ('pending', 'running')
495 AND effect_type IN ${sql.in(PROCESS_BOUND_EFFECT_TYPES)}
496 RETURNING effect_id
497 `;
498 const requeuedRows = yield* sql<{ readonly effect_id: string }>`
499 UPDATE orchestration_v2_effect_outbox
500 SET
501 status = 'pending',
502 lease_owner = NULL,
503 lease_expires_at = NULL,
504 available_at = ${now},
505 updated_at = ${now},
506 last_error = 'Requeued after the previous server process ended.'
507 WHERE status = 'running'
508 AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)}
509 RETURNING effect_id
510 `;
511 if (requeuedRows.length > 0) yield* notifyAvailable(requeuedRows.length);
512 return { requeued: requeuedRows.length, cancelled: cancelledRows.length };
513 }).pipe(
514 Effect.mapError(
515 (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }),
516 ),
517 ),
518 claimNext: ({ workerId, leaseDurationMs, excludeRestartContinuations = false }) =>
519 Effect.gen(function* () {
520 const now = yield* DateTime.now;
521 const nowIso = DateTime.formatIso(now);
522 const leaseExpiresAt = DateTime.formatIso(
523 DateTime.add(now, { milliseconds: Math.max(1, leaseDurationMs) }),
524 );
525 // Empty safety claims are expected while the daemon is idle. Tracing
526 // this query records the full SQL text on every poll and can dominate
527 // the local trace without adding actionable information.
528 const claimStatement = sql<EffectRow>`
529 UPDATE orchestration_v2_effect_outbox
530 SET
531 status = 'running',
532 attempt_count = attempt_count + 1,
533 lease_owner = ${workerId},
534 lease_expires_at = ${leaseExpiresAt},
535 updated_at = ${nowIso},
536 last_error = NULL
537 WHERE effect_id = (
538 SELECT candidate.effect_id
539 FROM orchestration_v2_effect_outbox AS candidate
540 WHERE ${claimableCandidatePredicate(nowIso, excludeRestartContinuations)}
541 AND ${excludeRestartContinuations ? sql`candidate.effect_type != 'provider-runtime.continue'` : sql`1 = 1`}
542 ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC
543 LIMIT 1
544 )
545 RETURNING *
546 `;
547 const rows = yield* claimStatement.pipe(Effect.withTracerEnabled(false));
548 const row = rows[0];
549 if (row === undefined) return Option.none();
550 cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());
551 return Option.some(yield* rowToEffect(row));
552 }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause }))),
553 nextClaimableAt: Effect.gen(function* () {
554 const rows = yield* sql<{ readonly available_at: string | null }>`
555 SELECT MIN(candidate.available_at) AS available_at
556 FROM orchestration_v2_effect_outbox AS candidate
557 WHERE ${claimableCandidatePredicate()}
558 `.pipe(Effect.withTracerEnabled(false));
559 const availableAt = rows[0]?.available_at;
560 if (availableAt === undefined || availableAt === null) return Option.none();
561 const parsed = DateTime.make(availableAt);
562 if (Option.isNone(parsed)) {
563 return yield* new EffectOutboxError({
564 operation: "next-claimable",
565 cause: `Invalid available_at timestamp: ${availableAt}`,
566 });
567 }
568 return parsed;
569 }).pipe(
570 Effect.mapError((cause) =>
571 isEffectOutboxError(cause)
572 ? cause
573 : new EffectOutboxError({ operation: "next-claimable", cause }),
574 ),
575 ),
576 succeed: ({ effectId, workerId }) =>
577 Effect.gen(function* () {
578 const now = DateTime.formatIso(yield* DateTime.now);
579 const rows = yield* sql<{ readonly effect_id: string }>`
580 UPDATE orchestration_v2_effect_outbox
581 SET
582 status = 'succeeded',
583 lease_owner = NULL,
584 lease_expires_at = NULL,
585 completed_at = ${now},
586 updated_at = ${now},
587 last_error = NULL
588 WHERE effect_id = ${effectId}
589 AND status = 'running'
590 AND lease_owner = ${workerId}
591 RETURNING effect_id
592 `;
593 if (rows.length === 1) {
594 cancellationSignals.delete(effectId);
595 yield* notifyAvailable();
596 }
597 return rows.length === 1;
598 }).pipe(
599 Effect.mapError(
600 (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
601 ),
602 ),
603 retry: ({ effectId, workerId, error, delayMs }) =>
604 Effect.gen(function* () {
605 const now = yield* DateTime.now;
606 const nowIso = DateTime.formatIso(now);
607 const availableAt = DateTime.formatIso(
608 DateTime.add(now, { milliseconds: Math.max(0, delayMs) }),
609 );
610 const rows = yield* sql<{ readonly effect_id: string }>`
611 UPDATE orchestration_v2_effect_outbox
612 SET
613 status = 'pending',
614 available_at = ${availableAt},
615 lease_owner = NULL,
616 lease_expires_at = NULL,
617 updated_at = ${nowIso},
618 last_error = ${error}
619 WHERE effect_id = ${effectId}
620 AND status = 'running'
621 AND lease_owner = ${workerId}
622 RETURNING effect_id
623 `;
624 if (rows.length === 1) {
625 cancellationSignals.delete(effectId);
626 yield* notifyAvailable();
627 }
628 return rows.length === 1;
629 }).pipe(
630 Effect.mapError(
631 (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
632 ),
633 ),
634 fail: ({ effectId, workerId, error }) =>
635 Effect.gen(function* () {
636 const now = DateTime.formatIso(yield* DateTime.now);
637 const rows = yield* sql<{ readonly effect_id: string }>`
638 UPDATE orchestration_v2_effect_outbox
639 SET
640 status = 'failed',
641 lease_owner = NULL,
642 lease_expires_at = NULL,
643 completed_at = ${now},
644 updated_at = ${now},
645 last_error = ${error}
646 WHERE effect_id = ${effectId}
647 AND status = 'running'
648 AND lease_owner = ${workerId}
649 RETURNING effect_id
650 `;
651 if (rows.length === 1) {
652 cancellationSignals.delete(effectId);
653 yield* notifyAvailable();
654 }
655 return rows.length === 1;
656 }).pipe(
657 Effect.mapError((cause) => new EffectOutboxError({ operation: "fail", effectId, cause })),
658 ),
659 pruneSettled: Effect.gen(function* () {
660 const cutoff = DateTime.formatIso(
661 DateTime.subtractDuration(yield* DateTime.now, SETTLED_EFFECT_RETENTION),
662 );
663 // Each batch is its own statement, so a large backlog never holds the
664 // write lock for long and writers can commit between batches.
665 const deleteBatch = sql<{ readonly effect_id: string }>`
666 DELETE FROM orchestration_v2_effect_outbox
667 WHERE rowid IN (
668 SELECT rowid
669 FROM orchestration_v2_effect_outbox
670 WHERE status IN ('succeeded', 'cancelled')
671 AND completed_at < ${cutoff}
672 LIMIT ${PRUNE_BATCH_SIZE}
673 )
674 RETURNING effect_id
675 `;
676 let pruned = 0;
677 while (true) {
678 const deleted = (yield* deleteBatch).length;
679 pruned += deleted;
680 if (deleted < PRUNE_BATCH_SIZE) return pruned;
681 yield* Effect.yieldNow;
682 }
683 }).pipe(
684 Effect.mapError((cause) => new EffectOutboxError({ operation: "prune-settled", cause })),
685 ),
686 };
687
688 return service;
689 }),
690);
691
692/** Prunes settled effect rows once the server is active, then every hour. */
693export const layerPruneWorker = Layer.effectDiscard(
694 Effect.gen(function* () {
695 const outbox = yield* EffectOutboxV2;
696 yield* forkParked(
697 outbox.pruneSettled.pipe(
698 Effect.catch((cause) => Effect.logWarning("Failed to prune settled effects", { cause })),
699 Effect.repeat(Schedule.spaced(Duration.hours(1))),
700 ),
701 );
702 }),
703);