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/**
156 * Command retries are deduplicated by their receipts first, and a run's effects
157 * are re-enqueued only around one server restart, so a week is far longer than
158 * either and leaves recent history for debugging. Failed rows are kept: storage
159 * cleanup keeps a deleted thread's worktree while any of its effects failed.
160 */
161export const SETTLED_EFFECT_RETENTION = Duration.days(7);
162const PRUNE_BATCH_SIZE = 500;
163
164export interface OrchestrationEffectV2 {
165 readonly id: string;
166 readonly commandId: CommandId;
167 readonly threadId: ThreadId;
168 readonly request: OrchestrationEffectRequestV2;
169 readonly status: OrchestrationEffectStatusV2;
170 readonly attemptCount: number;
171 readonly availableAt: string;
172 readonly leaseOwner: string | null;
173 readonly leaseExpiresAt: string | null;
174 readonly createdAt: string;
175 readonly updatedAt: string;
176 readonly completedAt: string | null;
177 readonly lastError: string | null;
178}
179
180export interface PendingOrchestrationEffectV2 {
181 readonly id: string;
182 readonly commandId: CommandId;
183 readonly threadId: ThreadId;
184 readonly request: OrchestrationEffectRequestV2;
185 readonly availableAt?: DateTime.Utc;
186}
187
188export class EffectOutboxError extends Schema.TaggedError<EffectOutboxError>()(
189 "EffectOutboxError",
190 {
191 operation: Schema.String,
192 effectId: Schema.optional(Schema.String),
193 cause: Schema.optional(Schema.Defect()),
194 },
195) {
196 override get message(): string {
197 return `Orchestration effect outbox ${this.operation} failed${this.effectId === undefined ? "" : ` for ${this.effectId}`}.`;
198 }
199}
200
201const isEffectOutboxError = Schema.is(EffectOutboxError);
202
203export interface EffectOutboxV2Shape {
204 readonly awaitAvailable: Effect.Effect<void>;
205 readonly notifyAvailable: (count?: number) => Effect.Effect<void>;
206 /** Persist rows only. Notify workers after the surrounding transaction commits. */
207 readonly enqueue: (
208 effects: ReadonlyArray<PendingOrchestrationEffectV2>,
209 ) => Effect.Effect<void, EffectOutboxError>;
210 readonly get: (
211 effectId: string,
212 ) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
213 readonly listByCommandId: (
214 commandId: CommandId,
215 ) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
216 readonly cancelUnsettled: (input: {
217 readonly threadId: ThreadId;
218 readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
219 readonly reason: string;
220 }) => Effect.Effect<ReadonlyArray<string>, EffectOutboxError>;
221 readonly signalCancellations: (effectIds: ReadonlyArray<string>) => Effect.Effect<void>;
222 readonly awaitCancellation: (effectId: string) => Effect.Effect<void>;
223 readonly clearCancellation: (effectId: string) => Effect.Effect<void>;
224 /** Resolves once the effect is neither pending nor running, or right away when it does not exist. */
225 readonly awaitSettled: (effectId: string) => Effect.Effect<void, EffectOutboxError>;
226 readonly reconcileAfterProcessLoss: Effect.Effect<
227 { readonly requeued: number; readonly cancelled: number },
228 EffectOutboxError
229 >;
230 readonly claimNext: (input: {
231 readonly workerId: string;
232 readonly leaseDurationMs: number;
233 readonly excludeRestartContinuations?: boolean;
234 }) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
235 readonly nextClaimableAt: Effect.Effect<Option.Option<DateTime.Utc>, EffectOutboxError>;
236 readonly succeed: (input: {
237 readonly effectId: string;
238 readonly workerId: string;
239 }) => Effect.Effect<boolean, EffectOutboxError>;
240 readonly retry: (input: {
241 readonly effectId: string;
242 readonly workerId: string;
243 readonly error: string;
244 readonly delayMs: number;
245 }) => Effect.Effect<boolean, EffectOutboxError>;
246 readonly fail: (input: {
247 readonly effectId: string;
248 readonly workerId: string;
249 readonly error: string;
250 }) => Effect.Effect<boolean, EffectOutboxError>;
251 readonly pruneSettled: Effect.Effect<number, EffectOutboxError>;
252}
253
254export class EffectOutboxV2 extends Context.Service<EffectOutboxV2, EffectOutboxV2Shape>()(
255 "t3/orchestration-v2/EffectOutbox/EffectOutboxV2",
256) {}
257
258type EffectRow = {
259 readonly effect_id: string;
260 readonly command_id: string;
261 readonly thread_id: string;
262 readonly effect_type: string;
263 readonly payload_json: string;
264 readonly status: string;
265 readonly attempt_count: number;
266 readonly available_at: string;
267 readonly lease_owner: string | null;
268 readonly lease_expires_at: string | null;
269 readonly created_at: string;
270 readonly updated_at: string;
271 readonly completed_at: string | null;
272 readonly last_error: string | null;
273};
274
275const encodeRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
276const decodeRequest = Schema.decodeUnknownEffect(
277 Schema.fromJsonString(OrchestrationEffectRequestV2),
278);
279
280const rowToEffect = (row: EffectRow) =>
281 decodeRequest(row.payload_json).pipe(
282 Effect.map((request): OrchestrationEffectV2 => ({
283 id: row.effect_id,
284 commandId: CommandId.make(row.command_id),
285 threadId: ThreadId.make(row.thread_id),
286 request,
287 status: row.status as OrchestrationEffectStatusV2,
288 attemptCount: row.attempt_count,
289 availableAt: row.available_at,
290 leaseOwner: row.lease_owner,
291 leaseExpiresAt: row.lease_expires_at,
292 createdAt: row.created_at,
293 updatedAt: row.updated_at,
294 completedAt: row.completed_at,
295 lastError: row.last_error,
296 })),
297 );
298
299export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = Layer.effect(
300 EffectOutboxV2,
301 Effect.gen(function* () {
302 const sql = yield* SqlClient.SqlClient;
303 const available = yield* Queue.dropping<void>(64);
304 const cancellationSignals = new Map<string, Deferred.Deferred<void>>();
305 const settledSignals = new Map<string, Deferred.Deferred<void>>();
306 const signalSettled = (effectIds: ReadonlyArray<string>) =>
307 Effect.forEach(
308 effectIds,
309 (effectId) => {
310 const signal = settledSignals.get(effectId);
311 if (signal === undefined) return Effect.void;
312 settledSignals.delete(effectId);
313 return Deferred.succeed(signal, undefined);
314 },
315 { discard: true },
316 );
317 const notifyAvailable = (count = 1) =>
318 Queue.offerAll(
319 available,
320 Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined),
321 ).pipe(Effect.asVoid);
322 // An earlier effect waiting out a retry backoff still blocks later ones, so
323 // a turn cannot start while a failed rollback is about to restore files.
324 const claimableCandidatePredicate = (
325 availableBefore?: string,
326 excludeRestartContinuations = false,
327 ) =>
328 sql`
329 ${
330 availableBefore === undefined
331 ? sql`1 = 1`
332 : sql`candidate.available_at <= ${availableBefore}`
333 }
334 AND candidate.status = 'pending'
335 AND NOT EXISTS (
336 SELECT 1
337 FROM orchestration_v2_effect_outbox AS active
338 WHERE active.thread_id = candidate.thread_id
339 AND (
340 active.status = 'running'
341 OR (
342 active.status = 'pending'
343 AND active.rowid < candidate.rowid
344 AND ${
345 excludeRestartContinuations
346 ? sql`active.effect_type != 'provider-runtime.continue'`
347 : sql`1 = 1`
348 }
349 )
350 )
351 AND (
352 (
353 candidate.effect_type = 'thread-title.generate'
354 AND active.effect_type = 'thread-title.generate'
355 )
356 OR
357 (
358 candidate.effect_type != 'thread-title.generate'
359 AND active.effect_type != 'thread-title.generate'
360 )
361 )
362 )
363 `;
364
365 const cancellationSignal = (effectId: string) => {
366 const existing = cancellationSignals.get(effectId);
367 if (existing !== undefined) return existing;
368 const created = Deferred.makeUnsafe<void>();
369 cancellationSignals.set(effectId, created);
370 return created;
371 };
372
373 const decodeRows = (operation: string, rows: ReadonlyArray<EffectRow>) =>
374 Effect.forEach(rows, rowToEffect).pipe(
375 Effect.mapError((cause) => new EffectOutboxError({ operation, cause })),
376 );
377
378 const service: EffectOutboxV2Shape = {
379 enqueue: Effect.fn("EffectOutbox.enqueue")(
380 function* (effects) {
381 const now = yield* DateTime.now;
382 const nowIso = DateTime.formatIso(now);
383 yield* Effect.forEach(
384 effects,
385 (effect) => sql`
386 INSERT INTO orchestration_v2_effect_outbox (
387 effect_id,
388 command_id,
389 thread_id,
390 effect_type,
391 payload_json,
392 status,
393 attempt_count,
394 available_at,
395 created_at,
396 updated_at
397 )
398 VALUES (
399 ${effect.id},
400 ${effect.commandId},
401 ${effect.threadId},
402 ${effect.request.type},
403 ${encodeRequest(effect.request)},
404 'pending',
405 0,
406 ${DateTime.formatIso(effect.availableAt ?? now)},
407 ${nowIso},
408 ${nowIso}
409 )
410 ON CONFLICT(effect_id) DO NOTHING
411 `,
412 { concurrency: 1, discard: true },
413 );
414 // EventSink owns the corresponding post-commit notification.
415 },
416 Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause })),
417 ),
418 get: (effectId) =>
419 sql<EffectRow>`
420 SELECT *
421 FROM orchestration_v2_effect_outbox
422 WHERE effect_id = ${effectId}
423 LIMIT 1
424 `.pipe(
425 NodeSqliteClient.readOnly,
426 Effect.flatMap((rows) => {
427 const row = rows[0];
428 return row === undefined
429 ? Effect.succeed(Option.none())
430 : rowToEffect(row).pipe(Effect.map(Option.some));
431 }),
432 Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })),
433 ),
434 awaitAvailable: Queue.take(available),
435 notifyAvailable,
436 listByCommandId: (commandId) =>
437 sql<EffectRow>`
438 SELECT *
439 FROM orchestration_v2_effect_outbox
440 WHERE command_id = ${commandId}
441 ORDER BY created_at ASC, effect_id ASC
442 `.pipe(
443 NodeSqliteClient.readOnly,
444 Effect.flatMap((rows) => decodeRows("list", rows)),
445 Effect.mapError((cause) =>
446 isEffectOutboxError(cause)
447 ? cause
448 : new EffectOutboxError({ operation: "list", cause }),
449 ),
450 ),
451 cancelUnsettled: Effect.fn("EffectOutbox.cancelUnsettled")(
452 function* ({ threadId, effectTypes, reason }) {
453 if (effectTypes.length === 0) return [];
454 const now = DateTime.formatIso(yield* DateTime.now);
455 const rows = yield* sql<{ readonly effect_id: string }>`
456 UPDATE orchestration_v2_effect_outbox
457 SET
458 status = 'cancelled',
459 lease_owner = NULL,
460 lease_expires_at = NULL,
461 completed_at = ${now},
462 updated_at = ${now},
463 last_error = ${reason}
464 WHERE thread_id = ${threadId}
465 AND status IN ('pending', 'running')
466 AND effect_type IN ${sql.in(effectTypes)}
467 RETURNING effect_id
468 `;
469 return rows.map(({ effect_id }) => effect_id);
470 },
471 Effect.mapError((cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause })),
472 ),
473 signalCancellations: Effect.fn("EffectOutbox.signalCancellations")(function* (effectIds) {
474 yield* Effect.forEach(
475 effectIds,
476 (effectId) => {
477 const signal = cancellationSignals.get(effectId);
478 return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
479 },
480 { discard: true },
481 );
482 yield* signalSettled(effectIds);
483 if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);
484 }),
485 awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)),
486 clearCancellation: (effectId) =>
487 Effect.sync(() => {
488 cancellationSignals.delete(effectId);
489 }),
490 awaitSettled: Effect.fn("EffectOutbox.awaitSettled")(function* (effectId) {
491 // Registered before the read, so a settle right after it still resolves.
492 const signal = settledSignals.get(effectId) ?? Deferred.makeUnsafe<void>();
493 settledSignals.set(effectId, signal);
494 const effect = yield* service.get(effectId);
495 if (Option.exists(effect, ({ status }) => status === "pending" || status === "running")) {
496 return yield* Deferred.await(signal);
497 }
498 yield* signalSettled([effectId]);
499 }),
500 reconcileAfterProcessLoss: Effect.gen(function* () {
501 const now = DateTime.formatIso(yield* DateTime.now);
502 const cancelledRows = yield* sql<{ readonly effect_id: string }>`
503 UPDATE orchestration_v2_effect_outbox
504 SET
505 status = 'cancelled',
506 lease_owner = NULL,
507 lease_expires_at = NULL,
508 completed_at = ${now},
509 updated_at = ${now},
510 last_error = 'Cancelled because the server process ended before the effect completed.'
511 WHERE status IN ('pending', 'running')
512 AND effect_type IN ${sql.in(PROCESS_BOUND_EFFECT_TYPES)}
513 RETURNING effect_id
514 `;
515 const requeuedRows = yield* sql<{ readonly effect_id: string }>`
516 UPDATE orchestration_v2_effect_outbox
517 SET
518 status = 'pending',
519 lease_owner = NULL,
520 lease_expires_at = NULL,
521 available_at = ${now},
522 updated_at = ${now},
523 last_error = 'Requeued after the previous server process ended.'
524 WHERE status = 'running'
525 AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)}
526 RETURNING effect_id
527 `;
528 if (requeuedRows.length > 0) yield* notifyAvailable(requeuedRows.length);
529 return { requeued: requeuedRows.length, cancelled: cancelledRows.length };
530 }).pipe(
531 Effect.mapError(
532 (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }),
533 ),
534 ),
535 // The worker polls for the next effect even when there is no work to claim.
536 claimNext: Effect.fnUntraced(
537 function* ({ workerId, leaseDurationMs, excludeRestartContinuations = false }) {
538 const now = yield* DateTime.now;
539 const nowIso = DateTime.formatIso(now);
540 const leaseExpiresAt = DateTime.formatIso(
541 DateTime.add(now, { milliseconds: Math.max(1, leaseDurationMs) }),
542 );
543 // Empty safety claims are expected while the daemon is idle. Tracing
544 // this query records the full SQL text on every poll and can dominate
545 // the local trace without adding actionable information.
546 const claimStatement = sql<EffectRow>`
547 UPDATE orchestration_v2_effect_outbox
548 SET
549 status = 'running',
550 attempt_count = attempt_count + 1,
551 lease_owner = ${workerId},
552 lease_expires_at = ${leaseExpiresAt},
553 updated_at = ${nowIso},
554 last_error = NULL
555 WHERE effect_id = (
556 SELECT candidate.effect_id
557 FROM orchestration_v2_effect_outbox AS candidate
558 WHERE ${claimableCandidatePredicate(nowIso, excludeRestartContinuations)}
559 AND ${excludeRestartContinuations ? sql`candidate.effect_type != 'provider-runtime.continue'` : sql`1 = 1`}
560 ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC
561 LIMIT 1
562 )
563 RETURNING *
564 `;
565 const rows = yield* claimStatement.pipe(Effect.withTracerEnabled(false));
566 const row = rows[0];
567 if (row === undefined) return Option.none();
568 cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());
569 return Option.some(yield* rowToEffect(row));
570 },
571 Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause })),
572 ),
573 nextClaimableAt: Effect.gen(function* () {
574 const rows = yield* sql<{ readonly available_at: string | null }>`
575 SELECT MIN(candidate.available_at) AS available_at
576 FROM orchestration_v2_effect_outbox AS candidate
577 WHERE ${claimableCandidatePredicate()}
578 `.pipe(NodeSqliteClient.readOnly, Effect.withTracerEnabled(false));
579 const availableAt = rows[0]?.available_at;
580 if (availableAt === undefined || availableAt === null) return Option.none();
581 const parsed = DateTime.make(availableAt);
582 if (Option.isNone(parsed)) {
583 return yield* new EffectOutboxError({
584 operation: "next-claimable",
585 cause: `Invalid available_at timestamp: ${availableAt}`,
586 });
587 }
588 return parsed;
589 }).pipe(
590 Effect.mapError((cause) =>
591 isEffectOutboxError(cause)
592 ? cause
593 : new EffectOutboxError({ operation: "next-claimable", cause }),
594 ),
595 ),
596 succeed: Effect.fn("EffectOutbox.succeed")(
597 function* ({ effectId, workerId }) {
598 const now = DateTime.formatIso(yield* DateTime.now);
599 const rows = yield* sql<{ readonly effect_id: string }>`
600 UPDATE orchestration_v2_effect_outbox
601 SET
602 status = 'succeeded',
603 lease_owner = NULL,
604 lease_expires_at = NULL,
605 completed_at = ${now},
606 updated_at = ${now},
607 last_error = NULL
608 WHERE effect_id = ${effectId}
609 AND status = 'running'
610 AND lease_owner = ${workerId}
611 RETURNING effect_id
612 `;
613 if (rows.length === 1) {
614 cancellationSignals.delete(effectId);
615 yield* signalSettled([effectId]);
616 yield* notifyAvailable();
617 }
618 return rows.length === 1;
619 },
620 (effect, { effectId }) =>
621 effect.pipe(
622 Effect.mapError(
623 (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
624 ),
625 ),
626 ),
627 retry: Effect.fn("EffectOutbox.retry")(
628 function* ({ effectId, workerId, error, delayMs }) {
629 const now = yield* DateTime.now;
630 const nowIso = DateTime.formatIso(now);
631 const availableAt = DateTime.formatIso(
632 DateTime.add(now, { milliseconds: Math.max(0, delayMs) }),
633 );
634 const rows = yield* sql<{ readonly effect_id: string }>`
635 UPDATE orchestration_v2_effect_outbox
636 SET
637 status = 'pending',
638 available_at = ${availableAt},
639 lease_owner = NULL,
640 lease_expires_at = NULL,
641 updated_at = ${nowIso},
642 last_error = ${error}
643 WHERE effect_id = ${effectId}
644 AND status = 'running'
645 AND lease_owner = ${workerId}
646 RETURNING effect_id
647 `;
648 if (rows.length === 1) {
649 cancellationSignals.delete(effectId);
650 yield* notifyAvailable();
651 }
652 return rows.length === 1;
653 },
654 (effect, { effectId }) =>
655 effect.pipe(
656 Effect.mapError(
657 (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
658 ),
659 ),
660 ),
661 fail: Effect.fn("EffectOutbox.fail")(
662 function* ({ effectId, workerId, error }) {
663 const now = DateTime.formatIso(yield* DateTime.now);
664 const rows = yield* sql<{ readonly effect_id: string }>`
665 UPDATE orchestration_v2_effect_outbox
666 SET
667 status = 'failed',
668 lease_owner = NULL,
669 lease_expires_at = NULL,
670 completed_at = ${now},
671 updated_at = ${now},
672 last_error = ${error}
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: "fail", effectId, cause }),
689 ),
690 ),
691 ),
692 pruneSettled: Effect.gen(function* () {
693 const cutoff = DateTime.formatIso(
694 DateTime.subtractDuration(yield* DateTime.now, SETTLED_EFFECT_RETENTION),
695 );
696 // Each batch is its own statement, so a large backlog never holds the
697 // write lock for long and writers can commit between batches.
698 const deleteBatch = sql<{ readonly effect_id: string }>`
699 DELETE FROM orchestration_v2_effect_outbox
700 WHERE rowid IN (
701 SELECT rowid
702 FROM orchestration_v2_effect_outbox
703 WHERE status IN ('succeeded', 'cancelled')
704 AND completed_at < ${cutoff}
705 LIMIT ${PRUNE_BATCH_SIZE}
706 )
707 RETURNING effect_id
708 `;
709 let pruned = 0;
710 while (true) {
711 const deleted = (yield* deleteBatch).length;
712 pruned += deleted;
713 if (deleted < PRUNE_BATCH_SIZE) return pruned;
714 yield* Effect.yieldNow;
715 }
716 }).pipe(
717 Effect.mapError((cause) => new EffectOutboxError({ operation: "prune-settled", cause })),
718 ),
719 };
720
721 return service;
722 }),
723);
724
725export const layerPruneWorker = Layer.effectDiscard(
726 Effect.gen(function* () {
727 const outbox = yield* EffectOutboxV2;
728 yield* forkParked(
729 outbox.pruneSettled.pipe(
730 Effect.catch((cause) => Effect.logWarning("Failed to prune settled effects", { cause })),
731 Effect.repeat(Schedule.spaced(Duration.hours(1))),
732 ),
733 );
734 }),
735);