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

EffectOutbox.ts

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