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-session.detach"),
29 providerSessionId: ProviderSessionId,
30 detail: Schema.optional(Schema.String),
31 }),
32 Schema.Struct({
33 type: Schema.Literal("provider-turn.start"),
34 runId: RunId,
35 }),
36 Schema.Struct({
37 type: Schema.Literal("provider-turn.interrupt"),
38 providerSessionId: ProviderSessionId,
39 providerThreadId: ProviderThreadId,
40 providerTurnId: ProviderTurnId,
41 }),
42 Schema.Struct({
43 type: Schema.Literal("provider-turn.steer"),
44 providerSessionId: ProviderSessionId,
45 providerThreadId: ProviderThreadId,
46 providerTurnId: ProviderTurnId,
47 messageId: MessageId,
48 }),
49 Schema.Struct({
50 type: Schema.Literal("provider-turn.restart"),
51 providerSessionId: ProviderSessionId,
52 providerThreadId: ProviderThreadId,
53 providerTurnId: ProviderTurnId,
54 interruptedAttemptId: RunAttemptId,
55 runId: RunId,
56 sessionTransition: Schema.optional(
57 Schema.Union([
58 Schema.Struct({
59 type: Schema.Literal("replace"),
60 replacementProviderSessionId: ProviderSessionId,
61 }),
62 Schema.Struct({ type: Schema.Literal("detach") }),
63 ]),
64 ),
65 }),
66 Schema.Struct({
67 type: Schema.Literal("runtime-request.respond"),
68 providerSessionId: ProviderSessionId,
69 requestId: RuntimeRequestId,
70 decision: Schema.optional(ProviderApprovalDecision),
71 answers: Schema.optional(ProviderUserInputAnswers),
72 }),
73 Schema.Struct({
74 type: Schema.Literal("provider-thread.rollback"),
75 providerThreadId: ProviderThreadId,
76 checkpointId: CheckpointId,
77 scopeId: CheckpointScopeId,
78 }),
79 Schema.Struct({
80 type: Schema.Literal("checkpoint.capture"),
81 runId: RunId,
82 scopeId: CheckpointScopeId,
83 }),
84 Schema.Struct({
85 type: Schema.Literal("terminal.cleanup"),
86 }),
87 Schema.Struct({
88 type: Schema.Literal("attachment.cleanup"),
89 attachmentIds: Schema.Array(Schema.String),
90 }),
91]);
92export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type;
93
94export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [
95 "provider-session.detach",
96 "provider-thread.rollback",
97 "checkpoint.capture",
98 "terminal.cleanup",
99 "attachment.cleanup",
100] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
101
102export const PROCESS_BOUND_EFFECT_TYPES = [
103 "provider-turn.start",
104 "provider-turn.interrupt",
105 "provider-turn.steer",
106 "provider-turn.restart",
107 "runtime-request.respond",
108] as const satisfies ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
109
110export const OrchestrationEffectStatusV2 = Schema.Literals([
111 "pending",
112 "running",
113 "succeeded",
114 "failed",
115 "cancelled",
116]);
117export type OrchestrationEffectStatusV2 = typeof OrchestrationEffectStatusV2.Type;
118
119export interface OrchestrationEffectV2 {
120 readonly id: string;
121 readonly commandId: CommandId;
122 readonly threadId: ThreadId;
123 readonly request: OrchestrationEffectRequestV2;
124 readonly status: OrchestrationEffectStatusV2;
125 readonly attemptCount: number;
126 readonly availableAt: string;
127 readonly leaseOwner: string | null;
128 readonly leaseExpiresAt: string | null;
129 readonly createdAt: string;
130 readonly updatedAt: string;
131 readonly completedAt: string | null;
132 readonly lastError: string | null;
133}
134
135export interface PendingOrchestrationEffectV2 {
136 readonly id: string;
137 readonly commandId: CommandId;
138 readonly threadId: ThreadId;
139 readonly request: OrchestrationEffectRequestV2;
140 readonly availableAt?: DateTime.Utc;
141}
142
143export class EffectOutboxError extends Schema.TaggedErrorClass<EffectOutboxError>()(
144 "EffectOutboxError",
145 {
146 operation: Schema.String,
147 effectId: Schema.optional(Schema.String),
148 cause: Schema.optional(Schema.Defect()),
149 },
150) {
151 override get message(): string {
152 return `Orchestration effect outbox ${this.operation} failed${this.effectId === undefined ? "" : ` for ${this.effectId}`}.`;
153 }
154}
155
156const isEffectOutboxError = Schema.is(EffectOutboxError);
157
158export interface EffectOutboxV2Shape {
159 readonly awaitAvailable: Effect.Effect<void>;
160 readonly notifyAvailable: Effect.Effect<void>;
161 readonly enqueue: (
162 effects: ReadonlyArray<PendingOrchestrationEffectV2>,
163 ) => Effect.Effect<void, EffectOutboxError>;
164 readonly get: (
165 effectId: string,
166 ) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
167 readonly listByCommandId: (
168 commandId: CommandId,
169 ) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
170 readonly cancelUnsettled: (input: {
171 readonly threadId: ThreadId;
172 readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
173 readonly reason: string;
174 }) => Effect.Effect<ReadonlyArray<string>, EffectOutboxError>;
175 readonly signalCancellations: (effectIds: ReadonlyArray<string>) => Effect.Effect<void>;
176 readonly awaitCancellation: (effectId: string) => Effect.Effect<void>;
177 readonly clearCancellation: (effectId: string) => Effect.Effect<void>;
178 readonly reconcileAfterProcessLoss: Effect.Effect<
179 { readonly requeued: number; readonly cancelled: number },
180 EffectOutboxError
181 >;
182 readonly claimNext: (input: {
183 readonly workerId: string;
184 readonly leaseDurationMs: number;
185 }) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
186 readonly succeed: (input: {
187 readonly effectId: string;
188 readonly workerId: string;
189 }) => Effect.Effect<boolean, EffectOutboxError>;
190 readonly retry: (input: {
191 readonly effectId: string;
192 readonly workerId: string;
193 readonly error: string;
194 readonly delayMs: number;
195 }) => Effect.Effect<boolean, EffectOutboxError>;
196 readonly fail: (input: {
197 readonly effectId: string;
198 readonly workerId: string;
199 readonly error: string;
200 }) => Effect.Effect<boolean, EffectOutboxError>;
201}
202
203export class EffectOutboxV2 extends Context.Service<EffectOutboxV2, EffectOutboxV2Shape>()(
204 "t3/orchestration-v2/EffectOutbox/EffectOutboxV2",
205) {}
206
207type EffectRow = {
208 readonly effect_id: string;
209 readonly command_id: string;
210 readonly thread_id: string;
211 readonly effect_type: string;
212 readonly payload_json: string;
213 readonly status: string;
214 readonly attempt_count: number;
215 readonly available_at: string;
216 readonly lease_owner: string | null;
217 readonly lease_expires_at: string | null;
218 readonly created_at: string;
219 readonly updated_at: string;
220 readonly completed_at: string | null;
221 readonly last_error: string | null;
222};
223
224const encodeRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
225const decodeRequest = Schema.decodeUnknownEffect(
226 Schema.fromJsonString(OrchestrationEffectRequestV2),
227);
228
229const rowToEffect = (row: EffectRow) =>
230 decodeRequest(row.payload_json).pipe(
231 Effect.map(
232 (request): OrchestrationEffectV2 => ({
233 id: row.effect_id,
234 commandId: CommandId.make(row.command_id),
235 threadId: ThreadId.make(row.thread_id),
236 request,
237 status: row.status as OrchestrationEffectStatusV2,
238 attemptCount: row.attempt_count,
239 availableAt: row.available_at,
240 leaseOwner: row.lease_owner,
241 leaseExpiresAt: row.lease_expires_at,
242 createdAt: row.created_at,
243 updatedAt: row.updated_at,
244 completedAt: row.completed_at,
245 lastError: row.last_error,
246 }),
247 ),
248 );
249
250export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = Layer.effect(
251 EffectOutboxV2,
252 Effect.gen(function* () {
253 const sql = yield* SqlClient.SqlClient;
254 // Availability is only a bounded latency hint; durable rows remain
255 // authoritative. Retaining a small burst lets multiple worker slots wake
256 // for distinct threads without allowing notifications to grow unbounded.
257 const available = yield* Queue.dropping<void>(64);
258 const cancellationSignals = new Map<string, Deferred.Deferred<void>>();
259
260 const cancellationSignal = (effectId: string) => {
261 const existing = cancellationSignals.get(effectId);
262 if (existing !== undefined) return existing;
263 const created = Deferred.makeUnsafe<void>();
264 cancellationSignals.set(effectId, created);
265 return created;
266 };
267
268 const decodeRows = (operation: string, rows: ReadonlyArray<EffectRow>) =>
269 Effect.forEach(rows, rowToEffect).pipe(
270 Effect.mapError((cause) => new EffectOutboxError({ operation, cause })),
271 );
272
273 const service: EffectOutboxV2Shape = {
274 enqueue: (effects) =>
275 Effect.gen(function* () {
276 const now = yield* DateTime.now;
277 const nowIso = DateTime.formatIso(now);
278 yield* Effect.forEach(
279 effects,
280 (effect) => sql`
281 INSERT INTO orchestration_v2_effect_outbox (
282 effect_id,
283 command_id,
284 thread_id,
285 effect_type,
286 payload_json,
287 status,
288 attempt_count,
289 available_at,
290 created_at,
291 updated_at
292 )
293 VALUES (
294 ${effect.id},
295 ${effect.commandId},
296 ${effect.threadId},
297 ${effect.request.type},
298 ${encodeRequest(effect.request)},
299 'pending',
300 0,
301 ${DateTime.formatIso(effect.availableAt ?? now)},
302 ${nowIso},
303 ${nowIso}
304 )
305 ON CONFLICT(effect_id) DO NOTHING
306 `,
307 { concurrency: 1, discard: true },
308 );
309 if (effects.length > 0) {
310 yield* Queue.offerAll(
311 available,
312 Array.from({ length: Math.min(effects.length, 64) }, () => undefined),
313 );
314 }
315 }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause }))),
316 get: (effectId) =>
317 sql<EffectRow>`
318 SELECT *
319 FROM orchestration_v2_effect_outbox
320 WHERE effect_id = ${effectId}
321 LIMIT 1
322 `.pipe(
323 Effect.flatMap((rows) => {
324 const row = rows[0];
325 return row === undefined
326 ? Effect.succeed(Option.none())
327 : rowToEffect(row).pipe(Effect.map(Option.some));
328 }),
329 Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })),
330 ),
331 awaitAvailable: Queue.take(available),
332 notifyAvailable: Queue.offer(available, undefined).pipe(Effect.asVoid),
333 listByCommandId: (commandId) =>
334 sql<EffectRow>`
335 SELECT *
336 FROM orchestration_v2_effect_outbox
337 WHERE command_id = ${commandId}
338 ORDER BY created_at ASC, effect_id ASC
339 `.pipe(
340 Effect.flatMap((rows) => decodeRows("list", rows)),
341 Effect.mapError((cause) =>
342 isEffectOutboxError(cause)
343 ? cause
344 : new EffectOutboxError({ operation: "list", cause }),
345 ),
346 ),
347 cancelUnsettled: ({ threadId, effectTypes, reason }) =>
348 Effect.gen(function* () {
349 if (effectTypes.length === 0) return [];
350 const now = DateTime.formatIso(yield* DateTime.now);
351 const rows = yield* sql<{ readonly effect_id: string }>`
352 UPDATE orchestration_v2_effect_outbox
353 SET
354 status = 'cancelled',
355 lease_owner = NULL,
356 lease_expires_at = NULL,
357 completed_at = ${now},
358 updated_at = ${now},
359 last_error = ${reason}
360 WHERE thread_id = ${threadId}
361 AND status IN ('pending', 'running')
362 AND effect_type IN ${sql.in(effectTypes)}
363 RETURNING effect_id
364 `;
365 return rows.map(({ effect_id }) => effect_id);
366 }).pipe(
367 Effect.mapError(
368 (cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause }),
369 ),
370 ),
371 signalCancellations: (effectIds) =>
372 Effect.forEach(
373 effectIds,
374 (effectId) => {
375 const signal = cancellationSignals.get(effectId);
376 return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
377 },
378 { discard: true },
379 ),
380 awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)),
381 clearCancellation: (effectId) =>
382 Effect.sync(() => {
383 cancellationSignals.delete(effectId);
384 }),
385 reconcileAfterProcessLoss: Effect.gen(function* () {
386 const now = DateTime.formatIso(yield* DateTime.now);
387 const cancelledRows = yield* sql<{ readonly effect_id: string }>`
388 UPDATE orchestration_v2_effect_outbox
389 SET
390 status = 'cancelled',
391 lease_owner = NULL,
392 lease_expires_at = NULL,
393 completed_at = ${now},
394 updated_at = ${now},
395 last_error = 'Cancelled because the server process ended before the effect completed.'
396 WHERE status IN ('pending', 'running')
397 AND effect_type IN ${sql.in(PROCESS_BOUND_EFFECT_TYPES)}
398 RETURNING effect_id
399 `;
400 const requeuedRows = yield* sql<{ readonly effect_id: string }>`
401 UPDATE orchestration_v2_effect_outbox
402 SET
403 status = 'pending',
404 lease_owner = NULL,
405 lease_expires_at = NULL,
406 available_at = ${now},
407 updated_at = ${now},
408 last_error = 'Requeued after the previous server process ended.'
409 WHERE status = 'running'
410 AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)}
411 RETURNING effect_id
412 `;
413 if (requeuedRows.length > 0) yield* Queue.offer(available, undefined);
414 return { requeued: requeuedRows.length, cancelled: cancelledRows.length };
415 }).pipe(
416 Effect.mapError(
417 (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }),
418 ),
419 ),
420 claimNext: ({ workerId, leaseDurationMs }) =>
421 Effect.gen(function* () {
422 const now = yield* DateTime.now;
423 const nowIso = DateTime.formatIso(now);
424 const leaseExpiresAt = DateTime.formatIso(
425 DateTime.add(now, { milliseconds: Math.max(1, leaseDurationMs) }),
426 );
427 const rows = yield* sql<EffectRow>`
428 UPDATE orchestration_v2_effect_outbox
429 SET
430 status = 'running',
431 attempt_count = attempt_count + 1,
432 lease_owner = ${workerId},
433 lease_expires_at = ${leaseExpiresAt},
434 updated_at = ${nowIso},
435 last_error = NULL
436 WHERE effect_id = (
437 SELECT candidate.effect_id
438 FROM orchestration_v2_effect_outbox AS candidate
439 WHERE candidate.available_at <= ${nowIso}
440 AND candidate.status = 'pending'
441 AND NOT EXISTS (
442 SELECT 1
443 FROM orchestration_v2_effect_outbox AS active
444 WHERE active.thread_id = candidate.thread_id
445 AND active.status = 'running'
446 )
447 ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC
448 LIMIT 1
449 )
450 RETURNING *
451 `;
452 const row = rows[0];
453 if (row === undefined) return Option.none();
454 cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());
455 return Option.some(yield* rowToEffect(row));
456 }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause }))),
457 succeed: ({ effectId, workerId }) =>
458 Effect.gen(function* () {
459 const now = DateTime.formatIso(yield* DateTime.now);
460 const rows = yield* sql<{ readonly effect_id: string }>`
461 UPDATE orchestration_v2_effect_outbox
462 SET
463 status = 'succeeded',
464 lease_owner = NULL,
465 lease_expires_at = NULL,
466 completed_at = ${now},
467 updated_at = ${now},
468 last_error = NULL
469 WHERE effect_id = ${effectId}
470 AND status = 'running'
471 AND lease_owner = ${workerId}
472 RETURNING effect_id
473 `;
474 if (rows.length === 1) cancellationSignals.delete(effectId);
475 return rows.length === 1;
476 }).pipe(
477 Effect.mapError(
478 (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
479 ),
480 ),
481 retry: ({ effectId, workerId, error, delayMs }) =>
482 Effect.gen(function* () {
483 const now = yield* DateTime.now;
484 const nowIso = DateTime.formatIso(now);
485 const availableAt = DateTime.formatIso(
486 DateTime.add(now, { milliseconds: Math.max(0, delayMs) }),
487 );
488 const rows = yield* sql<{ readonly effect_id: string }>`
489 UPDATE orchestration_v2_effect_outbox
490 SET
491 status = 'pending',
492 available_at = ${availableAt},
493 lease_owner = NULL,
494 lease_expires_at = NULL,
495 updated_at = ${nowIso},
496 last_error = ${error}
497 WHERE effect_id = ${effectId}
498 AND status = 'running'
499 AND lease_owner = ${workerId}
500 RETURNING effect_id
501 `;
502 if (rows.length === 1) cancellationSignals.delete(effectId);
503 return rows.length === 1;
504 }).pipe(
505 Effect.mapError(
506 (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
507 ),
508 ),
509 fail: ({ effectId, workerId, error }) =>
510 Effect.gen(function* () {
511 const now = DateTime.formatIso(yield* DateTime.now);
512 const rows = yield* sql<{ readonly effect_id: string }>`
513 UPDATE orchestration_v2_effect_outbox
514 SET
515 status = 'failed',
516 lease_owner = NULL,
517 lease_expires_at = NULL,
518 completed_at = ${now},
519 updated_at = ${now},
520 last_error = ${error}
521 WHERE effect_id = ${effectId}
522 AND status = 'running'
523 AND lease_owner = ${workerId}
524 RETURNING effect_id
525 `;
526 if (rows.length === 1) cancellationSignals.delete(effectId);
527 return rows.length === 1;
528 }).pipe(
529 Effect.mapError((cause) => new EffectOutboxError({ operation: "fail", effectId, cause })),
530 ),
531 };
532
533 return service;
534 }),
535);