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

ProjectionMaintenance.ts

405 lines17.1 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: (betweenPages?: Effect.Effect<void>) => 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 // Subagent snapshots stay intact because later rows can reference an earlier prompt.
226 // Commanded turn items stay for command-result replay.
227 // Small pages bound work on the reader worker and synchronous fallback.
228 const COMPACTION_PAGE_SIZE = 50;
229​
230 // Keep first/latest keyed events for replay order; page every event to bound sparse scans.
231 const compactEventStore = Effect.fn("ProjectionMaintenance.compactEventStore")(function* (
232 betweenPages: Effect.Effect<void> = Effect.void,
233 ) {
234 const bounds = yield* sql<{
235 readonly event_sequence: number;
236 readonly receipt_row_id: number;
237 }>`
238 SELECT
239 COALESCE((SELECT MAX(sequence) FROM orchestration_events), 0) AS event_sequence,
240 COALESCE((SELECT MAX(rowid) FROM orchestration_command_receipts), 0) AS receipt_row_id
241 `.pipe(NodeSqliteClient.readOnly);
242 let throughSequence = bounds[0]?.event_sequence ?? 0;
243 let throughReceiptRowId = bounds[0]?.receipt_row_id ?? 0;
244 const retainedThreadIds = new Set<string>();
245 const retainedReadStateThreadIds = new Set<string>();
246 // Retain each key's oldest candidate, deleting it only when an older event appears.
247 const oldestCandidateByEntityKey = new Map<string, number | null>();
248 let deletedEventCount = 0;
249 let deletedReceiptCount = 0;
250​
251 while (throughSequence > 0) {
252 const rows = yield* sql<{
253 readonly sequence: number;
254 readonly application_event_version: number;
255 readonly aggregate_kind: string;
256 readonly stream_id: string;
257 readonly event_type: string;
258 readonly entity_id: string | null;
259 readonly imported_legacy_thread: number;
260 }>`
261 SELECT
262 event.sequence,
263 event.application_event_version,
264 event.aggregate_kind,
265 event.stream_id,
266 event.event_type,
267 CASE
268 WHEN event.application_event_version = 2
269 AND event.event_type IN ('message.updated', 'node.updated')
270 THEN json_extract(event.payload_json, '$.id')
271 WHEN event.application_event_version = 2
272 AND event.event_type = 'turn-item.updated'
273 AND event.command_id IS NULL
274 AND json_extract(event.payload_json, '$.type') <> 'subagent'
275 THEN json_extract(event.payload_json, '$.id')
276 WHEN event.application_event_version = 2
277 AND event.event_type = 'thread.pull-request-link-updated'
278 THEN json_array(json_extract(event.payload_json, '$.host'),
279 json_extract(event.payload_json, '$.repository'),
280 json_extract(event.payload_json, '$.number'))
281 ELSE NULL
282 END AS entity_id,
283 CASE
284 WHEN event.application_event_version = 1 AND event.aggregate_kind = 'thread'
285 THEN EXISTS (
286 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
287 WHERE legacy_import.thread_id = event.stream_id
288 AND legacy_import.transcript_imported_at IS NOT NULL
289 )
290 ELSE 0
291 END AS imported_legacy_thread
292 FROM orchestration_events AS event
293 WHERE event.sequence <= ${throughSequence}
294 ORDER BY event.sequence DESC
295 LIMIT ${COMPACTION_PAGE_SIZE + 1}
296 `.pipe(NodeSqliteClient.readOnly);
297 const page = rows.slice(0, COMPACTION_PAGE_SIZE);
298 const obsolete: number[] = [];
299 for (const row of page) {
300 if (row.imported_legacy_thread === 1) {
301 obsolete.push(row.sequence);
302 } else if (row.application_event_version === 2) {
303 if (
304 row.aggregate_kind === "thread" &&
305 supersedableThreadEventTypes.has(row.event_type)
306 ) {
307 if (retainedThreadIds.has(row.stream_id)) obsolete.push(row.sequence);
308 else retainedThreadIds.add(row.stream_id);
309 } else if (
310 row.aggregate_kind === "thread" &&
311 readStateThreadEventTypes.has(row.event_type)
312 ) {
313 if (
314 retainedThreadIds.has(row.stream_id) ||
315 retainedReadStateThreadIds.has(row.stream_id)
316 ) {
317 obsolete.push(row.sequence);
318 } else retainedReadStateThreadIds.add(row.stream_id);
319 } else if (
320 row.event_type === "thread.pull-request-link-updated" &&
321 retainedThreadIds.has(row.stream_id)
322 ) {
323 // A newer whole-thread payload already carries this link's state.
324 obsolete.push(row.sequence);
325 } else if (
326 row.event_type === "thread.pull-request-link-updated" ||
327 row.event_type === "message.updated" ||
328 row.event_type === "node.updated" ||
329 (row.event_type === "turn-item.updated" && row.entity_id !== null)
330 ) {
331 const key = encodeEntityKey([row.event_type, row.stream_id, row.entity_id]);
332 const candidate = oldestCandidateByEntityKey.get(key);
333 if (candidate === undefined) oldestCandidateByEntityKey.set(key, null);
334 else {
335 if (candidate !== null) obsolete.push(candidate);
336 oldestCandidateByEntityKey.set(key, row.sequence);
337 }
338 }
339 }
340 }
341 // Never hold a transaction or the reader lock across a yield or a rest.
342 yield* Effect.yieldNow;
343 if (obsolete.length > 0) {
344 yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
345 deletedEventCount += obsolete.length;
346 yield* Effect.yieldNow;
347 }
348 throughSequence =
349 rows.length <= COMPACTION_PAGE_SIZE ? 0 : (page.at(-1)?.sequence ?? 1) - 1;
350 if (throughSequence > 0 || throughReceiptRowId > 0) yield* betweenPages;
351 }
352​
353 while (throughReceiptRowId > 0) {
354 const rows = yield* sql<{
355 readonly row_id: number;
356 readonly command_id: string;
357 readonly imported_legacy_thread: number;
358 }>`
359 SELECT
360 receipt.rowid AS row_id,
361 receipt.command_id,
362 CASE
363 WHEN receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread'
364 THEN EXISTS (
365 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
366 WHERE legacy_import.thread_id = receipt.aggregate_id
367 AND legacy_import.transcript_imported_at IS NOT NULL
368 )
369 ELSE 0
370 END AS imported_legacy_thread
371 FROM orchestration_command_receipts AS receipt
372 WHERE receipt.rowid <= ${throughReceiptRowId}
373 ORDER BY receipt.rowid DESC
374 LIMIT ${COMPACTION_PAGE_SIZE + 1}
375 `.pipe(NodeSqliteClient.readOnly);
376 const page = rows.slice(0, COMPACTION_PAGE_SIZE);
377 const obsolete = page
378 .filter((row) => row.imported_legacy_thread === 1)
379 .map((row) => row.command_id);
380 yield* Effect.yieldNow;
381 if (obsolete.length > 0) {
382 yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(obsolete)}`;
383 deletedReceiptCount += obsolete.length;
384 yield* Effect.yieldNow;
385 }
386 throughReceiptRowId = (page.at(-1)?.row_id ?? 1) - 1;
387 if (rows.length <= COMPACTION_PAGE_SIZE) break;
388 yield* betweenPages;
389 }
390​
391 const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
392 const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
393 const reclaimableBytes =
394 (freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
395​
396 return { deletedEventCount, deletedReceiptCount, reclaimableBytes };
397 }, mapError("compact event store"));
398​
399 return ProjectionMaintenanceV2.of({
400 verify: mapError("verify")(verify),
401 rebuild: mapError("rebuild")(rebuild),
402 compactEventStore,
403 });
404 }),
405);