Open History to see the last commit
1import {
2 CheckpointId,
3 CheckpointScopeId,
4 CommandId,
5 MessageId,
6 NodeId,
7 ProviderSessionId,
8 RunAttemptId,
9 ProviderApprovalDecision,
10 ProviderUserInputAnswers,
11 ProviderThreadId,
12 ProviderTurnId,
13 RunId,
14 RuntimeRequestId,
15 ThreadId,
16} from "@t3tools/contracts";
17import * as Context from "effect/Context";
18import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
19import * as DateTime from "effect/DateTime";
20import * as Deferred from "effect/Deferred";
21import * as Duration from "effect/Duration";
22import * as Effect from "effect/Effect";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as Queue from "effect/Queue";
26import * as Schedule from "effect/Schedule";
27import * as Schema from "effect/Schema";
28import * as SqlClient from "effect/sql/SqlClient";
29
30import { forkParked } from "../serverActivation.ts";
31
32export const OrchestrationEffectRequestV2 = Schema.Union([
33 Schema.Struct({
34 type: Schema.Literal("provider-runtime.continue"),
35 sourceRunId: RunId,
36 }),
37 Schema.Struct({
38 type: Schema.Literal("provider-session.detach"),
39 providerSessionId: ProviderSessionId,
40 detail: Schema.optional(Schema.String),
41 revokeMcpCredential: Schema.optional(Schema.Boolean),
42 }),
43 Schema.Struct({
44 type: Schema.Literal("provider-turn.start"),
45 runId: RunId,
46 }),
47 Schema.Struct({
48 type: Schema.Literal("provider-turn.interrupt"),
49 providerSessionId: ProviderSessionId,
50 providerThreadId: ProviderThreadId,
51 providerTurnId: ProviderTurnId,
52 subagent: Schema.optional(Schema.Struct({ id: NodeId, nativeTaskId: Schema.String })),
53 }),
54 Schema.Struct({
55 type: Schema.Literal("provider-turn.steer"),
56 providerSessionId: ProviderSessionId,
57 providerThreadId: ProviderThreadId,
58 providerTurnId: ProviderTurnId,
59 messageId: MessageId,
60 }),
61 Schema.Struct({
62 type: Schema.Literal("provider-turn.restart"),
63 providerSessionId: ProviderSessionId,
64 providerThreadId: ProviderThreadId,
65 providerTurnId: ProviderTurnId,
66 interruptedAttemptId: RunAttemptId,
67 runId: RunId,
68 sessionTransition: Schema.optional(
69 Schema.Union([
70 Schema.Struct({
71 type: Schema.Literal("replace"),
72 replacementProviderSessionId: ProviderSessionId,
73 }),
74 Schema.Struct({ type: Schema.Literal("detach") }),
75 ]),
76 ),
77 }),
78 Schema.Struct({
79 type: Schema.Literal("runtime-request.respond"),
80 providerSessionId: ProviderSessionId,
81 requestId: RuntimeRequestId,
82 decision: Schema.optional(ProviderApprovalDecision),
83 feedback: Schema.optional(Schema.String),
84 answers: Schema.optional(ProviderUserInputAnswers),
85 }),
86 Schema.Struct({
87 type: Schema.Literal("provider-thread.rollback"),
88 restoreFiles: Schema.optional(Schema.Boolean),
89 providerThreadId: ProviderThreadId,
90 checkpointId: CheckpointId,
91 scopeId: CheckpointScopeId,
92 }),
93 Schema.Struct({
94 type: Schema.Literal("checkpoint.capture"),
95 runId: RunId,
96 scopeId: CheckpointScopeId,
97 }),
98 Schema.Struct({
99 type: Schema.Literal("scheduled-tasks.cleanup"),
100 }),
101 Schema.Struct({
102 type: Schema.Literal("terminal.cleanup"),
103 }),
104 Schema.Struct({
105 type: Schema.Literal("preview.cleanup"),
106 }),
107 Schema.Struct({
108 type: Schema.Literal("attachment.cleanup"),
109 attachmentIds: Schema.Array(Schema.String),
110 }),
111 Schema.Struct({
112 type: Schema.Literal("thread-title.generate"),
113 kind: Schema.Union([
114 Schema.Struct({ type: Schema.Literal("initial"), messageId: MessageId }),
115 Schema.Struct({ type: Schema.Literal("regenerate") }),
116 ]),
117 }),
118 Schema.Struct({
119 type: Schema.Literal("delegated-tasks.stop"),
120 reason: Schema.optional(Schema.String),
121 }),
122]);
123export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type;
124
125export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [
126 "provider-runtime.continue",
127 "provider-session.detach",
128 "provider-thread.rollback",
129 "checkpoint.capture",
130 "scheduled-tasks.cleanup",
131 "terminal.cleanup",
132 "preview.cleanup",
133 "attachment.cleanup",
134 "thread-title.generate",
135 "delegated-tasks.stop",
136] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
137
138export const PROCESS_BOUND_EFFECT_TYPES = [
139 "provider-turn.start",
140 "provider-turn.interrupt",
141 "provider-turn.steer",
142 "provider-turn.restart",
143 "runtime-request.respond",
144] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
145
146export const OrchestrationEffectStatusV2 = Schema.Literals([
147 "pending",
148 "running",
149 "succeeded",
150 "failed",
151 "cancelled",
152]);
153export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type;
154
155/** Receipts deduplicate retries, and restart re-enqueues need far less than a week. Retain failed rows to keep deleted-thread worktrees. */
156export const SETTLED_EFFECT_RETENTION = Duration.days(7);
157const PRUNE_BATCH_SIZE = 500;
158
159export interface OrchestrationEffectV2 {
160 readonly id: string;
161 readonly commandId: CommandId;
162 readonly threadId: ThreadId;
163 readonly request: OrchestrationEffectRequestV2;
164 readonly status: OrchestrationEffectStatusV2;
165 readonly attemptCount: number;
166 readonly availableAt: string;
167 readonly leaseOwner: string | null;
168 readonly leaseExpiresAt: string | null;
169 readonly createdAt: string;
170 readonly updatedAt: string;
171 readonly completedAt: string | null;
172 readonly lastError: string | null;
173}
174
175export interface PendingOrchestrationEffectV2 {
176 readonly id: string;
177 readonly commandId: CommandId;
178 readonly threadId: ThreadId;
179 readonly request: OrchestrationEffectRequestV2;
180 readonly availableAt?: DateTime.Utc;
181}
182
183export class EffectOutboxError extends Schema.TaggedError<EffectOutboxError>()(
184 "EffectOutboxError",
185 {
186 operation: Schema.String,
187 effectId: Schema.optional(Schema.String),
188 cause: Schema.optional(Schema.Defect()),
189 },
190) {
191 override get message(): string {
192 return `Orchestration effect outbox ${this.operation} failed${this.effectId === undefined ? "" : ` for ${this.effectId}`}.`;
193 }
194}
195
196const isEffectOutboxError = Schema.is(EffectOutboxError);
197
198export interface EffectOutboxV2Shape {
199 readonly awaitAvailable: Effect.Effect<void>;
200 readonly notifyAvailable: (count?: number) => Effect.Effect<void>;
201 /** Persist rows only. Notify workers after the surrounding transaction commits. */
202 readonly enqueue: (
203 effects: ReadonlyArray<PendingOrchestrationEffectV2>,
204 ) => Effect.Effect<void, EffectOutboxError>;
205 readonly get: (
206 effectId: string,
207 ) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
208 readonly listByCommandId: (
209 commandId: CommandId,
210 ) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
211 readonly cancelUnsettled: (input: {
212 readonly threadId: ThreadId;
213 readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
214 readonly reason: string;
215 }) => Effect.Effect<ReadonlyArray<string>, EffectOutboxError>;
216 readonly signalCancellations: (effectIds: ReadonlyArray<string>) => Effect.Effect<void>;
217 readonly awaitCancellation: (effectId: string) => Effect.Effect<void>;
218 readonly clearCancellation: (effectId: string) => Effect.Effect<void>;
219 /** Resolves once the effect is neither pending nor running, or right away when it does not exist. */
220 readonly awaitSettled: (effectId: string) => Effect.Effect<void, EffectOutboxError>;
221 readonly reconcileAfterProcessLoss: Effect.Effect<
222 { readonly requeued: number; readonly cancelled: number },
223 EffectOutboxError
224 >;
225 readonly claimNext: (input: {
226 readonly workerId: string;
227 readonly leaseDurationMs: number;
228 readonly excludeRestartContinuations?: boolean;
229 }) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
230 readonly nextClaimableAt: Effect.Effect<Option.Option<DateTime.Utc>, EffectOutboxError>;
231 readonly succeed: (input: {
232 readonly effectId: string;
233 readonly workerId: string;
234 }) => Effect.Effect<boolean, EffectOutboxError>;
235 readonly retry: (input: {
236 readonly effectId: string;
237 readonly workerId: string;
238 readonly error: string;
239 readonly delayMs: number;
240 }) => Effect.Effect<boolean, EffectOutboxError>;
241 readonly fail: (input: {
242 readonly effectId: string;
243 readonly workerId: string;
244 readonly error: string;
245 }) => Effect.Effect<boolean, EffectOutboxError>;
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 const available = yield* Queue.dropping<void>(64);
299 const cancellationSignals = new Map<string, Deferred.Deferred<void>>();
300 const settledSignals = new Map<string, Deferred.Deferred<void>>();
301 const signalSettled = (effectIds: ReadonlyArray<string>) =>
302 Effect.forEach(
303 effectIds,
304 (effectId) => {
305 const signal = settledSignals.get(effectId);
306 if (signal === undefined) return Effect.void;
307 settledSignals.delete(effectId);
308 return Deferred.succeed(signal, undefined);
309 },
310 { discard: true },
311 );
312 const notifyAvailable = (count = 1) =>
313 Queue.offerAll(
314 available,
315 Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined),
316 ).pipe(Effect.asVoid);
317 // Retry backoff must block later effects so turns cannot race a pending rollback.
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 NodeSqliteClient.readOnly,
420 Effect.flatMap((rows) => {
421 const row = rows[0];
422 return row === undefined ? Effect.succeedNone : rowToEffect(row).pipe(Effect.asSome);
423 }),
424 Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })),
425 ),
426 awaitAvailable: Queue.take(available),
427 notifyAvailable,
428 listByCommandId: (commandId) =>
429 sql<EffectRow>`
430 SELECT *
431 FROM orchestration_v2_effect_outbox
432 WHERE command_id = ${commandId}
433 ORDER BY created_at ASC, effect_id ASC
434 `.pipe(
435 NodeSqliteClient.readOnly,
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 // Idle claims return empty; tracing their full SQL on every poll overwhelms useful traces.
536 const claimStatement = sql<EffectRow>`
537 UPDATE orchestration_v2_effect_outbox
538 SET
539 status = 'running',
540 attempt_count = attempt_count + 1,
541 lease_owner = ${workerId},
542 lease_expires_at = ${leaseExpiresAt},
543 updated_at = ${nowIso},
544 last_error = NULL
545 WHERE effect_id = (
546 SELECT candidate.effect_id
547 FROM orchestration_v2_effect_outbox AS candidate
548 WHERE ${claimableCandidatePredicate(nowIso, excludeRestartContinuations)}
549 AND ${excludeRestartContinuations ? sql`candidate.effect_type != 'provider-runtime.continue'` : sql`1 = 1`}
550 ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC
551 LIMIT 1
552 )
553 RETURNING *
554 `;
555 const rows = yield* claimStatement.pipe(Effect.withTracerEnabled(false));
556 const row = rows[0];
557 if (row === undefined) return Option.none();
558 cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());
559 return Option.some(yield* rowToEffect(row));
560 },
561 Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause })),
562 ),
563 nextClaimableAt: Effect.gen(function* () {
564 const rows = yield* sql<{ readonly available_at: string | null }>`
565 SELECT MIN(candidate.available_at) AS available_at
566 FROM orchestration_v2_effect_outbox AS candidate
567 WHERE ${claimableCandidatePredicate()}
568 `.pipe(NodeSqliteClient.readOnly, Effect.withTracerEnabled(false));
569 const availableAt = rows[0]?.available_at;
570 if (availableAt === undefined || availableAt === null) return Option.none();
571 const parsed = DateTime.make(availableAt);
572 if (Option.isNone(parsed)) {
573 return yield* new EffectOutboxError({
574 operation: "next-claimable",
575 cause: `Invalid available_at timestamp: ${availableAt}`,
576 });
577 }
578 return parsed;
579 }).pipe(
580 Effect.mapError((cause) =>
581 isEffectOutboxError(cause)
582 ? cause
583 : new EffectOutboxError({ operation: "next-claimable", cause }),
584 ),
585 ),
586 succeed: Effect.fn("EffectOutbox.succeed")(
587 function* ({ effectId, workerId }) {
588 const now = DateTime.formatIso(yield* DateTime.now);
589 const rows = yield* sql<{ readonly effect_id: string }>`
590 UPDATE orchestration_v2_effect_outbox
591 SET
592 status = 'succeeded',
593 lease_owner = NULL,
594 lease_expires_at = NULL,
595 completed_at = ${now},
596 updated_at = ${now},
597 last_error = NULL
598 WHERE effect_id = ${effectId}
599 AND status = 'running'
600 AND lease_owner = ${workerId}
601 RETURNING effect_id
602 `;
603 if (rows.length === 1) {
604 cancellationSignals.delete(effectId);
605 yield* signalSettled([effectId]);
606 yield* notifyAvailable();
607 }
608 return rows.length === 1;
609 },
610 (effect, { effectId }) =>
611 effect.pipe(
612 Effect.mapError(
613 (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
614 ),
615 ),
616 ),
617 retry: Effect.fn("EffectOutbox.retry")(
618 function* ({ effectId, workerId, error, delayMs }) {
619 const now = yield* DateTime.now;
620 const nowIso = DateTime.formatIso(now);
621 const availableAt = DateTime.formatIso(
622 DateTime.add(now, { milliseconds: Math.max(0, delayMs) }),
623 );
624 const rows = yield* sql<{ readonly effect_id: string }>`
625 UPDATE orchestration_v2_effect_outbox
626 SET
627 status = 'pending',
628 available_at = ${availableAt},
629 lease_owner = NULL,
630 lease_expires_at = NULL,
631 updated_at = ${nowIso},
632 last_error = ${error}
633 WHERE effect_id = ${effectId}
634 AND status = 'running'
635 AND lease_owner = ${workerId}
636 RETURNING effect_id
637 `;
638 if (rows.length === 1) {
639 cancellationSignals.delete(effectId);
640 yield* notifyAvailable();
641 }
642 return rows.length === 1;
643 },
644 (effect, { effectId }) =>
645 effect.pipe(
646 Effect.mapError(
647 (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
648 ),
649 ),
650 ),
651 fail: Effect.fn("EffectOutbox.fail")(
652 function* ({ effectId, workerId, error }) {
653 const now = DateTime.formatIso(yield* DateTime.now);
654 const rows = yield* sql<{ readonly effect_id: string }>`
655 UPDATE orchestration_v2_effect_outbox
656 SET
657 status = 'failed',
658 lease_owner = NULL,
659 lease_expires_at = NULL,
660 completed_at = ${now},
661 updated_at = ${now},
662 last_error = ${error}
663 WHERE effect_id = ${effectId}
664 AND status = 'running'
665 AND lease_owner = ${workerId}
666 RETURNING effect_id
667 `;
668 if (rows.length === 1) {
669 cancellationSignals.delete(effectId);
670 yield* signalSettled([effectId]);
671 yield* notifyAvailable();
672 }
673 return rows.length === 1;
674 },
675 (effect, { effectId }) =>
676 effect.pipe(
677 Effect.mapError(
678 (cause) => new EffectOutboxError({ operation: "fail", effectId, cause }),
679 ),
680 ),
681 ),
682 pruneSettled: Effect.gen(function* () {
683 const cutoff = DateTime.formatIso(
684 DateTime.subtractDuration(yield* DateTime.now, SETTLED_EFFECT_RETENTION),
685 );
686 // Separate batch statements release the write lock between batches.
687 const deleteBatch = sql<{ readonly effect_id: string }>`
688 DELETE FROM orchestration_v2_effect_outbox
689 WHERE rowid IN (
690 SELECT rowid
691 FROM orchestration_v2_effect_outbox
692 WHERE status IN ('succeeded', 'cancelled')
693 AND completed_at < ${cutoff}
694 LIMIT ${PRUNE_BATCH_SIZE}
695 )
696 RETURNING effect_id
697 `;
698 let pruned = 0;
699 while (true) {
700 const deleted = (yield* deleteBatch).length;
701 pruned += deleted;
702 if (deleted < PRUNE_BATCH_SIZE) return pruned;
703 yield* Effect.yieldNow;
704 }
705 }).pipe(
706 Effect.mapError((cause) => new EffectOutboxError({ operation: "prune-settled", cause })),
707 ),
708 };
709
710 return service;
711 }),
712);
713
714export const layerPruneWorker = Layer.effectDiscard(
715 Effect.gen(function* () {
716 const outbox = yield* EffectOutboxV2;
717 yield* forkParked(
718 outbox.pruneSettled.pipe(
719 Effect.catch((cause) => Effect.logWarning("Failed to prune settled effects", { cause })),
720 Effect.repeat(Schedule.spaced(Duration.hours(1))),
721 ),
722 );
723 }),
724);