Open History to see the last commit
1import {
2 CommandId,
3 EventId,
4 NodeId,
5 ProjectId,
6 ProviderDriverKind,
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 an unchanged subagent prompt once and replays it on every update", () =>
107 Effect.gen(function* () {
108 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
109 const sql = yield* SqlClient.SqlClient;
110 const afterSequence = yield* store.latestApplicationSequence;
111 const now = yield* DateTime.now;
112 const threadId = ThreadId.make("thread:subagent-prompt");
113 const id = NodeId.make("node:subagent-prompt");
114 const driver = ProviderDriverKind.make("claudeAgent");
115 const providerInstanceId = ProviderInstanceId.make("claudeAgent");
116 const prompt = "Audit the repository. ".repeat(200);
117 const subagent = (index: number, progress: string, nextPrompt = prompt) =>
118 ({
119 id: EventId.make(`event:subagent-prompt:subagent:${index}`),
120 type: "subagent.updated",
121 threadId,
122 occurredAt: now,
123 payload: {
124 id,
125 threadId,
126 runId: null,
127 parentNodeId: NodeId.make("node:subagent-prompt-parent"),
128 origin: "provider_native",
129 createdBy: "agent",
130 driver,
131 providerInstanceId,
132 providerThreadId: null,
133 childThreadId: null,
134 nativeTaskRef: { driver, nativeId: "subagent-prompt", strength: "strong" },
135 prompt: nextPrompt,
136 progress,
137 title: "Audit",
138 model: null,
139 status: "running",
140 result: null,
141 startedAt: now,
142 completedAt: null,
143 updatedAt: now,
144 },
145 }) satisfies OrchestrationV2DomainEvent;
146 const item = (index: number, progress: string, nextPrompt = prompt) =>
147 ({
148 id: EventId.make(`event:subagent-prompt:item:${index}`),
149 type: "turn-item.updated",
150 threadId,
151 occurredAt: now,
152 payload: {
153 id: TurnItemId.make("item:subagent-prompt"),
154 type: "subagent",
155 threadId,
156 runId: null,
157 nodeId: null,
158 providerThreadId: null,
159 providerTurnId: null,
160 nativeItemRef: null,
161 parentItemId: null,
162 ordinal: 1,
163 status: "running",
164 title: "Audit",
165 subagentId: id,
166 origin: "provider_native",
167 driver,
168 providerInstanceId,
169 childThreadId: null,
170 prompt: nextPrompt,
171 progress,
172 result: null,
173 startedAt: now,
174 completedAt: null,
175 updatedAt: now,
176 },
177 }) satisfies OrchestrationV2DomainEvent;
178 const events = [
179 subagent(0, "Reading files"),
180 item(0, "Reading files"),
181 subagent(1, "Running tests"),
182 item(1, "Running tests"),
183 subagent(2, "Writing report"),
184 item(2, "Writing report"),
185 subagent(3, "Retrying", "Audit again."),
186 item(3, "Retrying", "Audit again."),
187 ];
188 yield* store.appendAgentEvents({ events });
189
190 const stored = yield* sql<{ readonly payload_json: string }>`
191 SELECT payload_json FROM orchestration_events
192 WHERE stream_id = ${threadId} ORDER BY sequence ASC
193 `;
194 assert.deepEqual(
195 stored.map((row) => row.payload_json.includes(prompt)),
196 [true, true, false, false, false, false, false, false],
197 );
198 const replayed = yield* store
199 .readAgentEvents({ threadId, afterSequence })
200 .pipe(Stream.runCollect);
201 assert.deepEqual(
202 replayed.map((entry) => entry.event),
203 events,
204 );
205 const stats = yield* store.getAgentReplayStats({
206 threadId,
207 afterSequence,
208 throughSequence: yield* store.latestApplicationSequence,
209 maxEvents: events.length,
210 });
211 assert.isAbove(stats.rawPayloadBytes, prompt.length * 6);
212 const applicationStats = yield* store.getReplayStats({
213 afterSequence,
214 throughSequence: yield* store.latestApplicationSequence,
215 });
216 assert.isAbove(applicationStats.rawPayloadBytes, prompt.length * 6);
217 }),
218 );
219
220 it.effect("stores the full subagent prompt when its hint row was rolled back", () =>
221 Effect.gen(function* () {
222 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
223 const sql = yield* SqlClient.SqlClient;
224 const afterSequence = yield* store.latestApplicationSequence;
225 const now = yield* DateTime.now;
226 const threadId = ThreadId.make("thread:subagent-rollback");
227 const event = {
228 id: EventId.make("event:subagent-rollback"),
229 type: "subagent.updated",
230 threadId,
231 occurredAt: now,
232 payload: {
233 id: NodeId.make("node:subagent-rollback"),
234 threadId,
235 runId: null,
236 parentNodeId: NodeId.make("node:subagent-rollback-parent"),
237 origin: "provider_native",
238 createdBy: "agent",
239 driver: ProviderDriverKind.make("claudeAgent"),
240 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
241 providerThreadId: null,
242 childThreadId: null,
243 nativeTaskRef: null,
244 prompt: "Audit the repository. ".repeat(200),
245 progress: "Reading files",
246 title: "Audit",
247 model: null,
248 status: "running",
249 result: null,
250 startedAt: now,
251 completedAt: null,
252 updatedAt: now,
253 },
254 } satisfies OrchestrationV2DomainEvent;
255 const rolledBack = yield* sql
256 .withTransaction(
257 store
258 .appendAgentEvents({ events: [event] })
259 .pipe(Effect.andThen(Effect.fail("rollback"))),
260 )
261 .pipe(Effect.flip);
262 assert.equal(rolledBack, "rollback");
263 const rowsAfterRollback = yield* sql`
264 SELECT sequence FROM orchestration_events WHERE stream_id = ${threadId}
265 `;
266 assert.deepEqual(rowsAfterRollback, []);
267
268 const events = [event, { ...event, id: EventId.make("event:subagent-after-rollback") }];
269 const appended = yield* store.appendAgentEvents({ events });
270 assert.deepEqual(
271 appended.map((entry) => entry.event),
272 events,
273 );
274 const stored = yield* sql<{
275 readonly prompt: string | null;
276 readonly prompt_sequence: number | null;
277 }>`
278 SELECT json_extract(payload_json, '$.prompt') AS prompt,
279 json_extract(payload_json, '$.promptSequence') AS prompt_sequence
280 FROM orchestration_events WHERE stream_id = ${threadId} ORDER BY sequence
281 `;
282 assert.deepEqual(stored, [
283 { prompt: event.payload.prompt, prompt_sequence: null },
284 { prompt: "", prompt_sequence: appended[0]!.sequence },
285 ]);
286 const replayed = yield* store.readAgentEvents({ threadId }).pipe(Stream.runCollect);
287 assert.deepEqual(replayed, appended);
288 const applicationEvents = yield* store
289 .readApplicationEvents({
290 afterSequence,
291 throughSequence: appended[1]!.sequence,
292 })
293 .pipe(Stream.runCollect);
294 assert.deepEqual(applicationEvents, [...appended]);
295 }),
296 );
297
298 // Every snapshot the paragraph filter passes is appended holding the full text so far.
299 it.effect(
300 "stores snapshots of a long stream whose combined text stays within a few times its final text",
301 () =>
302 Effect.gen(function* () {
303 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
304 const sql = yield* SqlClient.SqlClient;
305 const now = yield* DateTime.now;
306 const threadId = ThreadId.make("thread:long-stream");
307 const reasoning = (index: number, text: string, streaming = true) =>
308 ({
309 id: EventId.make(`event:long-stream:${index}`),
310 type: "turn-item.updated",
311 threadId,
312 occurredAt: now,
313 payload: {
314 id: TurnItemId.make("item:long-stream"),
315 type: "reasoning",
316 threadId,
317 runId: null,
318 nodeId: null,
319 providerThreadId: null,
320 providerTurnId: null,
321 nativeItemRef: null,
322 parentItemId: null,
323 ordinal: 1,
324 status: streaming ? "running" : "completed",
325 title: null,
326 text,
327 streaming,
328 startedAt: now,
329 completedAt: streaming ? null : now,
330 updatedAt: now,
331 },
332 }) satisfies OrchestrationV2DomainEvent;
333 const storedTexts = sql<{ readonly text: string }>`
334 SELECT json_extract(payload_json, '$.text') AS text FROM orchestration_events
335 WHERE stream_id = ${threadId} AND event_type = 'turn-item.updated'
336 ORDER BY sequence ASC
337 `.pipe(Effect.map((rows) => rows.map((row) => row.text)));
338 const providerInstanceId = ProviderInstanceId.make("codex");
339 // An open client records a visit every few seconds while the item streams.
340 const visited = (index: number) =>
341 ({
342 id: EventId.make(`event:long-stream:visited:${index}`),
343 type: "thread.visited",
344 threadId,
345 occurredAt: now,
346 payload: {
347 id: threadId,
348 projectId: ProjectId.make("project:long-stream"),
349 title: "Thread",
350 providerInstanceId,
351 modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
352 runtimeMode: "full-access",
353 interactionMode: "default",
354 branch: null,
355 worktreePath: null,
356 activeProviderThreadId: null,
357 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
358 forkedFrom: null,
359 createdBy: "user",
360 creationSource: "web",
361 createdAt: now,
362 updatedAt: now,
363 archivedAt: null,
364 settledOverride: null,
365 settledAt: null,
366 lastVisitedAt: now,
367 deletedAt: null,
368 },
369 }) satisfies OrchestrationV2DomainEvent;
370 const paragraph = `${"Checking the next case in detail. ".repeat(8)}\n\n`;
371 let text = "";
372 for (let index = 0; index < 300; index++) {
373 text += paragraph;
374 if (index % 20 === 0) yield* store.appendAgentEvents({ events: [visited(index)] });
375 const [stored] = yield* store.appendAgentEvents({ events: [reasoning(index, text)] });
376 // Live clients and the projections still get every snapshot.
377 assert.deepEqual(stored?.event, reasoning(index, text));
378 // The newest text is durable after each append, as it was before.
379 assert.equal((yield* storedTexts).at(-1), text);
380 }
381 const storedChars = (yield* storedTexts).reduce((sum, stored) => sum + stored.length, 0);
382 assert.isAtMost(storedChars, text.length * 4);
383
384 // A snapshot rolled back with its transaction leaves the committed one in place.
385 yield* sql
386 .withTransaction(
387 store
388 .appendAgentEvents({ events: [reasoning(300, `${text}lost`)] })
389 .pipe(Effect.andThen(Effect.fail("rollback"))),
390 )
391 .pipe(Effect.flip);
392 assert.deepEqual(yield* storedTexts, [text]);
393 // The retried write reuses the event id; an event for something else ends the run.
394 const other = { ...reasoning(302, "Other."), id: EventId.make("event:long-stream:other") };
395 yield* store.appendAgentEvents({
396 events: [
397 reasoning(300, `${text}A`),
398 {
399 ...other,
400 payload: { ...other.payload, id: TurnItemId.make("item:long-stream-other") },
401 },
402 reasoning(301, `${text}AB`),
403 reasoning(303, `${text}ABC`, false),
404 ],
405 });
406 assert.deepEqual(yield* storedTexts, [
407 text,
408 `${text}A`,
409 "Other.",
410 `${text}AB`,
411 `${text}ABC`,
412 ]);
413 }),
414 );
415
416 it.effect("orders project and V2 agent events in the retained application event source", () =>
417 Effect.gen(function* () {
418 const eventStore = yield* OrchestrationEventStore.OrchestrationEventStore;
419 const projectId = ProjectId.make("project-shared-stream");
420 const threadId = ThreadId.make("thread-shared-stream");
421 const providerInstanceId = ProviderInstanceId.make("codex");
422 const occurredAt = DateTime.makeUnsafe("2026-01-02T00:00:00.000Z");
423 const now = DateTime.formatIso(occurredAt);
424 const baselineSequence = yield* eventStore.latestApplicationSequence;
425
426 const projectEvent = yield* eventStore.appendProjectEvent({
427 type: "project.created",
428 eventId: EventId.make("event-project-shared-stream"),
429 aggregateKind: "project",
430 aggregateId: projectId,
431 occurredAt: now,
432 commandId: CommandId.make("command-project-shared-stream"),
433 causationEventId: null,
434 correlationId: CommandId.make("command-project-shared-stream"),
435 metadata: {},
436 payload: {
437 projectId,
438 title: "Shared stream",
439 workspaceRoot: "/tmp/shared-stream",
440 defaultModelSelection: null,
441 scripts: [],
442 createdAt: now,
443 updatedAt: now,
444 },
445 });
446 const [threadEvent] = yield* eventStore.appendAgentEvents({
447 commandId: CommandId.make("command-thread-shared-stream"),
448 events: [
449 {
450 id: EventId.make("event-thread-shared-stream"),
451 type: "thread.created",
452 threadId,
453 providerInstanceId,
454 occurredAt,
455 payload: {
456 id: threadId,
457 projectId,
458 title: "Thread",
459 providerInstanceId,
460 modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
461 runtimeMode: "full-access",
462 interactionMode: "default",
463 branch: null,
464 worktreePath: null,
465 activeProviderThreadId: null,
466 lineage: {
467 rootThreadId: threadId,
468 parentThreadId: null,
469 relationshipToParent: null,
470 },
471 forkedFrom: null,
472 createdBy: "user",
473 creationSource: "web",
474 createdAt: occurredAt,
475 updatedAt: occurredAt,
476 archivedAt: null,
477 settledOverride: null,
478 settledAt: null,
479 lastVisitedAt: null,
480 deletedAt: null,
481 },
482 },
483 ],
484 });
485
486 const applicationEvents = yield* eventStore
487 .streamApplicationEvents({ afterSequence: baselineSequence })
488 .pipe(
489 Stream.take(2),
490 Stream.runCollect,
491 Effect.map((chunk) => Array.from(chunk)),
492 );
493 assert.deepEqual(
494 applicationEvents.map((event) => event.sequence),
495 [projectEvent.sequence, threadEvent!.sequence],
496 );
497 assert.isTrue("aggregateKind" in applicationEvents[0]!);
498 assert.isTrue("event" in applicationEvents[1]!);
499
500 const finiteReplay = yield* eventStore
501 .readApplicationEvents({
502 afterSequence: baselineSequence,
503 throughSequence: threadEvent!.sequence,
504 })
505 .pipe(
506 Stream.runCollect,
507 Effect.map((chunk) => Array.from(chunk)),
508 );
509 assert.deepEqual(
510 finiteReplay.map((event) => event.sequence),
511 [projectEvent.sequence, threadEvent!.sequence],
512 );
513 }),
514 );
515 it.effect("measures only a bounded thread replay before decoding its payloads", () =>
516 Effect.gen(function* () {
517 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
518 const sql = yield* SqlClient.SqlClient;
519 const threadId = ThreadId.make("measured-replay-thread");
520 const baseline = yield* store.latestApplicationSequence;
521 const unicodePayload = '{"text":"🦊"}';
522 const oversizedPayload = "{" + "x".repeat(1_048_576);
523 let streamVersion = 0;
524 const insert = Effect.fn(function* (input: {
525 readonly id: string;
526 readonly payload: string;
527 readonly type?: string;
528 readonly threadId?: string;
529 readonly version?: number;
530 }) {
531 const rows = yield* sql<{ readonly sequence: number }>`
532 INSERT INTO orchestration_events (
533 event_id, aggregate_kind, stream_id, stream_version, event_type,
534 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
535 ) VALUES (
536 ${input.id}, 'thread', ${input.threadId ?? threadId},
537 ${streamVersion++}, ${input.type ?? "thread.metadata-updated"},
538 '2026-09-04T00:00:00.000Z', 'server', ${input.payload}, '{}', ${input.version ?? 2}
539 ) RETURNING sequence
540 `;
541 return rows[0]!.sequence;
542 });
543 const first = yield* insert({
544 id: "measured-replay-1",
545 payload: unicodePayload,
546 type: "thread.created",
547 });
548 yield* insert({
549 id: "measured-unrelated",
550 threadId: "other-replay-thread",
551 payload: oversizedPayload,
552 });
553 yield* insert({ id: "measured-legacy", payload: oversizedPayload, version: 1 });
554 const head = yield* insert({ id: "measured-replay-02", payload: oversizedPayload });
555 const later = yield* insert({ id: "measured-replay-003", payload: "{}" });
556 const range = { threadId, afterSequence: baseline, throughSequence: head, maxEvents: 128 };
557 assert.deepEqual(yield* store.getAgentReplayStats(range), {
558 eventCount: 2,
559 rawPayloadBytes: Buffer.byteLength(unicodePayload) + Buffer.byteLength(oversizedPayload),
560 hasCreateEvent: true,
561 });
562 assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: first }), {
563 eventCount: 1,
564 rawPayloadBytes: Buffer.byteLength(oversizedPayload),
565 hasCreateEvent: false,
566 });
567 assert.equal(
568 (yield* store.getAgentReplayStats({ ...range, throughSequence: later, maxEvents: 1 }))
569 .eventCount,
570 2,
571 );
572 assert.deepEqual(yield* store.getAgentReplayStats({ ...range, afterSequence: later }), {
573 eventCount: 0,
574 rawPayloadBytes: 0,
575 hasCreateEvent: false,
576 });
577 assert.deepEqual(
578 yield* store.getReplayStats({ afterSequence: baseline, throughSequence: head }),
579 {
580 eventCount: 3,
581 rawPayloadBytes:
582 Buffer.byteLength(unicodePayload) + 2 * Buffer.byteLength(oversizedPayload),
583 },
584 );
585 }),
586 );
587
588 it.effect.each([
589 ["agent", "thread"],
590 ["application", "thread"],
591 ["application", "project"],
592 ] as const)(
593 "%s replay skips unknown %s types but rejects malformed known payloads",
594 ([reader, aggregateKind]) =>
595 Effect.gen(function* () {
596 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
597 const sql = yield* SqlClient.SqlClient;
598 const streamId = ThreadId.make(`skip-unknown:${reader}:${aggregateKind}`);
599 const now = "2026-01-05T00:00:00.000Z";
600 const insertRow = Effect.fnUntraced(function* (
601 version: number,
602 eventType: string,
603 payload: string,
604 ) {
605 const [row] = yield* sql<{ sequence: number }>`
606 INSERT INTO orchestration_events (
607 event_id, aggregate_kind, stream_id, stream_version, event_type,
608 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
609 ) VALUES (
610 ${`${streamId}:${version}`}, ${aggregateKind}, ${streamId}, ${version}, ${eventType},
611 ${now}, 'server', ${payload}, '{}', 2
612 ) RETURNING sequence
613 `;
614 return row!.sequence;
615 });
616 const read = (
617 afterSequence: number,
618 throughSequence: number,
619 skipUnknownEventTypes = false,
620 limit?: number,
621 ) => {
622 const input = { afterSequence, throughSequence, skipUnknownEventTypes };
623 return reader === "agent"
624 ? store
625 .readAgentEvents({
626 ...input,
627 threadId: streamId,
628 ...(limit === undefined ? {} : { limit }),
629 })
630 .pipe(
631 Stream.map((event) => event.sequence),
632 Stream.runCollect,
633 )
634 : store.readApplicationEvents(input).pipe(
635 Stream.map((event) => event.sequence),
636 Stream.runCollect,
637 );
638 };
639 const knownType =
640 aggregateKind === "thread" ? "provider-session.detached" : "project.meta-updated";
641 const knownPayload = JSON.stringify(
642 aggregateKind === "thread"
643 ? { providerSessionId: "session:known", detachedAt: now }
644 : { projectId: streamId, updatedAt: now },
645 );
646 const baseline = yield* store.latestApplicationSequence;
647 const before = yield* insertRow(0, knownType, knownPayload);
648 yield* Effect.forEach(
649 Array.from({ length: 1_000 }, (_, i) => i + 1),
650 (version) => insertRow(version, "future.event", "not JSON"),
651 { discard: true },
652 );
653 yield* insertRow(
654 1_001,
655 aggregateKind === "thread" ? "project.meta-updated" : "provider-session.detached",
656 "{}",
657 );
658 const after = yield* insertRow(1_002, knownType, knownPayload);
659 const highWater = yield* insertRow(1_003, "future.trailing", "{}");
660 yield* insertRow(1_004, knownType, knownPayload);
661 assert.deepEqual(yield* read(baseline, highWater, true), [before, after]);
662 assert.isTrue(isPersistenceDecodeError(yield* read(baseline, highWater).pipe(Effect.flip)));
663 if (reader === "agent") {
664 assert.deepEqual(yield* read(baseline, highWater, true, 2), [before]);
665 }
666 const beforeBroken = yield* store.latestApplicationSequence;
667 const broken = yield* insertRow(
668 1_005,
669 aggregateKind === "thread" ? "thread.metadata-updated" : "project.created",
670 "{}",
671 );
672 assert.isTrue(
673 isPersistenceDecodeError(yield* read(beforeBroken, broken, true).pipe(Effect.flip)),
674 );
675 }),
676 );
677});
678
679it.effect.each(["high-water", "replay"] as const)(
680 "bounds application live events while the %s query is blocked",
681 (phase) =>
682 Effect.scoped(
683 Effect.gen(function* () {
684 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
685 const now = "2026-01-03T00:00:00.000Z";
686 const projectId = ProjectId.make(`project:blocked-${phase}`);
687 const projectEvent = yield* store.appendProjectEvent({
688 type: "project.created",
689 eventId: EventId.make(`event:blocked-${phase}:created`),
690 aggregateKind: "project",
691 aggregateId: projectId,
692 occurredAt: now,
693 commandId: CommandId.make(`command:blocked-${phase}`),
694 causationEventId: null,
695 correlationId: null,
696 metadata: {},
697 payload: {
698 projectId,
699 title: "Blocked stream",
700 workspaceRoot: "/tmp/blocked-stream",
701 defaultModelSelection: null,
702 scripts: [],
703 createdAt: now,
704 updatedAt: now,
705 },
706 });
707 if (projectEvent.type !== "project.created")
708 return yield* Effect.die("Expected project.created");
709 const readStarted = yield* Deferred.make<void>();
710 const readClosed = yield* Deferred.make<void>();
711 const blockRead: Statement.Transformer = (statement) => {
712 const [query] = statement.compile();
713 if (
714 query.includes("FROM orchestration_events") &&
715 query.includes("MAX(sequence)") === (phase === "high-water")
716 ) {
717 return Deferred.succeed(readStarted, undefined).pipe(
718 Effect.andThen(Effect.never),
719 Effect.ensuring(Deferred.succeed(readClosed, undefined)),
720 Effect.as(statement),
721 );
722 }
723 return Effect.succeed(statement);
724 };
725 const reader = yield* store
726 .streamApplicationEvents({ afterSequence: projectEvent.sequence })
727 .pipe(
728 Stream.provideService(Statement.CurrentTransformer, blockRead),
729 Stream.runDrain,
730 Effect.result,
731 Effect.forkScoped,
732 );
733 yield* Deferred.await(readStarted);
734 yield* store.publishCommitted(
735 Array.from({ length: LIVE_STREAM_MAX_ITEMS + 1 }, (_, index) => ({
736 ...projectEvent,
737 eventId: EventId.make(`event:blocked-${phase}:${index}`),
738 sequence: projectEvent.sequence + index + 1,
739 })),
740 );
741 yield* Deferred.await(readClosed);
742 const result = yield* Fiber.join(reader);
743 assert.equal(result._tag, "Failure");
744 if (result._tag === "Failure") {
745 assert.equal(result.failure._tag, "PersistenceSqlError");
746 assert.isTrue(isLiveStreamBufferError(result.failure.cause));
747 }
748 }),
749 ).pipe(Effect.provide(Layer.fresh(layerTest))),
750);