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

ProjectionMaintenance.ts

393 lines16.4 KB

1import { ThreadId } from "@t3tools/contracts";
2import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Schema from "effect/Schema";
8import * as Stream from "effect/Stream";
9import * as SqlClient from "effect/sql/SqlClient";
10​
11import * as EventStore from "./EventStore.ts";
12import * as ProjectionStore from "./ProjectionStore.ts";
13​
14export interface ProjectionVerificationV2 {
15 readonly valid: boolean;
16 readonly schemaVersion: number;
17 readonly expectedSequence: number;
18 readonly projectionSequence: number;
19 readonly unreadableThreadIds: ReadonlyArray<ThreadId>;
20 readonly missingThreadIds: ReadonlyArray<ThreadId>;
21 readonly unexpectedThreadIds: ReadonlyArray<ThreadId>;
23​
24export class ProjectionMaintenanceError extends Schema.TaggedError<ProjectionMaintenanceError>()(
25 "ProjectionMaintenanceError",
26 {
27 operation: Schema.String,
28 cause: Schema.optional(Schema.Defect()),
29 },
30) {}
31​
32export interface ProjectionMaintenanceV2Shape {
33 readonly verify: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
34 readonly rebuild: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
35 readonly compactEventStore: Effect.Effect<
36 {
37 readonly deletedEventCount: number;
38 readonly deletedReceiptCount: number;
39 readonly reclaimableBytes: number;
40 },
41 ProjectionMaintenanceError
42 >;
44​
45export class ProjectionMaintenanceV2 extends Context.Service<
46 ProjectionMaintenanceV2,
47 ProjectionMaintenanceV2Shape
48>()("t3/orchestration-v2/ProjectionMaintenance/ProjectionMaintenanceV2") {}
49​
50type ProjectionMetadataRow = {
51 readonly schema_version: number;
52 readonly last_sequence: number;
53};
54​
55const encodeEntityKey = Schema.encodeSync(
56 Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String, Schema.NullOr(Schema.String)])),
57);
58​
59export const layer: Layer.Layer<
60 ProjectionMaintenanceV2,
61 never,
62 EventStore.EventStoreV2 | ProjectionStore.ProjectionStoreV2 | SqlClient.SqlClient
63> = Layer.effect(
64 ProjectionMaintenanceV2,
65 Effect.gen(function* () {
66 const sql = yield* SqlClient.SqlClient;
67 const eventStore = yield* EventStore.EventStoreV2;
68 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
69​
70 const verify = Effect.gen(function* () {
71 const expectedThreadRows = yield* sql<{ readonly thread_id: string }>`
72 SELECT DISTINCT stream_id AS thread_id
73 FROM orchestration_events INDEXED BY orchestration_events_v2_created_threads_idx
74 WHERE application_event_version = 2
75 AND aggregate_kind = 'thread'
76 AND event_type = 'thread.created'
77 ORDER BY stream_id ASC
78 `;
79 const projectionRows = yield* sql<{ readonly thread_id: string }>`
80 SELECT thread_id
81 FROM orchestration_v2_projection_threads
82 ORDER BY thread_id ASC
83 `;
84 const actualIds = projectionRows.map((row) => ThreadId.make(row.thread_id));
85 const expectedIds = expectedThreadRows.map((row) => ThreadId.make(row.thread_id));
86 const actualSet = new Set(actualIds);
87 const expectedSet = new Set(expectedIds);
88 const missingThreadIds = expectedIds.filter((threadId) => !actualSet.has(threadId));
89 const unexpectedThreadIds = actualIds.filter((threadId) => !expectedSet.has(threadId));
90 const unreadableThreadIds = yield* projectionStore.getUnreadableThreadIds();
91 const metadata = yield* sql<ProjectionMetadataRow>`
92 SELECT schema_version, last_sequence
93 FROM orchestration_v2_projection_metadata
94 WHERE projection_name = 'thread-projections'
95 LIMIT 1
96 `;
97 const expectedSequence = yield* eventStore.latestSequence();
98 const schemaVersion = metadata[0]?.schema_version ?? 0;
99 const projectionSequence = metadata[0]?.last_sequence ?? 0;
100 return {
101 valid:
102 schemaVersion === ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION &&
103 projectionSequence === expectedSequence &&
104 missingThreadIds.length === 0 &&
105 unexpectedThreadIds.length === 0 &&
106 unreadableThreadIds.length === 0,
107 schemaVersion,
108 expectedSequence,
109 projectionSequence,
110 unreadableThreadIds,
111 missingThreadIds,
112 unexpectedThreadIds,
113 } satisfies ProjectionVerificationV2;
114 }).pipe(sql.withTransaction);
115​
116 const rebuild = Effect.gen(function* () {
117 yield* sql.withTransaction(
118 Effect.gen(function* () {
119 const throughSequence = yield* eventStore.latestSequence();
120 yield* sql`DELETE FROM orchestration_v2_projection_context_transfers`;
121 yield* sql`DELETE FROM orchestration_v2_projection_context_handoffs`;
122 yield* sql`DELETE FROM orchestration_v2_projection_checkpoints`;
123 yield* sql`DELETE FROM orchestration_v2_projection_checkpoint_scopes`;
124 yield* sql`DELETE FROM orchestration_v2_projection_turn_items`;
125 yield* sql`DELETE FROM orchestration_v2_projection_plans`;
126 yield* sql`DELETE FROM orchestration_v2_projection_messages`;
127 yield* sql`DELETE FROM orchestration_v2_projection_runtime_requests`;
128 yield* sql`DELETE FROM orchestration_v2_projection_provider_turns`;
129 yield* sql`DELETE FROM orchestration_v2_projection_provider_threads`;
130 yield* sql`DELETE FROM orchestration_v2_projection_provider_session_bindings`;
131 yield* sql`DELETE FROM orchestration_v2_projection_provider_sessions`;
132 yield* sql`DELETE FROM orchestration_v2_projection_subagents`;
133 yield* sql`DELETE FROM orchestration_v2_projection_nodes`;
134 yield* sql`DELETE FROM orchestration_v2_projection_run_attempts`;
135 yield* sql`DELETE FROM orchestration_v2_projection_runs`;
136 yield* sql`DELETE FROM orchestration_v2_projection_threads`;
137 yield* sql`DELETE FROM orchestration_v2_turn_item_positions`;
138​
139 const pageSize = 500;
140 let lastSequence = 0;
141 while (true) {
142 const page = yield* eventStore
143 .read({ afterSequence: lastSequence, throughSequence, limit: pageSize })
144 .pipe(Stream.runCollect);
145 for (const stored of page) {
146 yield* projectionStore.apply(stored.event);
147 if (stored.event.type === "turn-item.updated") {
148 yield* sql`
149 INSERT INTO orchestration_v2_turn_item_positions (
150 thread_id,
151 turn_item_id,
152 ordinal
153 )
154 VALUES (
155 ${stored.event.threadId},
156 ${stored.event.payload.id},
157 ${stored.event.payload.ordinal}
158 )
159 ON CONFLICT(thread_id, turn_item_id) DO UPDATE SET
160 ordinal = excluded.ordinal
161 `;
162 }
163 lastSequence = stored.sequence;
164 }
165 if (page.length < pageSize) break;
166 yield* Effect.yieldNow;
167 }
168 const now = DateTime.formatIso(yield* DateTime.now);
169 yield* sql`
170 INSERT INTO orchestration_v2_projection_metadata (
171 projection_name,
172 schema_version,
173 last_sequence,
174 updated_at
175 )
176 VALUES (
177 'thread-projections',
178 ${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
179 ${lastSequence},
180 ${now}
181 )
182 ON CONFLICT(projection_name) DO UPDATE SET
183 schema_version = excluded.schema_version,
184 last_sequence = excluded.last_sequence,
185 updated_at = excluded.updated_at
186 `;
187 }),
188 );
189 return yield* verify;
190 });
191​
192 const mapError =
193 (operation: string) =>
194 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
195 effect.pipe(
196 Effect.mapError((cause) => new ProjectionMaintenanceError({ operation, cause })),
197 );
198​
199 // Keep thread.created as the verification and replay anchor; clients recognize deletion by thread.deleted event type.
200 const SUPERSEDABLE_THREAD_EVENT_TYPES = [
201 "thread.archived",
202 "thread.unarchived",
203 "thread.settled",
204 "thread.unsettled",
205 "thread.snoozed",
206 "thread.unsnoozed",
207 "thread.pinned",
208 "thread.auto-settle-set",
209 "thread.unpinned",
210 "thread.pin-reordered",
211 "thread.active-reordered",
212 "thread.metadata-updated",
213 "thread.pull-request-synced",
214 "thread.runtime-mode-updated",
215 "thread.interaction-mode-updated",
216 "thread.model-selection-updated",
217 "thread.provider-switched",
218 "thread.guest-share-updated",
219 ];
220 // Read-state events preserve updatedAt and supersede only each other. Activity events supersede both groups.
221 const READ_STATE_THREAD_EVENT_TYPES = ["thread.visited", "thread.marked-unread"];
222​
223 const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
224 const readStateThreadEventTypes = new Set(READ_STATE_THREAD_EVENT_TYPES);
225 // Keep subagent.updated and turn-item.updated rows: slimmed payloads reference their prompts.
226 // Small pages bound work on the reader worker and synchronous fallback.
227 const COMPACTION_PAGE_SIZE = 50;
228​
229 /** Retain newest and oldest keyed events to preserve client insertion order; page all events to bound sparse scans.
230 * Keep turn-item.updated because replay assigns positions on first write. */
231 const compactEventStore = Effect.gen(function* () {
232 const bounds = yield* sql<{
233 readonly event_sequence: number;
234 readonly receipt_row_id: number;
235 }>`
236 SELECT
237 COALESCE((SELECT MAX(sequence) FROM orchestration_events), 0) AS event_sequence,
238 COALESCE((SELECT MAX(rowid) FROM orchestration_command_receipts), 0) AS receipt_row_id
239 `;
240 let throughSequence = bounds[0]?.event_sequence ?? 0;
241 let throughReceiptRowId = bounds[0]?.receipt_row_id ?? 0;
242 const retainedThreadIds = new Set<string>();
243 const retainedReadStateThreadIds = new Set<string>();
244 // Retain each key's oldest candidate, deleting it only when an older event appears.
245 const oldestCandidateByEntityKey = new Map<string, number | null>();
246 let deletedEventCount = 0;
247 let deletedReceiptCount = 0;
248​
249 while (throughSequence > 0) {
250 const rows = yield* sql<{
251 readonly sequence: number;
252 readonly application_event_version: number;
253 readonly aggregate_kind: string;
254 readonly stream_id: string;
255 readonly event_type: string;
256 readonly entity_id: string | null;
257 readonly imported_legacy_thread: number;
258 }>`
259 SELECT
260 event.sequence,
261 event.application_event_version,
262 event.aggregate_kind,
263 event.stream_id,
264 event.event_type,
265 CASE
266 WHEN event.application_event_version = 2
267 AND event.event_type IN ('message.updated', 'node.updated')
268 THEN json_extract(event.payload_json, '$.id')
269 WHEN event.application_event_version = 2
270 AND event.event_type = 'thread.pull-request-link-updated'
271 THEN json_array(json_extract(event.payload_json, '$.host'),
272 json_extract(event.payload_json, '$.repository'),
273 json_extract(event.payload_json, '$.number'))
274 ELSE NULL
275 END AS entity_id,
276 CASE
277 WHEN event.application_event_version = 1 AND event.aggregate_kind = 'thread'
278 THEN EXISTS (
279 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
280 WHERE legacy_import.thread_id = event.stream_id
281 AND legacy_import.transcript_imported_at IS NOT NULL
282 )
283 ELSE 0
284 END AS imported_legacy_thread
285 FROM orchestration_events AS event
286 WHERE event.sequence <= ${throughSequence}
287 ORDER BY event.sequence DESC
288 LIMIT ${COMPACTION_PAGE_SIZE}
289 `.pipe(NodeSqliteClient.readOnly);
290 const obsolete: number[] = [];
291 for (const row of rows) {
292 if (row.imported_legacy_thread === 1) {
293 obsolete.push(row.sequence);
294 } else if (row.application_event_version === 2) {
295 if (
296 row.aggregate_kind === "thread" &&
297 supersedableThreadEventTypes.has(row.event_type)
298 ) {
299 if (retainedThreadIds.has(row.stream_id)) obsolete.push(row.sequence);
300 else retainedThreadIds.add(row.stream_id);
301 } else if (
302 row.aggregate_kind === "thread" &&
303 readStateThreadEventTypes.has(row.event_type)
304 ) {
305 if (
306 retainedThreadIds.has(row.stream_id) ||
307 retainedReadStateThreadIds.has(row.stream_id)
308 ) {
309 obsolete.push(row.sequence);
310 } else retainedReadStateThreadIds.add(row.stream_id);
311 } else if (
312 row.event_type === "thread.pull-request-link-updated" &&
313 retainedThreadIds.has(row.stream_id)
314 ) {
315 // A newer whole-thread payload already carries this link's state.
316 obsolete.push(row.sequence);
317 } else if (
318 row.event_type === "thread.pull-request-link-updated" ||
319 row.event_type === "message.updated" ||
320 row.event_type === "node.updated"
321 ) {
322 const key = encodeEntityKey([row.event_type, row.stream_id, row.entity_id]);
323 const candidate = oldestCandidateByEntityKey.get(key);
324 if (candidate === undefined) oldestCandidateByEntityKey.set(key, null);
325 else {
326 if (candidate !== null) obsolete.push(candidate);
327 oldestCandidateByEntityKey.set(key, row.sequence);
328 }
329 }
330 }
331 }
332 // Yield even without deletions for clients using the synchronous fallback.
333 yield* Effect.yieldNow;
334 if (obsolete.length > 0) {
335 yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
336 deletedEventCount += obsolete.length;
337 yield* Effect.yieldNow;
338 }
339 throughSequence = (rows.at(-1)?.sequence ?? 1) - 1;
340 if (rows.length < COMPACTION_PAGE_SIZE) break;
341 }
342​
343 while (throughReceiptRowId > 0) {
344 const rows = yield* sql<{
345 readonly row_id: number;
346 readonly command_id: string;
347 readonly imported_legacy_thread: number;
348 }>`
349 SELECT
350 receipt.rowid AS row_id,
351 receipt.command_id,
352 CASE
353 WHEN receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread'
354 THEN EXISTS (
355 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
356 WHERE legacy_import.thread_id = receipt.aggregate_id
357 AND legacy_import.transcript_imported_at IS NOT NULL
358 )
359 ELSE 0
360 END AS imported_legacy_thread
361 FROM orchestration_command_receipts AS receipt
362 WHERE receipt.rowid <= ${throughReceiptRowId}
363 ORDER BY receipt.rowid DESC
364 LIMIT ${COMPACTION_PAGE_SIZE}
365 `.pipe(NodeSqliteClient.readOnly);
366 const obsolete = rows
367 .filter((row) => row.imported_legacy_thread === 1)
368 .map((row) => row.command_id);
369 yield* Effect.yieldNow;
370 if (obsolete.length > 0) {
371 yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(obsolete)}`;
372 deletedReceiptCount += obsolete.length;
373 yield* Effect.yieldNow;
374 }
375 throughReceiptRowId = (rows.at(-1)?.row_id ?? 1) - 1;
376 if (rows.length < COMPACTION_PAGE_SIZE) break;
377 }
378​
379 const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
380 const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
381 const reclaimableBytes =
382 (freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
383​
384 return { deletedEventCount, deletedReceiptCount, reclaimableBytes };
385 });
386​
387 return ProjectionMaintenanceV2.of({
388 verify: mapError("verify")(verify),
389 rebuild: mapError("rebuild")(rebuild),
390 compactEventStore: mapError("compact event store")(compactEventStore),
391 });
392 }),
393);