Open History to see the last commit
1import * as NodeV8 from "node:v8";
2
3import {
4 CommandId,
5 EventId,
6 NodeId,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ThreadId,
11 TurnItemId,
12 type OrchestrationV2DomainEvent,
13} from "@t3tools/contracts";
14import { assert, it } from "@effect/vitest";
15import * as DateTime from "effect/DateTime";
16import * as Deferred from "effect/Deferred";
17import * as Fiber from "effect/Fiber";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as Schema from "effect/Schema";
21import * as Stream from "effect/Stream";
22import * as SqlClient from "effect/sql/SqlClient";
23import * as Statement from "effect/sql/Statement";
24
25import {
26 LIVE_STREAM_MAX_ITEMS,
27 LiveStreamBufferError,
28} from "../orchestration-v2/LiveStreamBudget.ts";
29import { PersistenceDecodeError } from "./Errors.ts";
30import { toShellApplicationEvent } from "../orchestration-v2/ShellStream.ts";
31import * as OrchestrationEventStore from "./OrchestrationEventStore.ts";
32import * as SqlitePersistence from "./Sqlite.ts";
33const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
34const isLiveStreamBufferError = Schema.is(LiveStreamBufferError);
35
36const layerTest = OrchestrationEventStore.layer.pipe(
37 Layer.provideMerge(SqlitePersistence.layerMemory),
38);
39const layer = it.layer(layerTest);
40
41layer("OrchestrationEventStore", (it) => {
42 it.effect("retains only shell metadata from oversized replay and live application events", () =>
43 Effect.scoped(
44 Effect.gen(function* () {
45 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
46 const afterSequence = yield* store.latestApplicationSequence;
47 const now = yield* DateTime.now;
48 const threadId = ThreadId.make("thread:large-shell-body");
49 const input = "x".repeat(9 * 1024 * 1024);
50 const event: OrchestrationV2DomainEvent = {
51 id: EventId.make("event:large-shell-body:replay"),
52 type: "turn-item.updated",
53 threadId,
54 occurredAt: now,
55 payload: {
56 id: TurnItemId.make("tool:large-shell-body"),
57 type: "command_execution",
58 threadId,
59 runId: null,
60 nodeId: null,
61 providerThreadId: null,
62 providerTurnId: null,
63 nativeItemRef: null,
64 parentItemId: null,
65 ordinal: 1,
66 status: "running",
67 title: "Large command",
68 input,
69 startedAt: now,
70 completedAt: null,
71 updatedAt: now,
72 },
73 };
74 const [replayed] = yield* store.appendAgentEvents({ events: [event] });
75 const pull = yield* Stream.toPull(
76 store.streamProjectedApplicationEvents({
77 afterSequence,
78 project: toShellApplicationEvent,
79 }),
80 );
81 assert.deepEqual(yield* pull, [{ sequence: replayed!.sequence, event: { threadId } }]);
82 const [live] = yield* store.appendAgentEvents({
83 events: [
84 {
85 ...event,
86 id: EventId.make("event:large-shell-body:live"),
87 payload: { ...event.payload, status: "completed", completedAt: now },
88 },
89 ],
90 });
91 yield* store.publishCommitted([live!]);
92 assert.deepEqual(yield* pull, [{ sequence: live!.sequence, event: { threadId } }]);
93 const durable = yield* store
94 .readAgentEvents({ threadId, afterSequence })
95 .pipe(Stream.runCollect);
96 assert.lengthOf(durable, 2);
97 for (const stored of durable) {
98 assert.equal(stored.event.type, "turn-item.updated");
99 if (stored.event.type !== "turn-item.updated") return;
100 assert.equal(stored.event.payload.type, "command_execution");
101 if (stored.event.payload.type !== "command_execution") return;
102 assert.equal(stored.event.payload.input, input);
103 }
104 }),
105 ),
106 );
107
108 it.effect("stores an unchanged subagent prompt once and replays it on every update", () =>
109 Effect.gen(function* () {
110 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
111 const sql = yield* SqlClient.SqlClient;
112 const afterSequence = yield* store.latestApplicationSequence;
113 const now = yield* DateTime.now;
114 const threadId = ThreadId.make("thread:subagent-prompt");
115 const id = NodeId.make("node:subagent-prompt");
116 const driver = ProviderDriverKind.make("claudeAgent");
117 const providerInstanceId = ProviderInstanceId.make("claudeAgent");
118 const prompt = "Audit the repository. ".repeat(200);
119 const subagent = (index: number, progress: string, nextPrompt = prompt) =>
120 ({
121 id: EventId.make(`event:subagent-prompt:subagent:${index}`),
122 type: "subagent.updated",
123 threadId,
124 occurredAt: now,
125 payload: {
126 id,
127 threadId,
128 runId: null,
129 parentNodeId: NodeId.make("node:subagent-prompt-parent"),
130 origin: "provider_native",
131 createdBy: "agent",
132 driver,
133 providerInstanceId,
134 providerThreadId: null,
135 childThreadId: null,
136 nativeTaskRef: { driver, nativeId: "subagent-prompt", strength: "strong" },
137 prompt: nextPrompt,
138 progress,
139 title: "Audit",
140 model: null,
141 status: "running",
142 result: null,
143 startedAt: now,
144 completedAt: null,
145 updatedAt: now,
146 },
147 }) satisfies OrchestrationV2DomainEvent;
148 const item = (index: number, progress: string, nextPrompt = prompt) =>
149 ({
150 id: EventId.make(`event:subagent-prompt:item:${index}`),
151 type: "turn-item.updated",
152 threadId,
153 occurredAt: now,
154 payload: {
155 id: TurnItemId.make("item:subagent-prompt"),
156 type: "subagent",
157 threadId,
158 runId: null,
159 nodeId: null,
160 providerThreadId: null,
161 providerTurnId: null,
162 nativeItemRef: null,
163 parentItemId: null,
164 ordinal: 1,
165 status: "running",
166 title: "Audit",
167 subagentId: id,
168 origin: "provider_native",
169 driver,
170 providerInstanceId,
171 childThreadId: null,
172 prompt: nextPrompt,
173 progress,
174 result: null,
175 startedAt: now,
176 completedAt: null,
177 updatedAt: now,
178 },
179 }) satisfies OrchestrationV2DomainEvent;
180 const events = [
181 subagent(0, "Reading files"),
182 item(0, "Reading files"),
183 subagent(1, "Running tests"),
184 item(1, "Running tests"),
185 subagent(2, "Writing report"),
186 item(2, "Writing report"),
187 subagent(3, "Retrying", "Audit again."),
188 item(3, "Retrying", "Audit again."),
189 ];
190 yield* store.appendAgentEvents({ events });
191
192 const stored = yield* sql<{ readonly payload_json: string }>`
193 SELECT payload_json FROM orchestration_events
194 WHERE stream_id = ${threadId} ORDER BY sequence ASC
195 `;
196 assert.deepEqual(
197 stored.map((row) => row.payload_json.includes(prompt)),
198 [true, true, false, false, false, false, false, false],
199 );
200 const replayed = yield* store
201 .readAgentEvents({ threadId, afterSequence })
202 .pipe(Stream.runCollect);
203 assert.deepEqual(
204 replayed.map((entry) => entry.event),
205 events,
206 );
207 const stats = yield* store.getAgentReplayStats({
208 threadId,
209 afterSequence,
210 throughSequence: yield* store.latestApplicationSequence,
211 maxEvents: events.length,
212 });
213 assert.isAbove(stats.rawPayloadBytes, prompt.length * 6);
214 const applicationStats = yield* store.getReplayStats({
215 afterSequence,
216 throughSequence: yield* store.latestApplicationSequence,
217 });
218 assert.isAbove(applicationStats.rawPayloadBytes, prompt.length * 6);
219 }),
220 );
221
222 it.effect("stores the full subagent prompt when its hint row was rolled back", () =>
223 Effect.gen(function* () {
224 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
225 const sql = yield* SqlClient.SqlClient;
226 const afterSequence = yield* store.latestApplicationSequence;
227 const now = yield* DateTime.now;
228 const threadId = ThreadId.make("thread:subagent-rollback");
229 const event = {
230 id: EventId.make("event:subagent-rollback"),
231 type: "subagent.updated",
232 threadId,
233 occurredAt: now,
234 payload: {
235 id: NodeId.make("node:subagent-rollback"),
236 threadId,
237 runId: null,
238 parentNodeId: NodeId.make("node:subagent-rollback-parent"),
239 origin: "provider_native",
240 createdBy: "agent",
241 driver: ProviderDriverKind.make("claudeAgent"),
242 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
243 providerThreadId: null,
244 childThreadId: null,
245 nativeTaskRef: null,
246 prompt: "Audit the repository. ".repeat(200),
247 progress: "Reading files",
248 title: "Audit",
249 model: null,
250 status: "running",
251 result: null,
252 startedAt: now,
253 completedAt: null,
254 updatedAt: now,
255 },
256 } satisfies OrchestrationV2DomainEvent;
257 const rolledBack = yield* sql
258 .withTransaction(
259 store
260 .appendAgentEvents({ events: [event] })
261 .pipe(Effect.andThen(Effect.fail("rollback"))),
262 )
263 .pipe(Effect.flip);
264 assert.equal(rolledBack, "rollback");
265 const rowsAfterRollback = yield* sql`
266 SELECT sequence FROM orchestration_events WHERE stream_id = ${threadId}
267 `;
268 assert.deepEqual(rowsAfterRollback, []);
269
270 const events = [event, { ...event, id: EventId.make("event:subagent-after-rollback") }];
271 const appended = yield* store.appendAgentEvents({ events });
272 assert.deepEqual(
273 appended.map((entry) => entry.event),
274 events,
275 );
276 const stored = yield* sql<{
277 readonly prompt: string | null;
278 readonly prompt_sequence: number | null;
279 }>`
280 SELECT json_extract(payload_json, '$.prompt') AS prompt,
281 json_extract(payload_json, '$.promptSequence') AS prompt_sequence
282 FROM orchestration_events WHERE stream_id = ${threadId} ORDER BY sequence
283 `;
284 assert.deepEqual(stored, [
285 { prompt: event.payload.prompt, prompt_sequence: null },
286 { prompt: "", prompt_sequence: appended[0]!.sequence },
287 ]);
288 const replayed = yield* store.readAgentEvents({ threadId }).pipe(Stream.runCollect);
289 assert.deepEqual(replayed, appended);
290 const applicationEvents = yield* store
291 .readApplicationEvents({
292 afterSequence,
293 throughSequence: appended[1]!.sequence,
294 })
295 .pipe(Stream.runCollect);
296 assert.deepEqual(applicationEvents, [...appended]);
297 }),
298 );
299
300 it.effect("stores json columns as strings and replays CLI-origin events", () =>
301 Effect.gen(function* () {
302 const eventStore = yield* OrchestrationEventStore.OrchestrationEventStore;
303 const sql = yield* SqlClient.SqlClient;
304 const now = "2026-01-01T00:00:00.000Z";
305
306 const appended = yield* eventStore.appendProjectEvent({
307 type: "project.created",
308 eventId: EventId.make("evt-store-roundtrip"),
309 aggregateKind: "project",
310 aggregateId: ProjectId.make("project-roundtrip"),
311 occurredAt: now,
312 commandId: CommandId.make("cmd-store-roundtrip"),
313 causationEventId: null,
314 correlationId: CommandId.make("cmd-store-roundtrip"),
315 metadata: {
316 adapterKey: "codex",
317 origin: {
318 surface: "cli",
319 },
320 },
321 payload: {
322 projectId: ProjectId.make("project-roundtrip"),
323 title: "Roundtrip Project",
324 workspaceRoot: "/tmp/project-roundtrip",
325 defaultModelSelection: null,
326 scripts: [],
327 createdAt: now,
328 updatedAt: now,
329 },
330 });
331
332 const storedRows = yield* sql<{
333 readonly payloadJson: string;
334 readonly metadataJson: string;
335 }>`
336 SELECT
337 payload_json AS "payloadJson",
338 metadata_json AS "metadataJson"
339 FROM orchestration_events
340 WHERE event_id = ${appended.eventId}
341 `;
342 assert.equal(storedRows.length, 1);
343 assert.equal(typeof storedRows[0]?.payloadJson, "string");
344 assert.equal(typeof storedRows[0]?.metadataJson, "string");
345
346 const replayed = yield* eventStore
347 .readApplicationEvents({
348 afterSequence: appended.sequence - 1,
349 throughSequence: appended.sequence,
350 })
351 .pipe(
352 Stream.runCollect,
353 Effect.map((chunk) => Array.from(chunk)),
354 );
355 assert.equal(replayed.length, 1);
356 const [project] = replayed;
357 if (project === undefined || !("aggregateKind" in project)) {
358 return assert.fail("Expected a project event");
359 }
360 assert.equal(project.type, "project.created");
361 assert.equal(project.metadata.adapterKey, "codex");
362 assert.deepEqual(project.metadata.origin, { surface: "cli" });
363 }),
364 );
365
366 it.effect("fails with PersistenceDecodeError when stored json is invalid", () =>
367 Effect.gen(function* () {
368 const eventStore = yield* OrchestrationEventStore.OrchestrationEventStore;
369 const sql = yield* SqlClient.SqlClient;
370 const now = "2026-01-01T00:00:00.000Z";
371
372 yield* sql`
373 INSERT INTO orchestration_events (
374 event_id,
375 aggregate_kind,
376 stream_id,
377 stream_version,
378 event_type,
379 occurred_at,
380 command_id,
381 causation_event_id,
382 correlation_id,
383 actor_kind,
384 payload_json,
385 metadata_json
386 )
387 VALUES (
388 ${EventId.make("evt-store-invalid-json")},
389 ${"project"},
390 ${ProjectId.make("project-invalid-json")},
391 ${0},
392 ${"project.created"},
393 ${now},
394 ${CommandId.make("cmd-store-invalid-json")},
395 ${null},
396 ${null},
397 ${"server"},
398 ${"{"},
399 ${"{}"}
400 )
401 `;
402
403 const replayResult = yield* Effect.result(
404 Stream.runCollect(
405 eventStore.readApplicationEvents({
406 afterSequence: 0,
407 throughSequence: Number.MAX_SAFE_INTEGER,
408 }),
409 ),
410 );
411 assert.equal(replayResult._tag, "Failure");
412 if (replayResult._tag === "Failure") {
413 assert.ok(isPersistenceDecodeError(replayResult.failure));
414 }
415 }),
416 );
417
418 it.effect("orders project and V2 agent events in the retained application event source", () =>
419 Effect.gen(function* () {
420 const eventStore = yield* OrchestrationEventStore.OrchestrationEventStore;
421 const projectId = ProjectId.make("project-shared-stream");
422 const threadId = ThreadId.make("thread-shared-stream");
423 const providerInstanceId = ProviderInstanceId.make("codex");
424 const occurredAt = DateTime.makeUnsafe("2026-01-02T00:00:00.000Z");
425 const now = DateTime.formatIso(occurredAt);
426 const baselineSequence = yield* eventStore.latestApplicationSequence;
427
428 const projectEvent = yield* eventStore.appendProjectEvent({
429 type: "project.created",
430 eventId: EventId.make("event-project-shared-stream"),
431 aggregateKind: "project",
432 aggregateId: projectId,
433 occurredAt: now,
434 commandId: CommandId.make("command-project-shared-stream"),
435 causationEventId: null,
436 correlationId: CommandId.make("command-project-shared-stream"),
437 metadata: {},
438 payload: {
439 projectId,
440 title: "Shared stream",
441 workspaceRoot: "/tmp/shared-stream",
442 defaultModelSelection: null,
443 scripts: [],
444 createdAt: now,
445 updatedAt: now,
446 },
447 });
448 const [threadEvent] = yield* eventStore.appendAgentEvents({
449 commandId: CommandId.make("command-thread-shared-stream"),
450 events: [
451 {
452 id: EventId.make("event-thread-shared-stream"),
453 type: "thread.created",
454 threadId,
455 providerInstanceId,
456 occurredAt,
457 payload: {
458 id: threadId,
459 projectId,
460 title: "Thread",
461 providerInstanceId,
462 modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
463 runtimeMode: "full-access",
464 interactionMode: "default",
465 branch: null,
466 worktreePath: null,
467 activeProviderThreadId: null,
468 lineage: {
469 rootThreadId: threadId,
470 parentThreadId: null,
471 relationshipToParent: null,
472 },
473 forkedFrom: null,
474 createdBy: "user",
475 creationSource: "web",
476 createdAt: occurredAt,
477 updatedAt: occurredAt,
478 archivedAt: null,
479 settledOverride: null,
480 settledAt: null,
481 lastVisitedAt: null,
482 deletedAt: null,
483 },
484 },
485 ],
486 });
487
488 const applicationEvents = yield* eventStore
489 .streamApplicationEvents({ afterSequence: baselineSequence })
490 .pipe(
491 Stream.take(2),
492 Stream.runCollect,
493 Effect.map((chunk) => Array.from(chunk)),
494 );
495 assert.deepEqual(
496 applicationEvents.map((event) => event.sequence),
497 [projectEvent.sequence, threadEvent!.sequence],
498 );
499 assert.isTrue("aggregateKind" in applicationEvents[0]!);
500 assert.isTrue("event" in applicationEvents[1]!);
501
502 const finiteReplay = yield* eventStore
503 .readApplicationEvents({
504 afterSequence: baselineSequence,
505 throughSequence: threadEvent!.sequence,
506 })
507 .pipe(
508 Stream.runCollect,
509 Effect.map((chunk) => Array.from(chunk)),
510 );
511 assert.deepEqual(
512 finiteReplay.map((event) => event.sequence),
513 [projectEvent.sequence, threadEvent!.sequence],
514 );
515 }),
516 );
517 it.effect("measures only a bounded thread replay before decoding its payloads", () =>
518 Effect.gen(function* () {
519 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
520 const sql = yield* SqlClient.SqlClient;
521 const threadId = ThreadId.make("measured-replay-thread");
522 const baseline = yield* store.latestApplicationSequence;
523 const unicodePayload = '{"text":"🦊"}';
524 const oversizedPayload = "{" + "x".repeat(1_048_576);
525 let streamVersion = 0;
526 const insert = Effect.fn(function* (input: {
527 readonly id: string;
528 readonly payload: string;
529 readonly type?: string;
530 readonly threadId?: string;
531 readonly version?: number;
532 }) {
533 const rows = yield* sql<{ readonly sequence: number }>`
534 INSERT INTO orchestration_events (
535 event_id, aggregate_kind, stream_id, stream_version, event_type,
536 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
537 ) VALUES (
538 ${input.id}, 'thread', ${input.threadId ?? threadId},
539 ${streamVersion++}, ${input.type ?? "thread.metadata-updated"},
540 '2026-09-04T00:00:00.000Z', 'server', ${input.payload}, '{}', ${input.version ?? 2}
541 ) RETURNING sequence
542 `;
543 return rows[0]!.sequence;
544 });
545 const first = yield* insert({
546 id: "measured-replay-1",
547 payload: unicodePayload,
548 type: "thread.created",
549 });
550 yield* insert({
551 id: "measured-unrelated",
552 threadId: "other-replay-thread",
553 payload: oversizedPayload,
554 });
555 yield* insert({ id: "measured-legacy", payload: oversizedPayload, version: 1 });
556 const head = yield* insert({ id: "measured-replay-02", payload: oversizedPayload });
557 const later = yield* insert({ id: "measured-replay-003", payload: "{}" });
558 const range = { threadId, afterSequence: baseline, throughSequence: head, maxEvents: 128 };
559 assert.deepEqual(yield* store.getAgentReplayStats(range), {
560 eventCount: 2,
561 rawPayloadBytes: Buffer.byteLength(unicodePayload) + Buffer.byteLength(oversizedPayload),
562 hasCreateEvent: true,
563 });
564 assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: first }), {
565 eventCount: 1,
566 rawPayloadBytes: Buffer.byteLength(oversizedPayload),
567 hasCreateEvent: false,
568 });
569 assert.equal(
570 (yield* store.getAgentReplayStats({ ...range, throughSequence: later, maxEvents: 1 }))
571 .eventCount,
572 2,
573 );
574 assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: later }), {
575 eventCount: 0,
576 rawPayloadBytes: 0,
577 hasCreateEvent: false,
578 });
579 assert.deepEqual(
580 yield* store.getReplayStats({ afterSequence: baseline, throughSequence: head }),
581 {
582 eventCount: 3,
583 rawPayloadBytes:
584 Buffer.byteLength(unicodePayload) + 2 * Buffer.byteLength(oversizedPayload),
585 },
586 );
587 }),
588 );
589
590 it.effect.each([
591 ["agent", "thread"],
592 ["application", "thread"],
593 ["application", "project"],
594 ] as const)(
595 "%s replay skips unknown %s types but rejects malformed known payloads",
596 ([reader, aggregateKind]) =>
597 Effect.gen(function* () {
598 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
599 const sql = yield* SqlClient.SqlClient;
600 const streamId = ThreadId.make(`skip-unknown:${reader}:${aggregateKind}`);
601 const now = "2026-01-05T00:00:00.000Z";
602 const insertRow = Effect.fnUntraced(function* (
603 version: number,
604 eventType: string,
605 payload: string,
606 ) {
607 const [row] = yield* sql<{ sequence: number }>`
608 INSERT INTO orchestration_events (
609 event_id, aggregate_kind, stream_id, stream_version, event_type,
610 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
611 ) VALUES (
612 ${`${streamId}:${version}`}, ${aggregateKind}, ${streamId}, ${version}, ${eventType},
613 ${now}, 'server', ${payload}, '{}', 2
614 ) RETURNING sequence
615 `;
616 return row!.sequence;
617 });
618 const read = (
619 afterSequence: number,
620 throughSequence: number,
621 skipUnknownEventTypes = false,
622 limit?: number,
623 ) => {
624 const input = { afterSequence, throughSequence, skipUnknownEventTypes };
625 return reader === "agent"
626 ? store
627 .readAgentEvents({
628 ...input,
629 threadId: streamId,
630 ...(limit === undefined ? {} : { limit }),
631 })
632 .pipe(
633 Stream.map((event) => event.sequence),
634 Stream.runCollect,
635 )
636 : store.readApplicationEvents(input).pipe(
637 Stream.map((event) => event.sequence),
638 Stream.runCollect,
639 );
640 };
641 const knownType =
642 aggregateKind === "thread" ? "provider-session.detached" : "project.meta-updated";
643 const knownPayload = JSON.stringify(
644 aggregateKind === "thread"
645 ? { providerSessionId: "session:known", detachedAt: now }
646 : { projectId: streamId, updatedAt: now },
647 );
648 const baseline = yield* store.latestApplicationSequence;
649 const before = yield* insertRow(0, knownType, knownPayload);
650 yield* Effect.forEach(
651 Array.from({ length: 1_000 }, (_, i) => i + 1),
652 (version) => insertRow(version, "future.event", "not JSON"),
653 { discard: true },
654 );
655 yield* insertRow(
656 1_001,
657 aggregateKind === "thread" ? "project.meta-updated" : "provider-session.detached",
658 "{}",
659 );
660 const after = yield* insertRow(1_002, knownType, knownPayload);
661 const highWater = yield* insertRow(1_003, "future.trailing", "{}");
662 yield* insertRow(1_004, knownType, knownPayload);
663 assert.deepEqual(yield* read(baseline, highWater, true), [before, after]);
664 assert.isTrue(isPersistenceDecodeError(yield* read(baseline, highWater).pipe(Effect.flip)));
665 if (reader === "agent") {
666 assert.deepEqual(yield* read(baseline, highWater, true, 2), [before]);
667 }
668 const beforeBroken = yield* store.latestApplicationSequence;
669 const broken = yield* insertRow(
670 1_005,
671 aggregateKind === "thread" ? "thread.metadata-updated" : "project.created",
672 "{}",
673 );
674 assert.isTrue(
675 isPersistenceDecodeError(yield* read(beforeBroken, broken, true).pipe(Effect.flip)),
676 );
677 }),
678 );
679});
680
681it.effect.each(["high-water", "replay"] as const)(
682 "bounds application live events while the %s query is blocked",
683 (phase) =>
684 Effect.scoped(
685 Effect.gen(function* () {
686 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
687 const now = "2026-01-03T00:00:00.000Z";
688 const projectId = ProjectId.make(`project:blocked-${phase}`);
689 const projectEvent = yield* store.appendProjectEvent({
690 type: "project.created",
691 eventId: EventId.make(`event:blocked-${phase}:created`),
692 aggregateKind: "project",
693 aggregateId: projectId,
694 occurredAt: now,
695 commandId: CommandId.make(`command:blocked-${phase}`),
696 causationEventId: null,
697 correlationId: null,
698 metadata: {},
699 payload: {
700 projectId,
701 title: "Blocked stream",
702 workspaceRoot: "/tmp/blocked-stream",
703 defaultModelSelection: null,
704 scripts: [],
705 createdAt: now,
706 updatedAt: now,
707 },
708 });
709 if (projectEvent.type !== "project.created")
710 return yield* Effect.die("Expected project.created");
711 const readStarted = yield* Deferred.make<void>();
712 const readClosed = yield* Deferred.make<void>();
713 const blockRead: Statement.Transformer = (statement) => {
714 const [query] = statement.compile();
715 if (
716 query.includes("FROM orchestration_events") &&
717 query.includes("MAX(sequence)") === (phase === "high-water")
718 ) {
719 return Deferred.succeed(readStarted, undefined).pipe(
720 Effect.andThen(Effect.never),
721 Effect.ensuring(Deferred.succeed(readClosed, undefined)),
722 Effect.as(statement),
723 );
724 }
725 return Effect.succeed(statement);
726 };
727 const reader = yield* store
728 .streamApplicationEvents({ afterSequence: projectEvent.sequence })
729 .pipe(
730 Stream.provideService(Statement.CurrentTransformer, blockRead),
731 Stream.runDrain,
732 Effect.result,
733 Effect.forkScoped,
734 );
735 yield* Deferred.await(readStarted);
736 yield* store.publishCommitted(
737 Array.from({ length: LIVE_STREAM_MAX_ITEMS + 1 }, (_, index) => ({
738 ...projectEvent,
739 eventId: EventId.make(`event:blocked-${phase}:${index}`),
740 sequence: projectEvent.sequence + index + 1,
741 })),
742 );
743 yield* Deferred.await(readClosed);
744 const result = yield* Fiber.join(reader);
745 assert.equal(result._tag, "Failure");
746 if (result._tag === "Failure") {
747 assert.equal(result.failure._tag, "PersistenceSqlError");
748 assert.isTrue(isLiveStreamBufferError(result.failure.cause));
749 }
750 }),
751 ).pipe(Effect.provide(Layer.fresh(layerTest))),
752);
753
754it.effect("releases consumed application replay pages", () =>
755 Effect.gen(function* () {
756 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
757 const afterSequence = yield* store.latestApplicationSequence;
758 yield* Effect.forEach(
759 Array.from({ length: 1501 }, (_, index) => index),
760 (index) =>
761 store.appendProjectEvent({
762 type: "project.created",
763 eventId: EventId.make(`retention-${index}`),
764 aggregateKind: "project",
765 aggregateId: ProjectId.make(`retention-${index}`),
766 occurredAt: "2026-09-08T00:00:00Z",
767 commandId: null,
768 causationEventId: null,
769 correlationId: null,
770 metadata: {},
771 payload: {
772 projectId: ProjectId.make(`retention-${index}`),
773 title: "Replay",
774 workspaceRoot: "/tmp/replay",
775 defaultModelSelection: null,
776 scripts: [],
777 createdAt: "2026-09-08T00:00:00Z",
778 updatedAt: "2026-09-08T00:00:00Z",
779 },
780 }),
781 { discard: true },
782 );
783 // oxlint-disable-next-line typescript/no-extraneous-class -- Counts retained page markers after full GC.
784 class ReplayPage {}
785 let count = 0;
786 yield* store
787 .readApplicationEvents({
788 afterSequence,
789 throughSequence: yield* store.latestApplicationSequence,
790 })
791 .pipe(
792 Stream.runForEach((event) =>
793 Effect.sync(() => {
794 if (count % 500 === 0) {
795 Object.assign(event, { replayPage: new ReplayPage() });
796 assert.isAtMost(NodeV8.queryObjects(ReplayPage, { format: "count" }), 1);
797 }
798 count++;
799 }),
800 ),
801 );
802 assert.equal(count, 1501);
803 }).pipe(Effect.provide(layerTest)),
804);