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

OrchestrationEventStore.sequence.test.ts

273 lines10.3 KB

1import { CommandId, EventId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
2import { assert, it } from "@effect/vitest";
3import * as DateTime from "effect/DateTime";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Schema from "effect/Schema";
7import * as Stream from "effect/Stream";
8import * as Tracer from "effect/Tracer";
9import * as SqlClient from "effect/unstable/sql/SqlClient";
10​
11import { runMigrations } from "../Migrations.ts";
12import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
13import { OrchestrationEventStore } from "../Services/OrchestrationEventStore.ts";
14import { OrchestrationEventStoreLive } from "./OrchestrationEventStore.ts";
15import { SqlitePersistenceMemory } from "./Sqlite.ts";
16​
17const eventStoreLayer = OrchestrationEventStoreLive.pipe(
18 Layer.provideMerge(SqlitePersistenceMemory),
19);
20const occurredAt = "2026-09-03T00:00:00.000Z";
21const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
22​
23function eventRow(
24 ordinal: number,
25 aggregateKind: "project" | "thread",
26 version: number,
27 streamId = `${aggregateKind}:${ordinal}`,
28 commandId: string | null = null,
29) {
30 return {
31 event_id: `event:${ordinal}`,
32 aggregate_kind: aggregateKind,
33 stream_id: streamId,
34 stream_version: ordinal,
35 event_type: aggregateKind === "project" ? "project.created" : "provider-session.detached",
36 occurred_at: occurredAt,
37 command_id: commandId,
38 causation_event_id: null,
39 correlation_id: null,
40 actor_kind: "server",
41 payload_json: encodeJson(
42 aggregateKind === "project"
43 ? {
44 projectId: streamId,
45 title: "Sequence fixture",
46 workspaceRoot: "/tmp/sequence-fixture",
47 defaultModelSelection: null,
48 scripts: [],
49 createdAt: occurredAt,
50 updatedAt: occurredAt,
51 }
52 : { providerSessionId: `session:${ordinal}`, detachedAt: occurredAt },
53 ),
54 metadata_json: "{}",
55 application_event_version: version,
56 };
58​
59const seedEvents = Effect.fn("test.seedSequenceEvents")(function* (
60 rows: ReadonlyArray<ReturnType<typeof eventRow>>,
61) {
62 const sql = yield* SqlClient.SqlClient;
63 return yield* sql<{
64 readonly sequence: number;
65 readonly aggregate_kind: string;
66 readonly application_event_version: number;
67 readonly stream_id: string;
68 readonly command_id: string | null;
69 }>`
70 INSERT INTO orchestration_events ${sql.insert(rows)}
71 RETURNING sequence, aggregate_kind, application_event_version, stream_id, command_id
72 `;
73});
74​
75it.effect("keeps application and scoped agent high-water marks separate from legacy history", () =>
76 Effect.gen(function* () {
77 const store = yield* OrchestrationEventStore;
78 const sql = yield* SqlClient.SqlClient;
79 const target = ThreadId.make("target");
80 assert.equal(yield* store.latestApplicationSequence, 0);
81 assert.equal(yield* store.latestAgentSequence(), 0);
82 assert.equal(yield* store.latestAgentSequence(target), 0);
83​
84 yield* seedEvents([eventRow(1, "thread", 1, "legacy-only")]);
85 assert.equal(yield* store.latestApplicationSequence, 0);
86 assert.equal(yield* store.latestAgentSequence(ThreadId.make("legacy-only")), 0);
87​
88 const [legacyProject, targetEvent, otherEvent] = yield* seedEvents([
89 eventRow(2, "project", 1),
90 eventRow(3, "thread", 2, target),
91 eventRow(4, "thread", 2, "other"),
92 ]);
93 assert.ok(legacyProject);
94 assert.ok(targetEvent);
95 assert.ok(otherEvent);
96 assert.equal(yield* store.latestApplicationSequence, otherEvent.sequence);
97 assert.equal(yield* store.latestAgentSequence(), otherEvent.sequence);
98 assert.equal(yield* store.latestAgentSequence(target), targetEvent.sequence);
99​
100 const [projectEvent] = yield* seedEvents([
101 eventRow(5, "project", 2),
102 eventRow(6, "thread", 1, target),
103 eventRow(7, "thread", 3, target),
104 ]);
105 assert.ok(projectEvent);
106 assert.equal(yield* store.latestApplicationSequence, projectEvent.sequence);
107 assert.equal(yield* store.latestAgentSequence(), otherEvent.sequence);
108 assert.equal(yield* store.latestAgentSequence(target), targetEvent.sequence);
109 assert.equal(yield* store.latestAgentSequence(ThreadId.make("missing")), 0);
110​
111 yield* sql`DELETE FROM orchestration_events WHERE sequence > ${legacyProject.sequence}`;
112 assert.equal(yield* store.latestApplicationSequence, legacyProject.sequence);
113 assert.equal(yield* store.latestAgentSequence(), 0);
114 assert.equal(yield* store.latestAgentSequence(target), 0);
115 }).pipe(Effect.provide(Layer.fresh(eventStoreLayer))),
116);
117​
118it.effect(
119 "preserves mixed application paging, scoped replay, and the catch-up to live boundary",
120 () =>
121 Effect.gen(function* () {
122 const store = yield* OrchestrationEventStore;
123 const rows = yield* seedEvents(
124 Array.from({ length: 1_560 }, (_, index) => {
125 const kind = index % 3 === 1 ? "project" : "thread";
126 return eventRow(
127 index,
128 kind,
129 index % 3 === 0 ? 1 : 2,
130 kind === "project" ? `project:${index}` : index % 2 === 0 ? "target" : "other",
131 index % 5 === 0 ? "selected-command" : "other-command",
132 );
133 }),
134 );
135 const afterSequence = rows[25]!.sequence;
136 const throughSequence = rows[1_525]!.sequence;
137 const retained = rows.filter(
138 (row) => row.aggregate_kind === "project" || row.application_event_version === 2,
139 );
140 const replay = yield* store
141 .readApplicationEvents({ afterSequence, throughSequence })
142 .pipe(Stream.runCollect);
143 assert.deepEqual(
144 replay.map((event) => event.sequence),
145 retained
146 .filter((row) => row.sequence > afterSequence && row.sequence <= throughSequence)
147 .map((row) => row.sequence),
148 );
149​
150 const scoped = yield* store
151 .readAgentEvents({
152 afterSequence,
153 throughSequence,
154 threadId: ThreadId.make("target"),
155 commandId: CommandId.make("selected-command"),
156 limit: 17,
157 })
158 .pipe(Stream.runCollect);
159 assert.deepEqual(
160 scoped.map((event) => event.sequence),
161 retained
162 .filter(
163 (row) =>
164 row.sequence > afterSequence &&
165 row.sequence <= throughSequence &&
166 row.aggregate_kind === "thread" &&
167 row.stream_id === "target" &&
168 row.command_id === "selected-command",
169 )
170 .slice(0, 17)
171 .map((row) => row.sequence),
172 );
173​
174 const catchUp = retained.filter((row) => row.sequence > afterSequence);
175 const highWater = catchUp.at(-1)!.sequence;
176 let liveSequence = 0;
177 const streamed = yield* store.streamApplicationEvents({ afterSequence }).pipe(
178 Stream.tap((event) =>
179 event.sequence !== highWater
180 ? Effect.void
181 : Effect.gen(function* () {
182 const [stored] = yield* store.appendAgentEvents({
183 events: [
184 {
185 id: EventId.make("live-after-catch-up"),
186 type: "provider-session.detached",
187 threadId: ThreadId.make("target"),
188 occurredAt: DateTime.makeUnsafe(occurredAt),
189 payload: {
190 providerSessionId: ProviderSessionId.make("live-session"),
191 detachedAt: DateTime.makeUnsafe(occurredAt),
192 },
193 },
194 ],
195 });
196 assert.ok(stored);
197 liveSequence = stored.sequence;
198 yield* store.publishCommitted([stored]);
199 }),
200 ),
201 Stream.take(catchUp.length + 1),
202 Stream.runCollect,
203 );
204 assert.deepEqual(
205 streamed.map((event) => event.sequence),
206 [...catchUp.map((row) => row.sequence), liveSequence],
207 );
208 assert.isAbove(liveSequence, highWater);
209 }).pipe(Effect.provide(Layer.fresh(eventStoreLayer))),
210);
211​
212it.effect("uses indexed high-water lookups for populated history without OR scans", () =>
213 Effect.gen(function* () {
214 const store = yield* OrchestrationEventStore;
215 const sql = yield* SqlClient.SqlClient;
216 yield* runMigrations();
217 yield* sql`
218 WITH RECURSIVE history(n) AS (
219 SELECT 1 UNION ALL SELECT n + 1 FROM history WHERE n < 25000
220 )
221 INSERT INTO orchestration_events (
222 event_id, aggregate_kind, stream_id, stream_version, event_type,
223 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
224 )
225 SELECT 'history:' || n, 'thread',
226 CASE WHEN n = 1 THEN 'target' ELSE 'other' END,
227 n, 'provider-session.detached', ${occurredAt}, 'server', '{}', '{}',
228 CASE WHEN n % 3 = 0 THEN 1 ELSE 2 END
229 FROM history
230 `;
231 const statements: Array<string> = [];
232 const tracer = Tracer.make({
233 span(options) {
234 const span = new Tracer.NativeSpan(options);
235 const end = span.end.bind(span);
236 span.end = (endTime, exit) => {
237 end(endTime, exit);
238 const query = span.attributes.get("db.query.text");
239 if (typeof query === "string") statements.push(query);
240 };
241 return span;
242 },
243 });
244 assert.equal(yield* store.latestApplicationSequence.pipe(Effect.withTracer(tracer)), 25_000);
245 assert.equal(
246 yield* store.latestAgentSequence(ThreadId.make("target")).pipe(Effect.withTracer(tracer)),
247 1,
248 );
249 assert.equal(statements.length, 2);
250 const applicationPlan = yield* sql.unsafe<{ readonly detail: string }>(
251 `EXPLAIN QUERY PLAN ${statements[0]}`,
252 );
253 const agentPlan = yield* sql.unsafe<{ readonly detail: string }>(
254 `EXPLAIN QUERY PLAN ${statements[1]}`,
255 ["target"],
256 );
257 assert.match(
258 applicationPlan.map((row) => row.detail).join("\n"),
259 /SEARCH orchestration_events USING INDEX idx_orchestration_events_application_high_water/,
260 );
261 assert.match(
262 agentPlan.map((row) => row.detail).join("\n"),
263 /USING COVERING INDEX idx_orchestration_events_agent_stream_sequence \(stream_id=\?\)/,
264 );
265 for (const row of [...applicationPlan, ...agentPlan]) {
266 assert.notMatch(row.detail, /MULTI-INDEX OR|TEMP B-TREE/);
267 }
268 }).pipe(
269 Effect.provide(
270 OrchestrationEventStoreLive.pipe(Layer.provideMerge(NodeSqliteClient.layerMemory())),
271 ),
272 ),
273);