Open History to see the last commit
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 Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Queue from "effect/Queue";
23import * as Schema from "effect/Schema";
24import * as SqlClient from "effect/unstable/sql/SqlClient";
25
26export const OrchestrationEffectRequestV2 = Schema.Union([
27 Schema.Struct({
28 type: Schema.Literal("provider-runtime.continue"),
29 sourceRunId: RunId,
30 }),
31 Schema.Struct({
32 type: Schema.Literal("provider-session.detach"),
33 providerSessionId: ProviderSessionId,
34 detail: Schema.optional(Schema.String),
35 /** Set on terminal detaches (thread archive/delete): revoke the thread's MCP credentials. */
36 revokeMcpCredential: Schema.optional(Schema.Boolean),
37 }),
38 Schema.Struct({
39 type: Schema.Literal("provider-turn.start"),
40 runId: RunId,
41 }),
42 Schema.Struct({
43 type: Schema.Literal("provider-turn.interrupt"),
44 providerSessionId: ProviderSessionId,
45 providerThreadId: ProviderThreadId,
46 providerTurnId: ProviderTurnId,
47 }),
48 Schema.Struct({
49 type: Schema.Literal("provider-turn.steer"),
50 providerSessionId: ProviderSessionId,
51 providerThreadId: ProviderThreadId,
52 providerTurnId: ProviderTurnId,
53 messageId: MessageId,
54 }),
55 Schema.Struct({
56 type: Schema.Literal("provider-turn.restart"),
57 providerSessionId: ProviderSessionId,
58 providerThreadId: ProviderThreadId,
59 providerTurnId: ProviderTurnId,
60 interruptedAttemptId: RunAttemptId,
61 runId: RunId,
62 sessionTransition: Schema.optional(
63 Schema.Union([
64 Schema.Struct({
65 type: Schema.Literal("replace"),
66 replacementProviderSessionId: ProviderSessionId,
67 }),
68 Schema.Struct({ type: Schema.Literal("detach") }),
69 ]),
70 ),
71 }),
72 Schema.Struct({
73 type: Schema.Literal("runtime-request.respond"),
74 providerSessionId: ProviderSessionId,
75 requestId: RuntimeRequestId,
76 decision: Schema.optional(ProviderApprovalDecision),
77 answers: Schema.optional(ProviderUserInputAnswers),
78 }),
79 Schema.Struct({
80 type: Schema.Literal("provider-thread.rollback"),
81 restoreFiles: Schema.optional(Schema.Boolean),
82 providerThreadId: ProviderThreadId,
83 checkpointId: CheckpointId,
84 scopeId: CheckpointScopeId,
85 }),
86 Schema.Struct({
87 type: Schema.Literal("checkpoint.capture"),
88 runId: RunId,
89 scopeId: CheckpointScopeId,
90 }),
91 Schema.Struct({
92 type: Schema.Literal("terminal.cleanup"),
93 }),
94 Schema.Struct({
95 type: Schema.Literal("attachment.cleanup"),
96 attachmentIds: Schema.Array(Schema.String),
97 }),
98 Schema.Struct({
99 type: Schema.Literal("thread-title.generate"),
100 kind: Schema.Union([
101 Schema.Struct({ type: Schema.Literal("initial"), messageId: MessageId }),
102 Schema.Struct({ type: Schema.Literal("regenerate") }),
103 ]),
104 }),
105]);
106export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type;
107
108export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [
109 "provider-runtime.continue",
110 "provider-session.detach",
111 "provider-thread.rollback",
112 "checkpoint.capture",
113 "terminal.cleanup",
114 "attachment.cleanup",
115 "thread-title.generate",
116] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
117
118export const PROCESS_BOUND_EFFECT_TYPES = [
119 "provider-turn.start",
120 "provider-turn.interrupt",
121 "provider-turn.steer",
122 "provider-turn.restart",
123 "runtime-request.respond",
124] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
125
126export const OrchestrationEffectStatusV2 = Schema.Literals([
127 "pending",
128 "running",
129 "succeeded",
130 "failed",
131 "cancelled",
132]);
133export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type;
134
135export interface OrchestrationEffectV2 {
136 readonly id: string;
137 readonly commandId: CommandId;
138 readonly threadId: ThreadId;
139 readonly request: OrchestrationEffectRequestV2;
140 readonly status: OrchestrationEffectStatusV2;
141 readonly attemptCount: number;
142 readonly availableAt: string;
143 readonly leaseOwner: string | null;
144 readonly leaseExpiresAt: string | null;
145 readonly createdAt: string;
146 readonly updatedAt: string;
147 readonly completedAt: string | null;
148 readonly lastError: string | null;
149}
150
151export interface PendingOrchestrationEffectV2 {
152 readonly id: string;
153 readonly commandId: CommandId;
154 readonly threadId: ThreadId;
155 readonly request: OrchestrationEffectRequestV2;
156 readonly availableAt?: DateTime.Utc;
157}
158
159export class EffectOutboxError extends Schema.TaggedError<EffectOutboxError>()(
160 "EffectOutboxError",
161 {
162 operation: Schema.String,
163 effectId: Schema.optional(Schema.String),
164 cause: Schema.optional(Schema.Defect()),
165 },
166) {
167 override get message(): string {
168 return `Orchestration effect outbox ${this.operation} failed${this.effectId === undefined ? "" : ` for ${this.effectId}`}.`;
169 }
170}
171
172const isEffectOutboxError = Schema.is(EffectOutboxError);
173
174export interface EffectOutboxV2Shape {
175 readonly awaitAvailable: Effect.Effect<void>;
176 readonly notifyAvailable: (count?: number) => Effect.Effect<void>;
177 /** Persist rows only. Notify workers after the surrounding transaction commits. */
178 readonly enqueue: (
179 effects: ReadonlyArray<PendingOrchestrationEffectV2>,
180 ) => Effect.Effect<void, EffectOutboxError>;
181 readonly get: (
182 effectId: string,
183 ) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
184 readonly listByCommandId: (
185 commandId: CommandId,
186 ) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
187 readonly cancelUnsettled: (input: {
188 readonly threadId: ThreadId;
189 readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
190 readonly reason: string;
191 }) => Effect.Effect<ReadonlyArray<string>, EffectOutboxError>;
192 readonly signalCancellations: (effectIds: ReadonlyArray<string>) => Effect.Effect<void>;
193 readonly awaitCancellation: (effectId: string) => Effect.Effect<void>;
194 readonly clearCancellation: (effectId: string) => Effect.Effect<void>;
195 readonly reconcileAfterProcessLoss: Effect.Effect<
196 { readonly requeued: number; readonly cancelled: number },
197 EffectOutboxError
198 >;
199 readonly claimNext: (input: {
200 readonly workerId: string;
201 readonly leaseDurationMs: number;
202 readonly excludeRestartContinuations?: boolean;
203 }) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
204 readonly nextClaimableAt: Effect.Effect<Option.Option<DateTime.Utc>, EffectOutboxError>;
205 readonly succeed: (input: {
206 readonly effectId: string;
207 readonly workerId: string;
208 }) => Effect.Effect<boolean, EffectOutboxError>;
209 readonly retry: (input: {
210 readonly effectId: string;
211 readonly workerId: string;
212 readonly error: string;
213 readonly delayMs: number;
214 }) => Effect.Effect<boolean, EffectOutboxError>;
215 readonly fail: (input: {
216 readonly effectId: string;
217 readonly workerId: string;
218 readonly error: string;
219 }) => Effect.Effect<boolean, EffectOutboxError>;
220}
221
222export class EffectOutboxV2 extends Context.Service<EffectOutboxV2, EffectOutboxV2Shape>()(
223 "t3/orchestration-v2/EffectOutbox/EffectOutboxV2",
224) {}
225
226type EffectRow = {
227 readonly effect_id: string;
228 readonly command_id: string;
229 readonly thread_id: string;
230 readonly effect_type: string;
231 readonly payload_json: string;
232 readonly status: string;
233 readonly attempt_count: number;
234 readonly available_at: string;
235 readonly lease_owner: string | null;
236 readonly lease_expires_at: string | null;
237 readonly created_at: string;
238 readonly updated_at: string;
239 readonly completed_at: string | null;
240 readonly last_error: string | null;
241};
242
243const encodeRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
244const decodeRequest = Schema.decodeUnknownEffect(
245 Schema.fromJsonString(OrchestrationEffectRequestV2),
246);
247
248const rowToEffect = (row: EffectRow) =>
249 decodeRequest(row.payload_json).pipe(
250 Effect.map((request): OrchestrationEffectV2 => ({
251 id: row.effect_id,
252 commandId: CommandId.make(row.command_id),
253 threadId: ThreadId.make(row.thread_id),
254 request,
255 status: row.status as OrchestrationEffectStatusV2,
256 attemptCount: row.attempt_count,
257 availableAt: row.available_at,
258 leaseOwner: row.lease_owner,
259 leaseExpiresAt: row.lease_expires_at,
260 createdAt: row.created_at,
261 updatedAt: row.updated_at,
262 completedAt: row.completed_at,
263 lastError: row.last_error,
264 })),
265 );
266
267export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = Layer.effect(
268 EffectOutboxV2,
269 Effect.gen(function* () {
270 const sql = yield* SqlClient.SqlClient;
271 // Availability is only a bounded latency hint; durable rows remain
272 // authoritative. Retaining a small burst lets multiple worker slots wake
273 // for distinct threads without allowing notifications to grow unbounded.
274 const available = yield* Queue.dropping<void>(64);
275 const cancellationSignals = new Map<string, Deferred.Deferred<void>>();
276 const notifyAvailable = (count = 1) =>
277 Queue.offerAll(
278 available,
279 Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined),
280 ).pipe(Effect.asVoid);
281 // Each thread runs its effects one at a time, in enqueue (rowid) order. An earlier
282 // effect waiting out a retry backoff still blocks later ones, so a turn
283 // cannot start while a failed rollback is about to restore files. A claim
284 // that skips restart continuations is not blocked by them either.
285 // Title generation is correlated metadata work, so it has its own
286 // per-thread lane and cannot delay provider lifecycle effects.
287 const claimableCandidatePredicate = (
288 availableBefore?: string,
289 excludeRestartContinuations = false,
290 ) =>
291 sql`
292 ${
293 availableBefore === undefined
294 ? sql`1 = 1`
295 : sql`candidate.available_at <= ${availableBefore}`
296 }
297 AND candidate.status = 'pending'
298 AND NOT EXISTS (
299 SELECT 1
300 FROM orchestration_v2_effect_outbox AS active
301 WHERE active.thread_id = candidate.thread_id
302 AND (
303 active.status = 'running'
304 OR (
305 active.status = 'pending'
306 AND active.rowid < candidate.rowid
307 AND ${
308 excludeRestartContinuations
309 ? sql`active.effect_type != 'provider-runtime.continue'`
310 : sql`1 = 1`
311 }
312 )
313 )
314 AND (
315 (
316 candidate.effect_type = 'thread-title.generate'
317 AND active.effect_type = 'thread-title.generate'
318 )
319 OR
320 (
321 candidate.effect_type != 'thread-title.generate'
322 AND active.effect_type != 'thread-title.generate'
323 )
324 )
325 )
326 `;
327
328 const cancellationSignal = (effectId: string) => {
329 const existing = cancellationSignals.get(effectId);
330 if (existing !== undefined) return existing;
331 const created = Deferred.makeUnsafe<void>();
332 cancellationSignals.set(effectId, created);
333 return created;
334 };
335
336 const decodeRows = (operation: string, rows: ReadonlyArray<EffectRow>) =>
337 Effect.forEach(rows, rowToEffect).pipe(
338 Effect.mapError((cause) => new EffectOutboxError({ operation, cause })),
339 );
340
341 const service: EffectOutboxV2Shape = {
342 enqueue: (effects) =>
343 Effect.gen(function* () {
344 const now = yield* DateTime.now;
345 const nowIso = DateTime.formatIso(now);
346 yield* Effect.forEach(
347 effects,
348 (effect) => sql`
349 INSERT INTO orchestration_v2_effect_outbox (
350 effect_id,
351 command_id,
352 thread_id,
353 effect_type,
354 payload_json,
355 status,
356 attempt_count,
357 available_at,
358 created_at,
359 updated_at
360 )
361 VALUES (
362 ${effect.id},
363 ${effect.commandId},
364 ${effect.threadId},
365 ${effect.request.type},
366 ${encodeRequest(effect.request)},
367 'pending',
368 0,
369 ${DateTime.formatIso(effect.availableAt ?? now)},
370 ${nowIso},
371 ${nowIso}
372 )
373 ON CONFLICT(effect_id) DO NOTHING
374 `,
375 { concurrency: 1, discard: true },
376 );
377 // Do not signal here: callers enqueue inside a larger transaction,
378 // and workers must only observe availability after that transaction
379 // commits. EventSink owns the corresponding post-commit notification.
380 }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause }))),
381 get: (effectId) =>
382 sql<EffectRow>`
383 SELECT *
384 FROM orchestration_v2_effect_outbox
385 WHERE effect_id = ${effectId}
386 LIMIT 1
387 `.pipe(
388 Effect.flatMap((rows) => {
389 const row = rows[0];
390 return row === undefined
391 ? Effect.succeed(Option.none())
392 : rowToEffect(row).pipe(Effect.map(Option.some));
393 }),
394 Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })),
395 ),
396 awaitAvailable: Queue.take(available),
397 notifyAvailable,
398 listByCommandId: (commandId) =>
399 sql<EffectRow>`
400 SELECT *
401 FROM orchestration_v2_effect_outbox
402 WHERE command_id = ${commandId}
403 ORDER BY created_at ASC, effect_id ASC
404 `.pipe(
405 Effect.flatMap((rows) => decodeRows("list", rows)),
406 Effect.mapError((cause) =>
407 isEffectOutboxError(cause)
408 ? cause
409 : new EffectOutboxError({ operation: "list", cause }),
410 ),
411 ),
412 cancelUnsettled: ({ threadId, effectTypes, reason }) =>
413 Effect.gen(function* () {
414 if (effectTypes.length === 0) return [];
415 const now = DateTime.formatIso(yield* DateTime.now);
416 const rows = yield* sql<{ readonly effect_id: string }>`
417 UPDATE orchestration_v2_effect_outbox
418 SET
419 status = 'cancelled',
420 lease_owner = NULL,
421 lease_expires_at = NULL,
422 completed_at = ${now},
423 updated_at = ${now},
424 last_error = ${reason}
425 WHERE thread_id = ${threadId}
426 AND status IN ('pending', 'running')
427 AND effect_type IN ${sql.in(effectTypes)}
428 RETURNING effect_id
429 `;
430 return rows.map(({ effect_id }) => effect_id);
431 }).pipe(
432 Effect.mapError(
433 (cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause }),
434 ),
435 ),
436 signalCancellations: (effectIds) =>
437 Effect.gen(function* () {
438 yield* Effect.forEach(
439 effectIds,
440 (effectId) => {
441 const signal = cancellationSignals.get(effectId);
442 return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
443 },
444 { discard: true },
445 );
446 // Cancellation can unblock other pending work on the same thread.
447 // This method is deliberately post-commit, so it is also the safe
448 // place to wake claimers after the durable status change.
449 if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);
450 }),
451 awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)),
452 clearCancellation: (effectId) =>
453 Effect.sync(() => {
454 cancellationSignals.delete(effectId);
455 }),
456 reconcileAfterProcessLoss: Effect.gen(function* () {
457 const now = DateTime.formatIso(yield* DateTime.now);
458 const cancelledRows = yield* sql<{ readonly effect_id: string }>`
459 UPDATE orchestration_v2_effect_outbox
460 SET
461 status = 'cancelled',
462 lease_owner = NULL,
463 lease_expires_at = NULL,
464 completed_at = ${now},
465 updated_at = ${now},
466 last_error = 'Cancelled because the server process ended before the effect completed.'
467 WHERE status IN ('pending', 'running')
468 AND effect_type IN ${sql.in(PROCESS_BOUND_EFFECT_TYPES)}
469 RETURNING effect_id
470 `;
471 const requeuedRows = yield* sql<{ readonly effect_id: string }>`
472 UPDATE orchestration_v2_effect_outbox
473 SET
474 status = 'pending',
475 lease_owner = NULL,
476 lease_expires_at = NULL,
477 available_at = ${now},
478 updated_at = ${now},
479 last_error = 'Requeued after the previous server process ended.'
480 WHERE status = 'running'
481 AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)}
482 RETURNING effect_id
483 `;
484 if (requeuedRows.length > 0) yield* notifyAvailable(requeuedRows.length);
485 return { requeued: requeuedRows.length, cancelled: cancelledRows.length };
486 }).pipe(
487 Effect.mapError(
488 (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }),
489 ),
490 ),
491 claimNext: ({ workerId, leaseDurationMs, excludeRestartContinuations = false }) =>
492 Effect.gen(function* () {
493 const now = yield* DateTime.now;
494 const nowIso = DateTime.formatIso(now);
495 const leaseExpiresAt = DateTime.formatIso(
496 DateTime.add(now, { milliseconds: Math.max(1, leaseDurationMs) }),
497 );
498 // Empty safety claims are expected while the daemon is idle. Tracing
499 // this query records the full SQL text on every poll and can dominate
500 // the local trace without adding actionable information.
501 const claimStatement = sql<EffectRow>`
502 UPDATE orchestration_v2_effect_outbox
503 SET
504 status = 'running',
505 attempt_count = attempt_count + 1,
506 lease_owner = ${workerId},
507 lease_expires_at = ${leaseExpiresAt},
508 updated_at = ${nowIso},
509 last_error = NULL
510 WHERE effect_id = (
511 SELECT candidate.effect_id
512 FROM orchestration_v2_effect_outbox AS candidate
513 WHERE ${claimableCandidatePredicate(nowIso, excludeRestartContinuations)}
514 AND ${excludeRestartContinuations ? sql`candidate.effect_type != 'provider-runtime.continue'` : sql`1 = 1`}
515 ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC
516 LIMIT 1
517 )
518 RETURNING *
519 `;
520 const rows = yield* claimStatement.pipe(Effect.withTracerEnabled(false));
521 const row = rows[0];
522 if (row === undefined) return Option.none();
523 cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());
524 return Option.some(yield* rowToEffect(row));
525 }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause }))),
526 nextClaimableAt: Effect.gen(function* () {
527 const rows = yield* sql<{ readonly available_at: string | null }>`
528 SELECT MIN(candidate.available_at) AS available_at
529 FROM orchestration_v2_effect_outbox AS candidate
530 WHERE ${claimableCandidatePredicate()}
531 `.pipe(Effect.withTracerEnabled(false));
532 const availableAt = rows[0]?.available_at;
533 if (availableAt === undefined || availableAt === null) return Option.none();
534 const parsed = DateTime.make(availableAt);
535 if (Option.isNone(parsed)) {
536 return yield* new EffectOutboxError({
537 operation: "next-claimable",
538 cause: `Invalid available_at timestamp: ${availableAt}`,
539 });
540 }
541 return parsed;
542 }).pipe(
543 Effect.mapError((cause) =>
544 isEffectOutboxError(cause)
545 ? cause
546 : new EffectOutboxError({ operation: "next-claimable", cause }),
547 ),
548 ),
549 succeed: ({ effectId, workerId }) =>
550 Effect.gen(function* () {
551 const now = DateTime.formatIso(yield* DateTime.now);
552 const rows = yield* sql<{ readonly effect_id: string }>`
553 UPDATE orchestration_v2_effect_outbox
554 SET
555 status = 'succeeded',
556 lease_owner = NULL,
557 lease_expires_at = NULL,
558 completed_at = ${now},
559 updated_at = ${now},
560 last_error = NULL
561 WHERE effect_id = ${effectId}
562 AND status = 'running'
563 AND lease_owner = ${workerId}
564 RETURNING effect_id
565 `;
566 if (rows.length === 1) {
567 cancellationSignals.delete(effectId);
568 yield* notifyAvailable();
569 }
570 return rows.length === 1;
571 }).pipe(
572 Effect.mapError(
573 (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
574 ),
575 ),
576 retry: ({ effectId, workerId, error, delayMs }) =>
577 Effect.gen(function* () {
578 const now = yield* DateTime.now;
579 const nowIso = DateTime.formatIso(now);
580 const availableAt = DateTime.formatIso(
581 DateTime.add(now, { milliseconds: Math.max(0, delayMs) }),
582 );
583 const rows = yield* sql<{ readonly effect_id: string }>`
584 UPDATE orchestration_v2_effect_outbox
585 SET
586 status = 'pending',
587 available_at = ${availableAt},
588 lease_owner = NULL,
589 lease_expires_at = NULL,
590 updated_at = ${nowIso},
591 last_error = ${error}
592 WHERE effect_id = ${effectId}
593 AND status = 'running'
594 AND lease_owner = ${workerId}
595 RETURNING effect_id
596 `;
597 if (rows.length === 1) {
598 cancellationSignals.delete(effectId);
599 yield* notifyAvailable();
600 }
601 return rows.length === 1;
602 }).pipe(
603 Effect.mapError(
604 (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
605 ),
606 ),
607 fail: ({ effectId, workerId, error }) =>
608 Effect.gen(function* () {
609 const now = DateTime.formatIso(yield* DateTime.now);
610 const rows = yield* sql<{ readonly effect_id: string }>`
611 UPDATE orchestration_v2_effect_outbox
612 SET
613 status = 'failed',
614 lease_owner = NULL,
615 lease_expires_at = NULL,
616 completed_at = ${now},
617 updated_at = ${now},
618 last_error = ${error}
619 WHERE effect_id = ${effectId}
620 AND status = 'running'
621 AND lease_owner = ${workerId}
622 RETURNING effect_id
623 `;
624 if (rows.length === 1) {
625 cancellationSignals.delete(effectId);
626 yield* notifyAvailable();
627 }
628 return rows.length === 1;
629 }).pipe(
630 Effect.mapError((cause) => new EffectOutboxError({ operation: "fail", effectId, cause })),
631 ),
632 };
633
634 return service;
635 }),
636);