Repository navigation
Expand file tree
/
Copy pathProjectionMaintenance.ts
More file actions
319 lines (302 loc) · 13.9 KB
/
Copy pathProjectionMaintenance.ts
File metadata and controls
319 lines (302 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/sql/SqlClient";
import {
EVENT_LOG_PRUNE_MARK,
EVENT_LOG_PRUNED_THROUGH,
} from "../persistence/OrchestrationEventStore.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
export class ProjectionMaintenanceError extends Schema.TaggedError<ProjectionMaintenanceError>()(
"ProjectionMaintenanceError",
{
operation: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {}
export interface ProjectionMaintenanceV2Shape {
/** Deletes events the projections already cover once they are older than the retained history. */
readonly pruneEventStore: (betweenPages?: Effect.Effect<void>) => Effect.Effect<
{
readonly deletedEventCount: number;
readonly deletedReceiptCount: number;
readonly reclaimableBytes: number;
},
ProjectionMaintenanceError
>;
}
export class ProjectionMaintenanceV2 extends Context.Service<
ProjectionMaintenanceV2,
ProjectionMaintenanceV2Shape
>()("t3/orchestration-v2/ProjectionMaintenance/ProjectionMaintenanceV2") {}
// Reconnect replay and command-id retries read this tail; older cursors resync from a snapshot.
const RETAINED_EVENT_HISTORY = Duration.days(1);
// Small pages bound work on the reader worker and synchronous fallback.
const PAGE_SIZE = 50;
const REFERENCE_SCAN_WINDOW = 1000;
type MetadataRow = {
readonly projection_name: string;
readonly last_sequence: number;
readonly updated_at: string;
};
export const layer: Layer.Layer<ProjectionMaintenanceV2, never, SqlClient.SqlClient> = Layer.effect(
ProjectionMaintenanceV2,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const writeMetadata = (name: string, sequence: number, at: DateTime.Utc) => sql`
INSERT INTO orchestration_v2_projection_metadata (
projection_name, schema_version, last_sequence, updated_at
)
VALUES (
${name},
${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
${sequence},
${DateTime.formatIso(at)}
)
ON CONFLICT(projection_name) DO UPDATE SET
last_sequence = excluded.last_sequence,
updated_at = excluded.updated_at
`;
// Collects anchors whose prompt later rows borrow through promptSequence.
const readPromptReferences = Effect.fnUntraced(function* (
afterSequence: number,
throughSequence: number,
betweenPages: Effect.Effect<void>,
) {
const referenced = new Set<number>();
for (let cursor = afterSequence; cursor < throughSequence;) {
const windowEnd = Math.min(cursor + REFERENCE_SCAN_WINDOW, throughSequence);
const rows = yield* sql<{ readonly prompt_sequence: number }>`
SELECT json_extract(payload_json, '$.promptSequence') AS prompt_sequence
FROM orchestration_events
WHERE sequence > ${cursor}
AND sequence <= ${windowEnd}
AND event_type IN ('subagent.updated', 'turn-item.updated')
AND json_type(payload_json, '$.promptSequence') = 'integer'
`.pipe(NodeSqliteClient.readOnly);
for (const row of rows) referenced.add(row.prompt_sequence);
cursor = windowEnd;
yield* betweenPages;
}
return referenced;
});
const pruneEvents = Effect.fnUntraced(function* (
throughSequence: number,
head: number,
betweenPages: Effect.Effect<void>,
) {
const referenced = yield* readPromptReferences(throughSequence, head, betweenPages);
// Stream heads at or below the boundary are kept, so the anchors they borrow must stay too.
const keptHeadReferences = yield* sql<{ readonly prompt_sequence: number }>`
SELECT json_extract(event.payload_json, '$.promptSequence') AS prompt_sequence
FROM (
SELECT MAX(sequence) AS sequence FROM orchestration_events
GROUP BY aggregate_kind, stream_id
) AS heads
JOIN orchestration_events AS event ON event.sequence = heads.sequence
WHERE heads.sequence <= ${throughSequence}
AND event.event_type IN ('subagent.updated', 'turn-item.updated')
AND json_type(event.payload_json, '$.promptSequence') = 'integer'
`.pipe(NodeSqliteClient.readOnly);
for (const row of keptHeadReferences) referenced.add(row.prompt_sequence);
yield* betweenPages;
let referencesThrough = head;
let deleted = 0;
let cursor = 0;
while (cursor < throughSequence) {
const rows = yield* sql<{ readonly sequence: number; readonly prunable: number }>`
SELECT
event.sequence,
CASE
WHEN event.application_event_version = 1 THEN 0
-- The legacy importer treats a thread without thread.created as not yet imported.
WHEN event.event_type = 'thread.created' THEN 0
-- Codex usage history reads the selection a run attempt started with.
WHEN event.event_type = 'run.updated'
AND json_extract(event.payload_json, '$.status') = 'running' THEN 0
-- The newest row keeps each stream's high water, stream_version, and snapshot sequence.
WHEN event.sequence = (
SELECT MAX(newer.sequence) FROM orchestration_events AS newer
WHERE newer.aggregate_kind = event.aggregate_kind
AND newer.stream_id = event.stream_id
) THEN 0
ELSE 1
END AS prunable
FROM orchestration_events AS event
WHERE event.sequence > ${cursor}
AND event.sequence <= ${throughSequence}
ORDER BY event.sequence ASC
LIMIT ${PAGE_SIZE}
`.pipe(NodeSqliteClient.readOnly);
const candidates = rows.filter((row) => row.prunable === 1).map((row) => row.sequence);
// Never hold a transaction or the reader lock across a yield or a rest.
yield* Effect.yieldNow;
if (candidates.length > 0) {
deleted += yield* sql.withTransaction(
Effect.gen(function* () {
// Rows appended since the reference scan may borrow a prompt from a candidate.
const appended = yield* sql<{
readonly sequence: number;
readonly prompt_sequence: number | null;
}>`
SELECT
sequence,
CASE
WHEN event_type IN ('subagent.updated', 'turn-item.updated')
AND json_type(payload_json, '$.promptSequence') = 'integer'
THEN json_extract(payload_json, '$.promptSequence')
END AS prompt_sequence
FROM orchestration_events
WHERE sequence > ${referencesThrough}
`;
for (const row of appended) {
if (row.prompt_sequence !== null) referenced.add(row.prompt_sequence);
referencesThrough = Math.max(referencesThrough, row.sequence);
}
const obsolete = candidates.filter((sequence) => !referenced.has(sequence));
if (obsolete.length === 0) return 0;
yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
return obsolete.length;
}),
);
yield* Effect.yieldNow;
}
// Rest after every page, including the last, so the next loop starts a fresh slice.
yield* betweenPages;
if (rows.length < PAGE_SIZE) break;
cursor = rows.at(-1)?.sequence ?? throughSequence;
}
return deleted;
});
// Imported legacy threads are served from v2 rows; their v1 events and receipts have no reader.
const pruneImportedLegacyHistory = Effect.fnUntraced(function* (
throughSequence: number,
throughReceiptRowId: number,
betweenPages: Effect.Effect<void>,
) {
let deletedEventCount = 0;
let deletedReceiptCount = 0;
for (let cursor = 0; ;) {
const rows = yield* sql<{ readonly sequence: number; readonly imported: number }>`
SELECT
event.sequence,
event.aggregate_kind = 'thread' AND EXISTS (
SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
WHERE legacy_import.thread_id = event.stream_id
AND legacy_import.transcript_imported_at IS NOT NULL
) AS imported
FROM orchestration_events AS event
INDEXED BY idx_orchestration_events_application_sequence
WHERE event.application_event_version = 1
AND event.sequence > ${cursor}
AND event.sequence <= ${throughSequence}
ORDER BY event.sequence ASC
LIMIT ${PAGE_SIZE}
`.pipe(NodeSqliteClient.readOnly);
const obsolete = rows.filter((row) => row.imported === 1).map((row) => row.sequence);
yield* Effect.yieldNow;
if (obsolete.length > 0) {
yield* sql`DELETE FROM orchestration_events WHERE sequence IN ${sql.in(obsolete)}`;
deletedEventCount += obsolete.length;
yield* Effect.yieldNow;
}
yield* betweenPages;
if (rows.length < PAGE_SIZE) break;
cursor = rows.at(-1)?.sequence ?? cursor;
}
for (let cursor = 0; ;) {
const rows = yield* sql<{
readonly row_id: number;
readonly command_id: string;
readonly imported: number;
}>`
SELECT
receipt.rowid AS row_id,
receipt.command_id,
receipt.command_type = 'legacy' AND receipt.aggregate_kind = 'thread' AND EXISTS (
SELECT 1 FROM orchestration_v2_legacy_imports AS legacy_import
WHERE legacy_import.thread_id = receipt.aggregate_id
AND legacy_import.transcript_imported_at IS NOT NULL
) AS imported
FROM orchestration_command_receipts AS receipt
WHERE receipt.rowid > ${cursor} AND receipt.rowid <= ${throughReceiptRowId}
ORDER BY receipt.rowid ASC
LIMIT ${PAGE_SIZE}
`.pipe(NodeSqliteClient.readOnly);
const obsolete = rows.filter((row) => row.imported === 1).map((row) => row.command_id);
yield* Effect.yieldNow;
if (obsolete.length > 0) {
yield* sql`DELETE FROM orchestration_command_receipts WHERE command_id IN ${sql.in(obsolete)}`;
deletedReceiptCount += obsolete.length;
yield* Effect.yieldNow;
}
yield* betweenPages;
if (rows.length < PAGE_SIZE) break;
cursor = rows.at(-1)?.row_id ?? cursor;
}
return { deletedEventCount, deletedReceiptCount };
});
// A pass prunes through the mark the previous pass left once that mark is a day old, so
// at least RETAINED_EVENT_HISTORY of events always remains. Receipts stay for idempotency.
const pruneEventStore = Effect.fn("ProjectionMaintenance.pruneEventStore")(
function* (betweenPages: Effect.Effect<void> = Effect.void) {
const now = yield* DateTime.now;
const metadata = yield* sql<MetadataRow>`
SELECT projection_name, last_sequence, updated_at
FROM orchestration_v2_projection_metadata
WHERE projection_name IN (
'thread-projections', ${EVENT_LOG_PRUNE_MARK}, ${EVENT_LOG_PRUNED_THROUGH}
)
`.pipe(NodeSqliteClient.readOnly);
const read = (name: string) => metadata.find((row) => row.projection_name === name);
const projected = read("thread-projections")?.last_sequence ?? 0;
const mark = read(EVENT_LOG_PRUNE_MARK);
const prunedThrough = read(EVENT_LOG_PRUNED_THROUGH)?.last_sequence ?? 0;
// Fixed bounds: foreground commits during the pass wait for the next one.
const bounds = yield* sql<{ readonly sequence: number; readonly receipt_row_id: number }>`
SELECT
COALESCE((SELECT MAX(sequence) FROM orchestration_events), 0) AS sequence,
COALESCE((SELECT MAX(rowid) FROM orchestration_command_receipts), 0) AS receipt_row_id
`.pipe(NodeSqliteClient.readOnly);
const head = bounds[0]?.sequence ?? 0;
let deletedEventCount = 0;
const markIsDue =
mark !== undefined &&
DateTime.toEpochMillis(now) - Date.parse(mark.updated_at) >=
Duration.toMillis(RETAINED_EVENT_HISTORY);
if (mark !== undefined && markIsDue) {
const throughSequence = Math.max(Math.min(mark.last_sequence, projected), prunedThrough);
if (throughSequence > prunedThrough) {
// Publish the boundary first so resuming clients take a snapshot, never a partial replay.
yield* writeMetadata(EVENT_LOG_PRUNED_THROUGH, throughSequence, now);
}
deletedEventCount += yield* pruneEvents(throughSequence, head, betweenPages);
}
if (mark === undefined || markIsDue) yield* writeMetadata(EVENT_LOG_PRUNE_MARK, head, now);
const legacy = yield* pruneImportedLegacyHistory(
head,
bounds[0]?.receipt_row_id ?? 0,
betweenPages,
);
deletedEventCount += legacy.deletedEventCount;
const freelistRows = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
const pageSizeRows = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
const reclaimableBytes =
(freelistRows[0]?.freelist_count ?? 0) * (pageSizeRows[0]?.page_size ?? 0);
return {
deletedEventCount,
deletedReceiptCount: legacy.deletedReceiptCount,
reclaimableBytes,
};
},
Effect.mapError(
(cause) => new ProjectionMaintenanceError({ operation: "prune event store", cause }),
),
);
return ProjectionMaintenanceV2.of({ pruneEventStore });
}),
);