Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

EffectOutbox.ts

731 lines26.5 KB

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