Open History to see the last commit
1import {
2 CommandId,
3 type OrchestrationV2Run,
4 OrchestrationV2DomainEvent,
5 type OrchestrationV2ProviderThread,
6 type OrchestrationV2TurnItem,
7 OrchestrationV2StoredEvent,
8 ProviderThreadId,
9 RunAttemptId,
10 RunId,
11 RuntimeRequestId,
12 NodeId,
13 type ProjectId,
14 ThreadId,
15} from "@t3tools/contracts";
16import * as ProviderCommitBatch from "./ProviderCommitBatch.ts";
17import * as Context from "effect/Context";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as PubSub from "effect/PubSub";
23import * as Semaphore from "effect/Semaphore";
24import * as Schema from "effect/Schema";
25import * as Stream from "effect/Stream";
26import * as SqlClient from "effect/sql/SqlClient";
27import * as SqlError from "effect/sql/SqlError";
28
29import { replayAndBufferProjectedLiveEvents } from "./LiveStreamBudget.ts";
30import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts";
31import { projectStoredEventForWire } from "./WireProjection.ts";
32import { makeRunOutcomeRecorder, type RunOutcome } from "./RunMetrics.ts";
33
34import * as CommandReceiptStore from "./CommandReceiptStore.ts";
35import * as EffectOutbox from "./EffectOutbox.ts";
36import * as EventStore from "./EventStore.ts";
37import * as ProjectionStore from "./ProjectionStore.ts";
38import * as ProjectStore from "./ProjectStore.ts";
39import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";
40
41export class EventSinkWriteError extends Schema.TaggedError<EventSinkWriteError>()(
42 "EventSinkWriteError",
43 {
44 eventCount: Schema.Number,
45 commandId: Schema.optional(CommandId),
46 cause: Schema.optional(Schema.Defect()),
47 },
48) {
49 override get message(): string {
50 return `Failed to write ${this.eventCount} orchestration V2 event(s).`;
51 }
52}
53
54export class EventSinkStreamError extends Schema.TaggedError<EventSinkStreamError>()(
55 "EventSinkStreamError",
56 {
57 threadId: Schema.optional(ThreadId),
58 afterSequence: Schema.optional(Schema.Number),
59 cause: Schema.optional(Schema.Defect()),
60 },
61) {
62 override get message(): string {
63 return this.threadId === undefined
64 ? "Failed to stream orchestration V2 events."
65 : `Failed to stream orchestration V2 events for thread ${this.threadId}.`;
66 }
67}
68
69export const EventSinkV2Error = Schema.Union([EventSinkWriteError, EventSinkStreamError]);
70export type EventSinkV2Error = typeof EventSinkV2Error.Type;
71
72interface ProviderBatchPublication {
73 readonly publish: Array<Effect.Effect<void>>;
74 eventCount: number;
75}
76const CurrentProviderBatch = Context.Reference<ProviderBatchPublication | undefined>(
77 "t3/orchestration-v2/EventSink/CurrentProviderBatch",
78 { defaultValue: () => undefined },
79);
80
81export interface EventSinkV2Shape {
82 /** Items that are not provider snapshots, such as a consumer's own control items, never batch. */
83 readonly consumeProviderEvents: <A extends { readonly type: string }, E, R, E2, R2>(
84 source: Stream.Stream<A, E, R>,
85 process: (event: A) => Effect.Effect<void, E2, R2>,
86 after: Effect.Effect<boolean, E2, R2>,
87 canBatch: Effect.Effect<boolean, never, R2>,
88 ) => Effect.Effect<
89 void,
90 E | E2 | ProviderCommitBatch.CommitBatchError | Schema.SchemaError,
91 R | R2
92 >;
93
94 /** Normalize and persist an ordered group against one transaction; publish after its commit. */
95 readonly withProviderBatch: <A, E, R>(
96 effect: Effect.Effect<A, E, R>,
97 ) => Effect.Effect<A, E | EventSinkV2Error, R>;
98
99 readonly write: (input: {
100 /** Return no events if another thread owns this native session at commit time. */
101 readonly unlessNativeThreadOwned?: Pick<
102 OrchestrationV2ProviderThread,
103 "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
104 >;
105 readonly guardPendingUserInputCancellations?: boolean;
106 readonly commandId?: CommandId;
107 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
108 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
109 readonly writeWithEffects: (input: {
110 /**
111 * Rebuilds each run.updated from the stored row with only its delegatedCompletion replaced.
112 * The batch must not also change that run's lifecycle.
113 */
114 readonly updateDelegatedCompletionOnly?: boolean;
115 readonly unlessNativeThreadOwned?: Pick<
116 OrchestrationV2ProviderThread,
117 "driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
118 >;
119 readonly guardPendingUserInputCancellations?: boolean;
120 readonly commandId?: CommandId;
121 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
122 readonly effects: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
123 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
124 readonly writeIfRunCurrent: (input: {
125 readonly guardPendingUserInputCancellations?: boolean;
126 readonly commandId?: CommandId;
127 readonly threadId: ThreadId;
128 readonly runId: RunId;
129 readonly activeAttemptId: RunAttemptId;
130 readonly expectedStatus: OrchestrationV2Run["status"];
131 /** Also refuse while this run interrupt request is stored without its result. */
132 readonly unlessInterruptRequested?: {
133 readonly requestId: OrchestrationV2TurnItem["id"];
134 readonly resultId: OrchestrationV2TurnItem["id"];
135 };
136 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
137 readonly effects?: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
138 }) => Effect.Effect<
139 {
140 readonly committed: boolean;
141 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
142 },
143 EventSinkV2Error
144 >;
145 /** Commits only if the expected attempt and ordinal still own the provider thread, protecting newer attempts. */
146 readonly writeIfProviderThreadOwner: (input: {
147 readonly guardPendingUserInputCancellations?: boolean;
148 readonly commandId?: CommandId;
149 readonly providerThreadId: ProviderThreadId;
150 readonly runId: RunId;
151 readonly activeAttemptId: RunAttemptId;
152 readonly expectedLastRunOrdinal: number;
153 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
154 }) => Effect.Effect<
155 {
156 readonly committed: boolean;
157 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
158 },
159 EventSinkV2Error
160 >;
161 /** Commits only if the full provider row equals expected; some writers do not advance updatedAt. */
162 readonly writeIfProviderThreadUnchanged: (input: {
163 readonly expected: OrchestrationV2ProviderThread;
164 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
165 }) => Effect.Effect<
166 {
167 readonly committed: boolean;
168 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
169 },
170 EventSinkV2Error
171 >;
172 readonly commitCommand: (input: {
173 readonly commandId: CommandId;
174 readonly threadId: ThreadId;
175 readonly commandType: string;
176 readonly acceptedAt: DateTime.Utc;
177 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
178 readonly effects: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
179 readonly cancelUnsettledEffects?: {
180 readonly effectTypes: ReadonlyArray<EffectOutbox.OrchestrationEffectRequestV2["type"]>;
181 readonly reason: string;
182 };
183 /** Like writeWithEffects' updateDelegatedCompletionOnly, for this run's run.updated only. */
184 readonly updateDelegatedCompletionOnlyRunId?: RunId;
185 }) => Effect.Effect<
186 {
187 readonly receipt: CommandReceiptStore.CommandReceiptV2;
188 readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
189 readonly committed: boolean;
190 readonly cancelledEffectCount: number;
191 },
192 EventSinkV2Error
193 >;
194 readonly commitRejectedCommand: (input: {
195 readonly commandId: CommandId;
196 readonly threadId: ThreadId;
197 readonly commandType: string;
198 readonly rejectedAt: DateTime.Utc;
199 readonly error: string;
200 }) => Effect.Effect<CommandReceiptStore.CommandReceiptV2, EventSinkV2Error>;
201 readonly commitProjectCommand: (input: {
202 readonly commandId: CommandId;
203 readonly projectId: ProjectId;
204 readonly commandType: string;
205 readonly acceptedAt: DateTime.Utc;
206 readonly event: UnsequencedProjectEvent;
207 }) => Effect.Effect<
208 { readonly receipt: CommandReceiptStore.ProjectCommandReceiptV2; readonly committed: boolean },
209 EventSinkV2Error
210 >;
211 readonly commitRejectedProjectCommand: (input: {
212 readonly commandId: CommandId;
213 readonly projectId: ProjectId;
214 readonly commandType: string;
215 readonly rejectedAt: DateTime.Utc;
216 readonly error: string;
217 }) => Effect.Effect<CommandReceiptStore.ProjectCommandReceiptV2, EventSinkV2Error>;
218 readonly stream: (input?: {
219 readonly threadId?: ThreadId;
220 readonly afterSequence?: number;
221 readonly eventType?: OrchestrationV2DomainEvent["type"];
222 /** Bound RPC subscribers; internal workers must not drop their subscription under load. */
223 readonly bounded?: boolean;
224 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
225 readonly latestSequence: (input?: {
226 readonly threadId?: ThreadId;
227 }) => Effect.Effect<number, EventSinkV2Error>;
228 readonly readByCommandId: (input: {
229 readonly commandId: CommandId;
230 }) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
231}
232
233export class EventSinkV2 extends Context.Service<EventSinkV2, EventSinkV2Shape>()(
234 "t3/orchestration-v2/EventSink/EventSinkV2",
235) {}
236
237const layerBase: Layer.Layer<
238 EventSinkV2,
239 never,
240 | CommandReceiptStore.CommandReceiptStoreV2
241 | EffectOutbox.EffectOutboxV2
242 | EventStore.EventStoreV2
243 | ProjectionStore.ProjectionStoreV2
244 | ProjectStore.ProjectStoreV2
245 | SqlClient.SqlClient
246 | TurnItemPositionStore.TurnItemPositionStoreV2
247> = Layer.effect(
248 EventSinkV2,
249 Effect.gen(function* () {
250 const sql = yield* SqlClient.SqlClient;
251 const commandReceipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
252 const effectOutbox = yield* EffectOutbox.EffectOutboxV2;
253 const eventStore = yield* EventStore.EventStoreV2;
254 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
255 const projectStore = yield* ProjectStore.ProjectStoreV2;
256 const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
257 const liveEvents = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
258 const liveEventsByType = new Map<
259 OrchestrationV2DomainEvent["type"],
260 PubSub.PubSub<OrchestrationV2StoredEvent>
261 >();
262 const publishLiveEvents =
263 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
264 Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2StoredEvent>) {
265 yield* PubSub.publishAll(liveEvents, events);
266 for (const [type, pubsub] of liveEventsByType) {
267 yield* PubSub.publishAll(
268 pubsub,
269 events.filter((stored) => stored.event.type === type),
270 );
271 }
272 });
273 const runOutcomes = makeRunOutcomeRecorder((threadId) =>
274 // One payload row; unlike the shell, it still resolves a deleted child thread.
275 projectionStore
276 .getThread(threadId)
277 .pipe(Effect.map((thread) => thread.lineage.relationshipToParent === "subagent")),
278 );
279 // Recorded before publication, so an interrupted publish cannot lose a committed outcome.
280 const publishStoredEvents = (
281 events: ReadonlyArray<OrchestrationV2StoredEvent>,
282 outcomes: ReadonlyArray<RunOutcome>,
283 ) =>
284 runOutcomes
285 .record(outcomes)
286 .pipe(
287 Effect.andThen(eventStore.publishCommitted(events)),
288 Effect.andThen(publishLiveEvents(events)),
289 );
290
291 // Serialize commit and publish; reordered publication makes clients drop earlier sequences.
292 const publishLane = yield* Semaphore.make(1);
293 const commitThenPublishNow = <A, E, R>(
294 transaction: Effect.Effect<A, E, R>,
295 publish: (committed: A) => Effect.Effect<void>,
296 ) =>
297 Effect.uninterruptibleMask((restore) => {
298 let holdsLane = false;
299 const takeLane = publishLane.take(1).pipe(
300 Effect.andThen(
301 Effect.sync(() => {
302 holdsLane = true;
303 }),
304 ),
305 Effect.uninterruptible,
306 );
307 // Cancellation may roll back the transaction's work. Once it commits,
308 // every subscriber must hear about it before this writer can exit.
309 // Otherwise a failed child run can leave its parent's task running.
310 return sql
311 .withTransaction(Effect.tap(restore(transaction), () => takeLane))
312 .pipe(
313 Effect.tap(publish),
314 Effect.ensuring(
315 Effect.suspend(() => (holdsLane ? publishLane.release(1) : Effect.void)),
316 ),
317 );
318 });
319
320 // A user can answer after terminal normalization reads the pending request.
321 // Recheck inside the write transaction so stale cleanup cannot erase answers.
322 const guardUserInputCancellations =
323 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
324 Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2DomainEvent>) {
325 const staleRequests = new Set<RuntimeRequestId>();
326 const staleNodes = new Set<NodeId>();
327 for (const event of events) {
328 if (
329 event.type !== "runtime-request.updated" ||
330 event.payload.kind !== "user_input" ||
331 event.payload.status !== "cancelled"
332 )
333 continue;
334 const current = yield* projectionStore.getRuntimeRequest(
335 event.threadId,
336 event.payload.id,
337 );
338 if (
339 current?.status !== "pending" ||
340 current.kind !== "user_input" ||
341 current.providerTurnId !== event.payload.providerTurnId ||
342 current.responseCapability.type === "message"
343 ) {
344 staleRequests.add(event.payload.id);
345 staleNodes.add(event.payload.nodeId);
346 }
347 }
348 return events.filter((event) => {
349 switch (event.type) {
350 case "runtime-request.updated":
351 return event.payload.status !== "cancelled" || !staleRequests.has(event.payload.id);
352 case "node.updated":
353 return event.payload.status !== "cancelled" || !staleNodes.has(event.payload.id);
354 case "turn-item.updated":
355 return (
356 event.payload.type !== "user_input_request" ||
357 event.payload.status !== "cancelled" ||
358 !staleRequests.has(event.payload.requestId)
359 );
360 default:
361 return true;
362 }
363 });
364 });
365
366 const normalizeEvents = (events: ReadonlyArray<OrchestrationV2DomainEvent>) => {
367 const runOrdinals = new Map(
368 events.flatMap((event) =>
369 event.type === "run.created" || event.type === "run.updated"
370 ? [[event.payload.id, event.payload.ordinal] as const]
371 : [],
372 ),
373 );
374 return Effect.forEach(
375 events,
376 (event): Effect.Effect<OrchestrationV2DomainEvent, unknown> =>
377 event.type === "turn-item.updated"
378 ? turnItemPositions
379 .normalize(
380 event.payload,
381 event.payload.runId === null ? undefined : runOrdinals.get(event.payload.runId),
382 )
383 .pipe(Effect.map((payload) => ({ ...event, payload })))
384 : Effect.succeed(event),
385 { concurrency: 1 },
386 );
387 };
388
389 const applyStoredEvents =
390 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
391 Effect.fnUntraced(function* (storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>) {
392 yield* Effect.forEach(storedEvents, (stored) => projectionStore.apply(stored.event), {
393 concurrency: 1,
394 });
395 const sequence = storedEvents.at(-1)?.sequence;
396 if (sequence !== undefined) {
397 const now = DateTime.formatIso(yield* DateTime.now);
398 yield* sql`
399 INSERT INTO orchestration_v2_projection_metadata (
400 projection_name,
401 schema_version,
402 last_sequence,
403 updated_at
404 )
405 VALUES (
406 'thread-projections',
407 ${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
408 ${sequence},
409 ${now}
410 )
411 ON CONFLICT(projection_name)
412 DO UPDATE SET
413 schema_version = excluded.schema_version,
414 last_sequence = excluded.last_sequence,
415 updated_at = excluded.updated_at
416 `;
417 }
418 // Read lineage here, on the connection this transaction holds; see makeRunOutcomeRecorder.
419 return yield* runOutcomes.prepare(storedEvents);
420 });
421
422 // The enclosing write or commit span already traces this per-event projection merge.
423 const updateDelegatedCompletionOnly = Effect.fnUntraced(function* (
424 events: ReadonlyArray<OrchestrationV2DomainEvent>,
425 includesRun: (runId: RunId) => boolean,
426 ) {
427 return yield* Effect.forEach(events, (event) =>
428 Effect.gen(function* () {
429 if (event.type !== "run.updated" || !includesRun(event.payload.id)) return event;
430 const { runs } = yield* projectionStore.getThreadRecords(event.threadId, ["runs"], {
431 runIds: [event.payload.id],
432 });
433 const current = runs[0];
434 return current === undefined
435 ? event
436 : {
437 ...event,
438 payload: { ...current, delegatedCompletion: event.payload.delegatedCompletion },
439 };
440 }),
441 );
442 });
443
444 const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* (
445 input: Parameters<EventSinkV2Shape["writeWithEffects"]>[0],
446 ) {
447 yield* Effect.annotateCurrentSpan({
448 "orchestration_v2.command_id": input.commandId ?? null,
449 "orchestration_v2.event_count": input.events.length,
450 "orchestration_v2.thread_id": input.events[0]?.threadId ?? null,
451 });
452
453 const batch = yield* CurrentProviderBatch;
454 if (batch !== undefined) batch.eventCount += input.events.length;
455 const { committed } = yield* commitThenPublish(
456 Effect.gen(function* () {
457 // Check ownership in the same transaction that claims the native session.
458 const imported = input.unlessNativeThreadOwned;
459 if (imported?.nativeThreadRef != null) {
460 const owners = yield* sql`
461 SELECT provider_thread_id
462 FROM orchestration_v2_projection_provider_threads
463 WHERE driver = ${imported.driver}
464 AND provider_instance_id = ${imported.providerInstanceId}
465 AND thread_id IS NOT ${imported.appThreadId}
466 AND json_extract(payload_json, '$.nativeThreadRef.nativeId') = ${imported.nativeThreadRef.nativeId}
467 LIMIT 1
468 `;
469 if (owners.length > 0) return { committed: [], outcomes: [] };
470 }
471 // Checkpoint capture can finish after a cohort writer reads its parent run.
472 // Merge in this transaction so the event log and projection keep that completion.
473 const events = input.updateDelegatedCompletionOnly
474 ? yield* updateDelegatedCompletionOnly(input.events, () => true)
475 : input.events;
476 const normalized = yield* normalizeEvents(
477 input.guardPendingUserInputCancellations === true
478 ? yield* guardUserInputCancellations(events)
479 : events,
480 );
481 const committed = yield* eventStore.append({
482 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
483 events: normalized,
484 });
485 const outcomes = yield* applyStoredEvents(committed);
486 yield* effectOutbox.enqueue(input.effects);
487 return { committed, outcomes };
488 }).pipe(Effect.withTracerEnabled(false)),
489 ({ committed, outcomes }) =>
490 Effect.gen(function* () {
491 if (input.effects.length > 0) {
492 yield* effectOutbox.notifyAvailable(input.effects.length);
493 }
494 yield* publishStoredEvents(committed, outcomes);
495 }),
496 );
497 return committed;
498 });
499
500 const writeIfRunCurrentEffect = Effect.fn("orchestrationV2.EventSink.writeIfRunCurrent")(
501 function* (input: Parameters<EventSinkV2Shape["writeIfRunCurrent"]>[0]) {
502 yield* Effect.annotateCurrentSpan({
503 "orchestration_v2.command_id": input.commandId ?? null,
504 "orchestration_v2.event_count": input.events.length,
505 "orchestration_v2.run_id": input.runId,
506 "orchestration_v2.thread_id": input.threadId,
507 });
508
509 return yield* commitThenPublish(
510 Effect.gen(function* () {
511 const rows = yield* sql<{
512 readonly status: string;
513 readonly active_attempt_id: string | null;
514 }>`
515 SELECT
516 status,
517 json_extract(payload_json, '$.activeAttemptId') AS active_attempt_id
518 FROM orchestration_v2_projection_runs
519 WHERE run_id = ${input.runId}
520 AND thread_id = ${input.threadId}
521 LIMIT 1
522 `;
523 const current = rows[0];
524 if (
525 current === undefined ||
526 current.status !== input.expectedStatus ||
527 current.active_attempt_id !== input.activeAttemptId
528 ) {
529 return {
530 committed: false as const,
531 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
532 };
533 }
534 if (input.unlessInterruptRequested !== undefined) {
535 const { requestId, resultId } = input.unlessInterruptRequested;
536 const pending = yield* sql<{ readonly pending: number }>`
537 SELECT EXISTS (
538 SELECT 1 FROM orchestration_v2_projection_turn_items
539 WHERE thread_id = ${input.threadId} AND turn_item_id = ${requestId}
540 ) AND NOT EXISTS (
541 SELECT 1 FROM orchestration_v2_projection_turn_items
542 WHERE thread_id = ${input.threadId} AND turn_item_id = ${resultId}
543 ) AS pending
544 `;
545 if (pending[0]?.pending === 1) {
546 return {
547 committed: false as const,
548 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
549 };
550 }
551 }
552
553 const normalized = yield* normalizeEvents(
554 input.guardPendingUserInputCancellations === true
555 ? yield* guardUserInputCancellations(input.events)
556 : input.events,
557 );
558 const storedEvents = yield* eventStore.append({
559 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
560 events: normalized,
561 });
562 const outcomes = yield* applyStoredEvents(storedEvents);
563 yield* effectOutbox.enqueue(input.effects ?? []);
564 return { committed: true as const, storedEvents, outcomes };
565 }),
566 (result) =>
567 Effect.gen(function* () {
568 if (!result.committed) return;
569 if (input.effects !== undefined && input.effects.length > 0) {
570 yield* effectOutbox.notifyAvailable(input.effects.length);
571 }
572 yield* publishStoredEvents(result.storedEvents, result.outcomes);
573 }),
574 );
575 },
576 );
577
578 const writeIfProviderThreadOwnerEffect = Effect.fn(
579 "orchestrationV2.EventSink.writeIfProviderThreadOwner",
580 )(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadOwner"]>[0]) {
581 yield* Effect.annotateCurrentSpan({
582 "orchestration_v2.command_id": input.commandId ?? null,
583 "orchestration_v2.event_count": input.events.length,
584 "orchestration_v2.provider_thread_id": input.providerThreadId,
585 "orchestration_v2.run_id": input.runId,
586 "orchestration_v2.active_attempt_id": input.activeAttemptId,
587 "orchestration_v2.expected_last_run_ordinal": input.expectedLastRunOrdinal,
588 });
589
590 return yield* commitThenPublish(
591 Effect.gen(function* () {
592 const rows = yield* sql<{
593 readonly active_attempt_id: string | null;
594 readonly last_run_ordinal: number | null;
595 }>`
596 SELECT
597 json_extract(r.payload_json, '$.activeAttemptId') AS active_attempt_id,
598 p.last_run_ordinal
599 FROM orchestration_v2_projection_provider_threads p
600 JOIN orchestration_v2_projection_runs r
601 ON r.run_id = ${input.runId}
602 AND r.thread_id = p.thread_id
603 WHERE p.provider_thread_id = ${input.providerThreadId}
604 LIMIT 1
605 `;
606 const current = rows[0];
607 if (
608 current === undefined ||
609 current.active_attempt_id !== input.activeAttemptId ||
610 current.last_run_ordinal !== input.expectedLastRunOrdinal
611 ) {
612 return {
613 committed: false as const,
614 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
615 };
616 }
617
618 const normalized = yield* normalizeEvents(
619 input.guardPendingUserInputCancellations === true
620 ? yield* guardUserInputCancellations(input.events)
621 : input.events,
622 );
623 const storedEvents = yield* eventStore.append({
624 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
625 events: normalized,
626 });
627 const outcomes = yield* applyStoredEvents(storedEvents);
628 return { committed: true as const, storedEvents, outcomes };
629 }),
630 (result) =>
631 result.committed
632 ? publishStoredEvents(result.storedEvents, result.outcomes)
633 : Effect.void,
634 );
635 });
636
637 const writeIfProviderThreadUnchangedEffect = Effect.fn(
638 "orchestrationV2.EventSink.writeIfProviderThreadUnchanged",
639 )(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadUnchanged"]>[0]) {
640 yield* Effect.annotateCurrentSpan({
641 "orchestration_v2.event_count": input.events.length,
642 "orchestration_v2.provider_thread_id": input.expected.id,
643 });
644 const expectedJson = yield* ProjectionStore.encodeProviderThreadPayload(input.expected);
645
646 return yield* commitThenPublish(
647 Effect.gen(function* () {
648 const rows = yield* sql<{ readonly payload_json: string }>`
649 SELECT payload_json
650 FROM orchestration_v2_projection_provider_threads
651 WHERE provider_thread_id = ${input.expected.id}
652 LIMIT 1
653 `;
654 if (rows[0]?.payload_json !== expectedJson) {
655 return {
656 committed: false as const,
657 storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
658 };
659 }
660
661 const normalized = yield* normalizeEvents(input.events);
662 const storedEvents = yield* eventStore.append({ events: normalized });
663 const outcomes = yield* applyStoredEvents(storedEvents);
664 return { committed: true as const, storedEvents, outcomes };
665 }),
666 (result) =>
667 result.committed
668 ? publishStoredEvents(result.storedEvents, result.outcomes)
669 : Effect.void,
670 );
671 });
672
673 const existingCommandResult =
674 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
675 Effect.fnUntraced(function* (commandId: CommandId) {
676 const existing = yield* commandReceipts.getByCommandId(commandId);
677 if (Option.isNone(existing)) {
678 return yield* Effect.die(
679 new Error(`Command receipt ${commandId} disappeared during its transaction.`),
680 );
681 }
682 const storedEvents = yield* eventStore.readByCommandId({ commandId }).pipe(
683 Stream.runCollect,
684 Effect.map((events): ReadonlyArray<OrchestrationV2StoredEvent> => Array.from(events)),
685 );
686 return { receipt: existing.value, storedEvents };
687 });
688
689 const commitCommandEffect = Effect.fn("orchestrationV2.EventSink.commitCommand")(function* (
690 input: Parameters<EventSinkV2Shape["commitCommand"]>[0],
691 ) {
692 const result = yield* commitThenPublish(
693 Effect.gen(function* () {
694 const reserved = yield* commandReceipts.insertIfAbsent({
695 commandId: input.commandId,
696 threadId: input.threadId,
697 commandType: input.commandType,
698 acceptedAt: input.acceptedAt,
699 resultSequence: 0,
700 status: "accepted",
701 error: null,
702 });
703 if (!reserved) {
704 const existing = yield* existingCommandResult(input.commandId);
705 return { ...existing, committed: false as const, cancelledEffectIds: [] };
706 }
707
708 const runId = input.updateDelegatedCompletionOnlyRunId;
709 const normalized = yield* normalizeEvents(
710 runId === undefined
711 ? input.events
712 : yield* updateDelegatedCompletionOnly(input.events, (id) => id === runId),
713 );
714 const storedEvents = yield* eventStore.append({
715 commandId: input.commandId,
716 events: normalized,
717 });
718 // A Stop that changes nothing can still queue the stop of its delegated tasks.
719 const sequence =
720 storedEvents.at(-1)?.sequence ??
721 (input.effects.length === 0
722 ? undefined
723 : yield* eventStore.latestSequence({ threadId: input.threadId }));
724 if (sequence === undefined) {
725 return yield* Effect.die(
726 new Error(`Command ${input.commandId} produced no orchestration events.`),
727 );
728 }
729 const outcomes = yield* applyStoredEvents(storedEvents);
730 yield* effectOutbox.enqueue(input.effects);
731 const receipt: CommandReceiptStore.CommandReceiptV2 = {
732 commandId: input.commandId,
733 threadId: input.threadId,
734 commandType: input.commandType,
735 acceptedAt: input.acceptedAt,
736 resultSequence: sequence,
737 status: "accepted",
738 error: null,
739 };
740 yield* commandReceipts.upsert(receipt);
741 const cancelledEffectIds =
742 input.cancelUnsettledEffects === undefined
743 ? []
744 : yield* effectOutbox.cancelUnsettled({
745 threadId: input.threadId,
746 ...input.cancelUnsettledEffects,
747 });
748 return { receipt, storedEvents, outcomes, committed: true as const, cancelledEffectIds };
749 }),
750 (result) =>
751 Effect.gen(function* () {
752 yield* effectOutbox.signalCancellations(result.cancelledEffectIds);
753 if (result.committed && input.effects.length > 0) {
754 yield* effectOutbox.notifyAvailable(input.effects.length);
755 }
756 if (result.committed) yield* publishStoredEvents(result.storedEvents, result.outcomes);
757 }),
758 );
759 return {
760 receipt: result.receipt,
761 storedEvents: result.storedEvents,
762 committed: result.committed,
763 cancelledEffectCount: result.cancelledEffectIds.length,
764 };
765 });
766
767 const commitRejectedCommandEffect = Effect.fn(
768 "orchestrationV2.EventSink.commitRejectedCommand",
769 )(function* (input: Parameters<EventSinkV2Shape["commitRejectedCommand"]>[0]) {
770 return yield* sql.withTransaction(
771 Effect.gen(function* () {
772 const sequence = yield* eventStore.latestSequence({ threadId: input.threadId });
773 const receipt: CommandReceiptStore.CommandReceiptV2 = {
774 commandId: input.commandId,
775 threadId: input.threadId,
776 commandType: input.commandType,
777 acceptedAt: input.rejectedAt,
778 resultSequence: sequence,
779 status: "rejected",
780 error: input.error,
781 };
782 const inserted = yield* commandReceipts.insertIfAbsent(receipt);
783 if (inserted) {
784 return receipt;
785 }
786 const existing = yield* commandReceipts.getByCommandId(input.commandId);
787 return Option.getOrElse(existing, () => receipt);
788 }),
789 );
790 });
791
792 const existingProjectReceipt = (commandId: CommandId) =>
793 commandReceipts.getProjectByCommandId(commandId).pipe(
794 Effect.flatMap(
795 Option.match({
796 onNone: () =>
797 Effect.fail(`Command ${commandId} was already used by a thread command.` as const),
798 onSome: Effect.succeed,
799 }),
800 ),
801 );
802
803 const commitProjectCommandEffect = Effect.fn("orchestrationV2.EventSink.commitProjectCommand")(
804 function* (input: Parameters<EventSinkV2Shape["commitProjectCommand"]>[0]) {
805 const result = yield* commitThenPublish(
806 Effect.gen(function* () {
807 const reserved: CommandReceiptStore.ProjectCommandReceiptV2 = {
808 commandId: input.commandId,
809 projectId: input.projectId,
810 commandType: input.commandType,
811 acceptedAt: input.acceptedAt,
812 resultSequence: 0,
813 status: "accepted",
814 error: null,
815 };
816 if (!(yield* commandReceipts.insertIfAbsent(reserved))) {
817 return { receipt: yield* existingProjectReceipt(input.commandId), event: undefined };
818 }
819 const event = yield* eventStore.appendProjectEvent(input.event);
820 yield* projectStore.apply(event);
821 const receipt = { ...reserved, resultSequence: event.sequence };
822 yield* commandReceipts.upsert(receipt);
823 return { receipt, event };
824 }),
825 (result) =>
826 result.event === undefined ? Effect.void : eventStore.publishCommitted([result.event]),
827 );
828 return { receipt: result.receipt, committed: result.event !== undefined };
829 },
830 );
831
832 const commitRejectedProjectCommandEffect = Effect.fn(
833 "orchestrationV2.EventSink.commitRejectedProjectCommand",
834 )(function* (input: Parameters<EventSinkV2Shape["commitRejectedProjectCommand"]>[0]) {
835 return yield* sql.withTransaction(
836 Effect.gen(function* () {
837 const receipt: CommandReceiptStore.ProjectCommandReceiptV2 = {
838 commandId: input.commandId,
839 projectId: input.projectId,
840 commandType: input.commandType,
841 acceptedAt: input.rejectedAt,
842 resultSequence: yield* eventStore.latestApplicationSequence,
843 status: "rejected",
844 error: input.error,
845 };
846 return (yield* commandReceipts.insertIfAbsent(receipt))
847 ? receipt
848 : yield* existingProjectReceipt(input.commandId);
849 }),
850 );
851 });
852
853 const catchUp = (input: {
854 readonly afterSequence: number;
855 readonly throughSequence: number;
856 readonly threadId?: ThreadId;
857 readonly eventType?: OrchestrationV2DomainEvent["type"];
858 }): Stream.Stream<OrchestrationV2StoredEvent, unknown> => {
859 const pageSize = 256;
860 const loop = (afterSequence: number): Stream.Stream<OrchestrationV2StoredEvent, unknown> =>
861 Stream.unwrap(
862 eventStore
863 .read({
864 afterSequence,
865 throughSequence: input.throughSequence,
866 ...(input.threadId === undefined ? {} : { threadId: input.threadId }),
867 ...(input.eventType === undefined ? {} : { eventType: input.eventType }),
868 limit: pageSize,
869 })
870 .pipe(
871 Stream.runCollect,
872 Effect.map((chunk) => Array.from(chunk)),
873 Effect.map((events) => {
874 if (events.length === 0) {
875 return Stream.empty;
876 }
877 const current = Stream.fromIterable(events);
878 const last = events.at(-1)?.sequence ?? input.throughSequence;
879 return events.length < pageSize || last >= input.throughSequence
880 ? current
881 : Stream.concat(current, loop(last));
882 }),
883 ),
884 );
885 return loop(input.afterSequence);
886 };
887
888 const stream = (input?: Parameters<EventSinkV2Shape["stream"]>[0]) => {
889 const afterSequence = input?.afterSequence ?? 0;
890 const matches = (stored: OrchestrationV2StoredEvent) =>
891 (input?.threadId === undefined || stored.event.threadId === input.threadId) &&
892 (input?.eventType === undefined || stored.event.type === input.eventType);
893 const replay = (throughSequence: number) =>
894 catchUp({
895 afterSequence,
896 throughSequence,
897 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
898 ...(input?.eventType === undefined ? {} : { eventType: input.eventType }),
899 }).pipe(Stream.filter(matches));
900 return Stream.unwrap(
901 Effect.gen(function* () {
902 let pubsub = liveEvents;
903 if (input?.eventType !== undefined) {
904 const existing = liveEventsByType.get(input.eventType);
905 if (existing !== undefined) {
906 pubsub = existing;
907 } else {
908 const created = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
909 pubsub = liveEventsByType.get(input.eventType) ?? created;
910 liveEventsByType.set(input.eventType, pubsub);
911 }
912 }
913 if (input?.bounded === true) {
914 return replayAndBufferProjectedLiveEvents({
915 subscribe: PubSub.subscribe(pubsub),
916 latestSequence: eventStore.latestSequence(),
917 afterSequence,
918 filter: matches,
919 replay,
920 project: projectStoredEventForWire,
921 });
922 }
923 const subscription = yield* PubSub.subscribe(pubsub);
924 const highWater = yield* eventStore.latestSequence();
925 const live = Stream.fromSubscription(subscription).pipe(
926 Stream.filter((stored) => stored.sequence > Math.max(highWater, afterSequence)),
927 Stream.filter(matches),
928 );
929 return Stream.concat(replay(highWater), live);
930 }),
931 );
932 };
933
934 const commitThenPublish = <A, E, R>(
935 transaction: Effect.Effect<A, E, R>,
936 publish: (committed: A) => Effect.Effect<void>,
937 ) =>
938 Effect.flatMap(CurrentProviderBatch, (batch) =>
939 batch === undefined
940 ? Effect.flatMap(Effect.serviceOption(sql.transactionService), (existing) =>
941 Option.isSome(existing)
942 ? commitThenPublishNow(transaction, publish)
943 : coordinator.barrier(commitThenPublishNow(transaction, publish)),
944 )
945 : transaction.pipe(
946 Effect.tap((committed) =>
947 Effect.sync(() => {
948 batch.publish.push(publish(committed));
949 }),
950 ),
951 ),
952 );
953
954 const withProviderBatch: EventSinkV2Shape["withProviderBatch"] = Effect.fn(
955 "orchestrationV2.EventSink.providerBatch",
956 )(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
957 if ((yield* CurrentProviderBatch) !== undefined) return yield* effect;
958 const batch: ProviderBatchPublication = { publish: [], eventCount: 0 };
959 let started = false;
960 const result = yield* commitThenPublishNow(
961 Effect.sync(() => {
962 started = true;
963 }).pipe(Effect.andThen(Effect.provideService(effect, CurrentProviderBatch, batch))),
964 () => Effect.forEach(batch.publish, (publish) => publish, { discard: true }),
965 ).pipe(
966 // Normalization mutates run-local state, so only retry before its transaction body starts.
967 Effect.retry({
968 while: (cause) =>
969 !started && SqlError.isSqlError(cause) && cause.reason._tag === "LockTimeoutError",
970 times: 2,
971 }),
972 Effect.mapError((cause) =>
973 SqlError.isSqlError(cause)
974 ? new EventSinkWriteError({ eventCount: batch.eventCount, cause })
975 : cause,
976 ),
977 );
978 yield* Effect.annotateCurrentSpan({
979 "orchestration_v2.event_count": batch.eventCount,
980 "orchestration_v2.batch_writes": batch.publish.length,
981 });
982 return result;
983 });
984
985 const coordinator = yield* ProviderCommitBatch.make(
986 (work) =>
987 withProviderBatch(work).pipe(
988 Effect.mapError((cause) =>
989 ProviderCommitBatch.isCommitBatchError(cause)
990 ? cause
991 : new ProviderCommitBatch.CommitBatchError({ cause }),
992 ),
993 ),
994 yield* ProviderCommitBatch.enabled,
995 // Each snapshot owns a savepoint and its deferred publications within the shared commit.
996 Effect.fnUntraced(function* (
997 work: Effect.Effect<void, ProviderCommitBatch.CommitBatchError>,
998 ) {
999 const batch = yield* CurrentProviderBatch;
1000 const publicationCount = batch?.publish.length ?? 0;
1001 const eventCount = batch?.eventCount ?? 0;
1002 return yield* sql.withTransaction(work).pipe(
1003 Effect.onError(() =>
1004 Effect.sync(() => {
1005 if (batch !== undefined) {
1006 batch.publish.length = publicationCount;
1007 batch.eventCount = eventCount;
1008 }
1009 }),
1010 ),
1011 Effect.mapError((cause) =>
1012 ProviderCommitBatch.isCommitBatchError(cause)
1013 ? cause
1014 : new ProviderCommitBatch.CommitBatchError({ cause }),
1015 ),
1016 );
1017 }),
1018 );
1019
1020 return EventSinkV2.of({
1021 consumeProviderEvents: coordinator.consume,
1022 withProviderBatch,
1023 write: (input) =>
1024 writeEffect({ ...input, effects: [] }).pipe(
1025 Effect.mapError(
1026 (cause) =>
1027 new EventSinkWriteError({
1028 eventCount: input.events.length,
1029 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
1030 cause,
1031 }),
1032 ),
1033 ),
1034 writeWithEffects: (input) =>
1035 writeEffect(input).pipe(
1036 Effect.mapError(
1037 (cause) =>
1038 new EventSinkWriteError({
1039 eventCount: input.events.length,
1040 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
1041 cause,
1042 }),
1043 ),
1044 ),
1045 writeIfRunCurrent: (input) =>
1046 writeIfRunCurrentEffect(input).pipe(
1047 Effect.mapError(
1048 (cause) =>
1049 new EventSinkWriteError({
1050 eventCount: input.events.length,
1051 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
1052 cause,
1053 }),
1054 ),
1055 ),
1056 writeIfProviderThreadOwner: (input) =>
1057 writeIfProviderThreadOwnerEffect(input).pipe(
1058 Effect.mapError(
1059 (cause) =>
1060 new EventSinkWriteError({
1061 eventCount: input.events.length,
1062 ...(input.commandId === undefined ? {} : { commandId: input.commandId }),
1063 cause,
1064 }),
1065 ),
1066 ),
1067 writeIfProviderThreadUnchanged: (input) =>
1068 writeIfProviderThreadUnchangedEffect(input).pipe(
1069 Effect.mapError(
1070 (cause) => new EventSinkWriteError({ eventCount: input.events.length, cause }),
1071 ),
1072 ),
1073 commitCommand: (input) =>
1074 commitCommandEffect(input).pipe(
1075 Effect.mapError(
1076 (cause) =>
1077 new EventSinkWriteError({
1078 commandId: input.commandId,
1079 eventCount: input.events.length,
1080 cause,
1081 }),
1082 ),
1083 ),
1084 commitRejectedCommand: (input) =>
1085 commitRejectedCommandEffect(input).pipe(
1086 Effect.mapError(
1087 (cause) =>
1088 new EventSinkWriteError({
1089 commandId: input.commandId,
1090 eventCount: 0,
1091 cause,
1092 }),
1093 ),
1094 ),
1095 commitProjectCommand: (input) =>
1096 commitProjectCommandEffect(input).pipe(
1097 Effect.mapError(
1098 (cause) =>
1099 new EventSinkWriteError({ commandId: input.commandId, eventCount: 1, cause }),
1100 ),
1101 ),
1102 commitRejectedProjectCommand: (input) =>
1103 commitRejectedProjectCommandEffect(input).pipe(
1104 Effect.mapError(
1105 (cause) =>
1106 new EventSinkWriteError({ commandId: input.commandId, eventCount: 0, cause }),
1107 ),
1108 ),
1109 stream: (input) =>
1110 stream(input).pipe(
1111 Stream.mapError(
1112 (cause) =>
1113 new EventSinkStreamError({
1114 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
1115 ...(input?.afterSequence === undefined
1116 ? {}
1117 : { afterSequence: input.afterSequence }),
1118 cause,
1119 }),
1120 ),
1121 ),
1122 latestSequence: (input) =>
1123 eventStore.latestSequence(input).pipe(
1124 Effect.mapError(
1125 (cause) =>
1126 new EventSinkStreamError({
1127 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
1128 cause,
1129 }),
1130 ),
1131 ),
1132 readByCommandId: (input) =>
1133 eventStore.readByCommandId(input).pipe(
1134 Stream.mapError(
1135 (cause) =>
1136 new EventSinkStreamError({
1137 cause,
1138 }),
1139 ),
1140 ),
1141 } satisfies EventSinkV2Shape);
1142 }),
1143);
1144
1145/** Share the worker's outbox instance: enqueue wakeups are in-memory. */
1146export const layerFromStores = layerBase;
1147
1148export const layer: Layer.Layer<
1149 EventSinkV2,
1150 never,
1151 EventStore.EventStoreV2 | ProjectionStore.ProjectionStoreV2 | SqlClient.SqlClient
1152> = layerBase.pipe(
1153 Layer.provide(
1154 Layer.mergeAll(
1155 CommandReceiptStore.layer,
1156 EffectOutbox.layer,
1157 ProjectStore.layer,
1158 TurnItemPositionStore.layer,
1159 ),
1160 ),
1161);