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

OrchestrationEventStore.test.ts

359 lines12.8 KB

1import * as NodeV8 from "node:v8";
2​
3import {
4 CommandId,
5 EventId,
6 MessageId,
7 ProjectId,
8 ThreadId,
9 type OrchestrationEvent,
10} from "@t3tools/contracts";
11import { assert, it } from "@effect/vitest";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Schema from "effect/Schema";
15import * as Stream from "effect/Stream";
16import * as SqlClient from "effect/unstable/sql/SqlClient";
17​
18import { PersistenceDecodeError } from "../Errors.ts";
19import { OrchestrationEventStore } from "../Services/OrchestrationEventStore.ts";
20import { OrchestrationEventStoreLive } from "./OrchestrationEventStore.ts";
21import { SqlitePersistenceMemory } from "./Sqlite.ts";
22const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
23​
24function messageEvent(threadId: ThreadId, id: string): Omit<OrchestrationEvent, "sequence"> {
25 const now = "2026-01-01T00:00:00.000Z";
26 return {
27 type: "thread.message-sent",
28 eventId: EventId.make(id),
29 aggregateKind: "thread",
30 aggregateId: threadId,
31 occurredAt: now,
32 commandId: null,
33 causationEventId: null,
34 correlationId: null,
35 metadata: {},
36 payload: {
37 threadId,
38 messageId: MessageId.make(id),
39 role: "assistant",
40 text: id,
41 turnId: null,
42 streaming: false,
43 createdAt: now,
44 updatedAt: now,
45 },
46 };
48​
49const layer = it.layer(
50 OrchestrationEventStoreLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
51);
52​
53layer("OrchestrationEventStore", (it) => {
54 it.effect("stores json columns as strings and replays CLI-origin events", () =>
55 Effect.gen(function* () {
56 const eventStore = yield* OrchestrationEventStore;
57 const sql = yield* SqlClient.SqlClient;
58 const now = "2026-01-01T00:00:00.000Z";
59​
60 const appended = yield* eventStore.append({
61 type: "project.created",
62 eventId: EventId.make("evt-store-roundtrip"),
63 aggregateKind: "project",
64 aggregateId: ProjectId.make("project-roundtrip"),
65 occurredAt: now,
66 commandId: CommandId.make("cmd-store-roundtrip"),
67 causationEventId: null,
68 correlationId: CommandId.make("cmd-store-roundtrip"),
69 metadata: {
70 adapterKey: "codex",
71 origin: {
72 surface: "cli",
73 },
74 },
75 payload: {
76 projectId: ProjectId.make("project-roundtrip"),
77 title: "Roundtrip Project",
78 workspaceRoot: "/tmp/project-roundtrip",
79 defaultModelSelection: null,
80 scripts: [],
81 createdAt: now,
82 updatedAt: now,
83 },
84 });
85​
86 const storedRows = yield* sql<{
87 readonly payloadJson: string;
88 readonly metadataJson: string;
89 }>`
90 SELECT
91 payload_json AS "payloadJson",
92 metadata_json AS "metadataJson"
93 FROM orchestration_events
94 WHERE event_id = ${appended.eventId}
95 `;
96 assert.equal(storedRows.length, 1);
97 assert.equal(typeof storedRows[0]?.payloadJson, "string");
98 assert.equal(typeof storedRows[0]?.metadataJson, "string");
99​
100 const replayed = yield* Stream.runCollect(eventStore.readFromSequence(0, 10)).pipe(
101 Effect.map((chunk) => Array.from(chunk)),
102 );
103 assert.equal(replayed.length, 1);
104 assert.equal(replayed[0]?.type, "project.created");
105 assert.equal(replayed[0]?.metadata.adapterKey, "codex");
106 assert.deepEqual(replayed[0]?.metadata.origin, { surface: "cli" });
107 }),
108 );
109​
110 it.effect("fails with PersistenceDecodeError when stored json is invalid", () =>
111 Effect.gen(function* () {
112 const eventStore = yield* OrchestrationEventStore;
113 const sql = yield* SqlClient.SqlClient;
114 const now = "2026-01-01T00:00:00.000Z";
115​
116 const invalidRows = yield* sql<{ readonly sequence: number }>`
117 INSERT INTO orchestration_events (
118 event_id,
119 aggregate_kind,
120 stream_id,
121 stream_version,
122 event_type,
123 occurred_at,
124 command_id,
125 causation_event_id,
126 correlation_id,
127 actor_kind,
128 payload_json,
129 metadata_json
130 )
131 VALUES (
132 ${EventId.make("evt-store-invalid-json")},
133 ${"project"},
134 ${ProjectId.make("project-invalid-json")},
135 ${0},
136 ${"project.created"},
137 ${now},
138 ${CommandId.make("cmd-store-invalid-json")},
139 ${null},
140 ${null},
141 ${"server"},
142 ${"{"},
143 ${"{}"}
144 )
145 RETURNING sequence
146 `;
147​
148 const replayResult = yield* Effect.result(
149 Stream.runCollect(eventStore.readFromSequence(0, 10)),
150 );
151 assert.equal(replayResult._tag, "Failure");
152 if (replayResult._tag === "Failure") {
153 assert.ok(isPersistenceDecodeError(replayResult.failure));
154 assert.ok(
155 replayResult.failure.operation.includes(
156 "OrchestrationEventStore.readFromSequence:decodeRows",
157 ),
158 );
159 }
160 const scopedResult = yield* eventStore
161 .readAggregateRange({
162 aggregateKind: "project",
163 aggregateId: "project-invalid-json",
164 fromSequenceExclusive: 0,
165 toSequenceInclusive: invalidRows[0]!.sequence,
166 })
167 .pipe(Stream.runCollect, Effect.result);
168 assert.equal(scopedResult._tag, "Failure");
169 if (scopedResult._tag === "Failure") {
170 assert.ok(isPersistenceDecodeError(scopedResult.failure));
171 assert.ok(
172 scopedResult.failure.operation.includes(
173 "OrchestrationEventStore.readAggregateRange:decodeRows",
174 ),
175 );
176 }
177 }),
178 );
179​
180 it.effect("reads one aggregate through the captured head across pruned global gaps", () =>
181 Effect.gen(function* () {
182 const store = yield* OrchestrationEventStore;
183 const sql = yield* SqlClient.SqlClient;
184 const threadId = ThreadId.make("shared-stream-id");
185 const first = yield* store.append(messageEvent(threadId, "scoped-first"));
186 const pruned = yield* store.append(
187 messageEvent(ThreadId.make("pruned-thread"), "pruned-event"),
188 );
189 const second = yield* store.append(messageEvent(threadId, "scoped-second"));
190 // The same stream ID in a different aggregate is not part of this thread.
191 // Its invalid JSON must never reach the event decoder.
192 yield* sql`
193 INSERT INTO orchestration_events (
194 event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
195 actor_kind, payload_json, metadata_json
196 ) VALUES (
197 'same-id-project', 'project', ${threadId}, 0, 'project.created',
198 '2026-01-01T00:00:00.000Z', 'server', '{', '{'
199 ), (
200 'unrelated-invalid', 'thread', 'unrelated-invalid-thread', 0, 'thread.activity-appended',
201 '2026-01-01T00:00:00.000Z', 'server', '{', '{'
202 )
203 `;
204 const last = yield* store.append(messageEvent(threadId, "scoped-last"));
205 yield* sql`DELETE FROM orchestration_events WHERE sequence = ${pruned.sequence}`;
206 yield* store.append(messageEvent(threadId, "after-captured-head"));
207​
208 const events = yield* store
209 .readAggregateRange({
210 aggregateKind: "thread",
211 aggregateId: threadId,
212 fromSequenceExclusive: first.sequence,
213 toSequenceInclusive: last.sequence,
214 limit: 100,
215 })
216 .pipe(Stream.runCollect);
217 assert.deepEqual(
218 events.map((event) => event.sequence),
219 [second.sequence, last.sequence],
220 );
221 }),
222 );
223​
224 it.effect("bounds thread replay metadata and counts UTF-8 bytes without decoding payloads", () =>
225 Effect.gen(function* () {
226 const store = yield* OrchestrationEventStore;
227 const sql = yield* SqlClient.SqlClient;
228 const rows = yield* sql<{ readonly sequence: number }>`
229 INSERT INTO orchestration_events (
230 event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
231 actor_kind, payload_json, metadata_json
232 ) VALUES
233 ('stats-1', 'thread', 'stats-thread', 0, 'thread.message-sent',
234 '2026-01-01T00:00:00.000Z', 'provider', '{"output":"πŸ˜€"}', '{}'),
235 ('stats-unrelated', 'thread', 'another-thread', 0, 'thread.created',
236 '2026-01-01T00:00:00.000Z', 'provider', printf('%.*c', 10000, 'x'), '{}'),
237 ('stats-2', 'thread', 'stats-thread', 1, 'thread.activity-appended',
238 '2026-01-01T00:00:00.000Z', 'provider', '{', '{}'),
239 ('stats-other-kind', 'project', 'stats-thread', 0, 'project.deleted',
240 '2026-01-01T00:00:00.000Z', 'provider', printf('%.*c', 20000, 'x'), '{}'),
241 ('stats-3', 'thread', 'stats-thread', 2, 'thread.deleted',
242 '2026-01-01T00:00:00.000Z', 'provider', '{"output":"Γ©"}', '{}'),
243 ('stats-4', 'thread', 'stats-thread', 3, 'thread.created',
244 '2026-01-01T00:00:00.000Z', 'provider', printf('%.*c', 2000, 'x'), '{}')
245 RETURNING sequence
246 `;
247 const range = {
248 aggregateKind: "thread" as const,
249 aggregateId: "stats-thread",
250 fromSequenceExclusive: 0,
251 toSequenceInclusive: rows.at(-1)!.sequence,
252 };
253 assert.deepEqual(yield* store.getAggregateReplayStats({ ...range, maxEvents: 2 }), {
254 eventCount: 3,
255 payloadBytes: 33,
256 hasCreateEvent: false,
257 });
258 assert.deepEqual(yield* store.getAggregateReplayStats({ ...range, maxEvents: 10 }), {
259 eventCount: 4,
260 payloadBytes: 2033,
261 hasCreateEvent: true,
262 });
263 assert.deepEqual(
264 yield* store.getAggregateReplayStats({
265 ...range,
266 toSequenceInclusive: rows[2]!.sequence,
267 maxEvents: 10,
268 }),
269 {
270 eventCount: 2,
271 payloadBytes: 18,
272 hasCreateEvent: false,
273 },
274 );
275 }),
276 );
277​
278 it.effect("keeps later pages below the captured head when new events are appended", () =>
279 Effect.gen(function* () {
280 const store = yield* OrchestrationEventStore;
281 const threadId = ThreadId.make("paged-thread");
282 const persisted = yield* Effect.forEach(
283 Array.from({ length: 502 }, (_, index) => index),
284 (index) => store.append(messageEvent(threadId, `paged-${index}`)),
285 );
286 const head = persisted.at(-1)!.sequence;
287 let appendedDuringReplay = false;
288 const replayed = yield* store
289 .readAggregateRange({
290 aggregateKind: "thread",
291 aggregateId: threadId,
292 fromSequenceExclusive: 0,
293 toSequenceInclusive: head,
294 limit: 1_000,
295 })
296 .pipe(
297 Stream.tap(() => {
298 if (appendedDuringReplay) return Effect.void;
299 appendedDuringReplay = true;
300 return store.append(messageEvent(threadId, "appended-during-replay"));
301 }),
302 Stream.runCollect,
303 );
304 assert.deepEqual(
305 replayed.map((event) => event.sequence),
306 persisted.map((event) => event.sequence),
307 );
308 const limited = store.readFromSequence(persisted[0]!.sequence, 501.9);
309 for (let run = 0; run < 2; run++) {
310 assert.deepEqual(
311 (yield* Stream.runCollect(limited)).map((event) => event.sequence),
312 persisted.slice(1).map((event) => event.sequence),
313 );
314 }
315 assert.deepEqual(yield* Stream.runCollect(store.readFromSequence(0, -1)), []);
316 }),
317 );
318});
319​
320for (const reader of ["all", "aggregate"] as const) {
321 it.effect(`releases consumed pages during ${reader} replay`, () =>
322 Effect.gen(function* () {
323 const store = yield* OrchestrationEventStore;
324 const threadId = ThreadId.make(`retention-${reader}`);
325 yield* Effect.forEach(
326 Array.from({ length: 1_501 }, (_, index) => index),
327 (index) => store.append(messageEvent(threadId, `retention-${reader}-${index}`)),
328 { discard: true },
329 );
330 // oxlint-disable-next-line typescript/no-extraneous-class -- Identifies page markers for V8's heap query.
331 class ReplayPage {}
332 let count = 0;
333 const replay =
334 reader === "all"
335 ? store.readAll()
336 : store.readAggregateRange({
337 aggregateKind: "thread",
338 aggregateId: threadId,
339 fromSequenceExclusive: 0,
340 toSequenceInclusive: 1_501,
341 limit: 1_501,
342 });
343 yield* Stream.runForEach(replay, (event) =>
344 Effect.sync(() => {
345 assert.equal(event.sequence, count + 1);
346 if (count % 500 === 0) {
347 // Count live page markers after full GC, without timing or heap-size thresholds.
348 Object.assign(event, { replayPage: new ReplayPage() });
349 assert.isAtMost(NodeV8.queryObjects(ReplayPage, { format: "count" }), 1);
350 }
351 count++;
352 }),
353 );
354 assert.equal(count, 1_501);
355 }).pipe(
356 Effect.provide(OrchestrationEventStoreLive.pipe(Layer.provide(SqlitePersistenceMemory))),
357 ),
358 );