Open History to see the last commit
1/**
2 * Historical name for the shared application event store.
3 *
4 * Owns durable append/replay access for project events and V2 agent-thread
5 * events under one global sequence. It does not reduce events into read models
6 * or apply command validation rules.
7 *
8 * Uses Effect `Context.Service` for dependency injection and exposes typed
9 * persistence/decode errors for event append and replay operations.
10 *
11 * @module OrchestrationEventStore
12 */
13import {
14 ApplicationEventMetadata,
15 ApplicationProjectEvent,
16 type ApplicationStoredEvent,
17 CommandId,
18 EventId,
19 IsoDateTime,
20 isKnownOrchestrationV2EventType,
21 NonNegativeInt,
22 OrchestrationV2DomainEventJson,
23 OrchestrationV2StoredEvent,
24 ProjectId,
25 StoredProjectIcon,
26 ThreadId,
27 type OrchestrationV2DomainEvent,
28} from "@t3tools/contracts";
29import * as Context from "effect/Context";
30import * as SqlClient from "effect/sql/SqlClient";
31import * as SqlSchema from "effect/sql/SqlSchema";
32import * as Effect from "effect/Effect";
33import * as Layer from "effect/Layer";
34import * as PubSub from "effect/PubSub";
35import * as Option from "effect/Option";
36import * as Schema from "effect/Schema";
37import * as Stream from "effect/Stream";
38
39import { replayAndBufferProjectedLiveEvents } from "../orchestration-v2/LiveStreamBudget.ts";
40
41import {
42 toPersistenceDecodeError,
43 toPersistenceSqlError,
44 type OrchestrationEventStoreError,
45} from "./Errors.ts";
46
47/** A project event before the store assigns its sequence. */
48export type UnsequencedProjectEvent = ApplicationProjectEvent extends infer Event
49 ? Event extends ApplicationProjectEvent
50 ? Omit<Event, "sequence">
51 : never
52 : never;
53
54/** OrchestrationEventStore - Service tag for the shared application event log. */
55export class OrchestrationEventStore extends Context.Service<
56 OrchestrationEventStore,
57 {
58 /** Append one project event to the shared application log. */
59 readonly appendProjectEvent: (
60 event: UnsequencedProjectEvent,
61 ) => Effect.Effect<ApplicationProjectEvent, OrchestrationEventStoreError>;
62
63 /** Append V2 agent events to the same globally ordered application log. */
64 readonly appendAgentEvents: (input: {
65 readonly commandId?: CommandId;
66 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
67 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, OrchestrationEventStoreError>;
68
69 /**
70 * Read only V2 thread events from the application log.
71 *
72 * Reads in fixed-size sequence pages until the filtered range is exhausted;
73 * `limit` caps raw rows across pages, including skipped unknown types.
74 *
75 * A row whose `event_type` this build does not know fails the read unless
76 * `skipUnknownEventTypes` is set, which logs and drops it instead. Only
77 * client thread replay opts in; anything that builds server state stays strict.
78 */
79 readonly readAgentEvents: (input?: {
80 readonly afterSequence?: number;
81 readonly throughSequence?: number;
82 readonly threadId?: ThreadId;
83 readonly commandId?: CommandId;
84 readonly eventType?: OrchestrationV2DomainEvent["type"];
85 readonly limit?: number;
86 readonly skipUnknownEventTypes?: boolean;
87 }) => Stream.Stream<OrchestrationV2StoredEvent, OrchestrationEventStoreError>;
88
89 /** Measure one thread's bounded replay without loading or decoding its payloads. */
90 readonly getAgentReplayStats: (input: {
91 readonly threadId: ThreadId;
92 readonly afterSequence: number;
93 readonly throughSequence: number;
94 readonly maxEvents: number;
95 }) => Effect.Effect<
96 {
97 readonly eventCount: number;
98 /** UTF-8 bytes in persisted payload JSON before decoding or wire projection. */
99 readonly rawPayloadBytes: number;
100 readonly hasCreateEvent: boolean;
101 },
102 OrchestrationEventStoreError
103 >;
104
105 /**
106 * Measure the retained application-event range `(afterSequence, throughSequence]`
107 * without loading or decoding its payloads.
108 */
109 readonly getReplayStats: (input: {
110 readonly afterSequence: number;
111 readonly throughSequence: number;
112 }) => Effect.Effect<
113 {
114 readonly eventCount: number;
115 /** UTF-8 bytes in persisted payload JSON before decoding or wire projection. */
116 readonly rawPayloadBytes: number;
117 },
118 OrchestrationEventStoreError
119 >;
120
121 readonly latestAgentSequence: (
122 threadId?: ThreadId,
123 ) => Effect.Effect<number, OrchestrationEventStoreError>;
124
125 readonly latestApplicationSequence: Effect.Effect<number, OrchestrationEventStoreError>;
126
127 /**
128 * Read the finite retained application-event range `(afterSequence, throughSequence]`.
129 *
130 * A row whose `event_type` this build does not know fails the read unless
131 * `skipUnknownEventTypes` is set, which logs and drops it instead. Only
132 * client shell replay opts in; anything that builds server state stays strict.
133 */
134 readonly readApplicationEvents: (input: {
135 readonly afterSequence: number;
136 readonly throughSequence: number;
137 readonly skipUnknownEventTypes?: boolean;
138 }) => Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError>;
139
140 /** Publish only after the surrounding event/projection transaction commits. */
141 readonly publishCommitted: (
142 events: ReadonlyArray<ApplicationStoredEvent>,
143 ) => Effect.Effect<void>;
144
145 /** Race-free replay-to-live stream for project and V2 thread events. */
146 readonly streamApplicationEvents: (input?: {
147 readonly afterSequence?: number;
148 }) => Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError>;
149 /** Project transport events before bounding replay and the live tail. */
150 readonly streamProjectedApplicationEvents: <A extends { readonly sequence: number }>(input: {
151 readonly afterSequence?: number;
152 readonly project: (event: ApplicationStoredEvent) => A;
153 }) => Stream.Stream<A, OrchestrationEventStoreError>;
154 }
155>()("t3/persistence/OrchestrationEventStore") {}
156
157const encodeProjectIcon = Schema.encodeSync(StoredProjectIcon);
158const decodeProjectEvent = Schema.decodeUnknownEffect(ApplicationProjectEvent);
159const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);
160const EventMetadataFromJsonString = Schema.fromJsonString(ApplicationEventMetadata);
161const ProjectEventType = Schema.Literals([
162 "project.created",
163 "project.meta-updated",
164 "project.deleted",
165]);
166const ActorKind = Schema.Literals(["client", "server", "provider"]);
167
168const AppendProjectEventRequestSchema = Schema.Struct({
169 eventId: EventId,
170 streamId: ProjectId,
171 type: ProjectEventType,
172 causationEventId: Schema.NullOr(EventId),
173 correlationId: Schema.NullOr(CommandId),
174 actorKind: ActorKind,
175 occurredAt: IsoDateTime,
176 commandId: Schema.NullOr(CommandId),
177 payloadJson: UnknownFromJsonString,
178 metadataJson: EventMetadataFromJsonString,
179});
180
181const ProjectEventPersistedRowSchema = Schema.Struct({
182 sequence: NonNegativeInt,
183 eventId: EventId,
184 type: ProjectEventType,
185 aggregateKind: Schema.Literal("project"),
186 aggregateId: ProjectId,
187 occurredAt: IsoDateTime,
188 commandId: Schema.NullOr(CommandId),
189 causationEventId: Schema.NullOr(EventId),
190 correlationId: Schema.NullOr(CommandId),
191 payload: UnknownFromJsonString,
192 metadata: EventMetadataFromJsonString,
193});
194
195const READ_PAGE_SIZE = 500;
196
197interface ApplicationEventRow {
198 readonly sequence: number;
199 readonly event_id: string;
200 readonly command_id: string | null;
201 readonly aggregate_kind: "project" | "thread";
202 readonly stream_id: string;
203 readonly event_type: string;
204 readonly occurred_at: string;
205 readonly payload_json: string;
206 readonly metadata_json: string;
207 readonly application_event_version: number;
208 readonly causation_event_id: string | null;
209 readonly correlation_id: string | null;
210}
211
212const decodeV2EventJson = Schema.decodeUnknownEffect(OrchestrationV2DomainEventJson);
213const encodeV2EventJson = Schema.encodeEffect(OrchestrationV2DomainEventJson);
214const decodeV2StoredEvent = Schema.decodeUnknownEffect(OrchestrationV2StoredEvent);
215const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
216const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
217
218function metadataForV2Event(event: OrchestrationV2DomainEvent): Record<string, unknown> {
219 return {
220 ...(event.runId === undefined ? {} : { runId: event.runId }),
221 ...(event.nodeId === undefined ? {} : { nodeId: event.nodeId }),
222 ...(event.driver === undefined ? {} : { driver: event.driver }),
223 ...(event.providerInstanceId === undefined
224 ? {}
225 : { providerInstanceId: event.providerInstanceId }),
226 ...(event.rawEventId === undefined ? {} : { rawEventId: event.rawEventId }),
227 };
228}
229
230const rowToV2StoredEvent = Effect.fn("OrchestrationEventStore.rowToV2StoredEvent")(function* (
231 row: ApplicationEventRow,
232) {
233 const payload = yield* decodeJson(row.payload_json);
234 const metadata = yield* decodeJson(row.metadata_json);
235 const values =
236 typeof metadata === "object" && metadata !== null ? (metadata as Record<string, unknown>) : {};
237 const event = yield* decodeV2EventJson({
238 id: row.event_id,
239 threadId: row.stream_id,
240 type: row.event_type,
241 occurredAt: row.occurred_at,
242 payload,
243 ...(values.runId === undefined ? {} : { runId: values.runId }),
244 ...(values.nodeId === undefined ? {} : { nodeId: values.nodeId }),
245 ...(values.driver === undefined ? {} : { driver: values.driver }),
246 ...(values.providerInstanceId === undefined
247 ? {}
248 : { providerInstanceId: values.providerInstanceId }),
249 ...(values.rawEventId === undefined ? {} : { rawEventId: values.rawEventId }),
250 });
251 return yield* decodeV2StoredEvent({
252 sequence: row.sequence,
253 commandId: row.command_id,
254 event,
255 });
256});
257
258const rowToProjectEvent = Effect.fn("OrchestrationEventStore.rowToProjectEvent")(function* (
259 row: ApplicationEventRow,
260) {
261 return yield* decodeProjectEvent({
262 sequence: row.sequence,
263 eventId: row.event_id,
264 type: row.event_type,
265 aggregateKind: row.aggregate_kind,
266 aggregateId: row.stream_id,
267 occurredAt: row.occurred_at,
268 commandId: row.command_id,
269 causationEventId: row.causation_event_id,
270 correlationId: row.correlation_id,
271 payload: yield* decodeJson(row.payload_json),
272 metadata: yield* decodeJson(row.metadata_json),
273 });
274});
275
276function rowToApplicationStoredEvent(
277 row: ApplicationEventRow,
278): Effect.Effect<ApplicationStoredEvent, Schema.SchemaError> {
279 return row.aggregate_kind === "project" ? rowToProjectEvent(row) : rowToV2StoredEvent(row);
280}
281
282const isKnownProjectEventType = Schema.is(ProjectEventType);
283
284/** Filter only unknown discriminants; known types still undergo strict payload decoding. */
285const keepReplayRow = (row: ApplicationEventRow, skipUnknownEventTypes?: boolean) =>
286 skipUnknownEventTypes !== true ||
287 (row.aggregate_kind === "project"
288 ? isKnownProjectEventType(row.event_type)
289 : isKnownOrchestrationV2EventType(row.event_type))
290 ? Effect.succeed(true)
291 : Effect.logWarning("Skipping an application event row with an unknown event type", {
292 aggregateKind: row.aggregate_kind,
293 sequence: row.sequence,
294 eventTypeLength: row.event_type.length,
295 }).pipe(Effect.as(false));
296
297function inferActorKind(event: UnsequencedProjectEvent): typeof ActorKind.Type {
298 if (event.commandId !== null && event.commandId.startsWith("provider:")) {
299 return "provider";
300 }
301 if (event.commandId !== null && event.commandId.startsWith("server:")) {
302 return "server";
303 }
304 if (
305 event.metadata.providerTurnId !== undefined ||
306 event.metadata.providerItemId !== undefined ||
307 event.metadata.adapterKey !== undefined
308 ) {
309 return "provider";
310 }
311 if (event.commandId === null) {
312 return "server";
313 }
314 return "client";
315}
316
317function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
318 return (cause: unknown): OrchestrationEventStoreError =>
319 Schema.isSchemaError(cause)
320 ? toPersistenceDecodeError(decodeOperation)(cause)
321 : toPersistenceSqlError(sqlOperation)(cause);
322}
323
324const makeEventStore = Effect.gen(function* () {
325 const sql = yield* SqlClient.SqlClient;
326 const committedEvents = yield* PubSub.unbounded<ApplicationStoredEvent>();
327 // Sequence of the latest row storing each subagent's full prompt. The INSERT re-checks it.
328 const promptHints = new Map<string, number>();
329 // Puts back a subagent prompt that appendAgentEvents stored once, behind `promptSequence`.
330 const restoredPayloadJson = sql`CASE
331 WHEN orchestration_events.event_type IN ('subagent.updated', 'turn-item.updated')
332 AND json_type(orchestration_events.payload_json, '$.promptSequence') = 'integer'
333 THEN json_set(
334 json_remove(orchestration_events.payload_json, '$.promptSequence'),
335 '$.prompt',
336 (SELECT json_extract(anchor.payload_json, '$.prompt')
337 FROM orchestration_events AS anchor
338 WHERE anchor.sequence = json_extract(orchestration_events.payload_json, '$.promptSequence'))
339 )
340 ELSE orchestration_events.payload_json
341 END`;
342
343 const appendProjectEventRow = SqlSchema.findOne({
344 Request: AppendProjectEventRequestSchema,
345 Result: ProjectEventPersistedRowSchema,
346 execute: (request) =>
347 sql`
348 INSERT INTO orchestration_events (
349 event_id,
350 aggregate_kind,
351 stream_id,
352 stream_version,
353 event_type,
354 occurred_at,
355 command_id,
356 causation_event_id,
357 correlation_id,
358 actor_kind,
359 payload_json,
360 metadata_json,
361 application_event_version
362 )
363 VALUES (
364 ${request.eventId},
365 'project',
366 ${request.streamId},
367 COALESCE(
368 (
369 SELECT stream_version + 1
370 FROM orchestration_events
371 WHERE aggregate_kind = 'project'
372 AND stream_id = ${request.streamId}
373 ORDER BY stream_version DESC
374 LIMIT 1
375 ),
376 0
377 ),
378 ${request.type},
379 ${request.occurredAt},
380 ${request.commandId},
381 ${request.causationEventId},
382 ${request.correlationId},
383 ${request.actorKind},
384 ${request.payloadJson},
385 ${request.metadataJson},
386 2
387 )
388 RETURNING
389 sequence,
390 event_id AS "eventId",
391 event_type AS "type",
392 aggregate_kind AS "aggregateKind",
393 stream_id AS "aggregateId",
394 occurred_at AS "occurredAt",
395 command_id AS "commandId",
396 causation_event_id AS "causationEventId",
397 correlation_id AS "correlationId",
398 payload_json AS "payload",
399 metadata_json AS "metadata"
400 `,
401 });
402
403 const appendProjectEvent: OrchestrationEventStore["Service"]["appendProjectEvent"] = (event) =>
404 appendProjectEventRow({
405 eventId: event.eventId,
406 streamId: event.aggregateId,
407 type: event.type,
408 causationEventId: event.causationEventId,
409 correlationId: event.correlationId,
410 actorKind: inferActorKind(event),
411 occurredAt: event.occurredAt,
412 commandId: event.commandId,
413 payloadJson:
414 event.type === "project.deleted" || !event.payload.projectIcon
415 ? event.payload
416 : { ...event.payload, projectIcon: encodeProjectIcon(event.payload.projectIcon) },
417 metadataJson: event.metadata,
418 }).pipe(
419 Effect.flatMap((row) => decodeProjectEvent(row)),
420 Effect.mapError(
421 toPersistenceSqlOrDecodeError(
422 "OrchestrationEventStore.appendProjectEvent:insert",
423 "OrchestrationEventStore.appendProjectEvent:decode",
424 ),
425 ),
426 );
427
428 const readApplicationRows = (input: {
429 readonly afterSequence: number;
430 readonly throughSequence?: number;
431 readonly threadId?: ThreadId;
432 readonly commandId?: CommandId;
433 readonly eventType?: OrchestrationV2DomainEvent["type"];
434 readonly onlyAgentEvents?: boolean;
435 readonly limit: number;
436 }) =>
437 sql<ApplicationEventRow>`
438 SELECT
439 sequence,
440 event_id,
441 command_id,
442 aggregate_kind,
443 stream_id,
444 event_type,
445 occurred_at,
446 ${restoredPayloadJson} AS payload_json,
447 metadata_json,
448 application_event_version,
449 causation_event_id,
450 correlation_id
451 FROM orchestration_events
452 ${
453 // The sequence range otherwise wins and a command lookup scans every
454 // V2 event, which blocks the server for seconds on large histories.
455 input.commandId !== undefined
456 ? sql`INDEXED BY idx_orch_events_command_id`
457 : input.onlyAgentEvents === true
458 ? sql``
459 : sql`INDEXED BY idx_orchestration_events_application_high_water`
460 }
461 WHERE sequence > ${input.afterSequence}
462 AND sequence <= ${input.throughSequence ?? Number.MAX_SAFE_INTEGER}
463 AND (
464 ${
465 input.onlyAgentEvents === true
466 ? sql`application_event_version = 2 AND aggregate_kind = 'thread'`
467 : sql`aggregate_kind = 'project'
468 OR (application_event_version = 2 AND aggregate_kind = 'thread')`
469 }
470 )
471 AND ${sql.and([
472 ...(input.threadId === undefined ? [] : [sql`stream_id = ${input.threadId}`]),
473 ...(input.commandId === undefined ? [] : [sql`command_id = ${input.commandId}`]),
474 ...(input.eventType === undefined ? [] : [sql`event_type = ${input.eventType}`]),
475 ])}
476 ORDER BY sequence ASC
477 LIMIT ${input.limit}
478 `;
479
480 const appendAgentEvents: OrchestrationEventStore["Service"]["appendAgentEvents"] = (input) =>
481 Effect.forEach(
482 input.events,
483 (event) =>
484 Effect.gen(function* () {
485 const encoded = yield* encodeV2EventJson(event);
486 const subagent =
487 encoded.type === "subagent.updated"
488 ? encoded.payload
489 : encoded.type === "turn-item.updated" && encoded.payload.type === "subagent"
490 ? encoded.payload
491 : undefined;
492 const promptKey = subagent === undefined ? undefined : `${event.type}:${subagent.id}`;
493 const hint = promptKey === undefined ? undefined : promptHints.get(promptKey);
494 const payloadJson = yield* encodeJson(encoded.payload);
495 // Progress ticks repeat an unchanged prompt, so store it once and point
496 // later rows at it. Keep an empty prompt so older servers still decode
497 // the row. ProjectionMaintenance never deletes these anchor rows. The
498 // hint is re-checked here because its transaction may have rolled back.
499 const storedPayload =
500 hint !== undefined && subagent !== undefined
501 ? sql`CASE WHEN EXISTS (
502 SELECT 1 FROM orchestration_events
503 WHERE sequence = ${hint}
504 AND json_type(payload_json, '$.promptSequence') IS NULL
505 AND json_extract(payload_json, '$.prompt') = ${subagent.prompt}
506 ) THEN json_set(${payloadJson}, '$.prompt', '', '$.promptSequence', CAST(${hint} AS INTEGER))
507 ELSE ${payloadJson} END`
508 : sql`${payloadJson}`;
509 const rows = yield* sql<{
510 readonly sequence: number;
511 readonly stores_full_prompt?: number;
512 }>`
513 INSERT INTO orchestration_events (
514 event_id,
515 aggregate_kind,
516 stream_id,
517 stream_version,
518 event_type,
519 occurred_at,
520 command_id,
521 causation_event_id,
522 correlation_id,
523 actor_kind,
524 payload_json,
525 metadata_json,
526 application_event_version
527 )
528 VALUES (
529 ${event.id},
530 'thread',
531 ${event.threadId},
532 COALESCE(
533 (
534 SELECT MAX(stream_version) + 1
535 FROM orchestration_events
536 WHERE aggregate_kind = 'thread' AND stream_id = ${event.threadId}
537 ),
538 0
539 ),
540 ${event.type},
541 ${encoded.occurredAt},
542 ${input.commandId ?? null},
543 NULL,
544 ${input.commandId ?? null},
545 ${event.rawEventId === undefined ? "server" : "provider"},
546 ${storedPayload},
547 ${yield* encodeJson(metadataForV2Event(event))},
548 2
549 )
550 RETURNING sequence${
551 hint === undefined
552 ? sql``
553 : sql`, json_type(payload_json, '$.promptSequence') IS NULL AS stores_full_prompt`
554 }
555 `;
556 const row = rows[0];
557 if (promptKey !== undefined && row !== undefined) {
558 // Delete first so Map order tracks recent use and eviction drops idle subagents.
559 promptHints.delete(promptKey);
560 promptHints.set(
561 promptKey,
562 hint === undefined || row.stores_full_prompt === 1 ? row.sequence : hint,
563 );
564 if (promptHints.size > 4096) {
565 const oldest = promptHints.keys().next().value;
566 if (oldest !== undefined) promptHints.delete(oldest);
567 }
568 }
569 return yield* decodeV2StoredEvent({
570 sequence: rows[0]?.sequence,
571 commandId: input.commandId ?? null,
572 event,
573 });
574 }),
575 { concurrency: 1 },
576 ).pipe(
577 Effect.mapError(
578 toPersistenceSqlOrDecodeError(
579 "OrchestrationEventStore.appendAgentEvents:insert",
580 "OrchestrationEventStore.appendAgentEvents:decode",
581 ),
582 ),
583 );
584
585 const readAgentEvents: OrchestrationEventStore["Service"]["readAgentEvents"] = (input) => {
586 const totalLimit =
587 input?.limit === undefined ? Number.MAX_SAFE_INTEGER : Math.max(0, Math.floor(input.limit));
588 if (totalLimit === 0) {
589 return Stream.empty;
590 }
591 return Stream.paginate(
592 { cursor: input?.afterSequence ?? 0, remaining: totalLimit },
593 ({ cursor, remaining }) => {
594 const pageLimit = Math.min(remaining, READ_PAGE_SIZE);
595 return readApplicationRows({
596 afterSequence: cursor,
597 ...(input?.throughSequence === undefined
598 ? {}
599 : { throughSequence: input.throughSequence }),
600 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
601 ...(input?.commandId === undefined ? {} : { commandId: input.commandId }),
602 ...(input?.eventType === undefined ? {} : { eventType: input.eventType }),
603 onlyAgentEvents: true,
604 limit: pageLimit,
605 }).pipe(
606 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.readAgentEvents:query")),
607 Effect.map((rows) => {
608 const last = rows.at(-1);
609 const nextRemaining = remaining - rows.length;
610 return [
611 rows,
612 last === undefined ||
613 rows.length < pageLimit ||
614 nextRemaining <= 0 ||
615 (input?.throughSequence !== undefined && last.sequence >= input.throughSequence)
616 ? Option.none()
617 : Option.some({ cursor: last.sequence, remaining: nextRemaining }),
618 ] as const;
619 }),
620 );
621 },
622 ).pipe(
623 Stream.filterEffect((row) => keepReplayRow(row, input?.skipUnknownEventTypes)),
624 Stream.mapEffect((row) =>
625 rowToV2StoredEvent(row).pipe(
626 Effect.mapError(
627 toPersistenceDecodeError("OrchestrationEventStore.readAgentEvents:decode"),
628 ),
629 ),
630 ),
631 );
632 };
633
634 const getAgentReplayStats: OrchestrationEventStore["Service"]["getAgentReplayStats"] = (input) =>
635 sql<{
636 readonly eventCount: number;
637 readonly rawPayloadBytes: number;
638 readonly hasCreateEvent: number;
639 }>`
640 SELECT
641 COUNT(*) AS "eventCount",
642 COALESCE(SUM(octet_length(payload_json)), 0) AS "rawPayloadBytes",
643 COALESCE(MAX(event_type = 'thread.created'), 0) AS "hasCreateEvent"
644 FROM (
645 SELECT ${restoredPayloadJson} AS payload_json, event_type
646 FROM orchestration_events
647 WHERE aggregate_kind = 'thread'
648 AND stream_id = ${input.threadId}
649 AND application_event_version = 2
650 AND sequence > ${input.afterSequence}
651 AND sequence <= ${input.throughSequence}
652 ORDER BY sequence ASC
653 LIMIT ${Math.max(0, Math.floor(input.maxEvents)) + 1}
654 )
655 `.pipe(
656 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getAgentReplayStats:query")),
657 Effect.map((rows) => ({
658 eventCount: rows[0]?.eventCount ?? 0,
659 rawPayloadBytes: rows[0]?.rawPayloadBytes ?? 0,
660 hasCreateEvent: (rows[0]?.hasCreateEvent ?? 0) !== 0,
661 })),
662 );
663
664 const getReplayStats: OrchestrationEventStore["Service"]["getReplayStats"] = (input) =>
665 sql<{ readonly eventCount: number; readonly rawPayloadBytes: number }>`
666 SELECT
667 COUNT(*) AS "eventCount",
668 COALESCE(SUM(octet_length(${restoredPayloadJson})), 0) AS "rawPayloadBytes"
669 FROM orchestration_events INDEXED BY idx_orchestration_events_application_high_water
670 WHERE sequence > ${input.afterSequence}
671 AND sequence <= ${input.throughSequence}
672 AND (
673 aggregate_kind = 'project'
674 OR (application_event_version = 2 AND aggregate_kind = 'thread')
675 )
676 `.pipe(
677 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getReplayStats:query")),
678 Effect.map((rows) => ({
679 eventCount: rows[0]?.eventCount ?? 0,
680 rawPayloadBytes: rows[0]?.rawPayloadBytes ?? 0,
681 })),
682 );
683
684 const latestAgentSequence: OrchestrationEventStore["Service"]["latestAgentSequence"] = (
685 threadId,
686 ) =>
687 sql<{ readonly sequence: number | null }>`
688 SELECT MAX(sequence) AS sequence
689 FROM orchestration_events
690 ${
691 threadId === undefined
692 ? sql``
693 : sql`INDEXED BY idx_orchestration_events_agent_stream_sequence`
694 }
695 WHERE application_event_version = 2
696 AND aggregate_kind = 'thread'
697 ${threadId === undefined ? sql`` : sql`AND stream_id = ${threadId}`}
698 `.pipe(
699 Effect.map((rows) => rows[0]?.sequence ?? 0),
700 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.latestAgentSequence:query")),
701 );
702
703 // The OR planner otherwise scans every V2 event instead of seeking the final sequence.
704 const latestApplicationSequence = sql<{ readonly sequence: number | null }>`
705 SELECT MAX(sequence) AS sequence
706 FROM orchestration_events INDEXED BY idx_orchestration_events_application_high_water
707 WHERE aggregate_kind = 'project'
708 OR (application_event_version = 2 AND aggregate_kind = 'thread')
709 `.pipe(
710 Effect.map((rows) => rows[0]?.sequence ?? 0),
711 Effect.mapError(
712 toPersistenceSqlError("OrchestrationEventStore.latestApplicationSequence:query"),
713 ),
714 );
715
716 // Advance over raw rows so even a full page of unknown types cannot end replay early.
717 const catchUpApplicationEvents = (input: {
718 readonly afterSequence: number;
719 readonly throughSequence: number;
720 readonly skipUnknownEventTypes?: boolean;
721 }): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> =>
722 Stream.paginate(input.afterSequence, (afterSequence) =>
723 readApplicationRows({
724 afterSequence,
725 throughSequence: input.throughSequence,
726 limit: READ_PAGE_SIZE,
727 }).pipe(
728 Effect.mapError(
729 toPersistenceSqlError("OrchestrationEventStore.readApplicationEvents:query"),
730 ),
731 Effect.map((rows) => {
732 const last = rows.at(-1);
733 return [
734 rows,
735 last === undefined ||
736 rows.length < READ_PAGE_SIZE ||
737 last.sequence >= input.throughSequence
738 ? Option.none()
739 : Option.some(last.sequence),
740 ] as const;
741 }),
742 ),
743 ).pipe(
744 Stream.filterEffect((row) => keepReplayRow(row, input.skipUnknownEventTypes)),
745 Stream.mapEffect((row) =>
746 rowToApplicationStoredEvent(row).pipe(
747 Effect.mapError(
748 toPersistenceDecodeError("OrchestrationEventStore.readApplicationEvents:decode"),
749 ),
750 ),
751 ),
752 );
753
754 const streamProjectedApplicationEvents: OrchestrationEventStore["Service"]["streamProjectedApplicationEvents"] =
755 (input) =>
756 replayAndBufferProjectedLiveEvents({
757 subscribe: PubSub.subscribe(committedEvents),
758 latestSequence: latestApplicationSequence,
759 afterSequence: input.afterSequence ?? 0,
760 project: input.project,
761 replay: (throughSequence) =>
762 catchUpApplicationEvents({
763 afterSequence: input?.afterSequence ?? 0,
764 throughSequence,
765 }),
766 }).pipe(
767 Stream.catchTag("LiveStreamBufferError", (cause) =>
768 Stream.fail(
769 toPersistenceSqlError("OrchestrationEventStore.streamApplicationEvents:buffer")(cause),
770 ),
771 ),
772 );
773
774 const streamApplicationEvents: OrchestrationEventStore["Service"]["streamApplicationEvents"] = (
775 input,
776 ) => streamProjectedApplicationEvents({ ...input, project: (event) => event });
777
778 return {
779 appendProjectEvent,
780 appendAgentEvents,
781 readAgentEvents,
782 getAgentReplayStats,
783 getReplayStats,
784 latestAgentSequence,
785 latestApplicationSequence,
786 readApplicationEvents: catchUpApplicationEvents,
787 publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid),
788 streamApplicationEvents,
789 streamProjectedApplicationEvents,
790 } satisfies OrchestrationEventStore["Service"];
791});
792
793export const layer = Layer.effect(OrchestrationEventStore, makeEventStore);