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

EventSink.ts

1,332 lines52.5 KB

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