Open History to see the last commit
1import {
2 CommandId,
3 EventId,
4 MessageId,
5 ProjectId,
6 ThreadId,
7 type OrchestrationEvent,
8} from "@t3tools/contracts";
9import { assert, it } from "@effect/vitest";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14import * as SqlClient from "effect/unstable/sql/SqlClient";
15
16import { PersistenceDecodeError } from "../Errors.ts";
17import { OrchestrationEventStore } from "../Services/OrchestrationEventStore.ts";
18import { OrchestrationEventStoreLive } from "./OrchestrationEventStore.ts";
19import { SqlitePersistenceMemory } from "./Sqlite.ts";
20const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
21
22function messageEvent(threadId: ThreadId, id: string): Omit<OrchestrationEvent, "sequence"> {
23 const now = "2026-01-01T00:00:00.000Z";
24 return {
25 type: "thread.message-sent",
26 eventId: EventId.make(id),
27 aggregateKind: "thread",
28 aggregateId: threadId,
29 occurredAt: now,
30 commandId: null,
31 causationEventId: null,
32 correlationId: null,
33 metadata: {},
34 payload: {
35 threadId,
36 messageId: MessageId.make(id),
37 role: "assistant",
38 text: id,
39 turnId: null,
40 streaming: false,
41 createdAt: now,
42 updatedAt: now,
43 },
44 };
45}
46
47const layer = it.layer(
48 OrchestrationEventStoreLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
49);
50
51layer("OrchestrationEventStore", (it) => {
52 it.effect("stores json columns as strings and replays CLI-origin events", () =>
53 Effect.gen(function* () {
54 const eventStore = yield* OrchestrationEventStore;
55 const sql = yield* SqlClient.SqlClient;
56 const now = "2026-01-01T00:00:00.000Z";
57
58 const appended = yield* eventStore.append({
59 type: "project.created",
60 eventId: EventId.make("evt-store-roundtrip"),
61 aggregateKind: "project",
62 aggregateId: ProjectId.make("project-roundtrip"),
63 occurredAt: now,
64 commandId: CommandId.make("cmd-store-roundtrip"),
65 causationEventId: null,
66 correlationId: CommandId.make("cmd-store-roundtrip"),
67 metadata: {
68 adapterKey: "codex",
69 origin: {
70 surface: "cli",
71 },
72 },
73 payload: {
74 projectId: ProjectId.make("project-roundtrip"),
75 title: "Roundtrip Project",
76 workspaceRoot: "/tmp/project-roundtrip",
77 defaultModelSelection: null,
78 scripts: [],
79 createdAt: now,
80 updatedAt: now,
81 },
82 });
83
84 const storedRows = yield* sql<{
85 readonly payloadJson: string;
86 readonly metadataJson: string;
87 }>`
88 SELECT
89 payload_json AS "payloadJson",
90 metadata_json AS "metadataJson"
91 FROM orchestration_events
92 WHERE event_id = ${appended.eventId}
93 `;
94 assert.equal(storedRows.length, 1);
95 assert.equal(typeof storedRows[0]?.payloadJson, "string");
96 assert.equal(typeof storedRows[0]?.metadataJson, "string");
97
98 const replayed = yield* Stream.runCollect(eventStore.readFromSequence(0, 10)).pipe(
99 Effect.map((chunk) => Array.from(chunk)),
100 );
101 assert.equal(replayed.length, 1);
102 assert.equal(replayed[0]?.type, "project.created");
103 assert.equal(replayed[0]?.metadata.adapterKey, "codex");
104 assert.deepEqual(replayed[0]?.metadata.origin, { surface: "cli" });
105 }),
106 );
107
108 it.effect("fails with PersistenceDecodeError when stored json is invalid", () =>
109 Effect.gen(function* () {
110 const eventStore = yield* OrchestrationEventStore;
111 const sql = yield* SqlClient.SqlClient;
112 const now = "2026-01-01T00:00:00.000Z";
113
114 const invalidRows = yield* sql<{ readonly sequence: number }>`
115 INSERT INTO orchestration_events (
116 event_id,
117 aggregate_kind,
118 stream_id,
119 stream_version,
120 event_type,
121 occurred_at,
122 command_id,
123 causation_event_id,
124 correlation_id,
125 actor_kind,
126 payload_json,
127 metadata_json
128 )
129 VALUES (
130 ${EventId.make("evt-store-invalid-json")},
131 ${"project"},
132 ${ProjectId.make("project-invalid-json")},
133 ${0},
134 ${"project.created"},
135 ${now},
136 ${CommandId.make("cmd-store-invalid-json")},
137 ${null},
138 ${null},
139 ${"server"},
140 ${"{"},
141 ${"{}"}
142 )
143 RETURNING sequence
144 `;
145
146 const replayResult = yield* Effect.result(
147 Stream.runCollect(eventStore.readFromSequence(0, 10)),
148 );
149 assert.equal(replayResult._tag, "Failure");
150 if (replayResult._tag === "Failure") {
151 assert.ok(isPersistenceDecodeError(replayResult.failure));
152 assert.ok(
153 replayResult.failure.operation.includes(
154 "OrchestrationEventStore.readFromSequence:decodeRows",
155 ),
156 );
157 }
158 const scopedResult = yield* eventStore
159 .readAggregateRange({
160 aggregateKind: "project",
161 aggregateId: "project-invalid-json",
162 fromSequenceExclusive: 0,
163 toSequenceInclusive: invalidRows[0]!.sequence,
164 })
165 .pipe(Stream.runCollect, Effect.result);
166 assert.equal(scopedResult._tag, "Failure");
167 if (scopedResult._tag === "Failure") {
168 assert.ok(isPersistenceDecodeError(scopedResult.failure));
169 assert.ok(
170 scopedResult.failure.operation.includes(
171 "OrchestrationEventStore.readAggregateRange:decodeRows",
172 ),
173 );
174 }
175 }),
176 );
177
178 it.effect("reads one aggregate through the captured head across pruned global gaps", () =>
179 Effect.gen(function* () {
180 const store = yield* OrchestrationEventStore;
181 const sql = yield* SqlClient.SqlClient;
182 const threadId = ThreadId.make("shared-stream-id");
183 const first = yield* store.append(messageEvent(threadId, "scoped-first"));
184 const pruned = yield* store.append(
185 messageEvent(ThreadId.make("pruned-thread"), "pruned-event"),
186 );
187 const second = yield* store.append(messageEvent(threadId, "scoped-second"));
188 // The same stream ID in a different aggregate is not part of this thread.
189 // Its invalid JSON must never reach the event decoder.
190 yield* sql`
191 INSERT INTO orchestration_events (
192 event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
193 actor_kind, payload_json, metadata_json
194 ) VALUES (
195 'same-id-project', 'project', ${threadId}, 0, 'project.created',
196 '2026-01-01T00:00:00.000Z', 'server', '{', '{'
197 ), (
198 'unrelated-invalid', 'thread', 'unrelated-invalid-thread', 0, 'thread.activity-appended',
199 '2026-01-01T00:00:00.000Z', 'server', '{', '{'
200 )
201 `;
202 const last = yield* store.append(messageEvent(threadId, "scoped-last"));
203 yield* sql`DELETE FROM orchestration_events WHERE sequence = ${pruned.sequence}`;
204 yield* store.append(messageEvent(threadId, "after-captured-head"));
205
206 const events = yield* store
207 .readAggregateRange({
208 aggregateKind: "thread",
209 aggregateId: threadId,
210 fromSequenceExclusive: first.sequence,
211 toSequenceInclusive: last.sequence,
212 limit: 100,
213 })
214 .pipe(Stream.runCollect);
215 assert.deepEqual(
216 events.map((event) => event.sequence),
217 [second.sequence, last.sequence],
218 );
219 }),
220 );
221
222 it.effect("bounds thread replay metadata and counts UTF-8 bytes without decoding payloads", () =>
223 Effect.gen(function* () {
224 const store = yield* OrchestrationEventStore;
225 const sql = yield* SqlClient.SqlClient;
226 const rows = yield* sql<{ readonly sequence: number }>`
227 INSERT INTO orchestration_events (
228 event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
229 actor_kind, payload_json, metadata_json
230 ) VALUES
231 ('stats-1', 'thread', 'stats-thread', 0, 'thread.message-sent',
232 '2026-01-01T00:00:00.000Z', 'provider', '{"output":"😀"}', '{}'),
233 ('stats-unrelated', 'thread', 'another-thread', 0, 'thread.created',
234 '2026-01-01T00:00:00.000Z', 'provider', printf('%.*c', 10000, 'x'), '{}'),
235 ('stats-2', 'thread', 'stats-thread', 1, 'thread.activity-appended',
236 '2026-01-01T00:00:00.000Z', 'provider', '{', '{}'),
237 ('stats-other-kind', 'project', 'stats-thread', 0, 'project.deleted',
238 '2026-01-01T00:00:00.000Z', 'provider', printf('%.*c', 20000, 'x'), '{}'),
239 ('stats-3', 'thread', 'stats-thread', 2, 'thread.deleted',
240 '2026-01-01T00:00:00.000Z', 'provider', '{"output":"é"}', '{}'),
241 ('stats-4', 'thread', 'stats-thread', 3, 'thread.created',
242 '2026-01-01T00:00:00.000Z', 'provider', printf('%.*c', 2000, 'x'), '{}')
243 RETURNING sequence
244 `;
245 const range = {
246 aggregateKind: "thread" as const,
247 aggregateId: "stats-thread",
248 fromSequenceExclusive: 0,
249 toSequenceInclusive: rows.at(-1)!.sequence,
250 };
251 assert.deepEqual(yield* store.getAggregateReplayStats({ ...range, maxEvents: 2 }), {
252 eventCount: 3,
253 payloadBytes: 33,
254 hasCreateEvent: false,
255 });
256 assert.deepEqual(yield* store.getAggregateReplayStats({ ...range, maxEvents: 10 }), {
257 eventCount: 4,
258 payloadBytes: 2033,
259 hasCreateEvent: true,
260 });
261 assert.deepEqual(
262 yield* store.getAggregateReplayStats({
263 ...range,
264 toSequenceInclusive: rows[2]!.sequence,
265 maxEvents: 10,
266 }),
267 {
268 eventCount: 2,
269 payloadBytes: 18,
270 hasCreateEvent: false,
271 },
272 );
273 }),
274 );
275
276 it.effect("keeps later pages below the captured head when new events are appended", () =>
277 Effect.gen(function* () {
278 const store = yield* OrchestrationEventStore;
279 const threadId = ThreadId.make("paged-thread");
280 const persisted = yield* Effect.forEach(
281 Array.from({ length: 502 }, (_, index) => index),
282 (index) => store.append(messageEvent(threadId, `paged-${index}`)),
283 );
284 const head = persisted.at(-1)!.sequence;
285 let appendedDuringReplay = false;
286 const replayed = yield* store
287 .readAggregateRange({
288 aggregateKind: "thread",
289 aggregateId: threadId,
290 fromSequenceExclusive: 0,
291 toSequenceInclusive: head,
292 limit: 1_000,
293 })
294 .pipe(
295 Stream.tap(() => {
296 if (appendedDuringReplay) return Effect.void;
297 appendedDuringReplay = true;
298 return store.append(messageEvent(threadId, "appended-during-replay"));
299 }),
300 Stream.runCollect,
301 );
302 assert.deepEqual(
303 replayed.map((event) => event.sequence),
304 persisted.map((event) => event.sequence),
305 );
306 }),
307 );
308});