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_threads`;
136 yield* sql`DELETE FROM orchestration_v2_turn_item_positions`;
137
138 const pageSize = 500;
139 let lastSequence = 0;
140 while (true) {
141 const page = yield* eventStore
142 .read({ afterSequence: lastSequence, throughSequence, limit: pageSize })
143 .pipe(Stream.runCollect);
144 for (const stored of page) {
145 yield* projectionStore.apply(stored.event);
146 if (stored.event.type === "turn-item.updated") {
147 yield* sql`
148 INSERT INTO orchestration_v2_turn_item_positions (
149 thread_id,
150 turn_item_id,
151 ordinal
152 )
153 VALUES (
154 ${stored.event.threadId},
155 ${stored.event.payload.id},
156 ${stored.event.payload.ordinal}
157 )
158 ON CONFLICT(thread_id, turn_item_id) DO UPDATE SET
159 ordinal = excluded.ordinal
160 `;
161 }
162 lastSequence = stored.sequence;
163 }
164 if (page.length < pageSize) break;
165 yield* Effect.yieldNow;
166 }
167 const now = DateTime.formatIso(yield* DateTime.now);
168 yield* sql`
169 INSERT INTO orchestration_v2_projection_metadata (
170 projection_name,
171 schema_version,
172 last_sequence,
173 updated_at
174 )
175 VALUES (
176 'thread-projections',
177 ${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
178 ${lastSequence},
179 ${now}
180 )
181 ON CONFLICT(projection_name) DO UPDATE SET
182 schema_version = excluded.schema_version,
183 last_sequence = excluded.last_sequence,
184 updated_at = excluded.updated_at
185 `;
186 }),
187 );
188 return yield* verify;
189 });
190
191 const mapError =
192 (operation: string) =>
193 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
194 effect.pipe(
195 Effect.mapError((cause) => new ProjectionMaintenanceError({ operation, cause })),
196 );
197
198 // thread.created stays out — verify derives the expected thread set from
199 // it, and it anchors replay ordering. thread.deleted stays out too: clients
200 // and waitForThread switch on the event type, not just the payload.
201 const SUPERSEDABLE_THREAD_EVENT_TYPES = [
202 "thread.archived",
203 "thread.unarchived",
204 "thread.settled",
205 "thread.unsettled",
206 "thread.snoozed",
207 "thread.unsnoozed",
208 "thread.pinned",
209 "thread.auto-settle-set",
210 "thread.unpinned",
211 "thread.pin-reordered",
212 "thread.active-reordered",
213 "thread.metadata-updated",
214 "thread.pull-request-synced",
215 "thread.runtime-mode-updated",
216 "thread.interaction-mode-updated",
217 "thread.model-selection-updated",
218 "thread.provider-switched",
219 ];
220 // Read-state events carry the whole thread too, but client reducers apply
221 // them without bumping 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 = ["thread.visited", "thread.marked-unread"];
225
226 const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
227 const readStateThreadEventTypes = new Set(READ_STATE_THREAD_EVENT_TYPES);
228 // Keep subagent.updated and turn-item.updated rows: slimmed payloads reference their prompts.
229 // Discovery runs on the shared synchronous connection; json_extract over
230 // large payloads made 500-row pages block the event loop for ~90ms.
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 `;
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 // Both discovery and deletion use the synchronous connection. Yield even
346 // when this page has nothing to delete so startup and requests can progress.
347 yield* Effect.yieldNow;
348 if (obsolete.length > 0) {
349 yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
350 deletedEventCount += obsolete.length;
351 yield* Effect.yieldNow;
352 }
353 throughSequence = (rows.at(-1)?.sequence ?? 1) - 1;
354 if (rows.length < COMPACTION_PAGE_SIZE) break;
355 }
356
357 while (throughReceiptRowId > 0) {
358 const rows = yield* sql<{
359 readonly row_id: number;
360 readonly command_id: string;
361 readonly imported_legacy_thread: number;
362 }>`
363 SELECT
364 receipt.rowid AS row_id,
365 receipt.command_id,
366 CASE
367 WHEN receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread'
368 THEN EXISTS (
369 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
370 WHERE legacy_import.thread_id = receipt.aggregate_id
371 AND legacy_import.transcript_imported_at IS NOT NULL
372 )
373 ELSE 0
374 END AS imported_legacy_thread
375 FROM orchestration_command_receipts AS receipt
376 WHERE receipt.rowid <= ${throughReceiptRowId}
377 ORDER BY receipt.rowid DESC
378 LIMIT ${COMPACTION_PAGE_SIZE}
379 `;
380 const obsolete = rows
381 .filter((row) => row.imported_legacy_thread === 1)
382 .map((row) => row.command_id);
383 yield* Effect.yieldNow;
384 if (obsolete.length > 0) {
385 yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(obsolete)}`;
386 deletedReceiptCount += obsolete.length;
387 yield* Effect.yieldNow;
388 }
389 throughReceiptRowId = (rows.at(-1)?.row_id ?? 1) - 1;
390 if (rows.length < COMPACTION_PAGE_SIZE) break;
391 }
392
393 const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
394 const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
395 const reclaimableBytes =
396 (freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
397
398 return { deletedEventCount, deletedReceiptCount, reclaimableBytes };
399 });
400
401 return ProjectionMaintenanceV2.of({
402 verify: mapError("verify")(verify),
403 rebuild: mapError("rebuild")(rebuild),
404 compactEventStore: mapError("compact event store")(compactEventStore),
405 });
406 }),
407);