Open History to see the last commit
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-v2/LiveStreamBudget.ts";
27import { PersistenceDecodeError } from "../Errors.ts";
28import { toShellApplicationEvent } from "../../orchestration-v2/ShellStream.ts";
29import * as 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.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.OrchestrationEventStore;
108 const sql = yield* SqlClient.SqlClient;
109 const now = "2026-01-01T00:00:00.000Z";
110
111 const appended = yield* eventStore.appendProjectEvent({
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* eventStore
152 .readApplicationEvents({
153 afterSequence: appended.sequence - 1,
154 throughSequence: appended.sequence,
155 })
156 .pipe(
157 Stream.runCollect,
158 Effect.map((chunk) => Array.from(chunk)),
159 );
160 assert.equal(replayed.length, 1);
161 const [project] = replayed;
162 if (project === undefined || !("aggregateKind" in project)) {
163 return assert.fail("Expected a project event");
164 }
165 assert.equal(project.type, "project.created");
166 assert.equal(project.metadata.adapterKey, "codex");
167 assert.deepEqual(project.metadata.origin, { surface: "cli" });
168 }),
169 );
170
171 it.effect("fails with PersistenceDecodeError when stored json is invalid", () =>
172 Effect.gen(function* () {
173 const eventStore = yield* OrchestrationEventStore.OrchestrationEventStore;
174 const sql = yield* SqlClient.SqlClient;
175 const now = "2026-01-01T00:00:00.000Z";
176
177 yield* sql`
178 INSERT INTO orchestration_events (
179 event_id,
180 aggregate_kind,
181 stream_id,
182 stream_version,
183 event_type,
184 occurred_at,
185 command_id,
186 causation_event_id,
187 correlation_id,
188 actor_kind,
189 payload_json,
190 metadata_json
191 )
192 VALUES (
193 ${EventId.make("evt-store-invalid-json")},
194 ${"project"},
195 ${ProjectId.make("project-invalid-json")},
196 ${0},
197 ${"project.created"},
198 ${now},
199 ${CommandId.make("cmd-store-invalid-json")},
200 ${null},
201 ${null},
202 ${"server"},
203 ${"{"},
204 ${"{}"}
205 )
206 `;
207
208 const replayResult = yield* Effect.result(
209 Stream.runCollect(
210 eventStore.readApplicationEvents({
211 afterSequence: 0,
212 throughSequence: Number.MAX_SAFE_INTEGER,
213 }),
214 ),
215 );
216 assert.equal(replayResult._tag, "Failure");
217 if (replayResult._tag === "Failure") {
218 assert.ok(isPersistenceDecodeError(replayResult.failure));
219 }
220 }),
221 );
222
223 it.effect("orders project and V2 agent events in the retained application event source", () =>
224 Effect.gen(function* () {
225 const eventStore = yield* OrchestrationEventStore.OrchestrationEventStore;
226 const projectId = ProjectId.make("project-shared-stream");
227 const threadId = ThreadId.make("thread-shared-stream");
228 const providerInstanceId = ProviderInstanceId.make("codex");
229 const occurredAt = DateTime.makeUnsafe("2026-01-02T00:00:00.000Z");
230 const now = DateTime.formatIso(occurredAt);
231 const baselineSequence = yield* eventStore.latestApplicationSequence;
232
233 const projectEvent = yield* eventStore.appendProjectEvent({
234 type: "project.created",
235 eventId: EventId.make("event-project-shared-stream"),
236 aggregateKind: "project",
237 aggregateId: projectId,
238 occurredAt: now,
239 commandId: CommandId.make("command-project-shared-stream"),
240 causationEventId: null,
241 correlationId: CommandId.make("command-project-shared-stream"),
242 metadata: {},
243 payload: {
244 projectId,
245 title: "Shared stream",
246 workspaceRoot: "/tmp/shared-stream",
247 defaultModelSelection: null,
248 scripts: [],
249 createdAt: now,
250 updatedAt: now,
251 },
252 });
253 const [threadEvent] = yield* eventStore.appendAgentEvents({
254 commandId: CommandId.make("command-thread-shared-stream"),
255 events: [
256 {
257 id: EventId.make("event-thread-shared-stream"),
258 type: "thread.created",
259 threadId,
260 providerInstanceId,
261 occurredAt,
262 payload: {
263 id: threadId,
264 projectId,
265 title: "Thread",
266 providerInstanceId,
267 modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
268 runtimeMode: "full-access",
269 interactionMode: "default",
270 branch: null,
271 worktreePath: null,
272 activeProviderThreadId: null,
273 lineage: {
274 rootThreadId: threadId,
275 parentThreadId: null,
276 relationshipToParent: null,
277 },
278 forkedFrom: null,
279 createdBy: "user",
280 creationSource: "web",
281 createdAt: occurredAt,
282 updatedAt: occurredAt,
283 archivedAt: null,
284 settledOverride: null,
285 settledAt: null,
286 lastVisitedAt: null,
287 deletedAt: null,
288 },
289 },
290 ],
291 });
292
293 const applicationEvents = yield* eventStore
294 .streamApplicationEvents({ afterSequence: baselineSequence })
295 .pipe(
296 Stream.take(2),
297 Stream.runCollect,
298 Effect.map((chunk) => Array.from(chunk)),
299 );
300 assert.deepEqual(
301 applicationEvents.map((event) => event.sequence),
302 [projectEvent.sequence, threadEvent!.sequence],
303 );
304 assert.isTrue("aggregateKind" in applicationEvents[0]!);
305 assert.isTrue("event" in applicationEvents[1]!);
306
307 const finiteReplay = yield* eventStore
308 .readApplicationEvents({
309 afterSequence: baselineSequence,
310 throughSequence: threadEvent!.sequence,
311 })
312 .pipe(
313 Stream.runCollect,
314 Effect.map((chunk) => Array.from(chunk)),
315 );
316 assert.deepEqual(
317 finiteReplay.map((event) => event.sequence),
318 [projectEvent.sequence, threadEvent!.sequence],
319 );
320 }),
321 );
322 it.effect("measures only a bounded thread replay before decoding its payloads", () =>
323 Effect.gen(function* () {
324 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
325 const sql = yield* SqlClient.SqlClient;
326 const threadId = ThreadId.make("measured-replay-thread");
327 const baseline = yield* store.latestApplicationSequence;
328 const unicodePayload = '{"text":"🦊"}';
329 const oversizedPayload = "{" + "x".repeat(1_048_576);
330 let streamVersion = 0;
331 const insert = Effect.fn(function* (input: {
332 readonly id: string;
333 readonly payload: string;
334 readonly type?: string;
335 readonly threadId?: string;
336 readonly version?: number;
337 }) {
338 const rows = yield* sql<{ readonly sequence: number }>`
339 INSERT INTO orchestration_events (
340 event_id, aggregate_kind, stream_id, stream_version, event_type,
341 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
342 ) VALUES (
343 ${input.id}, 'thread', ${input.threadId ?? threadId},
344 ${streamVersion++}, ${input.type ?? "thread.metadata-updated"},
345 '2026-09-04T00:00:00.000Z', 'server', ${input.payload}, '{}', ${input.version ?? 2}
346 ) RETURNING sequence
347 `;
348 return rows[0]!.sequence;
349 });
350 const first = yield* insert({
351 id: "measured-replay-1",
352 payload: unicodePayload,
353 type: "thread.created",
354 });
355 yield* insert({
356 id: "measured-unrelated",
357 threadId: "other-replay-thread",
358 payload: oversizedPayload,
359 });
360 yield* insert({ id: "measured-legacy", payload: oversizedPayload, version: 1 });
361 const head = yield* insert({ id: "measured-replay-02", payload: oversizedPayload });
362 const later = yield* insert({ id: "measured-replay-003", payload: "{}" });
363 const range = { threadId, afterSequence: baseline, throughSequence: head, maxEvents: 128 };
364 assert.deepEqual(yield* store.getAgentReplayStats(range), {
365 eventCount: 2,
366 rawPayloadBytes: Buffer.byteLength(unicodePayload) + Buffer.byteLength(oversizedPayload),
367 hasCreateEvent: true,
368 });
369 assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: first }), {
370 eventCount: 1,
371 rawPayloadBytes: Buffer.byteLength(oversizedPayload),
372 hasCreateEvent: false,
373 });
374 assert.equal(
375 (yield* store.getAgentReplayStats({ ...range, throughSequence: later, maxEvents: 1 }))
376 .eventCount,
377 2,
378 );
379 assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: later }), {
380 eventCount: 0,
381 rawPayloadBytes: 0,
382 hasCreateEvent: false,
383 });
384 // The application range skips V1 rows, which a shell resume never replays.
385 assert.deepEqual(
386 yield* store.getReplayStats({ afterSequence: baseline, throughSequence: head }),
387 {
388 eventCount: 3,
389 rawPayloadBytes:
390 Buffer.byteLength(unicodePayload) + 2 * Buffer.byteLength(oversizedPayload),
391 },
392 );
393 }),
394 );
395});
396
397it.effect.each(["high-water", "replay"] as const)(
398 "bounds application live events while the %s query is blocked",
399 (phase) =>
400 Effect.scoped(
401 Effect.gen(function* () {
402 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
403 const now = "2026-01-03T00:00:00.000Z";
404 const projectId = ProjectId.make(`project:blocked-${phase}`);
405 const projectEvent = yield* store.appendProjectEvent({
406 type: "project.created",
407 eventId: EventId.make(`event:blocked-${phase}:created`),
408 aggregateKind: "project",
409 aggregateId: projectId,
410 occurredAt: now,
411 commandId: CommandId.make(`command:blocked-${phase}`),
412 causationEventId: null,
413 correlationId: null,
414 metadata: {},
415 payload: {
416 projectId,
417 title: "Blocked stream",
418 workspaceRoot: "/tmp/blocked-stream",
419 defaultModelSelection: null,
420 scripts: [],
421 createdAt: now,
422 updatedAt: now,
423 },
424 });
425 if (projectEvent.type !== "project.created")
426 return yield* Effect.die("Expected project.created");
427 const readStarted = yield* Deferred.make<void>();
428 const readClosed = yield* Deferred.make<void>();
429 const blockRead: Statement.Transformer = (statement) => {
430 const [query] = statement.compile();
431 if (
432 query.includes("FROM orchestration_events") &&
433 query.includes("MAX(sequence)") === (phase === "high-water")
434 ) {
435 return Deferred.succeed(readStarted, undefined).pipe(
436 Effect.andThen(Effect.never),
437 Effect.ensuring(Deferred.succeed(readClosed, undefined)),
438 Effect.as(statement),
439 );
440 }
441 return Effect.succeed(statement);
442 };
443 const reader = yield* store
444 .streamApplicationEvents({ afterSequence: projectEvent.sequence })
445 .pipe(
446 Stream.provideService(Statement.CurrentTransformer, blockRead),
447 Stream.runDrain,
448 Effect.result,
449 Effect.forkScoped,
450 );
451 yield* Deferred.await(readStarted);
452 yield* store.publishCommitted(
453 Array.from({ length: LIVE_STREAM_MAX_ITEMS + 1 }, (_, index) => ({
454 ...projectEvent,
455 eventId: EventId.make(`event:blocked-${phase}:${index}`),
456 sequence: projectEvent.sequence + index + 1,
457 })),
458 );
459 yield* Deferred.await(readClosed);
460 const result = yield* Fiber.join(reader);
461 assert.equal(result._tag, "Failure");
462 if (result._tag === "Failure") {
463 assert.equal(result.failure._tag, "PersistenceSqlError");
464 assert.isTrue(isLiveStreamBufferError(result.failure.cause));
465 }
466 }),
467 ).pipe(Effect.provide(Layer.fresh(TestLayer))),
468);
469
470it.effect("releases consumed application replay pages", () =>
471 Effect.gen(function* () {
472 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
473 const afterSequence = yield* store.latestApplicationSequence;
474 yield* Effect.forEach(
475 Array.from({ length: 1501 }, (_, index) => index),
476 (index) =>
477 store.appendProjectEvent({
478 type: "project.created",
479 eventId: EventId.make(`retention-${index}`),
480 aggregateKind: "project",
481 aggregateId: ProjectId.make(`retention-${index}`),
482 occurredAt: "2026-09-08T00:00:00Z",
483 commandId: null,
484 causationEventId: null,
485 correlationId: null,
486 metadata: {},
487 payload: {
488 projectId: ProjectId.make(`retention-${index}`),
489 title: "Replay",
490 workspaceRoot: "/tmp/replay",
491 defaultModelSelection: null,
492 scripts: [],
493 createdAt: "2026-09-08T00:00:00Z",
494 updatedAt: "2026-09-08T00:00:00Z",
495 },
496 }),
497 { discard: true },
498 );
499 // oxlint-disable-next-line typescript/no-extraneous-class -- Counts retained page markers after full GC.
500 class ReplayPage {}
501 let count = 0;
502 yield* store
503 .readApplicationEvents({
504 afterSequence,
505 throughSequence: yield* store.latestApplicationSequence,
506 })
507 .pipe(
508 Stream.runForEach((event) =>
509 Effect.sync(() => {
510 if (count % 500 === 0) {
511 Object.assign(event, { replayPage: new ReplayPage() });
512 assert.isAtMost(NodeV8.queryObjects(ReplayPage, { format: "count" }), 1);
513 }
514 count++;
515 }),
516 ),
517 );
518 assert.equal(count, 1501);
519 }).pipe(Effect.provide(TestLayer)),
520);