Open History to see the last commit
1import { ThreadId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
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/unstable/sql/SqlClient";
9
10import { EventStoreV2 } from "./EventStore.ts";
11import {
12 ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
13 ProjectionStoreV2,
14} from "./ProjectionStore.ts";
15
16export interface ProjectionVerificationV2 {
17 readonly valid: boolean;
18 readonly schemaVersion: number;
19 readonly expectedSequence: number;
20 readonly projectionSequence: number;
21 readonly unreadableThreadIds: ReadonlyArray<ThreadId>;
22 readonly missingThreadIds: ReadonlyArray<ThreadId>;
23 readonly unexpectedThreadIds: ReadonlyArray<ThreadId>;
24}
25
26export class ProjectionMaintenanceError extends Schema.TaggedError<ProjectionMaintenanceError>()(
27 "ProjectionMaintenanceError",
28 {
29 operation: Schema.String,
30 cause: Schema.optional(Schema.Defect()),
31 },
32) {}
33
34export interface ProjectionMaintenanceV2Shape {
35 readonly verify: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
36 readonly rebuild: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
37 readonly compactEventStore: Effect.Effect<
38 {
39 readonly deletedEventCount: number;
40 readonly deletedReceiptCount: number;
41 readonly reclaimableBytes: number;
42 },
43 ProjectionMaintenanceError
44 >;
45}
46
47export class ProjectionMaintenanceV2 extends Context.Service<
48 ProjectionMaintenanceV2,
49 ProjectionMaintenanceV2Shape
50>()("t3/orchestration-v2/ProjectionMaintenance/ProjectionMaintenanceV2") {}
51
52type ProjectionMetadataRow = {
53 readonly schema_version: number;
54 readonly last_sequence: number;
55};
56
57const encodeEntityKey = Schema.encodeSync(
58 Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String, Schema.NullOr(Schema.String)])),
59);
60
61export const layer: Layer.Layer<
62 ProjectionMaintenanceV2,
63 never,
64 EventStoreV2 | ProjectionStoreV2 | SqlClient.SqlClient
65> = Layer.effect(
66 ProjectionMaintenanceV2,
67 Effect.gen(function* () {
68 const sql = yield* SqlClient.SqlClient;
69 const eventStore = yield* EventStoreV2;
70 const projectionStore = yield* ProjectionStoreV2;
71
72 /**
73 * EventSink commits the event, its projection updates, and projection metadata in one SQL
74 * transaction. Startup verification therefore checks that transaction boundary and that every
75 * stored projection can be decoded. It intentionally does not replay domain events through a
76 * second projector: doing so creates another implementation of projection semantics that must
77 * evolve in lockstep with ProjectionStore.
78 */
79 const verify = Effect.gen(function* () {
80 const expectedThreadRows = yield* sql<{ readonly thread_id: string }>`
81 SELECT DISTINCT stream_id AS thread_id
82 FROM orchestration_events INDEXED BY orchestration_events_v2_created_threads_idx
83 WHERE application_event_version = 2
84 AND aggregate_kind = 'thread'
85 AND event_type = 'thread.created'
86 ORDER BY stream_id ASC
87 `;
88 const projectionRows = yield* sql<{ readonly thread_id: string }>`
89 SELECT thread_id
90 FROM orchestration_v2_projection_threads
91 ORDER BY thread_id ASC
92 `;
93 const actualIds = projectionRows.map((row) => ThreadId.make(row.thread_id));
94 const expectedIds = expectedThreadRows.map((row) => ThreadId.make(row.thread_id));
95 const actualSet = new Set(actualIds);
96 const expectedSet = new Set(expectedIds);
97 const missingThreadIds = expectedIds.filter((threadId) => !actualSet.has(threadId));
98 const unexpectedThreadIds = actualIds.filter((threadId) => !expectedSet.has(threadId));
99 const unreadableThreadIds = yield* projectionStore.getUnreadableThreadIds();
100 const metadata = yield* sql<ProjectionMetadataRow>`
101 SELECT schema_version, last_sequence
102 FROM orchestration_v2_projection_metadata
103 WHERE projection_name = 'thread-projections'
104 LIMIT 1
105 `;
106 const expectedSequence = yield* eventStore.latestSequence();
107 const schemaVersion = metadata[0]?.schema_version ?? 0;
108 const projectionSequence = metadata[0]?.last_sequence ?? 0;
109 return {
110 valid:
111 schemaVersion === ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION &&
112 projectionSequence === expectedSequence &&
113 missingThreadIds.length === 0 &&
114 unexpectedThreadIds.length === 0 &&
115 unreadableThreadIds.length === 0,
116 schemaVersion,
117 expectedSequence,
118 projectionSequence,
119 unreadableThreadIds,
120 missingThreadIds,
121 unexpectedThreadIds,
122 } satisfies ProjectionVerificationV2;
123 }).pipe(sql.withTransaction);
124
125 const rebuild = Effect.gen(function* () {
126 yield* sql.withTransaction(
127 Effect.gen(function* () {
128 const throughSequence = yield* eventStore.latestSequence();
129 yield* sql`DELETE FROM orchestration_v2_projection_context_transfers`;
130 yield* sql`DELETE FROM orchestration_v2_projection_context_handoffs`;
131 yield* sql`DELETE FROM orchestration_v2_projection_checkpoints`;
132 yield* sql`DELETE FROM orchestration_v2_projection_checkpoint_scopes`;
133 yield* sql`DELETE FROM orchestration_v2_projection_turn_items`;
134 yield* sql`DELETE FROM orchestration_v2_projection_plans`;
135 yield* sql`DELETE FROM orchestration_v2_projection_messages`;
136 yield* sql`DELETE FROM orchestration_v2_projection_runtime_requests`;
137 yield* sql`DELETE FROM orchestration_v2_projection_provider_turns`;
138 yield* sql`DELETE FROM orchestration_v2_projection_provider_threads`;
139 yield* sql`DELETE FROM orchestration_v2_projection_provider_session_bindings`;
140 yield* sql`DELETE FROM orchestration_v2_projection_provider_sessions`;
141 yield* sql`DELETE FROM orchestration_v2_projection_subagents`;
142 yield* sql`DELETE FROM orchestration_v2_projection_nodes`;
143 yield* sql`DELETE FROM orchestration_v2_projection_run_attempts`;
144 yield* sql`DELETE FROM orchestration_v2_projection_runs`;
145 yield* sql`DELETE FROM orchestration_v2_projection_threads`;
146 yield* sql`DELETE FROM orchestration_v2_turn_item_positions`;
147
148 const pageSize = 500;
149 let lastSequence = 0;
150 while (true) {
151 const page = yield* eventStore
152 .read({ afterSequence: lastSequence, throughSequence, limit: pageSize })
153 .pipe(Stream.runCollect);
154 for (const stored of page) {
155 yield* projectionStore.apply(stored.event);
156 if (stored.event.type === "turn-item.updated") {
157 yield* sql`
158 INSERT INTO orchestration_v2_turn_item_positions (
159 thread_id,
160 turn_item_id,
161 ordinal
162 )
163 VALUES (
164 ${stored.event.threadId},
165 ${stored.event.payload.id},
166 ${stored.event.payload.ordinal}
167 )
168 ON CONFLICT(thread_id, turn_item_id) DO UPDATE SET
169 ordinal = excluded.ordinal
170 `;
171 }
172 lastSequence = stored.sequence;
173 }
174 if (page.length < pageSize) break;
175 yield* Effect.yieldNow;
176 }
177 const now = DateTime.formatIso(yield* DateTime.now);
178 yield* sql`
179 INSERT INTO orchestration_v2_projection_metadata (
180 projection_name,
181 schema_version,
182 last_sequence,
183 updated_at
184 )
185 VALUES (
186 'thread-projections',
187 ${ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
188 ${lastSequence},
189 ${now}
190 )
191 ON CONFLICT(projection_name) DO UPDATE SET
192 schema_version = excluded.schema_version,
193 last_sequence = excluded.last_sequence,
194 updated_at = excluded.updated_at
195 `;
196 }),
197 );
198 return yield* verify;
199 });
200
201 const mapError =
202 (operation: string) =>
203 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
204 effect.pipe(
205 Effect.mapError((cause) => new ProjectionMaintenanceError({ operation, cause })),
206 );
207
208 // Thread-state events whose payload is the complete thread: only the
209 // newest per thread can influence a replay or an afterSequence catch-up.
210 // thread.created stays out — verify derives the expected thread set from
211 // it, and it anchors replay ordering.
212 const SUPERSEDABLE_THREAD_EVENT_TYPES = [
213 "thread.archived",
214 "thread.unarchived",
215 "thread.deleted",
216 "thread.settled",
217 "thread.unsettled",
218 "thread.snoozed",
219 "thread.unsnoozed",
220 "thread.pinned",
221 "thread.unpinned",
222 "thread.pin-reordered",
223 "thread.active-reordered",
224 "thread.metadata-updated",
225 "thread.pull-request-synced",
226 "thread.runtime-mode-updated",
227 "thread.interaction-mode-updated",
228 "thread.model-selection-updated",
229 "thread.provider-switched",
230 "thread.visited",
231 "thread.marked-unread",
232 ];
233
234 const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
235 const COMPACTION_PAGE_SIZE = 500;
236
237 /**
238 * Scan newest first to retain the newest state for each entity.
239 * Page every event, including non-candidates: filtering before LIMIT could
240 * still scan the entire history when superseded events are sparse.
241 * turn-item.updated stays intact because replay assigns positions on first write.
242 */
243 const compactEventStore = Effect.gen(function* () {
244 const bounds = yield* sql<{
245 readonly event_sequence: number;
246 readonly receipt_row_id: number;
247 }>`
248 SELECT
249 COALESCE((SELECT MAX(sequence) FROM orchestration_events), 0) AS event_sequence,
250 COALESCE((SELECT MAX(rowid) FROM orchestration_command_receipts), 0) AS receipt_row_id
251 `;
252 let throughSequence = bounds[0]?.event_sequence ?? 0;
253 let throughReceiptRowId = bounds[0]?.receipt_row_id ?? 0;
254 const retainedThreadIds = new Set<string>();
255 const retainedEntityKeys = new Set<string>();
256 let deletedEventCount = 0;
257 let deletedReceiptCount = 0;
258
259 while (throughSequence > 0) {
260 const rows = yield* sql<{
261 readonly sequence: number;
262 readonly application_event_version: number;
263 readonly aggregate_kind: string;
264 readonly stream_id: string;
265 readonly event_type: string;
266 readonly entity_id: string | null;
267 readonly imported_legacy_thread: number;
268 }>`
269 SELECT
270 event.sequence,
271 event.application_event_version,
272 event.aggregate_kind,
273 event.stream_id,
274 event.event_type,
275 CASE
276 WHEN event.application_event_version = 2
277 AND event.event_type IN ('message.updated', 'node.updated')
278 THEN json_extract(event.payload_json, '$.id')
279 ELSE NULL
280 END AS entity_id,
281 CASE
282 WHEN event.application_event_version = 1 AND event.aggregate_kind = 'thread'
283 THEN EXISTS (
284 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
285 WHERE legacy_import.thread_id = event.stream_id
286 AND legacy_import.transcript_imported_at IS NOT NULL
287 )
288 ELSE 0
289 END AS imported_legacy_thread
290 FROM orchestration_events AS event
291 WHERE event.sequence <= ${throughSequence}
292 ORDER BY event.sequence DESC
293 LIMIT ${COMPACTION_PAGE_SIZE}
294 `;
295 const obsolete: number[] = [];
296 for (const row of rows) {
297 if (row.imported_legacy_thread === 1) {
298 obsolete.push(row.sequence);
299 } else if (row.application_event_version === 2) {
300 if (
301 row.aggregate_kind === "thread" &&
302 supersedableThreadEventTypes.has(row.event_type)
303 ) {
304 if (retainedThreadIds.has(row.stream_id)) obsolete.push(row.sequence);
305 else retainedThreadIds.add(row.stream_id);
306 } else if (row.event_type === "message.updated" || row.event_type === "node.updated") {
307 const key = encodeEntityKey([row.event_type, row.stream_id, row.entity_id]);
308 if (retainedEntityKeys.has(key)) obsolete.push(row.sequence);
309 else retainedEntityKeys.add(key);
310 }
311 }
312 }
313 // Both discovery and deletion use the synchronous connection. Yield even
314 // when this page has nothing to delete so startup and requests can progress.
315 yield* Effect.yieldNow;
316 if (obsolete.length > 0) {
317 yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
318 deletedEventCount += obsolete.length;
319 yield* Effect.yieldNow;
320 }
321 throughSequence = (rows.at(-1)?.sequence ?? 1) - 1;
322 if (rows.length < COMPACTION_PAGE_SIZE) break;
323 }
324
325 // Legacy receipts are removable only after their thread's v1 import finishes.
326 // Page by rowid before checking eligibility, as with event discovery above.
327 while (throughReceiptRowId > 0) {
328 const rows = yield* sql<{
329 readonly row_id: number;
330 readonly command_id: string;
331 readonly imported_legacy_thread: number;
332 }>`
333 SELECT
334 receipt.rowid AS row_id,
335 receipt.command_id,
336 CASE
337 WHEN receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread'
338 THEN EXISTS (
339 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
340 WHERE legacy_import.thread_id = receipt.aggregate_id
341 AND legacy_import.transcript_imported_at IS NOT NULL
342 )
343 ELSE 0
344 END AS imported_legacy_thread
345 FROM orchestration_command_receipts AS receipt
346 WHERE receipt.rowid <= ${throughReceiptRowId}
347 ORDER BY receipt.rowid DESC
348 LIMIT ${COMPACTION_PAGE_SIZE}
349 `;
350 const obsolete = rows
351 .filter((row) => row.imported_legacy_thread === 1)
352 .map((row) => row.command_id);
353 yield* Effect.yieldNow;
354 if (obsolete.length > 0) {
355 yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(obsolete)}`;
356 deletedReceiptCount += obsolete.length;
357 yield* Effect.yieldNow;
358 }
359 throughReceiptRowId = (rows.at(-1)?.row_id ?? 1) - 1;
360 if (rows.length < COMPACTION_PAGE_SIZE) break;
361 }
362
363 const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
364 const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
365 const reclaimableBytes =
366 (freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
367
368 return { deletedEventCount, deletedReceiptCount, reclaimableBytes };
369 });
370
371 return ProjectionMaintenanceV2.of({
372 verify: mapError("verify")(verify),
373 rebuild: mapError("rebuild")(rebuild),
374 compactEventStore: mapError("compact event store")(compactEventStore),
375 });
376 }),
377);