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

OrchestrationEventStore.ts

768 lines27.8 KB

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 * as Layer from "effect/Layer";
23import * as PubSub from "effect/PubSub";
24import * as Option from "effect/Option";
25import * as Schema from "effect/Schema";
26import * as Stream from "effect/Stream";
27​
28import { replayAndBufferProjectedLiveEvents } from "../orchestration-v2/LiveStreamBudget.ts";
29​
30import {
31 toPersistenceDecodeError,
32 toPersistenceSqlError,
33 type OrchestrationEventStoreError,
34} from "./Errors.ts";
35​
36export type UnsequencedProjectEvent = ApplicationProjectEvent extends infer Event
37 ? Event extends ApplicationProjectEvent
38 ? Omit<Event, "sequence">
39 : never
40 : never;
41​
42export class OrchestrationEventStore extends Context.Service<
43 OrchestrationEventStore,
44 {
45 readonly appendProjectEvent: (
46 event: UnsequencedProjectEvent,
47 ) => Effect.Effect<ApplicationProjectEvent, OrchestrationEventStoreError>;
48​
49 readonly appendAgentEvents: (input: {
50 readonly commandId?: CommandId;
51 readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
52 }) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, OrchestrationEventStoreError>;
53​
54 /**
55 * A row whose `event_type` this build does not know fails the read unless
56 * `skipUnknownEventTypes` is set, which logs and drops it instead. Only
57 * client thread replay opts in; anything that builds server state stays strict.
58 */
59 readonly readAgentEvents: (input?: {
60 readonly afterSequence?: number;
61 readonly throughSequence?: number;
62 readonly threadId?: ThreadId;
63 readonly commandId?: CommandId;
64 readonly eventType?: OrchestrationV2DomainEvent["type"];
65 readonly limit?: number;
66 readonly skipUnknownEventTypes?: boolean;
67 }) => Stream.Stream<OrchestrationV2StoredEvent, OrchestrationEventStoreError>;
68​
69 readonly getAgentReplayStats: (input: {
70 readonly threadId: ThreadId;
71 readonly afterSequence: number;
72 readonly throughSequence: number;
73 readonly maxEvents: number;
74 }) => Effect.Effect<
75 {
76 readonly eventCount: number;
77 readonly rawPayloadBytes: number;
78 readonly hasCreateEvent: boolean;
79 },
80 OrchestrationEventStoreError
81 >;
82​
83 readonly getReplayStats: (input: {
84 readonly afterSequence: number;
85 readonly throughSequence: number;
86 }) => Effect.Effect<
87 {
88 readonly eventCount: number;
89 readonly rawPayloadBytes: number;
90 },
91 OrchestrationEventStoreError
92 >;
93​
94 readonly latestAgentSequence: (
95 threadId?: ThreadId,
96 ) => Effect.Effect<number, OrchestrationEventStoreError>;
97​
98 readonly latestApplicationSequence: Effect.Effect<number, OrchestrationEventStoreError>;
99​
100 /**
101 * A row whose `event_type` this build does not know fails the read unless
102 * `skipUnknownEventTypes` is set, which logs and drops it instead. Only
103 * client shell replay opts in; anything that builds server state stays strict.
104 */
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;
181​
182const decodeV2EventJson = Schema.decodeUnknownEffect(OrchestrationV2DomainEventJson);
183const encodeV2EventJson = Schema.encodeEffect(OrchestrationV2DomainEventJson);
184const decodeV2StoredEvent = Schema.decodeUnknownEffect(OrchestrationV2StoredEvent);
185const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
186const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
187​
188function metadataForV2Event(event: OrchestrationV2DomainEvent): Record<string, unknown> {
189 return {
190 ...(event.runId === undefined ? {} : { runId: event.runId }),
191 ...(event.nodeId === undefined ? {} : { nodeId: event.nodeId }),
192 ...(event.driver === undefined ? {} : { driver: event.driver }),
193 ...(event.providerInstanceId === undefined
194 ? {}
195 : { providerInstanceId: event.providerInstanceId }),
196 ...(event.rawEventId === undefined ? {} : { rawEventId: event.rawEventId }),
197 };
199​
200const rowToV2StoredEvent = Effect.fn("OrchestrationEventStore.rowToV2StoredEvent")(function* (
201 row: ApplicationEventRow,
202) {
203 const payload = yield* decodeJson(row.payload_json);
204 const metadata = yield* decodeJson(row.metadata_json);
205 const values =
206 typeof metadata === "object" && metadata !== null ? (metadata as Record<string, unknown>) : {};
207 const event = yield* decodeV2EventJson({
208 id: row.event_id,
209 threadId: row.stream_id,
210 type: row.event_type,
211 occurredAt: row.occurred_at,
212 payload,
213 ...(values.runId === undefined ? {} : { runId: values.runId }),
214 ...(values.nodeId === undefined ? {} : { nodeId: values.nodeId }),
215 ...(values.driver === undefined ? {} : { driver: values.driver }),
216 ...(values.providerInstanceId === undefined
217 ? {}
218 : { providerInstanceId: values.providerInstanceId }),
219 ...(values.rawEventId === undefined ? {} : { rawEventId: values.rawEventId }),
220 });
221 return yield* decodeV2StoredEvent({
222 sequence: row.sequence,
223 commandId: row.command_id,
224 event,
225 });
226});
227​
228const rowToProjectEvent = Effect.fn("OrchestrationEventStore.rowToProjectEvent")(function* (
229 row: ApplicationEventRow,
230) {
231 return yield* decodeProjectEvent({
232 sequence: row.sequence,
233 eventId: row.event_id,
234 type: row.event_type,
235 aggregateKind: row.aggregate_kind,
236 aggregateId: row.stream_id,
237 occurredAt: row.occurred_at,
238 commandId: row.command_id,
239 causationEventId: row.causation_event_id,
240 correlationId: row.correlation_id,
241 payload: yield* decodeJson(row.payload_json),
242 metadata: yield* decodeJson(row.metadata_json),
243 });
244});
245​
246function rowToApplicationStoredEvent(
247 row: ApplicationEventRow,
248): Effect.Effect<ApplicationStoredEvent, Schema.SchemaError> {
249 return row.aggregate_kind === "project" ? rowToProjectEvent(row) : rowToV2StoredEvent(row);
251​
252const isKnownProjectEventType = Schema.is(ProjectEventType);
253​
254const keepReplayRow = (row: ApplicationEventRow, skipUnknownEventTypes?: boolean) =>
255 skipUnknownEventTypes !== true ||
256 (row.aggregate_kind === "project"
257 ? isKnownProjectEventType(row.event_type)
258 : isKnownOrchestrationV2EventType(row.event_type))
259 ? Effect.succeed(true)
260 : Effect.logWarning("Skipping an application event row with an unknown event type", {
261 aggregateKind: row.aggregate_kind,
262 sequence: row.sequence,
263 eventTypeLength: row.event_type.length,
264 }).pipe(Effect.as(false));
265​
266function inferActorKind(event: UnsequencedProjectEvent): typeof ActorKind.Type {
267 if (event.commandId !== null && event.commandId.startsWith("provider:")) {
268 return "provider";
269 }
270 if (event.commandId !== null && event.commandId.startsWith("server:")) {
271 return "server";
272 }
273 if (
274 event.metadata.providerTurnId !== undefined ||
275 event.metadata.providerItemId !== undefined ||
276 event.metadata.adapterKey !== undefined
277 ) {
278 return "provider";
279 }
280 if (event.commandId === null) {
281 return "server";
282 }
283 return "client";
285​
286function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
287 return (cause: unknown): OrchestrationEventStoreError =>
288 Schema.isSchemaError(cause)
289 ? toPersistenceDecodeError(decodeOperation)(cause)
290 : toPersistenceSqlError(sqlOperation)(cause);
292​
293const makeEventStore = Effect.gen(function* () {
294 const sql = yield* SqlClient.SqlClient;
295 const committedEvents = yield* PubSub.unbounded<ApplicationStoredEvent>();
296 const promptHints = new Map<string, number>();
297 const restoredPayloadJson = sql`CASE
298 WHEN orchestration_events.event_type IN ('subagent.updated', 'turn-item.updated')
299 AND json_type(orchestration_events.payload_json, '$.promptSequence') = 'integer'
300 THEN json_set(
301 json_remove(orchestration_events.payload_json, '$.promptSequence'),
302 '$.prompt',
303 (SELECT json_extract(anchor.payload_json, '$.prompt')
304 FROM orchestration_events AS anchor
305 WHERE anchor.sequence = json_extract(orchestration_events.payload_json, '$.promptSequence'))
306 )
307 ELSE orchestration_events.payload_json
308 END`;
309​
310 const appendProjectEventRow = SqlSchema.findOne({
311 Request: AppendProjectEventRequestSchema,
312 Result: ProjectEventPersistedRowSchema,
313 execute: (request) =>
314 sql`
315 INSERT INTO orchestration_events (
316 event_id,
317 aggregate_kind,
318 stream_id,
319 stream_version,
320 event_type,
321 occurred_at,
322 command_id,
323 causation_event_id,
324 correlation_id,
325 actor_kind,
326 payload_json,
327 metadata_json,
328 application_event_version
329 )
330 VALUES (
331 ${request.eventId},
332 'project',
333 ${request.streamId},
334 COALESCE(
335 (
336 SELECT stream_version + 1
337 FROM orchestration_events
338 WHERE aggregate_kind = 'project'
339 AND stream_id = ${request.streamId}
340 ORDER BY stream_version DESC
341 LIMIT 1
342 ),
343 0
344 ),
345 ${request.type},
346 ${request.occurredAt},
347 ${request.commandId},
348 ${request.causationEventId},
349 ${request.correlationId},
350 ${request.actorKind},
351 ${request.payloadJson},
352 ${request.metadataJson},
353 2
354 )
355 RETURNING
356 sequence,
357 event_id AS "eventId",
358 event_type AS "type",
359 aggregate_kind AS "aggregateKind",
360 stream_id AS "aggregateId",
361 occurred_at AS "occurredAt",
362 command_id AS "commandId",
363 causation_event_id AS "causationEventId",
364 correlation_id AS "correlationId",
365 payload_json AS "payload",
366 metadata_json AS "metadata"
367 `,
368 });
369​
370 const appendProjectEvent: OrchestrationEventStore["Service"]["appendProjectEvent"] = (event) =>
371 appendProjectEventRow({
372 eventId: event.eventId,
373 streamId: event.aggregateId,
374 type: event.type,
375 causationEventId: event.causationEventId,
376 correlationId: event.correlationId,
377 actorKind: inferActorKind(event),
378 occurredAt: event.occurredAt,
379 commandId: event.commandId,
380 payloadJson:
381 event.type === "project.deleted" || !event.payload.projectIcon
382 ? event.payload
383 : { ...event.payload, projectIcon: encodeProjectIcon(event.payload.projectIcon) },
384 metadataJson: event.metadata,
385 }).pipe(
386 Effect.flatMap((row) => decodeProjectEvent(row)),
387 Effect.mapError(
388 toPersistenceSqlOrDecodeError(
389 "OrchestrationEventStore.appendProjectEvent:insert",
390 "OrchestrationEventStore.appendProjectEvent:decode",
391 ),
392 ),
393 );
394​
395 const readApplicationRows = (input: {
396 readonly afterSequence: number;
397 readonly throughSequence?: number;
398 readonly threadId?: ThreadId;
399 readonly commandId?: CommandId;
400 readonly eventType?: OrchestrationV2DomainEvent["type"];
401 readonly onlyAgentEvents?: boolean;
402 readonly limit: number;
403 }) =>
404 sql<ApplicationEventRow>`
405 SELECT
406 sequence,
407 event_id,
408 command_id,
409 aggregate_kind,
410 stream_id,
411 event_type,
412 occurred_at,
413 ${restoredPayloadJson} AS payload_json,
414 metadata_json,
415 application_event_version,
416 causation_event_id,
417 correlation_id
418 FROM orchestration_events
419 ${
420 // The sequence range otherwise wins and a command lookup scans every
421 // V2 event, which blocks the server for seconds on large histories.
422 input.commandId !== undefined
423 ? sql`INDEXED BY idx_orch_events_command_id`
424 : input.onlyAgentEvents === true
425 ? sql``
426 : sql`INDEXED BY idx_orchestration_events_application_high_water`
427 }
428 WHERE sequence > ${input.afterSequence}
429 AND sequence <= ${input.throughSequence ?? Number.MAX_SAFE_INTEGER}
430 AND (
431 ${
432 input.onlyAgentEvents === true
433 ? sql`application_event_version = 2 AND aggregate_kind = 'thread'`
434 : sql`aggregate_kind = 'project'
435 OR (application_event_version = 2 AND aggregate_kind = 'thread')`
436 }
437 )
438 AND ${sql.and([
439 ...(input.threadId === undefined ? [] : [sql`stream_id = ${input.threadId}`]),
440 ...(input.commandId === undefined ? [] : [sql`command_id = ${input.commandId}`]),
441 ...(input.eventType === undefined ? [] : [sql`event_type = ${input.eventType}`]),
442 ])}
443 ORDER BY sequence ASC
444 LIMIT ${input.limit}
445 `.pipe(NodeSqliteClient.readOnly);
446​
447 const appendAgentEvents: OrchestrationEventStore["Service"]["appendAgentEvents"] = (input) =>
448 Effect.forEach(
449 input.events,
450 (event) =>
451 Effect.gen(function* () {
452 const encoded = yield* encodeV2EventJson(event);
453 const subagent =
454 encoded.type === "subagent.updated"
455 ? encoded.payload
456 : encoded.type === "turn-item.updated" && encoded.payload.type === "subagent"
457 ? encoded.payload
458 : undefined;
459 const promptKey = subagent === undefined ? undefined : `${event.type}:${subagent.id}`;
460 const hint = promptKey === undefined ? undefined : promptHints.get(promptKey);
461 const payloadJson = yield* encodeJson(encoded.payload);
462 // Progress ticks repeat an unchanged prompt, so store it once and point
463 // later rows at it. ProjectionMaintenance never deletes these anchor
464 // rows.
465 const storedPayload =
466 hint !== undefined && subagent !== undefined
467 ? sql`CASE WHEN EXISTS (
468 SELECT 1 FROM orchestration_events
469 WHERE sequence = ${hint}
470 AND json_type(payload_json, '$.promptSequence') IS NULL
471 AND json_extract(payload_json, '$.prompt') = ${subagent.prompt}
472 ) THEN json_set(${payloadJson}, '$.prompt', '', '$.promptSequence', CAST(${hint} AS INTEGER))
473 ELSE ${payloadJson} END`
474 : sql`${payloadJson}`;
475 const rows = yield* sql<{
476 readonly sequence: number;
477 readonly stores_full_prompt?: number;
478 }>`
479 INSERT INTO orchestration_events (
480 event_id,
481 aggregate_kind,
482 stream_id,
483 stream_version,
484 event_type,
485 occurred_at,
486 command_id,
487 causation_event_id,
488 correlation_id,
489 actor_kind,
490 payload_json,
491 metadata_json,
492 application_event_version
493 )
494 VALUES (
495 ${event.id},
496 'thread',
497 ${event.threadId},
498 COALESCE(
499 (
500 SELECT MAX(stream_version) + 1
501 FROM orchestration_events
502 WHERE aggregate_kind = 'thread' AND stream_id = ${event.threadId}
503 ),
504 0
505 ),
506 ${event.type},
507 ${encoded.occurredAt},
508 ${input.commandId ?? null},
509 NULL,
510 ${input.commandId ?? null},
511 ${event.rawEventId === undefined ? "server" : "provider"},
512 ${storedPayload},
513 ${yield* encodeJson(metadataForV2Event(event))},
514 2
515 )
516 RETURNING sequence${
517 hint === undefined
518 ? sql``
519 : sql`, json_type(payload_json, '$.promptSequence') IS NULL AS stores_full_prompt`
520 }
521 `;
522 const row = rows[0];
523 if (promptKey !== undefined && row !== undefined) {
524 promptHints.delete(promptKey);
525 promptHints.set(
526 promptKey,
527 hint === undefined || row.stores_full_prompt === 1 ? row.sequence : hint,
528 );
529 if (promptHints.size > 4096) {
530 const oldest = promptHints.keys().next().value;
531 if (oldest !== undefined) promptHints.delete(oldest);
532 }
533 }
534 return yield* decodeV2StoredEvent({
535 sequence: rows[0]?.sequence,
536 commandId: input.commandId ?? null,
537 event,
538 });
539 }),
540 { concurrency: 1 },
541 ).pipe(
542 Effect.mapError(
543 toPersistenceSqlOrDecodeError(
544 "OrchestrationEventStore.appendAgentEvents:insert",
545 "OrchestrationEventStore.appendAgentEvents:decode",
546 ),
547 ),
548 );
549​
550 const readAgentEvents: OrchestrationEventStore["Service"]["readAgentEvents"] = (input) => {
551 const totalLimit =
552 input?.limit === undefined ? Number.MAX_SAFE_INTEGER : Math.max(0, Math.floor(input.limit));
553 if (totalLimit === 0) {
554 return Stream.empty;
555 }
556 return Stream.paginate(
557 { cursor: input?.afterSequence ?? 0, remaining: totalLimit },
558 ({ cursor, remaining }) => {
559 const pageLimit = Math.min(remaining, READ_PAGE_SIZE);
560 return readApplicationRows({
561 afterSequence: cursor,
562 ...(input?.throughSequence === undefined
563 ? {}
564 : { throughSequence: input.throughSequence }),
565 ...(input?.threadId === undefined ? {} : { threadId: input.threadId }),
566 ...(input?.commandId === undefined ? {} : { commandId: input.commandId }),
567 ...(input?.eventType === undefined ? {} : { eventType: input.eventType }),
568 onlyAgentEvents: true,
569 limit: pageLimit,
570 }).pipe(
571 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.readAgentEvents:query")),
572 Effect.map((rows) => {
573 const last = rows.at(-1);
574 const nextRemaining = remaining - rows.length;
575 return [
576 rows,
577 last === undefined ||
578 rows.length < pageLimit ||
579 nextRemaining <= 0 ||
580 (input?.throughSequence !== undefined && last.sequence >= input.throughSequence)
581 ? Option.none()
582 : Option.some({ cursor: last.sequence, remaining: nextRemaining }),
583 ] as const;
584 }),
585 );
586 },
587 ).pipe(
588 Stream.filterEffect((row) => keepReplayRow(row, input?.skipUnknownEventTypes)),
589 Stream.mapEffect((row) =>
590 rowToV2StoredEvent(row).pipe(
591 Effect.mapError(
592 toPersistenceDecodeError("OrchestrationEventStore.readAgentEvents:decode"),
593 ),
594 ),
595 ),
596 );
597 };
598​
599 const getAgentReplayStats: OrchestrationEventStore["Service"]["getAgentReplayStats"] = (input) =>
600 sql<{
601 readonly eventCount: number;
602 readonly rawPayloadBytes: number;
603 readonly hasCreateEvent: number;
604 }>`
605 SELECT
606 COUNT(*) AS "eventCount",
607 COALESCE(SUM(octet_length(payload_json)), 0) AS "rawPayloadBytes",
608 COALESCE(MAX(event_type = 'thread.created'), 0) AS "hasCreateEvent"
609 FROM (
610 SELECT ${restoredPayloadJson} AS payload_json, event_type
611 FROM orchestration_events
612 WHERE aggregate_kind = 'thread'
613 AND stream_id = ${input.threadId}
614 AND application_event_version = 2
615 AND sequence > ${input.afterSequence}
616 AND sequence <= ${input.throughSequence}
617 ORDER BY sequence ASC
618 LIMIT ${Math.max(0, Math.floor(input.maxEvents)) + 1}
619 )
620 `.pipe(
621 NodeSqliteClient.readOnly,
622 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getAgentReplayStats:query")),
623 Effect.map((rows) => ({
624 eventCount: rows[0]?.eventCount ?? 0,
625 rawPayloadBytes: rows[0]?.rawPayloadBytes ?? 0,
626 hasCreateEvent: (rows[0]?.hasCreateEvent ?? 0) !== 0,
627 })),
628 );
629​
630 const getReplayStats: OrchestrationEventStore["Service"]["getReplayStats"] = (input) =>
631 sql<{ readonly eventCount: number; readonly rawPayloadBytes: number }>`
632 SELECT
633 COUNT(*) AS "eventCount",
634 COALESCE(SUM(octet_length(${restoredPayloadJson})), 0) AS "rawPayloadBytes"
635 FROM orchestration_events INDEXED BY idx_orchestration_events_application_high_water
636 WHERE sequence > ${input.afterSequence}
637 AND sequence <= ${input.throughSequence}
638 AND (
639 aggregate_kind = 'project'
640 OR (application_event_version = 2 AND aggregate_kind = 'thread')
641 )
642 `.pipe(
643 NodeSqliteClient.readOnly,
644 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.getReplayStats:query")),
645 Effect.map((rows) => ({
646 eventCount: rows[0]?.eventCount ?? 0,
647 rawPayloadBytes: rows[0]?.rawPayloadBytes ?? 0,
648 })),
649 );
650​
651 const latestAgentSequence: OrchestrationEventStore["Service"]["latestAgentSequence"] = (
652 threadId,
653 ) =>
654 sql<{ readonly sequence: number | null }>`
655 SELECT MAX(sequence) AS sequence
656 FROM orchestration_events
657 ${
658 threadId === undefined
659 ? sql``
660 : sql`INDEXED BY idx_orchestration_events_agent_stream_sequence`
661 }
662 WHERE application_event_version = 2
663 AND aggregate_kind = 'thread'
664 ${threadId === undefined ? sql`` : sql`AND stream_id = ${threadId}`}
665 `.pipe(
666 NodeSqliteClient.readOnly,
667 Effect.map((rows) => rows[0]?.sequence ?? 0),
668 Effect.mapError(toPersistenceSqlError("OrchestrationEventStore.latestAgentSequence:query")),
669 );
670​
671 // The OR planner otherwise scans every V2 event instead of seeking the final sequence.
672 const latestApplicationSequence = sql<{ readonly sequence: number | null }>`
673 SELECT MAX(sequence) AS sequence
674 FROM orchestration_events INDEXED BY idx_orchestration_events_application_high_water
675 WHERE aggregate_kind = 'project'
676 OR (application_event_version = 2 AND aggregate_kind = 'thread')
677 `.pipe(
678 NodeSqliteClient.readOnly,
679 Effect.map((rows) => rows[0]?.sequence ?? 0),
680 Effect.mapError(
681 toPersistenceSqlError("OrchestrationEventStore.latestApplicationSequence:query"),
682 ),
683 );
684​
685 // Advance over raw rows so even a full page of unknown types cannot end replay early.
686 const catchUpApplicationEvents = (input: {
687 readonly afterSequence: number;
688 readonly throughSequence: number;
689 readonly skipUnknownEventTypes?: boolean;
690 }): Stream.Stream<ApplicationStoredEvent, OrchestrationEventStoreError> =>
691 Stream.paginate(input.afterSequence, (afterSequence) =>
692 readApplicationRows({
693 afterSequence,
694 throughSequence: input.throughSequence,
695 limit: READ_PAGE_SIZE,
696 }).pipe(
697 Effect.mapError(
698 toPersistenceSqlError("OrchestrationEventStore.readApplicationEvents:query"),
699 ),
700 Effect.map((rows) => {
701 const last = rows.at(-1);
702 return [
703 rows,
704 last === undefined ||
705 rows.length < READ_PAGE_SIZE ||
706 last.sequence >= input.throughSequence
707 ? Option.none()
708 : Option.some(last.sequence),
709 ] as const;
710 }),
711 ),
712 ).pipe(
713 Stream.filterEffect((row) => keepReplayRow(row, input.skipUnknownEventTypes)),
714 Stream.mapEffect((row) =>
715 rowToApplicationStoredEvent(row).pipe(
716 Effect.mapError(
717 toPersistenceDecodeError("OrchestrationEventStore.readApplicationEvents:decode"),
718 ),
719 ),
720 ),
721 );
722​
723 const streamProjectedApplicationEvents: OrchestrationEventStore["Service"]["streamProjectedApplicationEvents"] =
724 (input) =>
725 replayAndBufferProjectedLiveEvents<
726 ApplicationStoredEvent,
727 ReturnType<typeof input.project>,
728 OrchestrationEventStoreError,
729 never
730 >({
731 subscribe: PubSub.subscribe(committedEvents),
732 latestSequence: latestApplicationSequence,
733 afterSequence: input.afterSequence ?? 0,
734 project: input.project,
735 ...(input.filter === undefined ? {} : { filter: input.filter }),
736 replay: (throughSequence) =>
737 catchUpApplicationEvents({
738 afterSequence: input?.afterSequence ?? 0,
739 throughSequence,
740 }),
741 }).pipe(
742 Stream.catchTag("LiveStreamBufferError", (cause) =>
743 Stream.fail(
744 toPersistenceSqlError("OrchestrationEventStore.streamApplicationEvents:buffer")(cause),
745 ),
746 ),
747 );
748​
749 const streamApplicationEvents: OrchestrationEventStore["Service"]["streamApplicationEvents"] = (
750 input,
751 ) => streamProjectedApplicationEvents({ ...input, project: (event) => event });
752​
753 return {
754 appendProjectEvent,
755 appendAgentEvents,
756 readAgentEvents,
757 getAgentReplayStats,
758 getReplayStats,
759 latestAgentSequence,
760 latestApplicationSequence,
761 readApplicationEvents: catchUpApplicationEvents,
762 publishCommitted: (events) => PubSub.publishAll(committedEvents, events).pipe(Effect.asVoid),
763 streamApplicationEvents,
764 streamProjectedApplicationEvents,
765 } satisfies OrchestrationEventStore["Service"];
766});
767​
768export const layer = Layer.effect(OrchestrationEventStore, makeEventStore);