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

OrchestrationEventStore.test.ts

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