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