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

OrchestrationEventStore.ts

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