Open History to see the last commit
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>;
22}
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 >;
43}
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 // thread.created stays out — verify derives the expected thread set from
200 // it, and it anchors replay ordering. thread.deleted stays out too: clients
201 // and waitForThread switch on the event type, not just the payload.
202 const SUPERSEDABLE_THREAD_EVENT_TYPES = [
203 "thread.archived",
204 "thread.unarchived",
205 "thread.settled",
206 "thread.unsettled",
207 "thread.snoozed",
208 "thread.unsnoozed",
209 "thread.pinned",
210 "thread.auto-settle-set",
211 "thread.unpinned",
212 "thread.pin-reordered",
213 "thread.active-reordered",
214 "thread.metadata-updated",
215 "thread.pull-request-synced",
216 "thread.runtime-mode-updated",
217 "thread.interaction-mode-updated",
218 "thread.model-selection-updated",
219 "thread.provider-switched",
220 ];
221 // Read-state events carry the whole thread too, but client reducers apply
222 // them without bumping updatedAt. They supersede only each other: a newer
223 // visit must not delete the rename that carries the activity timestamp,
224 // while any newer activity-bearing event supersedes both groups.
225 const READ_STATE_THREAD_EVENT_TYPES = ["thread.visited", "thread.marked-unread"];
226
227 const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
228 const readStateThreadEventTypes = new Set(READ_STATE_THREAD_EVENT_TYPES);
229 // Keep subagent.updated and turn-item.updated rows: slimmed payloads reference their prompts.
230 // Small pages bound work on the reader worker and synchronous fallback.
231 const COMPACTION_PAGE_SIZE = 50;
232
233 /**
234 * Scan newest first to retain the newest state for each entity. Keyed
235 * entities (messages, nodes, PR links) also keep their oldest event: client
236 * reducers append an entity where they first see it, so a replay from any
237 * cursor must either carry that first event or find the entity already
238 * present. Only the events in between are deleted.
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 retainedReadStateThreadIds = new Set<string>();
256 // Per key: the lowest sequence seen so far after the newest. It is
257 // deleted once an even older event turns up and kept otherwise.
258 const oldestCandidateByEntityKey = new Map<string, number | null>();
259 let deletedEventCount = 0;
260 let deletedReceiptCount = 0;
261
262 while (throughSequence > 0) {
263 const rows = yield* sql<{
264 readonly sequence: number;
265 readonly application_event_version: number;
266 readonly aggregate_kind: string;
267 readonly stream_id: string;
268 readonly event_type: string;
269 readonly entity_id: string | null;
270 readonly imported_legacy_thread: number;
271 }>`
272 SELECT
273 event.sequence,
274 event.application_event_version,
275 event.aggregate_kind,
276 event.stream_id,
277 event.event_type,
278 CASE
279 WHEN event.application_event_version = 2
280 AND event.event_type IN ('message.updated', 'node.updated')
281 THEN json_extract(event.payload_json, '$.id')
282 WHEN event.application_event_version = 2
283 AND event.event_type = 'thread.pull-request-link-updated'
284 THEN json_array(json_extract(event.payload_json, '$.host'),
285 json_extract(event.payload_json, '$.repository'),
286 json_extract(event.payload_json, '$.number'))
287 ELSE NULL
288 END AS entity_id,
289 CASE
290 WHEN event.application_event_version = 1 AND event.aggregate_kind = 'thread'
291 THEN EXISTS (
292 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
293 WHERE legacy_import.thread_id = event.stream_id
294 AND legacy_import.transcript_imported_at IS NOT NULL
295 )
296 ELSE 0
297 END AS imported_legacy_thread
298 FROM orchestration_events AS event
299 WHERE event.sequence <= ${throughSequence}
300 ORDER BY event.sequence DESC
301 LIMIT ${COMPACTION_PAGE_SIZE}
302 `.pipe(NodeSqliteClient.readOnly);
303 const obsolete: number[] = [];
304 for (const row of rows) {
305 if (row.imported_legacy_thread === 1) {
306 obsolete.push(row.sequence);
307 } else if (row.application_event_version === 2) {
308 if (
309 row.aggregate_kind === "thread" &&
310 supersedableThreadEventTypes.has(row.event_type)
311 ) {
312 if (retainedThreadIds.has(row.stream_id)) obsolete.push(row.sequence);
313 else retainedThreadIds.add(row.stream_id);
314 } else if (
315 row.aggregate_kind === "thread" &&
316 readStateThreadEventTypes.has(row.event_type)
317 ) {
318 if (
319 retainedThreadIds.has(row.stream_id) ||
320 retainedReadStateThreadIds.has(row.stream_id)
321 ) {
322 obsolete.push(row.sequence);
323 } else retainedReadStateThreadIds.add(row.stream_id);
324 } else if (
325 row.event_type === "thread.pull-request-link-updated" &&
326 retainedThreadIds.has(row.stream_id)
327 ) {
328 // A newer whole-thread payload already carries this link's state.
329 obsolete.push(row.sequence);
330 } else if (
331 row.event_type === "thread.pull-request-link-updated" ||
332 row.event_type === "message.updated" ||
333 row.event_type === "node.updated"
334 ) {
335 const key = encodeEntityKey([row.event_type, row.stream_id, row.entity_id]);
336 const candidate = oldestCandidateByEntityKey.get(key);
337 if (candidate === undefined) oldestCandidateByEntityKey.set(key, null);
338 else {
339 if (candidate !== null) obsolete.push(candidate);
340 oldestCandidateByEntityKey.set(key, row.sequence);
341 }
342 }
343 }
344 }
345 // Yield even without deletions for clients using the synchronous fallback.
346 yield* Effect.yieldNow;
347 if (obsolete.length > 0) {
348 yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
349 deletedEventCount += obsolete.length;
350 yield* Effect.yieldNow;
351 }
352 throughSequence = (rows.at(-1)?.sequence ?? 1) - 1;
353 if (rows.length < COMPACTION_PAGE_SIZE) break;
354 }
355
356 while (throughReceiptRowId > 0) {
357 const rows = yield* sql<{
358 readonly row_id: number;
359 readonly command_id: string;
360 readonly imported_legacy_thread: number;
361 }>`
362 SELECT
363 receipt.rowid AS row_id,
364 receipt.command_id,
365 CASE
366 WHEN receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread'
367 THEN EXISTS (
368 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
369 WHERE legacy_import.thread_id = receipt.aggregate_id
370 AND legacy_import.transcript_imported_at IS NOT NULL
371 )
372 ELSE 0
373 END AS imported_legacy_thread
374 FROM orchestration_command_receipts AS receipt
375 WHERE receipt.rowid <= ${throughReceiptRowId}
376 ORDER BY receipt.rowid DESC
377 LIMIT ${COMPACTION_PAGE_SIZE}
378 `.pipe(NodeSqliteClient.readOnly);
379 const obsolete = rows
380 .filter((row) => row.imported_legacy_thread === 1)
381 .map((row) => row.command_id);
382 yield* Effect.yieldNow;
383 if (obsolete.length > 0) {
384 yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(obsolete)}`;
385 deletedReceiptCount += obsolete.length;
386 yield* Effect.yieldNow;
387 }
388 throughReceiptRowId = (rows.at(-1)?.row_id ?? 1) - 1;
389 if (rows.length < COMPACTION_PAGE_SIZE) break;
390 }
391
392 const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
393 const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
394 const reclaimableBytes =
395 (freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
396
397 return { deletedEventCount, deletedReceiptCount, reclaimableBytes };
398 });
399
400 return ProjectionMaintenanceV2.of({
401 verify: mapError("verify")(verify),
402 rebuild: mapError("rebuild")(rebuild),
403 compactEventStore: mapError("compact event store")(compactEventStore),
404 });
405 }),
406);