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

EffectOutbox.ts

782 lines28.7 KB

1import {
2 CheckpointId,
3 CheckpointScopeId,
4 CommandId,
5 MessageId,
6 ModelSelection,
7 NodeId,
8 NonNegativeInt,
9 ProviderSessionId,
10 RunAttemptId,
11 ProviderApprovalDecision,
12 ProviderUserInputAnswers,
13 ProviderThreadId,
14 ProviderTurnId,
15 RunId,
16 RuntimeRequestId,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as Context from "effect/Context";
20import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
21import * as DateTime from "effect/DateTime";
22import * as Deferred from "effect/Deferred";
23import * as Duration from "effect/Duration";
24import * as Effect from "effect/Effect";
25import * as Layer from "effect/Layer";
26import * as Option from "effect/Option";
27import * as Queue from "effect/Queue";
28import * as Result from "effect/Result";
29import * as Schedule from "effect/Schedule";
30import * as Schema from "effect/Schema";
31import * as SqlClient from "effect/sql/SqlClient";
32​
33import { forkParked } from "../serverActivation.ts";
34​
35export const OrchestrationEffectRequestV2 = Schema.Union([
36 Schema.Struct({
37 type: Schema.Literal("provider-runtime.continue"),
38 sourceRunId: RunId,
39 processLossCount: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
40 }),
41 Schema.Struct({
42 type: Schema.Literal("provider-session.detach"),
43 providerSessionId: ProviderSessionId,
44 detail: Schema.optional(Schema.String),
45 revokeMcpCredential: Schema.optional(Schema.Boolean),
46 }),
47 Schema.Struct({
48 type: Schema.Literal("provider-session.apply-model-selection"),
49 providerSessionId: ProviderSessionId,
50 providerThreadId: ProviderThreadId,
51 modelSelection: ModelSelection,
52 }),
53 Schema.Struct({
54 type: Schema.Literal("provider-session.apply-thread-title"),
55 title: Schema.String,
56 }),
57 Schema.Struct({
58 type: Schema.Literal("provider-turn.start"),
59 runId: RunId,
60 }),
61 Schema.Struct({
62 type: Schema.Literal("provider-turn.interrupt"),
63 providerSessionId: ProviderSessionId,
64 providerThreadId: ProviderThreadId,
65 providerTurnId: ProviderTurnId,
66 subagent: Schema.optional(Schema.Struct({ id: NodeId, nativeTaskId: Schema.String })),
67 }),
68 Schema.Struct({
69 type: Schema.Literal("provider-turn.steer"),
70 providerSessionId: ProviderSessionId,
71 providerThreadId: ProviderThreadId,
72 providerTurnId: ProviderTurnId,
73 messageId: MessageId,
74 modelSelection: Schema.optional(ModelSelection),
75 steerFollowUpAfterRunOrdinal: Schema.optional(NonNegativeInt),
76 }),
77 Schema.Struct({
78 type: Schema.Literal("provider-turn.restart"),
79 providerSessionId: ProviderSessionId,
80 providerThreadId: ProviderThreadId,
81 providerTurnId: ProviderTurnId,
82 interruptedAttemptId: RunAttemptId,
83 runId: RunId,
84 sessionTransition: Schema.optional(
85 Schema.Union([
86 Schema.Struct({
87 type: Schema.Literal("replace"),
88 replacementProviderSessionId: ProviderSessionId,
89 }),
90 Schema.Struct({ type: Schema.Literal("detach") }),
91 ]),
92 ),
93 }),
94 Schema.Struct({
95 type: Schema.Literal("runtime-request.respond"),
96 providerSessionId: ProviderSessionId,
97 requestId: RuntimeRequestId,
98 decision: Schema.optional(ProviderApprovalDecision),
99 feedback: Schema.optional(Schema.String),
100 answers: Schema.optional(ProviderUserInputAnswers),
101 }),
102 Schema.Struct({
103 type: Schema.Literal("provider-thread.rollback"),
104 restoreFiles: Schema.optional(Schema.Boolean),
105 providerThreadId: ProviderThreadId,
106 checkpointId: CheckpointId,
107 scopeId: CheckpointScopeId,
108 }),
109 Schema.Struct({
110 type: Schema.Literal("checkpoint.capture"),
111 runId: RunId,
112 scopeId: CheckpointScopeId,
113 }),
114 Schema.Struct({
115 type: Schema.Literal("scheduled-tasks.cleanup"),
116 }),
117 Schema.Struct({
118 type: Schema.Literal("terminal.cleanup"),
119 }),
120 Schema.Struct({
121 type: Schema.Literal("preview.cleanup"),
122 }),
123 Schema.Struct({
124 type: Schema.Literal("attachment.cleanup"),
125 attachmentIds: Schema.Array(Schema.String),
126 skipReferenced: Schema.optional(Schema.Boolean),
127 }),
128 Schema.Struct({
129 type: Schema.Literal("thread-title.generate"),
130 kind: Schema.Union([
131 Schema.Struct({ type: Schema.Literal("initial"), messageId: MessageId }),
132 Schema.Struct({ type: Schema.Literal("regenerate") }),
133 ]),
134 }),
135 Schema.Struct({
136 type: Schema.Literal("delegated-tasks.stop"),
137 reason: Schema.optional(Schema.String),
138 }),
139]);
140export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type;
141​
142export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [
143 "provider-runtime.continue",
144 "provider-session.detach",
145 "provider-thread.rollback",
146 "checkpoint.capture",
147 "scheduled-tasks.cleanup",
148 "terminal.cleanup",
149 "preview.cleanup",
150 "attachment.cleanup",
151 "thread-title.generate",
152 "delegated-tasks.stop",
153] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
154​
155export const PROCESS_BOUND_EFFECT_TYPES = [
156 "provider-session.apply-model-selection",
157 "provider-session.apply-thread-title",
158 "provider-turn.start",
159 "provider-turn.interrupt",
160 "provider-turn.steer",
161 "provider-turn.restart",
162 "runtime-request.respond",
163] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
164​
165export const OrchestrationEffectStatusV2 = Schema.Literals([
166 "pending",
167 "running",
168 "succeeded",
169 "failed",
170 "cancelled",
171]);
172export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type;
173​
174/** Receipts deduplicate retries, and restart re-enqueues need far less than a week. Retain failed rows to keep deleted-thread worktrees. */
175export const SETTLED_EFFECT_RETENTION = Duration.days(7);
176const PRUNE_BATCH_SIZE = 500;
177​
178export interface OrchestrationEffectV2 {
179 readonly id: string;
180 readonly commandId: CommandId;
181 readonly threadId: ThreadId;
182 readonly request: OrchestrationEffectRequestV2;
183 readonly status: OrchestrationEffectStatusV2;
184 readonly attemptCount: number;
185 readonly availableAt: string;
186 readonly leaseOwner: string | null;
187 readonly createdAt: string;
188 readonly updatedAt: string;
189 readonly completedAt: string | null;
190 readonly lastError: string | null;
192​
193export interface PendingOrchestrationEffectV2 {
194 readonly id: string;
195 readonly commandId: CommandId;
196 readonly threadId: ThreadId;
197 readonly request: OrchestrationEffectRequestV2;
198 readonly availableAt?: DateTime.Utc;
200​
201export class EffectOutboxError extends Schema.TaggedError<EffectOutboxError>()(
202 "EffectOutboxError",
203 {
204 operation: Schema.String,
205 effectId: Schema.optional(Schema.String),
206 cause: Schema.optional(Schema.Defect()),
207 },
208) {
209 override get message(): string {
210 return `Orchestration effect outbox ${this.operation} failed${this.effectId === undefined ? "" : ` for ${this.effectId}`}.`;
211 }
213​
214const isEffectOutboxError = Schema.is(EffectOutboxError);
215​
216export interface EffectOutboxV2Shape {
217 readonly awaitAvailable: Effect.Effect<void>;
218 readonly notifyAvailable: (count?: number) => Effect.Effect<void>;
219 /** Persist rows only. Notify workers after the surrounding transaction commits. */
220 readonly enqueue: (
221 effects: ReadonlyArray<PendingOrchestrationEffectV2>,
222 ) => Effect.Effect<void, EffectOutboxError>;
223 readonly get: (
224 effectId: string,
225 ) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
226 readonly listByCommandId: (
227 commandId: CommandId,
228 ) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
229 readonly cancelUnsettled: (input: {
230 readonly threadId: ThreadId;
231 readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
232 readonly reason: string;
233 }) => Effect.Effect<ReadonlyArray<string>, EffectOutboxError>;
234 readonly signalCancellations: (effectIds: ReadonlyArray<string>) => Effect.Effect<void>;
235 readonly awaitCancellation: (effectId: string) => Effect.Effect<void>;
236 readonly clearCancellation: (effectId: string) => Effect.Effect<void>;
237 /** Resolves once the effect is neither pending nor running, or right away when it does not exist. */
238 readonly awaitSettled: (effectId: string) => Effect.Effect<void, EffectOutboxError>;
239 readonly reconcileAfterProcessLoss: Effect.Effect<
240 { readonly requeued: number; readonly cancelled: number },
241 EffectOutboxError
242 >;
243 readonly claimNext: (input: {
244 readonly workerId: string;
245 readonly excludeRestartContinuations?: boolean;
246 readonly maxRunningTitleGenerations?: number;
247 }) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
248 readonly nextClaimableAt: (input?: {
249 readonly maxRunningTitleGenerations?: number;
250 }) => Effect.Effect<Option.Option<DateTime.Utc>, EffectOutboxError>;
251 readonly succeed: (input: {
252 readonly effectId: string;
253 readonly workerId: string;
254 }) => Effect.Effect<boolean, EffectOutboxError>;
255 readonly retry: (input: {
256 readonly effectId: string;
257 readonly workerId: string;
258 readonly error: string;
259 readonly delayMs: number;
260 }) => Effect.Effect<boolean, EffectOutboxError>;
261 readonly fail: (input: {
262 readonly effectId: string;
263 readonly workerId: string;
264 readonly error: string;
265 }) => Effect.Effect<boolean, EffectOutboxError>;
266 readonly pruneSettled: Effect.Effect<number, EffectOutboxError>;
268​
269export class EffectOutboxV2 extends Context.Service<EffectOutboxV2, EffectOutboxV2Shape>()(
270 "t3/orchestration-v2/EffectOutbox/EffectOutboxV2",
271) {}
272​
273type EffectRow = {
274 readonly effect_id: string;
275 readonly command_id: string;
276 readonly thread_id: string;
277 readonly effect_type: string;
278 readonly payload_json: string;
279 readonly status: string;
280 readonly attempt_count: number;
281 readonly available_at: string;
282 readonly lease_owner: string | null;
283 readonly created_at: string;
284 readonly updated_at: string;
285 readonly completed_at: string | null;
286 readonly last_error: string | null;
287};
288​
289const encodeRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
290const decodeRequest = Schema.decodeUnknownEffect(
291 Schema.fromJsonString(OrchestrationEffectRequestV2),
292);
293​
294const rowToEffect = (row: EffectRow) =>
295 decodeRequest(row.payload_json).pipe(
296 Effect.map((request): OrchestrationEffectV2 => ({
297 id: row.effect_id,
298 commandId: CommandId.make(row.command_id),
299 threadId: ThreadId.make(row.thread_id),
300 request,
301 status: row.status as OrchestrationEffectStatusV2,
302 attemptCount: row.attempt_count,
303 availableAt: row.available_at,
304 leaseOwner: row.lease_owner,
305 createdAt: row.created_at,
306 updatedAt: row.updated_at,
307 completedAt: row.completed_at,
308 lastError: row.last_error,
309 })),
310 );
311​
312export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = Layer.effect(
313 EffectOutboxV2,
314 Effect.gen(function* () {
315 const sql = yield* SqlClient.SqlClient;
316 const available = yield* Queue.dropping<void>(64);
317 const cancellationSignals = new Map<string, Deferred.Deferred<void>>();
318 const settledSignals = new Map<string, Deferred.Deferred<void>>();
319 const signalSettled = (effectIds: ReadonlyArray<string>) =>
320 Effect.forEach(
321 effectIds,
322 (effectId) => {
323 const signal = settledSignals.get(effectId);
324 if (signal === undefined) return Effect.void;
325 settledSignals.delete(effectId);
326 return Deferred.succeed(signal, undefined);
327 },
328 { discard: true },
329 );
330 const notifyAvailable = (count = 1) =>
331 Queue.offerAll(
332 available,
333 Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined),
334 ).pipe(Effect.asVoid);
335 // Retry backoff must block later effects so turns cannot race a pending rollback.
336 const claimableCandidatePredicate = (
337 availableBefore?: string,
338 excludeRestartContinuations = false,
339 maxRunningTitleGenerations?: number,
340 ) =>
341 sql`
342 ${
343 availableBefore === undefined
344 ? sql`1 = 1`
345 : sql`candidate.available_at <= ${availableBefore}`
346 }
347 AND candidate.status = 'pending'
348 AND NOT EXISTS (
349 SELECT 1
350 FROM orchestration_v2_effect_outbox AS active
351 WHERE active.thread_id = candidate.thread_id
352 AND (
353 active.status = 'running'
354 OR (
355 active.status = 'pending'
356 AND active.rowid < candidate.rowid
357 AND ${
358 excludeRestartContinuations
359 ? sql`active.effect_type != 'provider-runtime.continue'`
360 : sql`1 = 1`
361 }
362 )
363 )
364 AND (
365 (
366 candidate.effect_type = 'thread-title.generate'
367 AND active.effect_type = 'thread-title.generate'
368 )
369 OR
370 (
371 candidate.effect_type != 'thread-title.generate'
372 AND active.effect_type != 'thread-title.generate'
373 )
374 )
375 )
376 AND ${
377 maxRunningTitleGenerations === undefined
378 ? sql`1 = 1`
379 : sql`(
380 candidate.effect_type != 'thread-title.generate'
381 OR (
382 SELECT COUNT(*)
383 FROM orchestration_v2_effect_outbox AS running_title
384 WHERE running_title.status = 'running'
385 AND running_title.effect_type = 'thread-title.generate'
386 ) < ${maxRunningTitleGenerations}
387 )`
388 }
389 `;
390​
391 const cancellationSignal = (effectId: string) => {
392 const existing = cancellationSignals.get(effectId);
393 if (existing !== undefined) return existing;
394 const created = Deferred.makeUnsafe<void>();
395 cancellationSignals.set(effectId, created);
396 return created;
397 };
398​
399 const decodeRows = (operation: string, rows: ReadonlyArray<EffectRow>) =>
400 Effect.forEach(rows, rowToEffect).pipe(
401 Effect.mapError((cause) => new EffectOutboxError({ operation, cause })),
402 );
403​
404 const service: EffectOutboxV2Shape = {
405 enqueue: Effect.fn("EffectOutbox.enqueue")(
406 function* (effects) {
407 const now = yield* DateTime.now;
408 const nowIso = DateTime.formatIso(now);
409 yield* Effect.forEach(
410 effects,
411 (effect) => sql`
412 INSERT INTO orchestration_v2_effect_outbox (
413 effect_id,
414 command_id,
415 thread_id,
416 effect_type,
417 payload_json,
418 status,
419 attempt_count,
420 available_at,
421 created_at,
422 updated_at
423 )
424 VALUES (
425 ${effect.id},
426 ${effect.commandId},
427 ${effect.threadId},
428 ${effect.request.type},
429 ${encodeRequest(effect.request)},
430 'pending',
431 0,
432 ${DateTime.formatIso(effect.availableAt ?? now)},
433 ${nowIso},
434 ${nowIso}
435 )
436 ON CONFLICT(effect_id) DO NOTHING
437 `,
438 { concurrency: 1, discard: true },
439 );
440 // EventSink owns the corresponding post-commit notification.
441 },
442 Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause })),
443 ),
444 get: (effectId) =>
445 sql<EffectRow>`
446 SELECT *
447 FROM orchestration_v2_effect_outbox
448 WHERE effect_id = ${effectId}
449 LIMIT 1
450 `.pipe(
451 NodeSqliteClient.readOnly,
452 Effect.flatMap((rows) => {
453 const row = rows[0];
454 return row === undefined ? Effect.succeedNone : rowToEffect(row).pipe(Effect.asSome);
455 }),
456 Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })),
457 ),
458 awaitAvailable: Queue.take(available),
459 notifyAvailable,
460 listByCommandId: (commandId) =>
461 sql<EffectRow>`
462 SELECT *
463 FROM orchestration_v2_effect_outbox
464 WHERE command_id = ${commandId}
465 ORDER BY created_at ASC, effect_id ASC
466 `.pipe(
467 NodeSqliteClient.readOnly,
468 Effect.flatMap((rows) => decodeRows("list", rows)),
469 Effect.mapError((cause) =>
470 isEffectOutboxError(cause)
471 ? cause
472 : new EffectOutboxError({ operation: "list", cause }),
473 ),
474 ),
475 cancelUnsettled: Effect.fn("EffectOutbox.cancelUnsettled")(
476 function* ({ threadId, effectTypes, reason }) {
477 if (effectTypes.length === 0) return [];
478 const now = DateTime.formatIso(yield* DateTime.now);
479 const rows = yield* sql<{ readonly effect_id: string }>`
480 UPDATE orchestration_v2_effect_outbox
481 SET
482 status = 'cancelled',
483 lease_owner = NULL,
484 completed_at = ${now},
485 updated_at = ${now},
486 last_error = ${reason}
487 WHERE thread_id = ${threadId}
488 AND status IN ('pending', 'running')
489 AND effect_type IN ${sql.in(effectTypes)}
490 RETURNING effect_id
491 `;
492 return rows.map(({ effect_id }) => effect_id);
493 },
494 Effect.mapError((cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause })),
495 ),
496 signalCancellations: Effect.fn("EffectOutbox.signalCancellations")(function* (effectIds) {
497 yield* Effect.forEach(
498 effectIds,
499 (effectId) => {
500 const signal = cancellationSignals.get(effectId);
501 return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
502 },
503 { discard: true },
504 );
505 yield* signalSettled(effectIds);
506 if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);
507 }),
508 awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)),
509 clearCancellation: (effectId) =>
510 Effect.sync(() => {
511 cancellationSignals.delete(effectId);
512 }),
513 awaitSettled: Effect.fn("EffectOutbox.awaitSettled")(function* (effectId) {
514 // Registered before the read, so a settle right after it still resolves.
515 const signal = settledSignals.get(effectId) ?? Deferred.makeUnsafe<void>();
516 settledSignals.set(effectId, signal);
517 const effect = yield* service.get(effectId);
518 if (Option.exists(effect, ({ status }) => status === "pending" || status === "running")) {
519 return yield* Deferred.await(signal);
520 }
521 yield* signalSettled([effectId]);
522 }),
523 reconcileAfterProcessLoss: Effect.gen(function* () {
524 const now = DateTime.formatIso(yield* DateTime.now);
525 const cancelledRows = yield* sql<{ readonly effect_id: string }>`
526 UPDATE orchestration_v2_effect_outbox
527 SET
528 status = 'cancelled',
529 lease_owner = NULL,
530 completed_at = ${now},
531 updated_at = ${now},
532 last_error = 'Cancelled because the server process ended before the effect completed.'
533 WHERE status IN ('pending', 'running')
534 AND effect_type IN ${sql.in(PROCESS_BOUND_EFFECT_TYPES)}
535 RETURNING effect_id
536 `;
537 const requeuedRows = yield* sql<{ readonly effect_id: string }>`
538 UPDATE orchestration_v2_effect_outbox
539 SET
540 status = 'pending',
541 lease_owner = NULL,
542 available_at = ${now},
543 updated_at = ${now},
544 last_error = 'Requeued after the previous server process ended.'
545 WHERE status = 'running'
546 AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)}
547 RETURNING effect_id
548 `;
549 if (requeuedRows.length > 0) yield* notifyAvailable(requeuedRows.length);
550 return { requeued: requeuedRows.length, cancelled: cancelledRows.length };
551 }).pipe(
552 Effect.mapError(
553 (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }),
554 ),
555 ),
556 // The worker polls for the next effect even when there is no work to claim.
557 claimNext: Effect.fnUntraced(
558 function* ({ workerId, excludeRestartContinuations = false, maxRunningTitleGenerations }) {
559 const now = yield* DateTime.now;
560 const nowIso = DateTime.formatIso(now);
561 // Idle claims return empty; tracing their full SQL on every poll overwhelms useful traces.
562 const claimStatement = sql<EffectRow>`
563 UPDATE orchestration_v2_effect_outbox
564 SET
565 status = 'running',
566 attempt_count = attempt_count + 1,
567 lease_owner = ${workerId},
568 updated_at = ${nowIso},
569 last_error = NULL
570 WHERE effect_id = (
571 SELECT candidate.effect_id
572 FROM orchestration_v2_effect_outbox AS candidate
573 WHERE ${claimableCandidatePredicate(
574 nowIso,
575 excludeRestartContinuations,
576 maxRunningTitleGenerations,
577 )}
578 AND ${excludeRestartContinuations ? sql`candidate.effect_type != 'provider-runtime.continue'` : sql`1 = 1`}
579 ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC
580 LIMIT 1
581 )
582 RETURNING *
583 `;
584 while (true) {
585 const rows = yield* claimStatement.pipe(Effect.withTracerEnabled(false));
586 const row = rows[0];
587 if (row === undefined) return Option.none();
588 const decoded = yield* Effect.result(rowToEffect(row));
589 if (Result.isSuccess(decoded)) {
590 cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());
591 return Option.some(decoded.success);
592 }
593 // Left running, an unreadable row would block every later effect on its thread.
594 yield* Effect.logWarning("Failing an orchestration effect this build cannot decode", {
595 effectId: row.effect_id,
596 effectType: row.effect_type,
597 cause: decoded.failure,
598 });
599 yield* service.fail({
600 effectId: row.effect_id,
601 workerId,
602 error: `This server build cannot decode the ${row.effect_type} effect.`,
603 });
604 }
605 },
606 Effect.mapError((cause) =>
607 isEffectOutboxError(cause) ? cause : new EffectOutboxError({ operation: "claim", cause }),
608 ),
609 ),
610 nextClaimableAt: Effect.fnUntraced(
611 function* ({
612 maxRunningTitleGenerations,
613 }: { readonly maxRunningTitleGenerations?: number } = {}) {
614 const rows = yield* sql<{ readonly available_at: string | null }>`
615 SELECT MIN(candidate.available_at) AS available_at
616 FROM orchestration_v2_effect_outbox AS candidate
617 WHERE ${claimableCandidatePredicate(undefined, false, maxRunningTitleGenerations)}
618 `.pipe(NodeSqliteClient.readOnly, Effect.withTracerEnabled(false));
619 const availableAt = rows[0]?.available_at;
620 if (availableAt === undefined || availableAt === null) return Option.none();
621 const parsed = DateTime.make(availableAt);
622 if (Option.isNone(parsed)) {
623 return yield* new EffectOutboxError({
624 operation: "next-claimable",
625 cause: `Invalid available_at timestamp: ${availableAt}`,
626 });
627 }
628 return parsed;
629 },
630 Effect.mapError((cause) =>
631 isEffectOutboxError(cause)
632 ? cause
633 : new EffectOutboxError({ operation: "next-claimable", cause }),
634 ),
635 ),
636 succeed: Effect.fn("EffectOutbox.succeed")(
637 function* ({ effectId, workerId }) {
638 const now = DateTime.formatIso(yield* DateTime.now);
639 const rows = yield* sql<{ readonly effect_id: string }>`
640 UPDATE orchestration_v2_effect_outbox
641 SET
642 status = 'succeeded',
643 lease_owner = NULL,
644 completed_at = ${now},
645 updated_at = ${now},
646 last_error = NULL
647 WHERE effect_id = ${effectId}
648 AND status = 'running'
649 AND lease_owner = ${workerId}
650 RETURNING effect_id
651 `;
652 if (rows.length === 1) {
653 cancellationSignals.delete(effectId);
654 yield* signalSettled([effectId]);
655 yield* notifyAvailable();
656 }
657 return rows.length === 1;
658 },
659 (effect, { effectId }) =>
660 effect.pipe(
661 Effect.mapError(
662 (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
663 ),
664 ),
665 ),
666 retry: Effect.fn("EffectOutbox.retry")(
667 function* ({ effectId, workerId, error, delayMs }) {
668 const now = yield* DateTime.now;
669 const nowIso = DateTime.formatIso(now);
670 const availableAt = DateTime.formatIso(
671 DateTime.add(now, { milliseconds: Math.max(0, delayMs) }),
672 );
673 const rows = yield* sql<{ readonly effect_id: string }>`
674 UPDATE orchestration_v2_effect_outbox
675 SET
676 status = 'pending',
677 available_at = ${availableAt},
678 lease_owner = NULL,
679 updated_at = ${nowIso},
680 last_error = ${error}
681 WHERE effect_id = ${effectId}
682 AND status = 'running'
683 AND lease_owner = ${workerId}
684 RETURNING effect_id
685 `;
686 if (rows.length === 1) {
687 cancellationSignals.delete(effectId);
688 yield* notifyAvailable();
689 }
690 return rows.length === 1;
691 },
692 (effect, { effectId }) =>
693 effect.pipe(
694 Effect.mapError(
695 (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
696 ),
697 ),
698 ),
699 fail: Effect.fn("EffectOutbox.fail")(
700 function* ({ effectId, workerId, error }) {
701 const now = DateTime.formatIso(yield* DateTime.now);
702 const rows = yield* sql<{ readonly effect_id: string }>`
703 UPDATE orchestration_v2_effect_outbox
704 SET
705 status = 'failed',
706 lease_owner = NULL,
707 completed_at = ${now},
708 updated_at = ${now},
709 last_error = ${error}
710 WHERE effect_id = ${effectId}
711 AND status = 'running'
712 AND lease_owner = ${workerId}
713 RETURNING effect_id
714 `;
715 if (rows.length === 1) {
716 cancellationSignals.delete(effectId);
717 yield* signalSettled([effectId]);
718 yield* notifyAvailable();
719 }
720 return rows.length === 1;
721 },
722 (effect, { effectId }) =>
723 effect.pipe(
724 Effect.mapError(
725 (cause) => new EffectOutboxError({ operation: "fail", effectId, cause }),
726 ),
727 ),
728 ),
729 pruneSettled: Effect.gen(function* () {
730 const cutoff = DateTime.formatIso(
731 DateTime.subtractDuration(yield* DateTime.now, SETTLED_EFFECT_RETENTION),
732 );
733 // Live continuations retain their preceding intent's cumulative crash budget.
734 // Separate batch statements release the write lock between batches.
735 const deleteBatch = sql<{ readonly effect_id: string }>`
736 DELETE FROM orchestration_v2_effect_outbox
737 WHERE rowid IN (
738 SELECT rowid
739 FROM orchestration_v2_effect_outbox
740 WHERE status IN ('succeeded', 'cancelled')
741 AND completed_at < ${cutoff}
742 AND NOT (
743 effect_type = 'provider-runtime.continue'
744 AND EXISTS (
745 SELECT 1 FROM orchestration_v2_projection_runs AS recovery_run
746 WHERE recovery_run.thread_id = orchestration_v2_effect_outbox.thread_id
747 AND recovery_run.status IN ('queued', 'preparing', 'starting', 'running', 'waiting')
748 AND json_extract(recovery_run.payload_json, '$.restartContinuationOfRunId') =
749 json_extract(orchestration_v2_effect_outbox.payload_json, '$.sourceRunId')
750 )
751 )
752 LIMIT ${PRUNE_BATCH_SIZE}
753 )
754 RETURNING effect_id
755 `;
756 let pruned = 0;
757 while (true) {
758 const deleted = (yield* deleteBatch).length;
759 pruned += deleted;
760 if (deleted < PRUNE_BATCH_SIZE) return pruned;
761 yield* Effect.yieldNow;
762 }
763 }).pipe(
764 Effect.mapError((cause) => new EffectOutboxError({ operation: "prune-settled", cause })),
765 ),
766 };
767​
768 return service;
769 }),
770);
771​
772export const layerPruneWorker = Layer.effectDiscard(
773 Effect.gen(function* () {
774 const outbox = yield* EffectOutboxV2;
775 yield* forkParked(
776 outbox.pruneSettled.pipe(
777 Effect.catch((cause) => Effect.logWarning("Failed to prune settled effects", { cause })),
778 Effect.repeat(Schedule.spaced(Duration.hours(1))),
779 ),
780 );
781 }),
782);