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

OrchestrationEventStore.sequence.test.ts

206 lines7.7 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 SqlClient from "effect/sql/SqlClient";
9​
10import * as OrchestrationEventStore from "./OrchestrationEventStore.ts";
11import * as SqlitePersistence from "./Sqlite.ts";
12​
13const layerEventStore = OrchestrationEventStore.layer.pipe(
14 Layer.provideMerge(SqlitePersistence.layerMemory),
15);
16const occurredAt = "2026-09-03T00:00:00.000Z";
17const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
18​
19function eventRow(
20 ordinal: number,
21 aggregateKind: "project" | "thread",
22 version: number,
23 streamId = `${aggregateKind}:${ordinal}`,
24 commandId: string | null = null,
25) {
26 return {
27 event_id: `event:${ordinal}`,
28 aggregate_kind: aggregateKind,
29 stream_id: streamId,
30 stream_version: ordinal,
31 event_type: aggregateKind === "project" ? "project.created" : "provider-session.detached",
32 occurred_at: occurredAt,
33 command_id: commandId,
34 causation_event_id: null,
35 correlation_id: null,
36 actor_kind: "server",
37 payload_json: encodeJson(
38 aggregateKind === "project"
39 ? {
40 projectId: streamId,
41 title: "Sequence fixture",
42 workspaceRoot: "/tmp/sequence-fixture",
43 defaultModelSelection: null,
44 scripts: [],
45 createdAt: occurredAt,
46 updatedAt: occurredAt,
47 }
48 : { providerSessionId: `session:${ordinal}`, detachedAt: occurredAt },
49 ),
50 metadata_json: "{}",
51 application_event_version: version,
52 };
54​
55const seedEvents = Effect.fn("test.seedSequenceEvents")(function* (
56 rows: ReadonlyArray<ReturnType<typeof eventRow>>,
57) {
58 const sql = yield* SqlClient.SqlClient;
59 return yield* sql<{
60 readonly sequence: number;
61 readonly aggregate_kind: string;
62 readonly application_event_version: number;
63 readonly stream_id: string;
64 readonly command_id: string | null;
65 }>`
66 INSERT INTO orchestration_events ${sql.insert(rows)}
67 RETURNING sequence, aggregate_kind, application_event_version, stream_id, command_id
68 `;
69});
70​
71it.effect("keeps application and scoped agent high-water marks separate from legacy history", () =>
72 Effect.gen(function* () {
73 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
74 const sql = yield* SqlClient.SqlClient;
75 const target = ThreadId.make("target");
76 assert.equal(yield* store.latestApplicationSequence, 0);
77 assert.equal(yield* store.latestAgentSequence(), 0);
78 assert.equal(yield* store.latestAgentSequence(target), 0);
79​
80 yield* seedEvents([eventRow(1, "thread", 1, "legacy-only")]);
81 assert.equal(yield* store.latestApplicationSequence, 0);
82 assert.equal(yield* store.latestAgentSequence(ThreadId.make("legacy-only")), 0);
83​
84 const [legacyProject, targetEvent, otherEvent] = yield* seedEvents([
85 eventRow(2, "project", 1),
86 eventRow(3, "thread", 2, target),
87 eventRow(4, "thread", 2, "other"),
88 ]);
89 assert.ok(legacyProject);
90 assert.ok(targetEvent);
91 assert.ok(otherEvent);
92 assert.equal(yield* store.latestApplicationSequence, otherEvent.sequence);
93 assert.equal(yield* store.latestAgentSequence(), otherEvent.sequence);
94 assert.equal(yield* store.latestAgentSequence(target), targetEvent.sequence);
95​
96 const [projectEvent] = yield* seedEvents([
97 eventRow(5, "project", 2),
98 eventRow(6, "thread", 1, target),
99 eventRow(7, "thread", 3, target),
100 ]);
101 assert.ok(projectEvent);
102 assert.equal(yield* store.latestApplicationSequence, projectEvent.sequence);
103 assert.equal(yield* store.latestAgentSequence(), otherEvent.sequence);
104 assert.equal(yield* store.latestAgentSequence(target), targetEvent.sequence);
105 assert.equal(yield* store.latestAgentSequence(ThreadId.make("missing")), 0);
106​
107 yield* sql`DELETE FROM orchestration_events WHERE sequence > ${legacyProject.sequence}`;
108 assert.equal(yield* store.latestApplicationSequence, legacyProject.sequence);
109 assert.equal(yield* store.latestAgentSequence(), 0);
110 assert.equal(yield* store.latestAgentSequence(target), 0);
111 }).pipe(Effect.provide(Layer.fresh(layerEventStore))),
112);
113​
114it.effect(
115 "preserves mixed application paging, scoped replay, and the catch-up to live boundary",
116 () =>
117 Effect.gen(function* () {
118 const store = yield* OrchestrationEventStore.OrchestrationEventStore;
119 const rows = yield* seedEvents(
120 Array.from({ length: 1_560 }, (_, index) => {
121 const kind = index % 3 === 1 ? "project" : "thread";
122 return eventRow(
123 index,
124 kind,
125 index % 3 === 0 ? 1 : 2,
126 kind === "project" ? `project:${index}` : index % 2 === 0 ? "target" : "other",
127 index % 5 === 0 ? "selected-command" : "other-command",
128 );
129 }),
130 );
131 const afterSequence = rows[25]!.sequence;
132 const throughSequence = rows[1_525]!.sequence;
133 const retained = rows.filter(
134 (row) => row.aggregate_kind === "project" || row.application_event_version === 2,
135 );
136 const replay = yield* store
137 .readApplicationEvents({ afterSequence, throughSequence })
138 .pipe(Stream.runCollect);
139 assert.deepEqual(
140 replay.map((event) => event.sequence),
141 retained
142 .filter((row) => row.sequence > afterSequence && row.sequence <= throughSequence)
143 .map((row) => row.sequence),
144 );
145​
146 const scoped = yield* store
147 .readAgentEvents({
148 afterSequence,
149 throughSequence,
150 threadId: ThreadId.make("target"),
151 commandId: CommandId.make("selected-command"),
152 limit: 17,
153 })
154 .pipe(Stream.runCollect);
155 assert.deepEqual(
156 scoped.map((event) => event.sequence),
157 retained
158 .filter(
159 (row) =>
160 row.sequence > afterSequence &&
161 row.sequence <= throughSequence &&
162 row.aggregate_kind === "thread" &&
163 row.stream_id === "target" &&
164 row.command_id === "selected-command",
165 )
166 .slice(0, 17)
167 .map((row) => row.sequence),
168 );
169​
170 const catchUp = retained.filter((row) => row.sequence > afterSequence);
171 const highWater = catchUp.at(-1)!.sequence;
172 let liveSequence = 0;
173 const streamed = yield* store.streamApplicationEvents({ afterSequence }).pipe(
174 Stream.tap((event) =>
175 event.sequence !== highWater
176 ? Effect.void
177 : Effect.gen(function* () {
178 const [stored] = yield* store.appendAgentEvents({
179 events: [
180 {
181 id: EventId.make("live-after-catch-up"),
182 type: "provider-session.detached",
183 threadId: ThreadId.make("target"),
184 occurredAt: DateTime.makeUnsafe(occurredAt),
185 payload: {
186 providerSessionId: ProviderSessionId.make("live-session"),
187 detachedAt: DateTime.makeUnsafe(occurredAt),
188 },
189 },
190 ],
191 });
192 assert.ok(stored);
193 liveSequence = stored.sequence;
194 yield* store.publishCommitted([stored]);
195 }),
196 ),
197 Stream.take(catchUp.length + 1),
198 Stream.runCollect,
199 );
200 assert.deepEqual(
201 streamed.map((event) => event.sequence),
202 [...catchUp.map((row) => row.sequence), liveSequence],
203 );
204 assert.isAbove(liveSequence, highWater);
205 }).pipe(Effect.provide(Layer.fresh(layerEventStore))),
206);