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 /**
70 * EventSink commits the event, its projection updates, and projection metadata in one SQL
71 * transaction. Startup verification therefore checks that transaction boundary and that every
72 * stored projection can be decoded. It intentionally does not replay domain events through a
73 * second projector: doing so creates another implementation of projection semantics that must
74 * evolve in lockstep with ProjectionStore.
75 */
76 const verify = Effect.gen(function* () {
77 const expectedThreadRows = yield* sql<{ readonly thread_id: string }>`
78 SELECT DISTINCT stream_id AS thread_id
79 FROM orchestration_events INDEXED BY orchestration_events_v2_created_threads_idx
80 WHERE application_event_version = 2
81 AND aggregate_kind = 'thread'
82 AND event_type = 'thread.created'
83 ORDER BY stream_id ASC
84 `;
85 const projectionRows = yield* sql<{ readonly thread_id: string }>`
86 SELECT thread_id
87 FROM orchestration_v2_projection_threads
88 ORDER BY thread_id ASC
89 `;
90 const actualIds = projectionRows.map((row) => ThreadId.make(row.thread_id));
91 const expectedIds = expectedThreadRows.map((row) => ThreadId.make(row.thread_id));
92 const actualSet = new Set(actualIds);
93 const expectedSet = new Set(expectedIds);
94 const missingThreadIds = expectedIds.filter((threadId) => !actualSet.has(threadId));
95 const unexpectedThreadIds = actualIds.filter((threadId) => !expectedSet.has(threadId));
96 const unreadableThreadIds = yield* projectionStore.getUnreadableThreadIds();
97 const metadata = yield* sql<ProjectionMetadataRow>`
98 SELECT schema_version, last_sequence
99 FROM orchestration_v2_projection_metadata
100 WHERE projection_name = 'thread-projections'
101 LIMIT 1
102 `;
103 const expectedSequence = yield* eventStore.latestSequence();
104 const schemaVersion = metadata[0]?.schema_version ?? 0;
105 const projectionSequence = metadata[0]?.last_sequence ?? 0;
106 return {
107 valid:
108 schemaVersion === ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION &&
109 projectionSequence === expectedSequence &&
110 missingThreadIds.length === 0 &&
111 unexpectedThreadIds.length === 0 &&
112 unreadableThreadIds.length === 0,
113 schemaVersion,
114 expectedSequence,
115 projectionSequence,
116 unreadableThreadIds,
117 missingThreadIds,
118 unexpectedThreadIds,
119 } satisfies ProjectionVerificationV2;
120 }).pipe(sql.withTransaction);
121
122 const rebuild = Effect.gen(function* () {
123 yield* sql.withTransaction(
124 Effect.gen(function* () {
125 const throughSequence = yield* eventStore.latestSequence();
126 yield* sql`DELETE FROM orchestration_v2_projection_context_transfers`;
127 yield* sql`DELETE FROM orchestration_v2_projection_context_handoffs`;
128 yield* sql`DELETE FROM orchestration_v2_projection_checkpoints`;
129 yield* sql`DELETE FROM orchestration_v2_projection_checkpoint_scopes`;
130 yield* sql`DELETE FROM orchestration_v2_projection_turn_items`;
131 yield* sql`DELETE FROM orchestration_v2_projection_plans`;
132 yield* sql`DELETE FROM orchestration_v2_projection_messages`;
133 yield* sql`DELETE FROM orchestration_v2_projection_runtime_requests`;
134 yield* sql`DELETE FROM orchestration_v2_projection_provider_turns`;
135 yield* sql`DELETE FROM orchestration_v2_projection_provider_threads`;
136 yield* sql`DELETE FROM orchestration_v2_projection_provider_session_bindings`;
137 yield* sql`DELETE FROM orchestration_v2_projection_provider_sessions`;
138 yield* sql`DELETE FROM orchestration_v2_projection_subagents`;
139 yield* sql`DELETE FROM orchestration_v2_projection_nodes`;
140 yield* sql`DELETE FROM orchestration_v2_projection_run_attempts`;
141 yield* sql`DELETE FROM orchestration_v2_projection_runs`;
142 yield* sql`DELETE FROM orchestration_v2_projection_threads`;
143 yield* sql`DELETE FROM orchestration_v2_turn_item_positions`;
144
145 const pageSize = 500;
146 let lastSequence = 0;
147 while (true) {
148 const page = yield* eventStore
149 .read({ afterSequence: lastSequence, throughSequence, limit: pageSize })
150 .pipe(Stream.runCollect);
151 for (const stored of page) {
152 yield* projectionStore.apply(stored.event);
153 if (stored.event.type === "turn-item.updated") {
154 yield* sql`
155 INSERT INTO orchestration_v2_turn_item_positions (
156 thread_id,
157 turn_item_id,
158 ordinal
159 )
160 VALUES (
161 ${stored.event.threadId},
162 ${stored.event.payload.id},
163 ${stored.event.payload.ordinal}
164 )
165 ON CONFLICT(thread_id, turn_item_id) DO UPDATE SET
166 ordinal = excluded.ordinal
167 `;
168 }
169 lastSequence = stored.sequence;
170 }
171 if (page.length < pageSize) break;
172 yield* Effect.yieldNow;
173 }
174 const now = DateTime.formatIso(yield* DateTime.now);
175 yield* sql`
176 INSERT INTO orchestration_v2_projection_metadata (
177 projection_name,
178 schema_version,
179 last_sequence,
180 updated_at
181 )
182 VALUES (
183 'thread-projections',
184 ${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
185 ${lastSequence},
186 ${now}
187 )
188 ON CONFLICT(projection_name) DO UPDATE SET
189 schema_version = excluded.schema_version,
190 last_sequence = excluded.last_sequence,
191 updated_at = excluded.updated_at
192 `;
193 }),
194 );
195 return yield* verify;
196 });
197
198 const mapError =
199 (operation: string) =>
200 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
201 effect.pipe(
202 Effect.mapError((cause) => new ProjectionMaintenanceError({ operation, cause })),
203 );
204
205 // Thread-state events whose payload is the complete thread: only the
206 // newest per thread can influence a replay or an afterSequence catch-up.
207 // thread.created stays out — verify derives the expected thread set from
208 // it, and it anchors replay ordering.
209 const SUPERSEDABLE_THREAD_EVENT_TYPES = [
210 "thread.archived",
211 "thread.unarchived",
212 "thread.deleted",
213 "thread.settled",
214 "thread.unsettled",
215 "thread.snoozed",
216 "thread.unsnoozed",
217 "thread.pinned",
218 "thread.auto-settle-set",
219 "thread.unpinned",
220 "thread.pin-reordered",
221 "thread.active-reordered",
222 "thread.metadata-updated",
223 "thread.pull-request-synced",
224 "thread.runtime-mode-updated",
225 "thread.interaction-mode-updated",
226 "thread.model-selection-updated",
227 "thread.provider-switched",
228 "thread.visited",
229 "thread.marked-unread",
230 ];
231
232 const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
233 // Keep subagent.updated and turn-item.updated rows: slimmed payloads reference their prompts.
234 const COMPACTION_PAGE_SIZE = 500;
235
236 /**
237 * Scan newest first to retain the newest state for each entity.
238 * Page every event, including non-candidates: filtering before LIMIT could
239 * still scan the entire history when superseded events are sparse.
240 * turn-item.updated stays intact because replay assigns positions on first write.
241 */
242 const compactEventStore = Effect.gen(function* () {
243 const bounds = yield* sql<{
244 readonly event_sequence: number;
245 readonly receipt_row_id: number;
246 }>`
247 SELECT
248 COALESCE((SELECT MAX(sequence) FROM orchestration_events), 0) AS event_sequence,
249 COALESCE((SELECT MAX(rowid) FROM orchestration_command_receipts), 0) AS receipt_row_id
250 `;
251 let throughSequence = bounds[0]?.event_sequence ?? 0;
252 let throughReceiptRowId = bounds[0]?.receipt_row_id ?? 0;
253 const retainedThreadIds = new Set<string>();
254 const retainedEntityKeys = new Set<string>();
255 let deletedEventCount = 0;
256 let deletedReceiptCount = 0;
257
258 while (throughSequence > 0) {
259 const rows = yield* sql<{
260 readonly sequence: number;
261 readonly application_event_version: number;
262 readonly aggregate_kind: string;
263 readonly stream_id: string;
264 readonly event_type: string;
265 readonly entity_id: string | null;
266 readonly imported_legacy_thread: number;
267 }>`
268 SELECT
269 event.sequence,
270 event.application_event_version,
271 event.aggregate_kind,
272 event.stream_id,
273 event.event_type,
274 CASE
275 WHEN event.application_event_version = 2
276 AND event.event_type IN ('message.updated', 'node.updated')
277 THEN json_extract(event.payload_json, '$.id')
278 ELSE NULL
279 END AS entity_id,
280 CASE
281 WHEN event.application_event_version = 1 AND event.aggregate_kind = 'thread'
282 THEN EXISTS (
283 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
284 WHERE legacy_import.thread_id = event.stream_id
285 AND legacy_import.transcript_imported_at IS NOT NULL
286 )
287 ELSE 0
288 END AS imported_legacy_thread
289 FROM orchestration_events AS event
290 WHERE event.sequence <= ${throughSequence}
291 ORDER BY event.sequence DESC
292 LIMIT ${COMPACTION_PAGE_SIZE}
293 `;
294 const obsolete: number[] = [];
295 for (const row of rows) {
296 if (row.imported_legacy_thread === 1) {
297 obsolete.push(row.sequence);
298 } else if (row.application_event_version === 2) {
299 if (
300 row.aggregate_kind === "thread" &&
301 supersedableThreadEventTypes.has(row.event_type)
302 ) {
303 if (retainedThreadIds.has(row.stream_id)) obsolete.push(row.sequence);
304 else retainedThreadIds.add(row.stream_id);
305 } else if (row.event_type === "message.updated" || row.event_type === "node.updated") {
306 const key = encodeEntityKey([row.event_type, row.stream_id, row.entity_id]);
307 if (retainedEntityKeys.has(key)) obsolete.push(row.sequence);
308 else retainedEntityKeys.add(key);
309 }
310 }
311 }
312 // Both discovery and deletion use the synchronous connection. Yield even
313 // when this page has nothing to delete so startup and requests can progress.
314 yield* Effect.yieldNow;
315 if (obsolete.length > 0) {
316 yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
317 deletedEventCount += obsolete.length;
318 yield* Effect.yieldNow;
319 }
320 throughSequence = (rows.at(-1)?.sequence ?? 1) - 1;
321 if (rows.length < COMPACTION_PAGE_SIZE) break;
322 }
323
324 // Legacy receipts are removable only after their thread's v1 import finishes.
325 // Page by rowid before checking eligibility, as with event discovery above.
326 while (throughReceiptRowId > 0) {
327 const rows = yield* sql<{
328 readonly row_id: number;
329 readonly command_id: string;
330 readonly imported_legacy_thread: number;
331 }>`
332 SELECT
333 receipt.rowid AS row_id,
334 receipt.command_id,
335 CASE
336 WHEN receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread'
337 THEN EXISTS (
338 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
339 WHERE legacy_import.thread_id = receipt.aggregate_id
340 AND legacy_import.transcript_imported_at IS NOT NULL
341 )
342 ELSE 0
343 END AS imported_legacy_thread
344 FROM orchestration_command_receipts AS receipt
345 WHERE receipt.rowid <= ${throughReceiptRowId}
346 ORDER BY receipt.rowid DESC
347 LIMIT ${COMPACTION_PAGE_SIZE}
348 `;
349 const obsolete = rows
350 .filter((row) => row.imported_legacy_thread === 1)
351 .map((row) => row.command_id);
352 yield* Effect.yieldNow;
353 if (obsolete.length > 0) {
354 yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(obsolete)}`;
355 deletedReceiptCount += obsolete.length;
356 yield* Effect.yieldNow;
357 }
358 throughReceiptRowId = (rows.at(-1)?.row_id ?? 1) - 1;
359 if (rows.length < COMPACTION_PAGE_SIZE) break;
360 }
361
362 const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
363 const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
364 const reclaimableBytes =
365 (freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
366
367 return { deletedEventCount, deletedReceiptCount, reclaimableBytes };
368 });
369
370 return ProjectionMaintenanceV2.of({
371 verify: mapError("verify")(verify),
372 rebuild: mapError("rebuild")(rebuild),
373 compactEventStore: mapError("compact event store")(compactEventStore),
374 });
375 }),
376);