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