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

EffectOutbox.ts

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