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

EffectOutbox.ts

618 lines22.6 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 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;
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;
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 }
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>;
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 // Title generation is correlated metadata work, so it has its own
282 // per-thread lane and cannot delay provider lifecycle effects.
283 const claimableCandidatePredicate = (availableBefore?: string) =>
284 sql`
285 ${
286 availableBefore === undefined
287 ? sql`1 = 1`
288 : sql`candidate.available_at <= ${availableBefore}`
289 }
290 AND candidate.status = 'pending'
291 AND NOT EXISTS (
292 SELECT 1
293 FROM orchestration_v2_effect_outbox AS active
294 WHERE active.thread_id = candidate.thread_id
295 AND active.status = 'running'
296 AND (
297 (
298 candidate.effect_type = 'thread-title.generate'
299 AND active.effect_type = 'thread-title.generate'
300 )
301 OR
302 (
303 candidate.effect_type != 'thread-title.generate'
304 AND active.effect_type != 'thread-title.generate'
305 )
306 )
307 )
308 `;
309​
310 const cancellationSignal = (effectId: string) => {
311 const existing = cancellationSignals.get(effectId);
312 if (existing !== undefined) return existing;
313 const created = Deferred.makeUnsafe<void>();
314 cancellationSignals.set(effectId, created);
315 return created;
316 };
317​
318 const decodeRows = (operation: string, rows: ReadonlyArray<EffectRow>) =>
319 Effect.forEach(rows, rowToEffect).pipe(
320 Effect.mapError((cause) => new EffectOutboxError({ operation, cause })),
321 );
322​
323 const service: EffectOutboxV2Shape = {
324 enqueue: (effects) =>
325 Effect.gen(function* () {
326 const now = yield* DateTime.now;
327 const nowIso = DateTime.formatIso(now);
328 yield* Effect.forEach(
329 effects,
330 (effect) => sql`
331 INSERT INTO orchestration_v2_effect_outbox (
332 effect_id,
333 command_id,
334 thread_id,
335 effect_type,
336 payload_json,
337 status,
338 attempt_count,
339 available_at,
340 created_at,
341 updated_at
342 )
343 VALUES (
344 ${effect.id},
345 ${effect.commandId},
346 ${effect.threadId},
347 ${effect.request.type},
348 ${encodeRequest(effect.request)},
349 'pending',
350 0,
351 ${DateTime.formatIso(effect.availableAt ?? now)},
352 ${nowIso},
353 ${nowIso}
354 )
355 ON CONFLICT(effect_id) DO NOTHING
356 `,
357 { concurrency: 1, discard: true },
358 );
359 // Do not signal here: callers enqueue inside a larger transaction,
360 // and workers must only observe availability after that transaction
361 // commits. EventSink owns the corresponding post-commit notification.
362 }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "enqueue", cause }))),
363 get: (effectId) =>
364 sql<EffectRow>`
365 SELECT *
366 FROM orchestration_v2_effect_outbox
367 WHERE effect_id = ${effectId}
368 LIMIT 1
369 `.pipe(
370 Effect.flatMap((rows) => {
371 const row = rows[0];
372 return row === undefined
373 ? Effect.succeed(Option.none())
374 : rowToEffect(row).pipe(Effect.map(Option.some));
375 }),
376 Effect.mapError((cause) => new EffectOutboxError({ operation: "get", effectId, cause })),
377 ),
378 awaitAvailable: Queue.take(available),
379 notifyAvailable,
380 listByCommandId: (commandId) =>
381 sql<EffectRow>`
382 SELECT *
383 FROM orchestration_v2_effect_outbox
384 WHERE command_id = ${commandId}
385 ORDER BY created_at ASC, effect_id ASC
386 `.pipe(
387 Effect.flatMap((rows) => decodeRows("list", rows)),
388 Effect.mapError((cause) =>
389 isEffectOutboxError(cause)
390 ? cause
391 : new EffectOutboxError({ operation: "list", cause }),
392 ),
393 ),
394 cancelUnsettled: ({ threadId, effectTypes, reason }) =>
395 Effect.gen(function* () {
396 if (effectTypes.length === 0) return [];
397 const now = DateTime.formatIso(yield* DateTime.now);
398 const rows = yield* sql<{ readonly effect_id: string }>`
399 UPDATE orchestration_v2_effect_outbox
400 SET
401 status = 'cancelled',
402 lease_owner = NULL,
403 lease_expires_at = NULL,
404 completed_at = ${now},
405 updated_at = ${now},
406 last_error = ${reason}
407 WHERE thread_id = ${threadId}
408 AND status IN ('pending', 'running')
409 AND effect_type IN ${sql.in(effectTypes)}
410 RETURNING effect_id
411 `;
412 return rows.map(({ effect_id }) => effect_id);
413 }).pipe(
414 Effect.mapError(
415 (cause) => new EffectOutboxError({ operation: "cancel-unsettled", cause }),
416 ),
417 ),
418 signalCancellations: (effectIds) =>
419 Effect.gen(function* () {
420 yield* Effect.forEach(
421 effectIds,
422 (effectId) => {
423 const signal = cancellationSignals.get(effectId);
424 return signal === undefined ? Effect.void : Deferred.succeed(signal, undefined);
425 },
426 { discard: true },
427 );
428 // Cancellation can unblock other pending work on the same thread.
429 // This method is deliberately post-commit, so it is also the safe
430 // place to wake claimers after the durable status change.
431 if (effectIds.length > 0) yield* notifyAvailable(effectIds.length);
432 }),
433 awaitCancellation: (effectId) => Deferred.await(cancellationSignal(effectId)),
434 clearCancellation: (effectId) =>
435 Effect.sync(() => {
436 cancellationSignals.delete(effectId);
437 }),
438 reconcileAfterProcessLoss: Effect.gen(function* () {
439 const now = DateTime.formatIso(yield* DateTime.now);
440 const cancelledRows = yield* sql<{ readonly effect_id: string }>`
441 UPDATE orchestration_v2_effect_outbox
442 SET
443 status = 'cancelled',
444 lease_owner = NULL,
445 lease_expires_at = NULL,
446 completed_at = ${now},
447 updated_at = ${now},
448 last_error = 'Cancelled because the server process ended before the effect completed.'
449 WHERE status IN ('pending', 'running')
450 AND effect_type IN ${sql.in(PROCESS_BOUND_EFFECT_TYPES)}
451 RETURNING effect_id
452 `;
453 const requeuedRows = yield* sql<{ readonly effect_id: string }>`
454 UPDATE orchestration_v2_effect_outbox
455 SET
456 status = 'pending',
457 lease_owner = NULL,
458 lease_expires_at = NULL,
459 available_at = ${now},
460 updated_at = ${now},
461 last_error = 'Requeued after the previous server process ended.'
462 WHERE status = 'running'
463 AND effect_type IN ${sql.in(REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS)}
464 RETURNING effect_id
465 `;
466 if (requeuedRows.length > 0) yield* notifyAvailable(requeuedRows.length);
467 return { requeued: requeuedRows.length, cancelled: cancelledRows.length };
468 }).pipe(
469 Effect.mapError(
470 (cause) => new EffectOutboxError({ operation: "reconcile-process-loss", cause }),
471 ),
472 ),
473 claimNext: ({ workerId, leaseDurationMs, excludeRestartContinuations = false }) =>
474 Effect.gen(function* () {
475 const now = yield* DateTime.now;
476 const nowIso = DateTime.formatIso(now);
477 const leaseExpiresAt = DateTime.formatIso(
478 DateTime.add(now, { milliseconds: Math.max(1, leaseDurationMs) }),
479 );
480 // Empty safety claims are expected while the daemon is idle. Tracing
481 // this query records the full SQL text on every poll and can dominate
482 // the local trace without adding actionable information.
483 const claimStatement = sql<EffectRow>`
484 UPDATE orchestration_v2_effect_outbox
485 SET
486 status = 'running',
487 attempt_count = attempt_count + 1,
488 lease_owner = ${workerId},
489 lease_expires_at = ${leaseExpiresAt},
490 updated_at = ${nowIso},
491 last_error = NULL
492 WHERE effect_id = (
493 SELECT candidate.effect_id
494 FROM orchestration_v2_effect_outbox AS candidate
495 WHERE ${claimableCandidatePredicate(nowIso)}
496 AND ${excludeRestartContinuations ? sql`candidate.effect_type != 'provider-runtime.continue'` : sql`1 = 1`}
497 ORDER BY candidate.available_at ASC, candidate.created_at ASC, candidate.effect_id ASC
498 LIMIT 1
499 )
500 RETURNING *
501 `;
502 const rows = yield* claimStatement.pipe(Effect.withTracerEnabled(false));
503 const row = rows[0];
504 if (row === undefined) return Option.none();
505 cancellationSignals.set(row.effect_id, Deferred.makeUnsafe<void>());
506 return Option.some(yield* rowToEffect(row));
507 }).pipe(Effect.mapError((cause) => new EffectOutboxError({ operation: "claim", cause }))),
508 nextClaimableAt: Effect.gen(function* () {
509 const rows = yield* sql<{ readonly available_at: string | null }>`
510 SELECT MIN(candidate.available_at) AS available_at
511 FROM orchestration_v2_effect_outbox AS candidate
512 WHERE ${claimableCandidatePredicate()}
513 `.pipe(Effect.withTracerEnabled(false));
514 const availableAt = rows[0]?.available_at;
515 if (availableAt === undefined || availableAt === null) return Option.none();
516 const parsed = DateTime.make(availableAt);
517 if (Option.isNone(parsed)) {
518 return yield* new EffectOutboxError({
519 operation: "next-claimable",
520 cause: `Invalid available_at timestamp: ${availableAt}`,
521 });
522 }
523 return parsed;
524 }).pipe(
525 Effect.mapError((cause) =>
526 isEffectOutboxError(cause)
527 ? cause
528 : new EffectOutboxError({ operation: "next-claimable", cause }),
529 ),
530 ),
531 succeed: ({ effectId, workerId }) =>
532 Effect.gen(function* () {
533 const now = DateTime.formatIso(yield* DateTime.now);
534 const rows = yield* sql<{ readonly effect_id: string }>`
535 UPDATE orchestration_v2_effect_outbox
536 SET
537 status = 'succeeded',
538 lease_owner = NULL,
539 lease_expires_at = NULL,
540 completed_at = ${now},
541 updated_at = ${now},
542 last_error = NULL
543 WHERE effect_id = ${effectId}
544 AND status = 'running'
545 AND lease_owner = ${workerId}
546 RETURNING effect_id
547 `;
548 if (rows.length === 1) {
549 cancellationSignals.delete(effectId);
550 yield* notifyAvailable();
551 }
552 return rows.length === 1;
553 }).pipe(
554 Effect.mapError(
555 (cause) => new EffectOutboxError({ operation: "succeed", effectId, cause }),
556 ),
557 ),
558 retry: ({ effectId, workerId, error, delayMs }) =>
559 Effect.gen(function* () {
560 const now = yield* DateTime.now;
561 const nowIso = DateTime.formatIso(now);
562 const availableAt = DateTime.formatIso(
563 DateTime.add(now, { milliseconds: Math.max(0, delayMs) }),
564 );
565 const rows = yield* sql<{ readonly effect_id: string }>`
566 UPDATE orchestration_v2_effect_outbox
567 SET
568 status = 'pending',
569 available_at = ${availableAt},
570 lease_owner = NULL,
571 lease_expires_at = NULL,
572 updated_at = ${nowIso},
573 last_error = ${error}
574 WHERE effect_id = ${effectId}
575 AND status = 'running'
576 AND lease_owner = ${workerId}
577 RETURNING effect_id
578 `;
579 if (rows.length === 1) {
580 cancellationSignals.delete(effectId);
581 yield* notifyAvailable();
582 }
583 return rows.length === 1;
584 }).pipe(
585 Effect.mapError(
586 (cause) => new EffectOutboxError({ operation: "retry", effectId, cause }),
587 ),
588 ),
589 fail: ({ effectId, workerId, error }) =>
590 Effect.gen(function* () {
591 const now = DateTime.formatIso(yield* DateTime.now);
592 const rows = yield* sql<{ readonly effect_id: string }>`
593 UPDATE orchestration_v2_effect_outbox
594 SET
595 status = 'failed',
596 lease_owner = NULL,
597 lease_expires_at = NULL,
598 completed_at = ${now},
599 updated_at = ${now},
600 last_error = ${error}
601 WHERE effect_id = ${effectId}
602 AND status = 'running'
603 AND lease_owner = ${workerId}
604 RETURNING effect_id
605 `;
606 if (rows.length === 1) {
607 cancellationSignals.delete(effectId);
608 yield* notifyAvailable();
609 }
610 return rows.length === 1;
611 }).pipe(
612 Effect.mapError((cause) => new EffectOutboxError({ operation: "fail", effectId, cause })),
613 ),
614 };
615​
616 return service;
617 }),
618);