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

EffectOutbox.ts

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