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