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

EventSink.ts

1,137 lines44.4 KB

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