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
423 ? Effect.succeed(Option.none())
424 : rowToEffect(row).pipe(Effect.map(Option.some));
425 }),
426 Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })),
427 ),
428 awaitAvailable: Queue.take(available),
429 notifyAvailable,
430 listByCommandId: (commandId) =>
431 sql<EffectRow>`
432 SELECT *
433 FROM orchestration_v2_effect_outbox
434 WHERE command_id = ${commandId}
435 ORDER BY created_at ASC, effect_id ASC
436 `.pipe(
437 NodeSqliteClient.readOnly,
438 Effect.flatMap((rows) => decodeRows("list", rows)),
439 Effect.mapError((cause) =>
440 isEffectOutboxError(cause)
441 ? cause
442 : new EffectOutboxError({ operation: "list", cause }),
443 ),
444 ),
445 cancelUnsettled: Effect.fn("EffectOutbox.cancelUnsettled")(
446 function* ({ threadId, effectTypes, reason }) {
447 if (effectTypes.length === 0) return [];
448 const now = DateTime.formatIso(yield* DateTime.now);
449 const rows = yield* sql<{ readonly effect_id: string }>`
450 UPDATE orchestration_v2_effect_outbox
451 SET
452 status = 'cancelled',
453 lease_owner = NULL,
454 lease_expires_at = NULL,
455 completed_at = ${now},
456 updated_at = ${now},
457 last_error = ${reason}
458 WHERE thread_id = ${threadId}
459 AND status IN ('pending', 'running')
460 AND effect_type IN ${sql.in(effectTypes)}
461 RETURNING effect_id
462 `;
463 return rows.map(({ effect_id }) => effect_id);
464 },
465 Effect.mapError((cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause })),
466 ),
467 signalCancellations: Effect.fn("EffectOutbox.signalCancellations")(function* (effectIds) {
468 yield* Effect.forEach(
469 effectIds,
470 (effectId) => {
471 const signal = cancellationSignals.get(effectId);
472 return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
473 },
474 { discard: true },
475 );
476 yield* signalSettled(effectIds);
477 if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);
478 }),
479 awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)),
480 clearCancellation: (effectId) =>
481 Effect.sync(() => {
482 cancellationSignals.delete(effectId);
483 }),
484 awaitSettled: Effect.fn("EffectOutbox.awaitSettled")(function* (effectId) {
485 // Registered before the read, so a settle right after it still resolves.
486 const signal = settledSignals.get(effectId) ?? Deferred.makeUnsafe<void>();
487 settledSignals.set(effectId, signal);
488 const effect = yield* service.get(effectId);
489 if (Option.exists(effect, ({ status }) => status === "pending" || status === "running")) {
490 return yield* Deferred.await(signal);
491 }
492 yield* signalSettled([effectId]);
493 }),
494 reconcileAfterProcessLoss: Effect.gen(function* () {
495 const now = DateTime.formatIso(yield* DateTime.now);
496 const cancelledRows = yield* sql<{ readonly effect_id: string }>`
497 UPDATE orchestration_v2_effect_outbox
498 SET
499 status = 'cancelled',
500 lease_owner = NULL,
501 lease_expires_at = NULL,
502 completed_at = ${now},
503 updated_at = ${now},
504 last_error = 'Cancelled because the server process ended before the effect completed.'
505 WHERE status IN ('pending', 'running')
506 AND effect_type IN ${sql.in(PROCESS_BOUND_EFFECT_TYPES)}
507 RETURNING effect_id
508 `;
509 const requeuedRows = yield* sql<{ readonly effect_id: string }>`
510 UPDATE orchestration_v2_effect_outbox
511 SET
512 status = 'pending',
513 lease_owner = NULL,
514 lease_expires_at = NULL,
515 available_at = ${now},
516 updated_at = ${now},
517 last_error = 'Requeued after the previous server process ended.'
518 WHERE status = 'running'
519 AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)}
520 RETURNING effect_id
521 `;
522 if (requeuedRows.length > 0) yield* notifyAvailable(requeuedRows.length);
523 return { requeued: requeuedRows.length, cancelled: cancelledRows.length };
524 }).pipe(
525 Effect.mapError(
526 (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }),
527 ),
528 ),
529 // The worker polls for the next effect even when there is no work to claim.
530 claimNext: Effect.fnUntraced(
531 function* ({ workerId, leaseDurationMs, excludeRestartContinuations = false }) {
532 const now = yield* DateTime.now;
533 const nowIso = DateTime.formatIso(now);
534 const leaseExpiresAt = DateTime.formatIso(
535 DateTime.add(now, { milliseconds: Math.max(1, leaseDurationMs) }),
536 );
537 // Idle claims return empty; tracing their full SQL on every poll overwhelms useful traces.
538 const claimStatement = sql<EffectRow>`
539 UPDATE orchestration_v2_effect_outbox
540 SET
541 status = 'running',
542 attempt_count = attempt_count + 1,
543 lease_owner = ${workerId},
544 lease_expires_at = ${leaseExpiresAt},
545 updated_at = ${nowIso},
546 last_error = NULL
547 WHERE effect_id = (
548 SELECT candidate.effect_id
549 FROM orchestration_v2_effect_outbox AS candidate
550 WHERE ${claimableCandidatePredicate(nowIso, excludeRestartContinuations)}
551 AND ${excludeRestartContinuations ? sql`candidate.effect_type != 'provider-runtime.continue'` : sql`1 = 1`}
552 ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC
553 LIMIT 1
554 )
555 RETURNING *
556 `;
557 const rows = yield* claimStatement.pipe(Effect.withTracerEnabled(false));
558 const row = rows[0];
559 if (row === undefined) return Option.none();
560 cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());
561 return Option.some(yield* rowToEffect(row));
562 },
563 Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause })),
564 ),
565 nextClaimableAt: Effect.gen(function* () {
566 const rows = yield* sql<{ readonly available_at: string | null }>`
567 SELECT MIN(candidate.available_at) AS available_at
568 FROM orchestration_v2_effect_outbox AS candidate
569 WHERE ${claimableCandidatePredicate()}
570 `.pipe(NodeSqliteClient.readOnly, Effect.withTracerEnabled(false));
571 const availableAt = rows[0]?.available_at;
572 if (availableAt === undefined || availableAt === null) return Option.none();
573 const parsed = DateTime.make(availableAt);
574 if (Option.isNone(parsed)) {
575 return yield* new EffectOutboxError({
576 operation: "next-claimable",
577 cause: `Invalid available_at timestamp: ${availableAt}`,
578 });
579 }
580 return parsed;
581 }).pipe(
582 Effect.mapError((cause) =>
583 isEffectOutboxError(cause)
584 ? cause
585 : new EffectOutboxError({ operation: "next-claimable", cause }),
586 ),
587 ),
588 succeed: Effect.fn("EffectOutbox.succeed")(
589 function* ({ effectId, workerId }) {
590 const now = DateTime.formatIso(yield* DateTime.now);
591 const rows = yield* sql<{ readonly effect_id: string }>`
592 UPDATE orchestration_v2_effect_outbox
593 SET
594 status = 'succeeded',
595 lease_owner = NULL,
596 lease_expires_at = NULL,
597 completed_at = ${now},
598 updated_at = ${now},
599 last_error = NULL
600 WHERE effect_id = ${effectId}
601 AND status = 'running'
602 AND lease_owner = ${workerId}
603 RETURNING effect_id
604 `;
605 if (rows.length === 1) {
606 cancellationSignals.delete(effectId);
607 yield* signalSettled([effectId]);
608 yield* notifyAvailable();
609 }
610 return rows.length === 1;
611 },
612 (effect, { effectId }) =>
613 effect.pipe(
614 Effect.mapError(
615 (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
616 ),
617 ),
618 ),
619 retry: Effect.fn("EffectOutbox.retry")(
620 function* ({ effectId, workerId, error, delayMs }) {
621 const now = yield* DateTime.now;
622 const nowIso = DateTime.formatIso(now);
623 const availableAt = DateTime.formatIso(
624 DateTime.add(now, { milliseconds: Math.max(0, delayMs) }),
625 );
626 const rows = yield* sql<{ readonly effect_id: string }>`
627 UPDATE orchestration_v2_effect_outbox
628 SET
629 status = 'pending',
630 available_at = ${availableAt},
631 lease_owner = NULL,
632 lease_expires_at = NULL,
633 updated_at = ${nowIso},
634 last_error = ${error}
635 WHERE effect_id = ${effectId}
636 AND status = 'running'
637 AND lease_owner = ${workerId}
638 RETURNING effect_id
639 `;
640 if (rows.length === 1) {
641 cancellationSignals.delete(effectId);
642 yield* notifyAvailable();
643 }
644 return rows.length === 1;
645 },
646 (effect, { effectId }) =>
647 effect.pipe(
648 Effect.mapError(
649 (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
650 ),
651 ),
652 ),
653 fail: Effect.fn("EffectOutbox.fail")(
654 function* ({ effectId, workerId, error }) {
655 const now = DateTime.formatIso(yield* DateTime.now);
656 const rows = yield* sql<{ readonly effect_id: string }>`
657 UPDATE orchestration_v2_effect_outbox
658 SET
659 status = 'failed',
660 lease_owner = NULL,
661 lease_expires_at = NULL,
662 completed_at = ${now},
663 updated_at = ${now},
664 last_error = ${error}
665 WHERE effect_id = ${effectId}
666 AND status = 'running'
667 AND lease_owner = ${workerId}
668 RETURNING effect_id
669 `;
670 if (rows.length === 1) {
671 cancellationSignals.delete(effectId);
672 yield* signalSettled([effectId]);
673 yield* notifyAvailable();
674 }
675 return rows.length === 1;
676 },
677 (effect, { effectId }) =>
678 effect.pipe(
679 Effect.mapError(
680 (cause) => new EffectOutboxError({ operation: "fail", effectId, cause }),
681 ),
682 ),
683 ),
684 pruneSettled: Effect.gen(function* () {
685 const cutoff = DateTime.formatIso(
686 DateTime.subtractDuration(yield* DateTime.now, SETTLED_EFFECT_RETENTION),
687 );
688 // Separate batch statements release the write lock between batches.
689 const deleteBatch = sql<{ readonly effect_id: string }>`
690 DELETE FROM orchestration_v2_effect_outbox
691 WHERE rowid IN (
692 SELECT rowid
693 FROM orchestration_v2_effect_outbox
694 WHERE status IN ('succeeded', 'cancelled')
695 AND completed_at < ${cutoff}
696 LIMIT ${PRUNE_BATCH_SIZE}
697 )
698 RETURNING effect_id
699 `;
700 let pruned = 0;
701 while (true) {
702 const deleted = (yield* deleteBatch).length;
703 pruned += deleted;
704 if (deleted < PRUNE_BATCH_SIZE) return pruned;
705 yield* Effect.yieldNow;
706 }
707 }).pipe(
708 Effect.mapError((cause) => new EffectOutboxError({ operation: "prune-settled", cause })),
709 ),
710 };
711
712 return service;
713 }),
714);
715
716export const layerPruneWorker = Layer.effectDiscard(
717 Effect.gen(function* () {
718 const outbox = yield* EffectOutboxV2;
719 yield* forkParked(
720 outbox.pruneSettled.pipe(
721 Effect.catch((cause) => Effect.logWarning("Failed to prune settled effects", { cause })),
722 Effect.repeat(Schedule.spaced(Duration.hours(1))),
723 ),
724 );
725 }),
726);