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

ProjectionMaintenance.ts

378 lines15.3 KB

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>;
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 >;
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.auto-settle-set",
222 "thread.unpinned",
223 "thread.pin-reordered",
224 "thread.active-reordered",
225 "thread.metadata-updated",
226 "thread.pull-request-synced",
227 "thread.runtime-mode-updated",
228 "thread.interaction-mode-updated",
229 "thread.model-selection-updated",
230 "thread.provider-switched",
231 "thread.visited",
232 "thread.marked-unread",
233 ];
234​
235 const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
236 const COMPACTION_PAGE_SIZE = 500;
237​
238 /**
239 * Scan newest first to retain the newest state for each entity.
240 * Page every event, including non-candidates: filtering before LIMIT could
241 * still scan the entire history when superseded events are sparse.
242 * turn-item.updated stays intact because replay assigns positions on first write.
243 */
244 const compactEventStore = Effect.gen(function* () {
245 const bounds = yield* sql<{
246 readonly event_sequence: number;
247 readonly receipt_row_id: number;
248 }>`
249 SELECT
250 COALESCE((SELECT MAX(sequence) FROM orchestration_events), 0) AS event_sequence,
251 COALESCE((SELECT MAX(rowid) FROM orchestration_command_receipts), 0) AS receipt_row_id
252 `;
253 let throughSequence = bounds[0]?.event_sequence ?? 0;
254 let throughReceiptRowId = bounds[0]?.receipt_row_id ?? 0;
255 const retainedThreadIds = new Set<string>();
256 const retainedEntityKeys = new Set<string>();
257 let deletedEventCount = 0;
258 let deletedReceiptCount = 0;
259​
260 while (throughSequence > 0) {
261 const rows = yield* sql<{
262 readonly sequence: number;
263 readonly application_event_version: number;
264 readonly aggregate_kind: string;
265 readonly stream_id: string;
266 readonly event_type: string;
267 readonly entity_id: string | null;
268 readonly imported_legacy_thread: number;
269 }>`
270 SELECT
271 event.sequence,
272 event.application_event_version,
273 event.aggregate_kind,
274 event.stream_id,
275 event.event_type,
276 CASE
277 WHEN event.application_event_version = 2
278 AND event.event_type IN ('message.updated', 'node.updated')
279 THEN json_extract(event.payload_json, '$.id')
280 ELSE NULL
281 END AS entity_id,
282 CASE
283 WHEN event.application_event_version = 1 AND event.aggregate_kind = 'thread'
284 THEN EXISTS (
285 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
286 WHERE legacy_import.thread_id = event.stream_id
287 AND legacy_import.transcript_imported_at IS NOT NULL
288 )
289 ELSE 0
290 END AS imported_legacy_thread
291 FROM orchestration_events AS event
292 WHERE event.sequence <= ${throughSequence}
293 ORDER BY event.sequence DESC
294 LIMIT ${COMPACTION_PAGE_SIZE}
295 `;
296 const obsolete: number[] = [];
297 for (const row of rows) {
298 if (row.imported_legacy_thread === 1) {
299 obsolete.push(row.sequence);
300 } else if (row.application_event_version === 2) {
301 if (
302 row.aggregate_kind === "thread" &&
303 supersedableThreadEventTypes.has(row.event_type)
304 ) {
305 if (retainedThreadIds.has(row.stream_id)) obsolete.push(row.sequence);
306 else retainedThreadIds.add(row.stream_id);
307 } else if (row.event_type === "message.updated" || row.event_type === "node.updated") {
308 const key = encodeEntityKey([row.event_type, row.stream_id, row.entity_id]);
309 if (retainedEntityKeys.has(key)) obsolete.push(row.sequence);
310 else retainedEntityKeys.add(key);
311 }
312 }
313 }
314 // Both discovery and deletion use the synchronous connection. Yield even
315 // when this page has nothing to delete so startup and requests can progress.
316 yield* Effect.yieldNow;
317 if (obsolete.length > 0) {
318 yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
319 deletedEventCount += obsolete.length;
320 yield* Effect.yieldNow;
321 }
322 throughSequence = (rows.at(-1)?.sequence ?? 1) - 1;
323 if (rows.length < COMPACTION_PAGE_SIZE) break;
324 }
325​
326 // Legacy receipts are removable only after their thread's v1 import finishes.
327 // Page by rowid before checking eligibility, as with event discovery above.
328 while (throughReceiptRowId > 0) {
329 const rows = yield* sql<{
330 readonly row_id: number;
331 readonly command_id: string;
332 readonly imported_legacy_thread: number;
333 }>`
334 SELECT
335 receipt.rowid AS row_id,
336 receipt.command_id,
337 CASE
338 WHEN receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread'
339 THEN EXISTS (
340 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
341 WHERE legacy_import.thread_id = receipt.aggregate_id
342 AND legacy_import.transcript_imported_at IS NOT NULL
343 )
344 ELSE 0
345 END AS imported_legacy_thread
346 FROM orchestration_command_receipts AS receipt
347 WHERE receipt.rowid <= ${throughReceiptRowId}
348 ORDER BY receipt.rowid DESC
349 LIMIT ${COMPACTION_PAGE_SIZE}
350 `;
351 const obsolete = rows
352 .filter((row) => row.imported_legacy_thread === 1)
353 .map((row) => row.command_id);
354 yield* Effect.yieldNow;
355 if (obsolete.length > 0) {
356 yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(obsolete)}`;
357 deletedReceiptCount += obsolete.length;
358 yield* Effect.yieldNow;
359 }
360 throughReceiptRowId = (rows.at(-1)?.row_id ?? 1) - 1;
361 if (rows.length < COMPACTION_PAGE_SIZE) break;
362 }
363​
364 const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
365 const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
366 const reclaimableBytes =
367 (freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
368​
369 return { deletedEventCount, deletedReceiptCount, reclaimableBytes };
370 });
371​
372 return ProjectionMaintenanceV2.of({
373 verify: mapError("verify")(verify),
374 rebuild: mapError("rebuild")(rebuild),
375 compactEventStore: mapError("compact event store")(compactEventStore),
376 });
377 }),
378);