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 const COMPACTION_PAGE_SIZE = 500;
234
235 /**
236 * Scan newest first to retain the newest state for each entity.
237 * Page every event, including non-candidates: filtering before LIMIT could
238 * still scan the entire history when superseded events are sparse.
239 * turn-item.updated stays intact because replay assigns positions on first write.
240 */
241 const compactEventStore = Effect.gen(function* () {
242 const bounds = yield* sql<{
243 readonly event_sequence: number;
244 readonly receipt_row_id: number;
245 }>`
246 SELECT
247 COALESCE((SELECT MAX(sequence) FROM orchestration_events), 0) AS event_sequence,
248 COALESCE((SELECT MAX(rowid) FROM orchestration_command_receipts), 0) AS receipt_row_id
249 `;
250 let throughSequence = bounds[0]?.event_sequence ?? 0;
251 let throughReceiptRowId = bounds[0]?.receipt_row_id ?? 0;
252 const retainedThreadIds = new Set<string>();
253 const retainedEntityKeys = new Set<string>();
254 let deletedEventCount = 0;
255 let deletedReceiptCount = 0;
256
257 while (throughSequence > 0) {
258 const rows = yield* sql<{
259 readonly sequence: number;
260 readonly application_event_version: number;
261 readonly aggregate_kind: string;
262 readonly stream_id: string;
263 readonly event_type: string;
264 readonly entity_id: string | null;
265 readonly imported_legacy_thread: number;
266 }>`
267 SELECT
268 event.sequence,
269 event.application_event_version,
270 event.aggregate_kind,
271 event.stream_id,
272 event.event_type,
273 CASE
274 WHEN event.application_event_version = 2
275 AND event.event_type IN ('message.updated', 'node.updated')
276 THEN json_extract(event.payload_json, '$.id')
277 ELSE NULL
278 END AS entity_id,
279 CASE
280 WHEN event.application_event_version = 1 AND event.aggregate_kind = 'thread'
281 THEN EXISTS (
282 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
283 WHERE legacy_import.thread_id = event.stream_id
284 AND legacy_import.transcript_imported_at IS NOT NULL
285 )
286 ELSE 0
287 END AS imported_legacy_thread
288 FROM orchestration_events AS event
289 WHERE event.sequence <= ${throughSequence}
290 ORDER BY event.sequence DESC
291 LIMIT ${COMPACTION_PAGE_SIZE}
292 `;
293 const obsolete: number[] = [];
294 for (const row of rows) {
295 if (row.imported_legacy_thread === 1) {
296 obsolete.push(row.sequence);
297 } else if (row.application_event_version === 2) {
298 if (
299 row.aggregate_kind === "thread" &&
300 supersedableThreadEventTypes.has(row.event_type)
301 ) {
302 if (retainedThreadIds.has(row.stream_id)) obsolete.push(row.sequence);
303 else retainedThreadIds.add(row.stream_id);
304 } else if (row.event_type === "message.updated" || row.event_type === "node.updated") {
305 const key = encodeEntityKey([row.event_type, row.stream_id, row.entity_id]);
306 if (retainedEntityKeys.has(key)) obsolete.push(row.sequence);
307 else retainedEntityKeys.add(key);
308 }
309 }
310 }
311 // Both discovery and deletion use the synchronous connection. Yield even
312 // when this page has nothing to delete so startup and requests can progress.
313 yield* Effect.yieldNow;
314 if (obsolete.length > 0) {
315 yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
316 deletedEventCount += obsolete.length;
317 yield* Effect.yieldNow;
318 }
319 throughSequence = (rows.at(-1)?.sequence ?? 1) - 1;
320 if (rows.length < COMPACTION_PAGE_SIZE) break;
321 }
322
323 // Legacy receipts are removable only after their thread's v1 import finishes.
324 // Page by rowid before checking eligibility, as with event discovery above.
325 while (throughReceiptRowId > 0) {
326 const rows = yield* sql<{
327 readonly row_id: number;
328 readonly command_id: string;
329 readonly imported_legacy_thread: number;
330 }>`
331 SELECT
332 receipt.rowid AS row_id,
333 receipt.command_id,
334 CASE
335 WHEN receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread'
336 THEN EXISTS (
337 SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
338 WHERE legacy_import.thread_id = receipt.aggregate_id
339 AND legacy_import.transcript_imported_at IS NOT NULL
340 )
341 ELSE 0
342 END AS imported_legacy_thread
343 FROM orchestration_command_receipts AS receipt
344 WHERE receipt.rowid <= ${throughReceiptRowId}
345 ORDER BY receipt.rowid DESC
346 LIMIT ${COMPACTION_PAGE_SIZE}
347 `;
348 const obsolete = rows
349 .filter((row) => row.imported_legacy_thread === 1)
350 .map((row) => row.command_id);
351 yield* Effect.yieldNow;
352 if (obsolete.length > 0) {
353 yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(obsolete)}`;
354 deletedReceiptCount += obsolete.length;
355 yield* Effect.yieldNow;
356 }
357 throughReceiptRowId = (rows.at(-1)?.row_id ?? 1) - 1;
358 if (rows.length < COMPACTION_PAGE_SIZE) break;
359 }
360
361 const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
362 const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
363 const reclaimableBytes =
364 (freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
365
366 return { deletedEventCount, deletedReceiptCount, reclaimableBytes };
367 });
368
369 return ProjectionMaintenanceV2.of({
370 verify: mapError("verify")(verify),
371 rebuild: mapError("rebuild")(rebuild),
372 compactEventStore: mapError("compact event store")(compactEventStore),
373 });
374 }),
375);