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

EffectOutbox.ts

617 lines22.5 KB

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