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

OrchestrationEventStore.test.ts

510 lines18.3 KB

1import * as NodeV8 from "node:v8";
2​
3import {
4 CommandId,
5 EventId,
6 ProjectId,
7 ProviderInstanceId,
8 ThreadId,
9 TurnItemId,
10 type OrchestrationV2DomainEvent,
11} from "@t3tools/contracts";
12import { assert, it } from "@effect/vitest";
13import * as DateTime from "effect/DateTime";
14import * as Deferred from "effect/Deferred";
15import * as Fiber from "effect/Fiber";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Schema from "effect/Schema";
19import * as Stream from "effect/Stream";
20import * as SqlClient from "effect/unstable/sql/SqlClient";
21import * as Statement from "effect/unstable/sql/Statement";
22​
23import {
24 LIVE_STREAM_MAX_ITEMS,
25 LiveStreamBufferError,
26} from "../../orchestration/LiveStreamBudget.ts";
27import { PersistenceDecodeError } from "../Errors.ts";
28import { toShellApplicationEvent } from "../../orchestration-v2/ShellStream.ts";
29import { OrchestrationEventStore } from "../Services/OrchestrationEventStore.ts";
30import { OrchestrationEventStoreLive } from "./OrchestrationEventStore.ts";
31import { SqlitePersistenceMemory } from "./Sqlite.ts";
32const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
33const isLiveStreamBufferError = Schema.is(LiveStreamBufferError);
34​
35const TestLayer = OrchestrationEventStoreLive.pipe(Layer.provideMerge(SqlitePersistenceMemory));
36const layer = it.layer(TestLayer);
37​
38layer("OrchestrationEventStore", (it) => {
39 it.effect("retains only shell metadata from oversized replay and live application events", () =>
40 Effect.scoped(
41 Effect.gen(function* () {
42 const store = yield* OrchestrationEventStore;
43 const afterSequence = yield* store.latestApplicationSequence;
44 const now = yield* DateTime.now;
45 const threadId = ThreadId.make("thread:large-shell-body");
46 const input = "x".repeat(9 * 1024 * 1024);
47 const event: OrchestrationV2DomainEvent = {
48 id: EventId.make("event:large-shell-body:replay"),
49 type: "turn-item.updated",
50 threadId,
51 occurredAt: now,
52 payload: {
53 id: TurnItemId.make("tool:large-shell-body"),
54 type: "command_execution",
55 threadId,
56 runId: null,
57 nodeId: null,
58 providerThreadId: null,
59 providerTurnId: null,
60 nativeItemRef: null,
61 parentItemId: null,
62 ordinal: 1,
63 status: "running",
64 title: "Large command",
65 input,
66 startedAt: now,
67 completedAt: null,
68 updatedAt: now,
69 },
70 };
71 const [replayed] = yield* store.appendAgentEvents({ events: [event] });
72 const pull = yield* Stream.toPull(
73 store.streamProjectedApplicationEvents({
74 afterSequence,
75 project: toShellApplicationEvent,
76 }),
77 );
78 assert.deepEqual(yield* pull, [{ sequence: replayed!.sequence, event: { threadId } }]);
79 const [live] = yield* store.appendAgentEvents({
80 events: [
81 {
82 ...event,
83 id: EventId.make("event:large-shell-body:live"),
84 payload: { ...event.payload, status: "completed", completedAt: now },
85 },
86 ],
87 });
88 yield* store.publishCommitted([live!]);
89 assert.deepEqual(yield* pull, [{ sequence: live!.sequence, event: { threadId } }]);
90 const durable = yield* store
91 .readAgentEvents({ threadId, afterSequence })
92 .pipe(Stream.runCollect);
93 assert.lengthOf(durable, 2);
94 for (const stored of durable) {
95 assert.equal(stored.event.type, "turn-item.updated");
96 if (stored.event.type !== "turn-item.updated") return;
97 assert.equal(stored.event.payload.type, "command_execution");
98 if (stored.event.payload.type !== "command_execution") return;
99 assert.equal(stored.event.payload.input, input);
100 }
101 }),
102 ),
103 );
104​
105 it.effect("stores json columns as strings and replays CLI-origin events", () =>
106 Effect.gen(function* () {
107 const eventStore = yield* OrchestrationEventStore;
108 const sql = yield* SqlClient.SqlClient;
109 const now = "2026-01-01T00:00:00.000Z";
110​
111 const appended = yield* eventStore.append({
112 type: "project.created",
113 eventId: EventId.make("evt-store-roundtrip"),
114 aggregateKind: "project",
115 aggregateId: ProjectId.make("project-roundtrip"),
116 occurredAt: now,
117 commandId: CommandId.make("cmd-store-roundtrip"),
118 causationEventId: null,
119 correlationId: CommandId.make("cmd-store-roundtrip"),
120 metadata: {
121 adapterKey: "codex",
122 origin: {
123 surface: "cli",
124 },
125 },
126 payload: {
127 projectId: ProjectId.make("project-roundtrip"),
128 title: "Roundtrip Project",
129 workspaceRoot: "/tmp/project-roundtrip",
130 defaultModelSelection: null,
131 scripts: [],
132 createdAt: now,
133 updatedAt: now,
134 },
135 });
136​
137 const storedRows = yield* sql<{
138 readonly payloadJson: string;
139 readonly metadataJson: string;
140 }>`
141 SELECT
142 payload_json AS "payloadJson",
143 metadata_json AS "metadataJson"
144 FROM orchestration_events
145 WHERE event_id = ${appended.eventId}
146 `;
147 assert.equal(storedRows.length, 1);
148 assert.equal(typeof storedRows[0]?.payloadJson, "string");
149 assert.equal(typeof storedRows[0]?.metadataJson, "string");
150​
151 const replayed = yield* Stream.runCollect(eventStore.readFromSequence(0, 10)).pipe(
152 Effect.map((chunk) => Array.from(chunk)),
153 );
154 assert.equal(replayed.length, 1);
155 assert.equal(replayed[0]?.type, "project.created");
156 assert.equal(replayed[0]?.metadata.adapterKey, "codex");
157 assert.deepEqual(replayed[0]?.metadata.origin, { surface: "cli" });
158 }),
159 );
160​
161 it.effect("fails with PersistenceDecodeError when stored json is invalid", () =>
162 Effect.gen(function* () {
163 const eventStore = yield* OrchestrationEventStore;
164 const sql = yield* SqlClient.SqlClient;
165 const now = "2026-01-01T00:00:00.000Z";
166​
167 yield* sql`
168 INSERT INTO orchestration_events (
169 event_id,
170 aggregate_kind,
171 stream_id,
172 stream_version,
173 event_type,
174 occurred_at,
175 command_id,
176 causation_event_id,
177 correlation_id,
178 actor_kind,
179 payload_json,
180 metadata_json
181 )
182 VALUES (
183 ${EventId.make("evt-store-invalid-json")},
184 ${"project"},
185 ${ProjectId.make("project-invalid-json")},
186 ${0},
187 ${"project.created"},
188 ${now},
189 ${CommandId.make("cmd-store-invalid-json")},
190 ${null},
191 ${null},
192 ${"server"},
193 ${"{"},
194 ${"{}"}
195 )
196 `;
197​
198 const replayResult = yield* Effect.result(
199 Stream.runCollect(eventStore.readFromSequence(0, 10)),
200 );
201 assert.equal(replayResult._tag, "Failure");
202 if (replayResult._tag === "Failure") {
203 assert.ok(isPersistenceDecodeError(replayResult.failure));
204 assert.ok(
205 replayResult.failure.operation.includes(
206 "OrchestrationEventStore.readFromSequence:decodeRows",
207 ),
208 );
209 }
210 }),
211 );
212​
213 it.effect("orders project and V2 agent events in the retained application event source", () =>
214 Effect.gen(function* () {
215 const eventStore = yield* OrchestrationEventStore;
216 const projectId = ProjectId.make("project-shared-stream");
217 const threadId = ThreadId.make("thread-shared-stream");
218 const providerInstanceId = ProviderInstanceId.make("codex");
219 const occurredAt = DateTime.makeUnsafe("2026-01-02T00:00:00.000Z");
220 const now = DateTime.formatIso(occurredAt);
221 const baselineSequence = yield* eventStore.latestApplicationSequence;
222​
223 const projectEvent = yield* eventStore.append({
224 type: "project.created",
225 eventId: EventId.make("event-project-shared-stream"),
226 aggregateKind: "project",
227 aggregateId: projectId,
228 occurredAt: now,
229 commandId: CommandId.make("command-project-shared-stream"),
230 causationEventId: null,
231 correlationId: CommandId.make("command-project-shared-stream"),
232 metadata: {},
233 payload: {
234 projectId,
235 title: "Shared stream",
236 workspaceRoot: "/tmp/shared-stream",
237 defaultModelSelection: null,
238 scripts: [],
239 createdAt: now,
240 updatedAt: now,
241 },
242 });
243 const [threadEvent] = yield* eventStore.appendAgentEvents({
244 commandId: CommandId.make("command-thread-shared-stream"),
245 events: [
246 {
247 id: EventId.make("event-thread-shared-stream"),
248 type: "thread.created",
249 threadId,
250 providerInstanceId,
251 occurredAt,
252 payload: {
253 id: threadId,
254 projectId,
255 title: "Thread",
256 providerInstanceId,
257 modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
258 runtimeMode: "full-access",
259 interactionMode: "default",
260 branch: null,
261 worktreePath: null,
262 activeProviderThreadId: null,
263 lineage: {
264 rootThreadId: threadId,
265 parentThreadId: null,
266 relationshipToParent: null,
267 },
268 forkedFrom: null,
269 createdBy: "user",
270 creationSource: "web",
271 createdAt: occurredAt,
272 updatedAt: occurredAt,
273 archivedAt: null,
274 settledOverride: null,
275 settledAt: null,
276 lastVisitedAt: null,
277 deletedAt: null,
278 },
279 },
280 ],
281 });
282​
283 const applicationEvents = yield* eventStore
284 .streamApplicationEvents({ afterSequence: baselineSequence })
285 .pipe(
286 Stream.take(2),
287 Stream.runCollect,
288 Effect.map((chunk) => Array.from(chunk)),
289 );
290 assert.deepEqual(
291 applicationEvents.map((event) => event.sequence),
292 [projectEvent.sequence, threadEvent!.sequence],
293 );
294 assert.isTrue("aggregateKind" in applicationEvents[0]!);
295 assert.isTrue("event" in applicationEvents[1]!);
296​
297 const finiteReplay = yield* eventStore
298 .readApplicationEvents({
299 afterSequence: baselineSequence,
300 throughSequence: threadEvent!.sequence,
301 })
302 .pipe(
303 Stream.runCollect,
304 Effect.map((chunk) => Array.from(chunk)),
305 );
306 assert.deepEqual(
307 finiteReplay.map((event) => event.sequence),
308 [projectEvent.sequence, threadEvent!.sequence],
309 );
310​
311 const legacyReplay = yield* eventStore.readFromSequence(projectEvent.sequence - 1).pipe(
312 Stream.runCollect,
313 Effect.map((chunk) => Array.from(chunk)),
314 );
315 assert.deepEqual(
316 legacyReplay.map((event) => event.type),
317 ["project.created"],
318 );
319 }),
320 );
321 it.effect("measures only a bounded thread replay before decoding its payloads", () =>
322 Effect.gen(function* () {
323 const store = yield* OrchestrationEventStore;
324 const sql = yield* SqlClient.SqlClient;
325 const threadId = ThreadId.make("measured-replay-thread");
326 const baseline = yield* store.latestApplicationSequence;
327 const unicodePayload = '{"text":"🦊"}';
328 const oversizedPayload = "{" + "x".repeat(1_048_576);
329 let streamVersion = 0;
330 const insert = Effect.fn(function* (input: {
331 readonly id: string;
332 readonly payload: string;
333 readonly type?: string;
334 readonly threadId?: string;
335 readonly version?: number;
336 }) {
337 const rows = yield* sql<{ readonly sequence: number }>`
338 INSERT INTO orchestration_events (
339 event_id, aggregate_kind, stream_id, stream_version, event_type,
340 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
341 ) VALUES (
342 ${input.id}, 'thread', ${input.threadId ?? threadId},
343 ${streamVersion++}, ${input.type ?? "thread.metadata-updated"},
344 '2026-09-04T00:00:00.000Z', 'server', ${input.payload}, '{}', ${input.version ?? 2}
345 ) RETURNING sequence
346 `;
347 return rows[0]!.sequence;
348 });
349 const first = yield* insert({
350 id: "measured-replay-1",
351 payload: unicodePayload,
352 type: "thread.created",
353 });
354 yield* insert({
355 id: "measured-unrelated",
356 threadId: "other-replay-thread",
357 payload: oversizedPayload,
358 });
359 yield* insert({ id: "measured-legacy", payload: oversizedPayload, version: 1 });
360 const head = yield* insert({ id: "measured-replay-02", payload: oversizedPayload });
361 const later = yield* insert({ id: "measured-replay-003", payload: "{}" });
362 const range = { threadId, afterSequence: baseline, throughSequence: head, maxEvents: 128 };
363 assert.deepEqual(yield* store.getAgentReplayStats(range), {
364 eventCount: 2,
365 rawPayloadBytes: Buffer.byteLength(unicodePayload) + Buffer.byteLength(oversizedPayload),
366 hasCreateEvent: true,
367 });
368 assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: first }), {
369 eventCount: 1,
370 rawPayloadBytes: Buffer.byteLength(oversizedPayload),
371 hasCreateEvent: false,
372 });
373 assert.equal(
374 (yield* store.getAgentReplayStats({ ...range, throughSequence: later, maxEvents: 1 }))
375 .eventCount,
376 2,
377 );
378 assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: later }), {
379 eventCount: 0,
380 rawPayloadBytes: 0,
381 hasCreateEvent: false,
382 });
383 }),
384 );
385});
386​
387for (const phase of ["high-water", "replay"] as const) {
388 it.effect(`bounds application live events while the ${phase} query is blocked`, () =>
389 Effect.scoped(
390 Effect.gen(function* () {
391 const store = yield* OrchestrationEventStore;
392 const now = "2026-01-03T00:00:00.000Z";
393 const projectId = ProjectId.make(`project:blocked-${phase}`);
394 const projectEvent = yield* store.append({
395 type: "project.created",
396 eventId: EventId.make(`event:blocked-${phase}:created`),
397 aggregateKind: "project",
398 aggregateId: projectId,
399 occurredAt: now,
400 commandId: CommandId.make(`command:blocked-${phase}`),
401 causationEventId: null,
402 correlationId: null,
403 metadata: {},
404 payload: {
405 projectId,
406 title: "Blocked stream",
407 workspaceRoot: "/tmp/blocked-stream",
408 defaultModelSelection: null,
409 scripts: [],
410 createdAt: now,
411 updatedAt: now,
412 },
413 });
414 if (projectEvent.type !== "project.created")
415 return yield* Effect.die("Expected project.created");
416 const readStarted = yield* Deferred.make<void>();
417 const readClosed = yield* Deferred.make<void>();
418 const blockRead: Statement.Transformer = (statement) => {
419 const [query] = statement.compile();
420 if (
421 query.includes("FROM orchestration_events") &&
422 query.includes("MAX(sequence)") === (phase === "high-water")
423 ) {
424 return Deferred.succeed(readStarted, undefined).pipe(
425 Effect.andThen(Effect.never),
426 Effect.ensuring(Deferred.succeed(readClosed, undefined)),
427 Effect.as(statement),
428 );
429 }
430 return Effect.succeed(statement);
431 };
432 const reader = yield* store
433 .streamApplicationEvents({ afterSequence: projectEvent.sequence })
434 .pipe(
435 Stream.provideService(Statement.CurrentTransformer, blockRead),
436 Stream.runDrain,
437 Effect.result,
438 Effect.forkScoped,
439 );
440 yield* Deferred.await(readStarted);
441 yield* store.publishCommitted(
442 Array.from({ length: LIVE_STREAM_MAX_ITEMS + 1 }, (_, index) => ({
443 ...projectEvent,
444 eventId: EventId.make(`event:blocked-${phase}:${index}`),
445 sequence: projectEvent.sequence + index + 1,
446 })),
447 );
448 yield* Deferred.await(readClosed);
449 const result = yield* Fiber.join(reader);
450 assert.equal(result._tag, "Failure");
451 if (result._tag === "Failure") {
452 assert.equal(result.failure._tag, "PersistenceSqlError");
453 assert.isTrue(isLiveStreamBufferError(result.failure.cause));
454 }
455 }),
456 ).pipe(Effect.provide(Layer.fresh(TestLayer))),
457 );
459​
460it.effect("releases consumed application replay pages", () =>
461 Effect.gen(function* () {
462 const store = yield* OrchestrationEventStore;
463 const afterSequence = yield* store.latestApplicationSequence;
464 yield* Effect.forEach(
465 Array.from({ length: 1501 }, (_, index) => index),
466 (index) =>
467 store.append({
468 type: "project.created",
469 eventId: EventId.make(`retention-${index}`),
470 aggregateKind: "project",
471 aggregateId: ProjectId.make(`retention-${index}`),
472 occurredAt: "2026-09-08T00:00:00Z",
473 commandId: null,
474 causationEventId: null,
475 correlationId: null,
476 metadata: {},
477 payload: {
478 projectId: ProjectId.make(`retention-${index}`),
479 title: "Replay",
480 workspaceRoot: "/tmp/replay",
481 defaultModelSelection: null,
482 scripts: [],
483 createdAt: "2026-09-08T00:00:00Z",
484 updatedAt: "2026-09-08T00:00:00Z",
485 },
486 }),
487 { discard: true },
488 );
489 // oxlint-disable-next-line typescript/no-extraneous-class -- Counts retained page markers after full GC.
490 class ReplayPage {}
491 let count = 0;
492 yield* store
493 .readApplicationEvents({
494 afterSequence,
495 throughSequence: yield* store.latestApplicationSequence,
496 })
497 .pipe(
498 Stream.runForEach((event) =>
499 Effect.sync(() => {
500 if (count % 500 === 0) {
501 Object.assign(event, { replayPage: new ReplayPage() });
502 assert.isAtMost(NodeV8.queryObjects(ReplayPage, { format: "count" }), 1);
503 }
504 count++;
505 }),
506 ),
507 );
508 assert.equal(count, 1501);
509 }).pipe(Effect.provide(TestLayer)),
510);