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

EffectOutbox.ts

708 lines26.3 KB

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