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/sql/SqlClient";
9
10import * as EventStore from "./EventStore.ts";
11import * as ProjectionStore from "./ProjectionStore.ts";
12
13export interface ProjectionVerificationV2 {
14 readonly valid: boolean;
15 readonly schemaVersion: number;
16 readonly expectedSequence: number;
17 readonly projectionSequence: number;
18 readonly unreadableThreadIds: ReadonlyArray<ThreadId>;
19 readonly missingThreadIds: ReadonlyArray<ThreadId>;
20 readonly unexpectedThreadIds: ReadonlyArray<ThreadId>;
21}
22
23export class ProjectionMaintenanceError extends Schema.TaggedError<ProjectionMaintenanceError>()(
24 "ProjectionMaintenanceError",
25 {
26 operation: Schema.String,
27 cause: Schema.optional(Schema.Defect()),
28 },
29) {}
30
31export interface ProjectionMaintenanceV2Shape {
32 readonly verify: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
33 readonly rebuild: Effect.Effect<ProjectionVerificationV2, ProjectionMaintenanceError>;
34 readonly compactEventStore: Effect.Effect<
35 {
36 readonly deletedEventCount: number;
37 readonly deletedReceiptCount: number;
38 readonly reclaimableBytes: number;
39 },
40 ProjectionMaintenanceError
41 >;
42}
43
44export class ProjectionMaintenanceV2 extends Context.Service<
45 ProjectionMaintenanceV2,
46 ProjectionMaintenanceV2Shape
47>()("t3/orchestration-v2/ProjectionMaintenance/ProjectionMaintenanceV2") {}
48
49type ProjectionMetadataRow = {
50 readonly schema_version: number;
51 readonly last_sequence: number;
52};
53
54const encodeEntityKey = Schema.encodeSync(
55 Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String, Schema.NullOr(Schema.String)])),
56);
57
58export const layer: Layer.Layer<
59 ProjectionMaintenanceV2,
60 never,
61 EventStore.EventStoreV2 | ProjectionStore.ProjectionStoreV2 | SqlClient.SqlClient
62> = Layer.effect(
63 ProjectionMaintenanceV2,
64 Effect.gen(function* () {
65 const sql = yield* SqlClient.SqlClient;
66 const eventStore = yield* EventStore.EventStoreV2;
67 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
68
69 const verify = Effect.gen(function* () {
70 const expectedThreadRows = yield* sql<{ readonly thread_id: string }>`
71 SELECT DISTINCT stream_id AS thread_id
72 FROM orchestration_events INDEXED BY orchestration_events_v2_created_threads_idx
73 WHERE application_event_version = 2
74 AND aggregate_kind = 'thread'
75 AND event_type = 'thread.created'
76 ORDER BY stream_id ASC
77 `;
78 const projectionRows = yield* sql<{ readonly thread_id: string }>`
79 SELECT thread_id
80 FROM orchestration_v2_projection_threads
81 ORDER BY thread_id ASC
82 `;
83 const actualIds = projectionRows.map((row) => ThreadId.make(row.thread_id));
84 const expectedIds = expectedThreadRows.map((row) => ThreadId.make(row.thread_id));
85 const actualSet = new Set(actualIds);
86 const expectedSet = new Set(expectedIds);
87 const missingThreadIds = expectedIds.filter((threadId) => !actualSet.has(threadId));
88 const unexpectedThreadIds = actualIds.filter((threadId) => !expectedSet.has(threadId));
89 const unreadableThreadIds = yield* projectionStore.getUnreadableThreadIds();
90 const metadata = yield* sql<ProjectionMetadataRow>`
91 SELECT schema_version, last_sequence
92 FROM orchestration_v2_projection_metadata
93 WHERE projection_name = 'thread-projections'
94 LIMIT 1
95 `;
96 const expectedSequence = yield* eventStore.latestSequence();
97 const schemaVersion = metadata[0]?.schema_version ?? 0;
98 const projectionSequence = metadata[0]?.last_sequence ?? 0;
99 return {
100 valid:
101 schemaVersion === ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION &&
102 projectionSequence === expectedSequence &&
103 missingThreadIds.length === 0 &&
104 unexpectedThreadIds.length === 0 &&
105 unreadableThreadIds.length === 0,
106 schemaVersion,
107 expectedSequence,
108 projectionSequence,
109 unreadableThreadIds,
110 missingThreadIds,
111 unexpectedThreadIds,
112 } satisfies ProjectionVerificationV2;
113 }).pipe(sql.withTransaction);
114
115 const rebuild = Effect.gen(function* () {
116 yield* sql.withTransaction(
117 Effect.gen(function* () {
118 const throughSequence = yield* eventStore.latestSequence();
119 yield* sql`DELETE FROM orchestration_v2_projection_context_transfers`;
120 yield* sql`DELETE FROM orchestration_v2_projection_context_handoffs`;
121 yield* sql`DELETE FROM orchestration_v2_projection_checkpoints`;
122 yield* sql`DELETE FROM orchestration_v2_projection_checkpoint_scopes`;
123 yield* sql`DELETE FROM orchestration_v2_projection_turn_items`;
124 yield* sql`DELETE FROM orchestration_v2_projection_plans`;
125 yield* sql`DELETE FROM orchestration_v2_projection_messages`;
126 yield* sql`DELETE FROM orchestration_v2_projection_runtime_requests`;
127 yield* sql`DELETE FROM orchestration_v2_projection_provider_turns`;
128 yield* sql`DELETE FROM orchestration_v2_projection_provider_threads`;
129 yield* sql`DELETE FROM orchestration_v2_projection_provider_session_bindings`;
130 yield* sql`DELETE FROM orchestration_v2_projection_provider_sessions`;
131 yield* sql`DELETE FROM orchestration_v2_projection_subagents`;
132 yield* sql`DELETE FROM orchestration_v2_projection_nodes`;
133 yield* sql`DELETE FROM orchestration_v2_projection_run_attempts`;
134 yield* sql`DELETE FROM orchestration_v2_projection_runs`;
135 yield* sql`DELETE FROM orchestration_v2_projection_thread_reads`;
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 do not bump updatedAt. They supersede only each other: a newer
222 // visit must not delete the rename that carries the activity timestamp,
223 // while any newer activity-bearing event supersedes both groups.
224 const READ_STATE_THREAD_EVENT_TYPES = [
225 "thread.visited",
226 "thread.marked-unread",
227 "thread.visit-recorded",
228 ];
229
230 const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
231 const readStateThreadEventTypes = new Set(READ_STATE_THREAD_EVENT_TYPES);
232 // Keep subagent.updated and turn-item.updated rows: slimmed payloads reference their prompts.
233 // Discovery runs on the shared synchronous connection; json_extract over
234 // large payloads made 500-row pages block the event loop for ~90ms.
235 const COMPACTION_PAGE_SIZE = 50;
236
237 /**
238 * Scan newest first to retain the newest state for each entity. Keyed
239 * entities (messages, nodes, PR links) also keep their oldest event: client
240 * reducers append an entity where they first see it, so a replay from any
241 * cursor must either carry that first event or find the entity already
242 * present. Only the events in between are deleted.
243 * Page every event, including non-candidates: filtering before LIMIT could
244 * still scan the entire history when superseded events are sparse.
245 * turn-item.updated stays intact because replay assigns positions on first write.
246 */
247 const compactEventStore = Effect.gen(function* () {
248 const bounds = yield* sql<{
249 readonly event_sequence: number;
250 readonly receipt_row_id: number;
251 }>`
252 SELECT
253 COALESCE((SELECT MAX(sequence) FROM orchestration_events), 0) AS event_sequence,
254 COALESCE((SELECT MAX(rowid) FROM orchestration_command_receipts), 0) AS receipt_row_id
255 `;
256 let throughSequence = bounds[0]?.event_sequence ?? 0;
257 let throughReceiptRowId = bounds[0]?.receipt_row_id ?? 0;
258 const retainedThreadIds = new Set<string>();
259 const retainedReadStateThreadIds = new Set<string>();
260 // Per key: the lowest sequence seen so far after the newest. It is
261 // deleted once an even older event turns up and kept otherwise.
262 const oldestCandidateByEntityKey = new Map<string, number | null>();
263 let deletedEventCount = 0;
264 let deletedReceiptCount = 0;
265
266 while (throughSequence > 0) {
267 const rows = yield* sql<{
268 readonly sequence: number;
269 readonly application_event_version: number;
270 readonly aggregate_kind: string;
271 readonly stream_id: string;
272 readonly event_type: string;
273 readonly entity_id: string | null;
274 readonly imported_legacy_thread: number;
275 }>`
276 SELECT
277 event.sequence,
278 event.application_event_version,
279 event.aggregate_kind,
280 event.stream_id,
281 event.event_type,
282 CASE
283 WHEN event.application_event_version = 2
284 AND event.event_type IN ('message.updated', 'node.updated')
285 THEN json_extract(event.payload_json, '$.id')
286 WHEN event.application_event_version = 2
287 AND event.event_type IN ('thread.pull-request-link-updated', 'thread.pull-request-link-synced')
288 THEN json_array(json_extract(event.payload_json, '$.host'),
289 json_extract(event.payload_json, '$.repository'),
290 json_extract(event.payload_json, '$.number'))
291 ELSE NULL
292 END AS entity_id,
293 CASE
294 WHEN event.application_event_version = 1 AND event.aggregate_kind = 'thread'
295 THEN EXISTS (
296 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
297 WHERE legacy_import.thread_id = event.stream_id
298 AND legacy_import.transcript_imported_at IS NOT NULL
299 )
300 ELSE 0
301 END AS imported_legacy_thread
302 FROM orchestration_events AS event
303 WHERE event.sequence <= ${throughSequence}
304 ORDER BY event.sequence DESC
305 LIMIT ${COMPACTION_PAGE_SIZE}
306 `;
307 const obsolete: number[] = [];
308 for (const row of rows) {
309 if (row.imported_legacy_thread === 1) {
310 obsolete.push(row.sequence);
311 } else if (row.application_event_version === 2) {
312 if (
313 row.aggregate_kind === "thread" &&
314 supersedableThreadEventTypes.has(row.event_type)
315 ) {
316 if (retainedThreadIds.has(row.stream_id)) obsolete.push(row.sequence);
317 else retainedThreadIds.add(row.stream_id);
318 } else if (
319 row.aggregate_kind === "thread" &&
320 readStateThreadEventTypes.has(row.event_type)
321 ) {
322 if (
323 retainedThreadIds.has(row.stream_id) ||
324 retainedReadStateThreadIds.has(row.stream_id)
325 ) {
326 obsolete.push(row.sequence);
327 } else retainedReadStateThreadIds.add(row.stream_id);
328 } else if (
329 (row.event_type === "thread.pull-request-link-updated" ||
330 row.event_type === "thread.pull-request-link-synced") &&
331 retainedThreadIds.has(row.stream_id)
332 ) {
333 // A newer whole-thread payload already carries this link's state.
334 obsolete.push(row.sequence);
335 } else if (
336 row.event_type === "thread.pull-request-link-updated" ||
337 row.event_type === "thread.pull-request-link-synced" ||
338 row.event_type === "message.updated" ||
339 row.event_type === "node.updated"
340 ) {
341 const key = encodeEntityKey([row.event_type, row.stream_id, row.entity_id]);
342 const candidate = oldestCandidateByEntityKey.get(key);
343 if (candidate === undefined) oldestCandidateByEntityKey.set(key, null);
344 else {
345 if (candidate !== null) obsolete.push(candidate);
346 oldestCandidateByEntityKey.set(key, row.sequence);
347 }
348 }
349 }
350 }
351 // Both discovery and deletion use the synchronous connection. Yield even
352 // when this page has nothing to delete so startup and requests can progress.
353 yield* Effect.yieldNow;
354 if (obsolete.length > 0) {
355 yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
356 deletedEventCount += obsolete.length;
357 yield* Effect.yieldNow;
358 }
359 throughSequence = (rows.at(-1)?.sequence ?? 1) - 1;
360 if (rows.length < COMPACTION_PAGE_SIZE) break;
361 }
362
363 while (throughReceiptRowId > 0) {
364 const rows = yield* sql<{
365 readonly row_id: number;
366 readonly command_id: string;
367 readonly imported_legacy_thread: number;
368 }>`
369 SELECT
370 receipt.rowid AS row_id,
371 receipt.command_id,
372 CASE
373 WHEN receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread'
374 THEN EXISTS (
375 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
376 WHERE legacy_import.thread_id = receipt.aggregate_id
377 AND legacy_import.transcript_imported_at IS NOT NULL
378 )
379 ELSE 0
380 END AS imported_legacy_thread
381 FROM orchestration_command_receipts AS receipt
382 WHERE receipt.rowid <= ${throughReceiptRowId}
383 ORDER BY receipt.rowid DESC
384 LIMIT ${COMPACTION_PAGE_SIZE}
385 `;
386 const obsolete = rows
387 .filter((row) => row.imported_legacy_thread === 1)
388 .map((row) => row.command_id);
389 yield* Effect.yieldNow;
390 if (obsolete.length > 0) {
391 yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(obsolete)}`;
392 deletedReceiptCount += obsolete.length;
393 yield* Effect.yieldNow;
394 }
395 throughReceiptRowId = (rows.at(-1)?.row_id ?? 1) - 1;
396 if (rows.length < COMPACTION_PAGE_SIZE) break;
397 }
398
399 const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
400 const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
401 const reclaimableBytes =
402 (freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
403
404 return { deletedEventCount, deletedReceiptCount, reclaimableBytes };
405 });
406
407 return ProjectionMaintenanceV2.of({
408 verify: mapError("verify")(verify),
409 rebuild: mapError("rebuild")(rebuild),
410 compactEventStore: mapError("compact event store")(compactEventStore),
411 });
412 }),
413);