fatedb 0.0.0-stage → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +264 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +3 -0
  5. package/dist/cli.d.ts +15 -0
  6. package/dist/cli.js +256 -0
  7. package/dist/client.d.ts +152 -0
  8. package/dist/client.js +416 -0
  9. package/dist/cloudflare.d.ts +197 -0
  10. package/dist/cloudflare.js +159 -0
  11. package/dist/datalog/ast.d.ts +35 -0
  12. package/dist/datalog/ast.js +40 -0
  13. package/dist/datalog/evaluator.d.ts +14 -0
  14. package/dist/datalog/evaluator.js +395 -0
  15. package/dist/datalog/fact-source.d.ts +30 -0
  16. package/dist/datalog/fact-source.js +1 -0
  17. package/dist/datalog/fingerprint.d.ts +12 -0
  18. package/dist/datalog/fingerprint.js +50 -0
  19. package/dist/datalog/parser.d.ts +3 -0
  20. package/dist/datalog/parser.js +302 -0
  21. package/dist/datalog/value.d.ts +34 -0
  22. package/dist/datalog/value.js +104 -0
  23. package/dist/domain/date-validation.d.ts +2 -0
  24. package/dist/domain/date-validation.js +32 -0
  25. package/dist/domain/fact-value.d.ts +91 -0
  26. package/dist/domain/fact-value.js +167 -0
  27. package/dist/domain/fact.d.ts +14 -0
  28. package/dist/domain/fact.js +47 -0
  29. package/dist/domain/failure.d.ts +44 -0
  30. package/dist/domain/failure.js +30 -0
  31. package/dist/domain/graph-id.d.ts +7 -0
  32. package/dist/domain/graph-id.js +10 -0
  33. package/dist/domain/histogram.d.ts +29 -0
  34. package/dist/domain/histogram.js +48 -0
  35. package/dist/domain/identifiers.d.ts +26 -0
  36. package/dist/domain/identifiers.js +75 -0
  37. package/dist/domain/numbers.d.ts +12 -0
  38. package/dist/domain/numbers.js +77 -0
  39. package/dist/domain/projection.d.ts +252 -0
  40. package/dist/domain/projection.js +51 -0
  41. package/dist/domain/query-metrics.d.ts +31 -0
  42. package/dist/domain/query-metrics.js +35 -0
  43. package/dist/domain/read-token.d.ts +37 -0
  44. package/dist/domain/read-token.js +93 -0
  45. package/dist/domain/result.d.ts +22 -0
  46. package/dist/domain/result.js +16 -0
  47. package/dist/domain/schema-observation.d.ts +20 -0
  48. package/dist/domain/schema-observation.js +61 -0
  49. package/dist/domain/string-order.d.ts +2 -0
  50. package/dist/domain/string-order.js +15 -0
  51. package/dist/domain/vocabulary.d.ts +101 -0
  52. package/dist/domain/vocabulary.js +276 -0
  53. package/dist/index.d.ts +15 -0
  54. package/dist/index.js +14 -0
  55. package/dist/projection-config.d.ts +3 -0
  56. package/dist/projection-config.js +212 -0
  57. package/dist/server/access.d.ts +32 -0
  58. package/dist/server/access.js +117 -0
  59. package/dist/server/admin.d.ts +233 -0
  60. package/dist/server/admin.js +483 -0
  61. package/dist/server/authorization.d.ts +35 -0
  62. package/dist/server/authorization.js +76 -0
  63. package/dist/server/console-assets.d.ts +6 -0
  64. package/dist/server/console-assets.js +2 -0
  65. package/dist/server/console.d.ts +8 -0
  66. package/dist/server/console.js +301 -0
  67. package/dist/server/index.d.ts +122 -0
  68. package/dist/server/index.js +487 -0
  69. package/dist/server/mcp.d.ts +31 -0
  70. package/dist/server/mcp.js +169 -0
  71. package/dist/server/telemetry-do.d.ts +31 -0
  72. package/dist/server/telemetry-do.js +342 -0
  73. package/dist/server/telemetry.d.ts +27 -0
  74. package/dist/server/telemetry.js +191 -0
  75. package/dist/storage/constants.d.ts +20 -0
  76. package/dist/storage/constants.js +21 -0
  77. package/dist/storage/environment.d.ts +438 -0
  78. package/dist/storage/environment.js +145 -0
  79. package/dist/storage/facts.d.ts +41 -0
  80. package/dist/storage/facts.js +73 -0
  81. package/dist/storage/http.d.ts +55 -0
  82. package/dist/storage/http.js +169 -0
  83. package/dist/storage/keys.d.ts +50 -0
  84. package/dist/storage/keys.js +84 -0
  85. package/dist/storage/layout.d.ts +67 -0
  86. package/dist/storage/layout.js +134 -0
  87. package/dist/storage/log.d.ts +41 -0
  88. package/dist/storage/log.js +137 -0
  89. package/dist/storage/manifest.d.ts +26 -0
  90. package/dist/storage/manifest.js +206 -0
  91. package/dist/storage/operations.d.ts +303 -0
  92. package/dist/storage/operations.js +719 -0
  93. package/dist/storage/partition.d.ts +125 -0
  94. package/dist/storage/partition.js +816 -0
  95. package/dist/storage/projection.d.ts +72 -0
  96. package/dist/storage/projection.js +1349 -0
  97. package/dist/storage/root.d.ts +120 -0
  98. package/dist/storage/root.js +596 -0
  99. package/dist/storage/segment.d.ts +145 -0
  100. package/dist/storage/segment.js +451 -0
  101. package/dist/storage/shard.d.ts +82 -0
  102. package/dist/storage/shard.js +710 -0
  103. package/dist/storage/source.d.ts +60 -0
  104. package/dist/storage/source.js +199 -0
  105. package/dist/telemetry/model.d.ts +123 -0
  106. package/dist/telemetry/model.js +292 -0
  107. package/dist/version.d.ts +4 -0
  108. package/dist/version.js +6 -0
  109. package/package.json +82 -4
@@ -0,0 +1,1349 @@
1
+ // ProjectionDO: durable watermark-driven change delivery, retries, dead-letter queue,
2
+ // start/stop, replay, backfill, and built-in R2 JSON export (RFD0016).
3
+ //
4
+ // Invariants modeled in specs/projection-delivery.spock and specs/projection-backfill.spock:
5
+ // - Incremental changes are read from each partition's durable log (R2 log chunks + SQLite rows),
6
+ // gated by `manifest.watermark`, so full shard compaction never hides retractions.
7
+ // - Partition cursors track both `last_seq` and `last_chunk_key` so archiving SQLite rows into
8
+ // an R2 chunk mid-consumption never skips rows inside that chunk.
9
+ // - New pending batches and advanced partition cursors commit in one SQLite `transactionSync`
10
+ // before calling the sink, so restarts never lose entities.
11
+ // - Built-in R2 export reads each entity's active facts from the latest published manifest,
12
+ // preventing delayed retries or backfills from clobbering newer writes, and writes `{ id, ...,
13
+ // facts: [] }` as a tombstone when all facts are retracted.
14
+ import { DurableObject } from "cloudflare:workers";
15
+ import { evaluateDatalog } from "../datalog/evaluator.js";
16
+ import { parseDatalogQuery } from "../datalog/parser.js";
17
+ import { parseUri } from "../domain/identifiers.js";
18
+ import { projectionEntityKey, projectionMatchesGraph, readProjectionsConfig, } from "../domain/projection.js";
19
+ import { compareCodeUnits } from "../domain/string-order.js";
20
+ import { SCHEMA } from "../domain/vocabulary.js";
21
+ import { partitionStub, segmentStore, traceSpock, } from "./environment.js";
22
+ import { canonicalValue } from "./facts.js";
23
+ import { epochEndMs, epochOf, firstTsOf, wallEpoch } from "./keys.js";
24
+ import { readLogChunksAfter } from "./log.js";
25
+ import { readManifest } from "./manifest.js";
26
+ import { emptyReadMetrics, readHeader } from "./segment.js";
27
+ import { SegmentFactSource } from "./source.js";
28
+ const ROWS_PER_PARTITION_TICK = 32;
29
+ const CHUNKS_PER_PARTITION_TICK = 4;
30
+ const DELIVERIES_PER_TICK = 4;
31
+ const BACKFILL_PAGE_LIMIT = 10_000;
32
+ const IDLE_ALARM_GAP_MS = 250;
33
+ const MAX_STORED_EVENTS = 200;
34
+ const SAMPLE_ENTITY_COUNT = 5;
35
+ export class ProjectionDO extends DurableObject {
36
+ sql = this.ctx.storage.sql;
37
+ meta = null;
38
+ cursors = new Map();
39
+ /**
40
+ * The currently executing alarm, if any (specs/projection-alarm.spock). While an alarm runs in
41
+ * workerd, `getAlarm()` still reports its old timestamp, so concurrent `wake()` / `start()` /
42
+ * `replayFromStart()` calls mark `woken = true` and let `alarm()` reschedule strictly in the future.
43
+ */
44
+ runningAlarm = null;
45
+ /** Monotonic generation incremented when cursors are reset so an in-flight scan never overwrites them. */
46
+ generation = 0;
47
+ constructor(ctx, env) {
48
+ super(ctx, env);
49
+ void ctx.blockConcurrencyWhile(async () => this.load());
50
+ }
51
+ load() {
52
+ this.sql.exec(`CREATE TABLE IF NOT EXISTS projection (
53
+ id INTEGER PRIMARY KEY CHECK (id = 1),
54
+ graph TEXT NOT NULL,
55
+ name TEXT NOT NULL,
56
+ status TEXT NOT NULL,
57
+ cursor_watermark INTEGER NOT NULL,
58
+ known_watermark INTEGER NOT NULL,
59
+ known_partitions INTEGER NOT NULL,
60
+ backfill_status TEXT NOT NULL,
61
+ backfill_watermark INTEGER NOT NULL,
62
+ backfill_cursor TEXT,
63
+ backfill_processed INTEGER NOT NULL,
64
+ backfill_started_at INTEGER,
65
+ backfill_finished_at INTEGER,
66
+ delivered_batches INTEGER NOT NULL,
67
+ delivered_entities INTEGER NOT NULL,
68
+ failed_deliveries INTEGER NOT NULL,
69
+ last_delivery_at INTEGER,
70
+ last_error TEXT
71
+ )`);
72
+ this.sql.exec(`CREATE TABLE IF NOT EXISTS partition_cursors (
73
+ partition INTEGER PRIMARY KEY,
74
+ last_seq INTEGER NOT NULL,
75
+ last_ts INTEGER NOT NULL,
76
+ last_offset INTEGER NOT NULL,
77
+ last_chunk_key TEXT NOT NULL
78
+ )`);
79
+ this.sql.exec(`CREATE TABLE IF NOT EXISTS pending_batches (
80
+ delivery_id TEXT PRIMARY KEY,
81
+ watermark INTEGER NOT NULL,
82
+ reason TEXT NOT NULL,
83
+ entities TEXT NOT NULL,
84
+ attempts INTEGER NOT NULL,
85
+ next_attempt_at INTEGER NOT NULL,
86
+ last_error TEXT,
87
+ created_at INTEGER NOT NULL
88
+ )`);
89
+ this.sql.exec(`CREATE TABLE IF NOT EXISTS dead_letters (
90
+ delivery_id TEXT PRIMARY KEY,
91
+ watermark INTEGER NOT NULL,
92
+ reason TEXT NOT NULL,
93
+ entities TEXT NOT NULL,
94
+ attempts INTEGER NOT NULL,
95
+ last_error TEXT NOT NULL,
96
+ created_at INTEGER NOT NULL,
97
+ failed_at INTEGER NOT NULL
98
+ )`);
99
+ this.sql.exec(`CREATE TABLE IF NOT EXISTS projection_events (
100
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
101
+ at INTEGER NOT NULL,
102
+ kind TEXT NOT NULL,
103
+ reason TEXT,
104
+ delivery_id TEXT,
105
+ watermark INTEGER,
106
+ entity_count INTEGER,
107
+ sample_entities TEXT NOT NULL,
108
+ duration_ms INTEGER,
109
+ attempt INTEGER,
110
+ detail TEXT
111
+ )`);
112
+ const row = this.sql.exec("SELECT * FROM projection WHERE id = 1").toArray()[0];
113
+ if (row !== undefined) {
114
+ this.meta = {
115
+ graph: row.graph,
116
+ name: row.name,
117
+ status: row.status,
118
+ cursorWatermark: row.cursor_watermark,
119
+ knownWatermark: row.known_watermark,
120
+ knownPartitions: row.known_partitions,
121
+ backfillStatus: row.backfill_status,
122
+ backfillWatermark: row.backfill_watermark,
123
+ backfillCursor: row.backfill_cursor,
124
+ backfillProcessed: row.backfill_processed,
125
+ backfillStartedAt: row.backfill_started_at,
126
+ backfillFinishedAt: row.backfill_finished_at,
127
+ deliveredBatches: row.delivered_batches,
128
+ deliveredEntities: row.delivered_entities,
129
+ failedDeliveries: row.failed_deliveries,
130
+ lastDeliveryAt: row.last_delivery_at,
131
+ lastError: row.last_error,
132
+ };
133
+ }
134
+ for (const c of this.sql.exec("SELECT partition, last_seq, last_ts, last_offset, last_chunk_key FROM partition_cursors")) {
135
+ this.cursors.set(c.partition, {
136
+ partition: c.partition, lastSeq: c.last_seq, lastTs: c.last_ts, lastOffset: c.last_offset, lastChunkKey: c.last_chunk_key,
137
+ });
138
+ }
139
+ }
140
+ configFor(graph, name) {
141
+ const configs = readProjectionsConfig(this.env.PROJECTIONS_CONFIG);
142
+ const found = configs.find((c) => c.name === name && projectionMatchesGraph(c, graph));
143
+ return found ?? null;
144
+ }
145
+ writeMeta(meta) {
146
+ this.sql.exec(`INSERT INTO projection (
147
+ id, graph, name, status, cursor_watermark, known_watermark, known_partitions,
148
+ backfill_status, backfill_watermark, backfill_cursor, backfill_processed,
149
+ backfill_started_at, backfill_finished_at,
150
+ delivered_batches, delivered_entities, failed_deliveries, last_delivery_at, last_error
151
+ ) VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
152
+ ON CONFLICT (id) DO UPDATE SET
153
+ graph = excluded.graph,
154
+ name = excluded.name,
155
+ status = excluded.status,
156
+ cursor_watermark = excluded.cursor_watermark,
157
+ known_watermark = excluded.known_watermark,
158
+ known_partitions = excluded.known_partitions,
159
+ backfill_status = excluded.backfill_status,
160
+ backfill_watermark = excluded.backfill_watermark,
161
+ backfill_cursor = excluded.backfill_cursor,
162
+ backfill_processed = excluded.backfill_processed,
163
+ backfill_started_at = excluded.backfill_started_at,
164
+ backfill_finished_at = excluded.backfill_finished_at,
165
+ delivered_batches = excluded.delivered_batches,
166
+ delivered_entities = excluded.delivered_entities,
167
+ failed_deliveries = excluded.failed_deliveries,
168
+ last_delivery_at = excluded.last_delivery_at,
169
+ last_error = excluded.last_error`, meta.graph, meta.name, meta.status, meta.cursorWatermark, meta.knownWatermark, meta.knownPartitions, meta.backfillStatus, meta.backfillWatermark, meta.backfillCursor, meta.backfillProcessed, meta.backfillStartedAt, meta.backfillFinishedAt, meta.deliveredBatches, meta.deliveredEntities, meta.failedDeliveries, meta.lastDeliveryAt, meta.lastError);
170
+ }
171
+ storeMeta(meta) {
172
+ this.writeMeta(meta);
173
+ this.meta = meta;
174
+ return meta;
175
+ }
176
+ recordEvent(event) {
177
+ const sample = event.sampleEntities === undefined ? [] : event.sampleEntities.slice(0, SAMPLE_ENTITY_COUNT);
178
+ this.sql.exec(`INSERT INTO projection_events (at, kind, reason, delivery_id, watermark, entity_count, sample_entities, duration_ms, attempt, detail)
179
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, event.at ?? Date.now(), event.kind, event.reason ?? null, event.deliveryId ?? null, event.watermark ?? null, event.entityCount ?? null, JSON.stringify(sample), event.durationMs ?? null, event.attempt ?? null, event.detail ?? null);
180
+ this.sql.exec("DELETE FROM projection_events WHERE id <= (SELECT id FROM projection_events ORDER BY id DESC LIMIT 1 OFFSET ?)", MAX_STORED_EVENTS - 1);
181
+ }
182
+ ensureMeta(graph, name) {
183
+ if (this.meta !== null) {
184
+ if (this.meta.graph !== graph || this.meta.name !== name) {
185
+ throw new Error(`projection ${this.meta.graph}/${this.meta.name} was called as ${graph}/${name}`);
186
+ }
187
+ return this.meta;
188
+ }
189
+ const config = this.configFor(graph, name);
190
+ const initial = {
191
+ graph,
192
+ name,
193
+ status: config?.autoStart === false ? "stopped" : "running",
194
+ cursorWatermark: 0,
195
+ knownWatermark: 0,
196
+ knownPartitions: 0,
197
+ backfillStatus: "idle",
198
+ backfillWatermark: 0,
199
+ backfillCursor: null,
200
+ backfillProcessed: 0,
201
+ backfillStartedAt: null,
202
+ backfillFinishedAt: null,
203
+ deliveredBatches: 0,
204
+ deliveredEntities: 0,
205
+ failedDeliveries: 0,
206
+ lastDeliveryAt: null,
207
+ lastError: null,
208
+ };
209
+ return this.storeMeta(initial);
210
+ }
211
+ async ensureAlarmSoon(at = Date.now()) {
212
+ if (this.runningAlarm !== null) {
213
+ this.runningAlarm.woken = true;
214
+ return;
215
+ }
216
+ const existing = await this.ctx.storage.getAlarm();
217
+ if (existing === null || existing > at) {
218
+ await this.ctx.storage.setAlarm(at);
219
+ }
220
+ }
221
+ /** Called by GraphRootDO after publishing a manifest. Idempotent and safe under retries. */
222
+ async wake(input) {
223
+ const meta = this.ensureMeta(input.graph, input.projection);
224
+ const nextWatermark = Math.max(meta.knownWatermark, input.watermark);
225
+ const nextPartitions = Math.max(meta.knownPartitions, input.partitions);
226
+ if (nextWatermark !== meta.knownWatermark || nextPartitions !== meta.knownPartitions) {
227
+ this.storeMeta({ ...meta, knownWatermark: nextWatermark, knownPartitions: nextPartitions });
228
+ }
229
+ if (this.requireMeta().status === "running") {
230
+ await this.ensureAlarmSoon(Date.now());
231
+ }
232
+ }
233
+ /** Starts or resumes the projection (including recovering from `error` state). */
234
+ async start(input) {
235
+ const meta = this.ensureMeta(input.graph, input.projection);
236
+ const now = Date.now();
237
+ const next = { ...meta, status: "running", lastError: meta.status === "error" ? null : meta.lastError };
238
+ this.ctx.storage.transactionSync(() => {
239
+ this.writeMeta(next);
240
+ if (meta.status === "error") {
241
+ this.sql.exec("UPDATE pending_batches SET attempts = 0, next_attempt_at = ?", now);
242
+ }
243
+ if (meta.status !== "running") {
244
+ this.recordEvent({ at: now, kind: "started", watermark: next.cursorWatermark });
245
+ }
246
+ });
247
+ this.meta = next;
248
+ await this.ensureAlarmSoon(now);
249
+ if (this.env.SPOCK_TRACE !== undefined) {
250
+ await traceSpock(this.env, input.graph, "projection.control", { projection: input.projection, op: "start", status: next.status, generation: this.generation });
251
+ }
252
+ return this.status(input);
253
+ }
254
+ /** Durably pauses live scanning, backfill, and retries without discarding cursors or pending work. */
255
+ async stop(input) {
256
+ const meta = this.ensureMeta(input.graph, input.projection);
257
+ if (meta.status !== "stopped") {
258
+ const now = Date.now();
259
+ const next = { ...meta, status: "stopped" };
260
+ this.ctx.storage.transactionSync(() => {
261
+ this.writeMeta(next);
262
+ this.recordEvent({ at: now, kind: "stopped", watermark: next.cursorWatermark });
263
+ });
264
+ this.meta = next;
265
+ }
266
+ await this.ctx.storage.deleteAlarm();
267
+ if (this.env.SPOCK_TRACE !== undefined) {
268
+ await traceSpock(this.env, input.graph, "projection.control", { projection: input.projection, op: "stop", status: this.requireMeta().status, generation: this.generation });
269
+ }
270
+ return this.status(input);
271
+ }
272
+ /**
273
+ * Starts a backfill:
274
+ * - `since: "current"` (default): scans currently active entities in the published R2 index once
275
+ * (anchoring live partition cursors first if live tailing has not started yet).
276
+ * - `since: 0`: rewinds partition cursors to 0 and replays the entire durable partition log.
277
+ * - `since: <epochMs>`: rewinds partition cursors so every write & retraction with `ts >= since`
278
+ * is reprocessed from the durable partition log.
279
+ */
280
+ async backfill(input) {
281
+ const meta = this.ensureMeta(input.graph, input.projection);
282
+ const since = input.since ?? "current";
283
+ if (since !== "current") {
284
+ if (typeof since !== "number" || !Number.isFinite(since) || since < 0) {
285
+ throw new RangeError("backfill since must be \"current\" or a non-negative timestamp in milliseconds");
286
+ }
287
+ return this.backfillFromLog(input, Math.floor(since));
288
+ }
289
+ const manifest = await readManifest(this.env, input.graph, true);
290
+ const watermark = manifest?.watermark ?? meta.knownWatermark;
291
+ const partitions = manifest?.partitions ?? meta.knownPartitions;
292
+ const now = Date.now();
293
+ // Anchor live cursors at backfill start only if live tailing has not started yet.
294
+ const snapped = [];
295
+ const shouldAnchor = meta.cursorWatermark === 0 && this.cursors.size === 0 && watermark > 0 && partitions > 0;
296
+ if (shouldAnchor) {
297
+ const heads = await Promise.all(Array.from({ length: partitions }, (_, p) => partitionStub(this.env, input.graph, p).logHead({ watermark }).then((head) => ({
298
+ partition: p,
299
+ lastSeq: head.seq,
300
+ lastTs: head.ts,
301
+ lastOffset: head.offset,
302
+ lastChunkKey: "",
303
+ }))));
304
+ snapped.push(...heads);
305
+ }
306
+ const latest = this.requireMeta();
307
+ const stillAnchor = shouldAnchor && latest.cursorWatermark === 0 && this.cursors.size === 0;
308
+ const next = {
309
+ ...latest,
310
+ status: "running",
311
+ cursorWatermark: stillAnchor ? watermark : latest.cursorWatermark,
312
+ knownWatermark: Math.max(latest.knownWatermark, watermark),
313
+ knownPartitions: Math.max(latest.knownPartitions, partitions),
314
+ backfillStatus: watermark === 0 ? "completed" : "running",
315
+ backfillWatermark: watermark,
316
+ backfillCursor: null,
317
+ backfillProcessed: 0,
318
+ backfillStartedAt: now,
319
+ backfillFinishedAt: watermark === 0 ? now : null,
320
+ lastError: latest.status === "error" ? null : latest.lastError,
321
+ };
322
+ this.ctx.storage.transactionSync(() => {
323
+ if (stillAnchor) {
324
+ for (const c of snapped) {
325
+ this.sql.exec("INSERT INTO partition_cursors (partition, last_seq, last_ts, last_offset, last_chunk_key) VALUES (?, ?, ?, ?, ?) ON CONFLICT (partition) DO UPDATE SET last_seq = excluded.last_seq, last_ts = excluded.last_ts, last_offset = excluded.last_offset, last_chunk_key = excluded.last_chunk_key", c.partition, c.lastSeq, c.lastTs, c.lastOffset, c.lastChunkKey);
326
+ }
327
+ }
328
+ if (latest.status === "error") {
329
+ this.sql.exec("UPDATE pending_batches SET attempts = 0, next_attempt_at = ?", now);
330
+ }
331
+ this.writeMeta(next);
332
+ this.recordEvent({ at: now, kind: "backfill_started", reason: "backfill", watermark, detail: "current state" });
333
+ });
334
+ if (stillAnchor) {
335
+ this.generation++;
336
+ for (const c of snapped)
337
+ this.cursors.set(c.partition, c);
338
+ }
339
+ this.meta = next;
340
+ await this.ensureAlarmSoon(now);
341
+ if (this.env.SPOCK_TRACE !== undefined) {
342
+ await traceSpock(this.env, input.graph, "projection.backfill", {
343
+ projection: input.projection,
344
+ mode: "current",
345
+ status: next.backfillStatus,
346
+ watermark: next.backfillWatermark,
347
+ cursorWatermark: next.cursorWatermark,
348
+ anchored: stillAnchor,
349
+ });
350
+ }
351
+ return this.status(input);
352
+ }
353
+ async backfillFromLog(input, sinceMs) {
354
+ const manifest = await readManifest(this.env, input.graph, true);
355
+ const meta = this.ensureMeta(input.graph, input.projection);
356
+ const watermark = manifest?.watermark ?? meta.knownWatermark;
357
+ const partitions = manifest?.partitions ?? meta.knownPartitions;
358
+ const now = Date.now();
359
+ // `sinceMs` is Unix epoch milliseconds (from Console / API). Convert to the 50ms epoch slot
360
+ // (`wallEpoch`) and HLC `ts` (`firstTsOf`) so cursors compare in the exact same units as `tx.key.ts`.
361
+ const sinceEpoch = sinceMs === 0 ? 0 : wallEpoch(sinceMs);
362
+ const prevEpoch = sinceMs === 0 ? 0 : Math.max(0, sinceEpoch - 1);
363
+ const sinceCursorTs = sinceEpoch === 0 ? 0 : firstTsOf(sinceEpoch) - 1;
364
+ const newCursors = [];
365
+ if (sinceMs > 0 && partitions > 0) {
366
+ // Query strictly before `sinceEpoch` so rows inside the same 50ms epoch as `sinceMs`
367
+ // (which may contain transactions with `ts >= firstTsOf(sinceEpoch)`) are never skipped (specs/projection-time-backfill.spock).
368
+ const heads = await Promise.all(Array.from({ length: partitions }, (_, p) => partitionStub(this.env, input.graph, p).logHead({ watermark: prevEpoch }).then((head) => ({
369
+ partition: p,
370
+ // Only skip archived chunks when logHead found a row strictly past the archived frontier.
371
+ lastSeq: head.seq > head.archived ? head.seq : 0,
372
+ lastTs: sinceCursorTs,
373
+ lastOffset: Number.MAX_SAFE_INTEGER,
374
+ lastChunkKey: "",
375
+ }))));
376
+ newCursors.push(...heads);
377
+ }
378
+ const latest = this.requireMeta();
379
+ const next = {
380
+ ...latest,
381
+ status: "running",
382
+ cursorWatermark: sinceMs === 0 ? 0 : Math.min(watermark, prevEpoch),
383
+ knownWatermark: Math.max(latest.knownWatermark, watermark),
384
+ knownPartitions: Math.max(latest.knownPartitions, partitions),
385
+ backfillStatus: "idle",
386
+ backfillCursor: null,
387
+ backfillFinishedAt: null,
388
+ lastError: null,
389
+ };
390
+ const detail = sinceMs === 0 ? "from beginning" : `since ${new Date(sinceMs).toISOString()}`;
391
+ this.ctx.storage.transactionSync(() => {
392
+ this.sql.exec("DELETE FROM partition_cursors");
393
+ for (const c of newCursors) {
394
+ this.sql.exec("INSERT INTO partition_cursors (partition, last_seq, last_ts, last_offset, last_chunk_key) VALUES (?, ?, ?, ?, ?)", c.partition, c.lastSeq, c.lastTs, c.lastOffset, c.lastChunkKey);
395
+ }
396
+ this.sql.exec("DELETE FROM pending_batches WHERE reason = 'live'");
397
+ if (latest.status === "error") {
398
+ this.sql.exec("UPDATE pending_batches SET attempts = 0, next_attempt_at = ?", now);
399
+ }
400
+ this.writeMeta(next);
401
+ this.recordEvent({ at: now, kind: "backfill_started", reason: "replay", watermark: next.cursorWatermark, detail });
402
+ });
403
+ this.generation++;
404
+ this.cursors.clear();
405
+ for (const c of newCursors)
406
+ this.cursors.set(c.partition, c);
407
+ this.meta = next;
408
+ await this.ensureAlarmSoon(now);
409
+ if (this.env.SPOCK_TRACE !== undefined) {
410
+ await traceSpock(this.env, input.graph, "projection.backfill", {
411
+ projection: input.projection,
412
+ mode: sinceMs === 0 ? "replay" : "since",
413
+ sinceMs,
414
+ status: next.backfillStatus,
415
+ generation: this.generation,
416
+ cursors: newCursors.map((c) => ({ p: c.partition, seq: c.lastSeq, ts: c.lastTs, chunk: c.lastChunkKey })),
417
+ });
418
+ }
419
+ return this.status(input);
420
+ }
421
+ /** Moves dead-lettered batches back into pending_batches with reset attempts. */
422
+ async replayDeadLetters(input) {
423
+ this.ensureMeta(input.graph, input.projection);
424
+ const now = Date.now();
425
+ const ids = input.deliveryIds;
426
+ const rows = ids === undefined
427
+ ? this.sql.exec("SELECT * FROM dead_letters ORDER BY failed_at").toArray()
428
+ : ids.flatMap((id) => this.sql.exec("SELECT * FROM dead_letters WHERE delivery_id = ?", id).toArray());
429
+ if (rows.length > 0) {
430
+ this.ctx.storage.transactionSync(() => {
431
+ for (const r of rows) {
432
+ this.sql.exec("INSERT INTO pending_batches (delivery_id, watermark, reason, entities, attempts, next_attempt_at, last_error, created_at) VALUES (?, ?, 'replay', ?, 0, ?, NULL, ?) ON CONFLICT (delivery_id) DO UPDATE SET reason = 'replay', attempts = 0, next_attempt_at = excluded.next_attempt_at, last_error = NULL", r.delivery_id, r.watermark, r.entities, now, r.created_at);
433
+ this.sql.exec("DELETE FROM dead_letters WHERE delivery_id = ?", r.delivery_id);
434
+ }
435
+ this.recordEvent({ at: now, kind: "dead_letters_replayed", reason: "replay", entityCount: rows.length, detail: `${rows.length} dead-letter batch${rows.length === 1 ? "" : "es"}` });
436
+ });
437
+ if (this.requireMeta().status === "running")
438
+ await this.ensureAlarmSoon(now);
439
+ }
440
+ return { replayed: rows.length, state: await this.status(input) };
441
+ }
442
+ /** Deletes dead-lettered batches permanently. */
443
+ async discardDeadLetters(input) {
444
+ this.ensureMeta(input.graph, input.projection);
445
+ const ids = input.deliveryIds;
446
+ const now = Date.now();
447
+ let discarded = 0;
448
+ this.ctx.storage.transactionSync(() => {
449
+ if (ids === undefined) {
450
+ discarded = this.sql.exec("SELECT COUNT(*) AS n FROM dead_letters").one().n;
451
+ this.sql.exec("DELETE FROM dead_letters");
452
+ }
453
+ else {
454
+ for (const id of ids) {
455
+ const exists = this.sql.exec("SELECT COUNT(*) AS n FROM dead_letters WHERE delivery_id = ?", id).one().n;
456
+ if (exists > 0) {
457
+ this.sql.exec("DELETE FROM dead_letters WHERE delivery_id = ?", id);
458
+ discarded++;
459
+ }
460
+ }
461
+ }
462
+ if (discarded > 0) {
463
+ this.recordEvent({ at: now, kind: "dead_letters_discarded", entityCount: discarded, detail: `${discarded} dead-letter batch${discarded === 1 ? "" : "es"}` });
464
+ }
465
+ });
466
+ return { discarded, state: await this.status(input) };
467
+ }
468
+ /** Resets partition cursors to 0 and replays the entire durable log from the start. */
469
+ async replayFromStart(input) {
470
+ return this.backfill({ ...input, since: 0 });
471
+ }
472
+ async deadLetters(input) {
473
+ this.ensureMeta(input.graph, input.projection);
474
+ const limit = Math.max(1, Math.min(500, Math.floor(input.limit ?? 100)));
475
+ return this.sql.exec("SELECT * FROM dead_letters ORDER BY failed_at DESC LIMIT ?", limit).toArray().map((row) => ({
476
+ deliveryId: row.delivery_id,
477
+ watermark: row.watermark,
478
+ reason: row.reason,
479
+ entities: parseStringArray(row.entities),
480
+ attempts: row.attempts,
481
+ lastError: row.last_error,
482
+ createdAt: row.created_at,
483
+ failedAt: row.failed_at,
484
+ }));
485
+ }
486
+ async status(input) {
487
+ const meta = this.ensureMeta(input.graph, input.projection);
488
+ const config = this.configFor(input.graph, input.projection);
489
+ if (config === null) {
490
+ throw new RangeError(`projection ${JSON.stringify(input.projection)} is not configured for graph ${JSON.stringify(input.graph)}`);
491
+ }
492
+ const manifest = await readManifest(this.env, input.graph, false);
493
+ const graphWatermark = Math.max(meta.knownWatermark, manifest?.watermark ?? 0);
494
+ const pendingBatches = this.sql.exec("SELECT COUNT(*) AS n FROM pending_batches").one().n;
495
+ const deadLetters = this.sql.exec("SELECT COUNT(*) AS n FROM dead_letters").one().n;
496
+ let lagMs = null;
497
+ if (graphWatermark > 0) {
498
+ if (meta.cursorWatermark >= graphWatermark && pendingBatches === 0) {
499
+ lagMs = 0;
500
+ }
501
+ else if (meta.cursorWatermark > 0) {
502
+ lagMs = Math.max(0, epochEndMs(graphWatermark) - epochEndMs(meta.cursorWatermark));
503
+ }
504
+ }
505
+ return {
506
+ name: meta.name,
507
+ graph: meta.graph,
508
+ status: meta.status,
509
+ sink: config.sink,
510
+ select: config.select,
511
+ cursorWatermark: meta.cursorWatermark,
512
+ graphWatermark,
513
+ lagMs,
514
+ backfill: {
515
+ status: meta.backfillStatus,
516
+ watermark: meta.backfillWatermark,
517
+ processed: meta.backfillProcessed,
518
+ startedAt: meta.backfillStartedAt,
519
+ finishedAt: meta.backfillFinishedAt,
520
+ },
521
+ counters: {
522
+ deliveredBatches: meta.deliveredBatches,
523
+ deliveredEntities: meta.deliveredEntities,
524
+ failedDeliveries: meta.failedDeliveries,
525
+ pendingBatches,
526
+ deadLetters,
527
+ },
528
+ lastDeliveryAt: meta.lastDeliveryAt,
529
+ lastError: meta.lastError,
530
+ };
531
+ }
532
+ /** Rich operational snapshot for the `/projections/:id` Console page. */
533
+ requireMeta() {
534
+ if (this.meta === null)
535
+ throw new Error("projection metadata is not initialized");
536
+ return this.meta;
537
+ }
538
+ async detail(input) {
539
+ const state = await this.status(input);
540
+ const config = this.configFor(input.graph, input.projection);
541
+ if (config === null)
542
+ throw new Error(`projection ${input.projection} is not configured for graph ${input.graph}`);
543
+ const limit = Math.max(1, Math.min(MAX_STORED_EVENTS, Math.floor(input.limit ?? 100)));
544
+ const partitions = [...this.cursors.values()]
545
+ .sort((a, b) => a.partition - b.partition)
546
+ .map((c) => ({ partition: c.partition, lastSeq: c.lastSeq, lastTs: c.lastTs, lastChunkKey: c.lastChunkKey }));
547
+ const pending = this.sql.exec("SELECT * FROM pending_batches ORDER BY next_attempt_at, created_at LIMIT 50").toArray().map((row) => {
548
+ const entities = parseStringArray(row.entities);
549
+ return {
550
+ deliveryId: row.delivery_id,
551
+ watermark: row.watermark,
552
+ reason: row.reason,
553
+ entityCount: entities.length,
554
+ sampleEntities: entities.slice(0, SAMPLE_ENTITY_COUNT),
555
+ attempts: row.attempts,
556
+ nextAttemptAt: row.next_attempt_at,
557
+ lastError: row.last_error,
558
+ createdAt: row.created_at,
559
+ };
560
+ });
561
+ const deadLetters = await this.deadLetters({ graph: input.graph, projection: input.projection, limit: 100 });
562
+ const events = this.sql.exec("SELECT * FROM projection_events ORDER BY id DESC LIMIT ?", limit).toArray().map((row) => ({
563
+ id: row.id,
564
+ at: row.at,
565
+ kind: row.kind,
566
+ reason: row.reason,
567
+ deliveryId: row.delivery_id,
568
+ watermark: row.watermark,
569
+ entityCount: row.entity_count,
570
+ sampleEntities: parseStringArray(row.sample_entities),
571
+ durationMs: row.duration_ms,
572
+ attempt: row.attempt,
573
+ detail: row.detail,
574
+ }));
575
+ return {
576
+ state,
577
+ config: {
578
+ graphs: config.graphs,
579
+ batch: config.batch,
580
+ retry: config.retry,
581
+ deadLetter: config.deadLetter,
582
+ autoStart: config.autoStart,
583
+ },
584
+ partitions,
585
+ pending,
586
+ deadLetters,
587
+ events,
588
+ };
589
+ }
590
+ async alarm() {
591
+ const meta = this.meta;
592
+ if (meta === null || meta.status !== "running")
593
+ return;
594
+ const config = this.configFor(meta.graph, meta.name);
595
+ if (config === null)
596
+ return;
597
+ const run = { woken: false };
598
+ this.runningAlarm = run;
599
+ let moreWork = false;
600
+ try {
601
+ if (meta.cursorWatermark === 0 || meta.knownWatermark > meta.cursorWatermark) {
602
+ const scannedMore = await this.scanLiveChanges(config);
603
+ if (scannedMore)
604
+ moreWork = true;
605
+ }
606
+ const afterScan = this.requireMeta();
607
+ if (afterScan.status === "running" && afterScan.backfillStatus === "running") {
608
+ const backfillMore = await this.stepBackfill(config);
609
+ if (backfillMore)
610
+ moreWork = true;
611
+ }
612
+ if (this.requireMeta().status === "running") {
613
+ await this.deliverDueBatches(config);
614
+ }
615
+ }
616
+ catch (error) {
617
+ const msg = error instanceof Error ? error.message : String(error);
618
+ console.error(JSON.stringify({ event: "projection.alarm_failed", graph: meta.graph, projection: meta.name, error: msg }));
619
+ this.storeMeta({ ...this.requireMeta(), lastError: msg });
620
+ this.runningAlarm = null;
621
+ await this.ctx.storage.setAlarm(Date.now() + Math.max(1_000, config.retry.initialBackoffMs));
622
+ return;
623
+ }
624
+ finally {
625
+ this.runningAlarm = null;
626
+ }
627
+ const finalMeta = this.requireMeta();
628
+ if (finalMeta.status !== "running")
629
+ return;
630
+ const nextPending = this.sql.exec("SELECT MIN(next_attempt_at) AS at FROM pending_batches").one().at;
631
+ let alarmSet = false;
632
+ if (run.woken || moreWork || finalMeta.backfillStatus === "running" || finalMeta.knownWatermark > finalMeta.cursorWatermark) {
633
+ await this.ctx.storage.setAlarm(Date.now() + IDLE_ALARM_GAP_MS);
634
+ alarmSet = true;
635
+ }
636
+ else if (nextPending !== null) {
637
+ await this.ctx.storage.setAlarm(Math.max(Date.now() + 50, nextPending));
638
+ alarmSet = true;
639
+ }
640
+ if (this.env.SPOCK_TRACE !== undefined) {
641
+ const pending = this.sql.exec("SELECT COUNT(*) AS n FROM pending_batches").one().n;
642
+ const deadLetters = this.sql.exec("SELECT COUNT(*) AS n FROM dead_letters").one().n;
643
+ await traceSpock(this.env, finalMeta.graph, "projection.alarm", {
644
+ projection: finalMeta.name,
645
+ status: finalMeta.status,
646
+ cursorWatermark: finalMeta.cursorWatermark,
647
+ knownWatermark: finalMeta.knownWatermark,
648
+ backfillStatus: finalMeta.backfillStatus,
649
+ deliveredBatches: finalMeta.deliveredBatches,
650
+ deliveredEntities: finalMeta.deliveredEntities,
651
+ failedDeliveries: finalMeta.failedDeliveries,
652
+ pending,
653
+ deadLetters,
654
+ alarmSet,
655
+ generation: this.generation,
656
+ });
657
+ }
658
+ }
659
+ /**
660
+ * Scans partitions from their durable `(lastSeq, lastChunkKey)` up to the latest published
661
+ * manifest watermark, selects matching entities, and atomically persists pending batches + cursors.
662
+ */
663
+ async scanLiveChanges(config) {
664
+ const startGen = this.generation;
665
+ const graph = this.requireMeta().graph;
666
+ const manifest = await readManifest(this.env, graph, true);
667
+ if (manifest === null || manifest.watermark === 0)
668
+ return false;
669
+ const targetWatermark = manifest.watermark;
670
+ const partitions = manifest.partitions;
671
+ const updatedCursors = new Map();
672
+ const collectedTxs = [];
673
+ let moreWork = false;
674
+ let heldByStraddlingRow = false;
675
+ for (let p = 0; p < partitions; p++) {
676
+ const prior = this.cursors.get(p) ?? { partition: p, lastSeq: 0, lastTs: 0, lastOffset: 0, lastChunkKey: "" };
677
+ let cursor = { ...prior };
678
+ let changed = false;
679
+ // Ask PartitionDO first so we only issue R2 Class A LIST calls when rows past cursor.lastSeq
680
+ // were actually archived to R2 chunks (specs/projection-delivery.spock).
681
+ let page = await partitionStub(this.env, graph, p).logRows({ after: cursor.lastSeq, limit: ROWS_PER_PARTITION_TICK });
682
+ if (page.archived > cursor.lastSeq) {
683
+ const chunkRes = await readLogChunksAfter(this.env.INDEX, graph, p, cursor.lastChunkKey, CHUNKS_PER_PARTITION_TICK);
684
+ for (const { key, chunk } of chunkRes.chunks) {
685
+ if (chunk.last <= cursor.lastSeq) {
686
+ cursor = { ...cursor, lastChunkKey: key };
687
+ changed = true;
688
+ continue;
689
+ }
690
+ let maxTs = cursor.lastTs;
691
+ let maxOffset = cursor.lastOffset;
692
+ for (const tx of chunk.txs) {
693
+ if (epochOf(tx.key.ts) > targetWatermark)
694
+ continue;
695
+ if (!isAfterKey(tx.key, cursor.lastTs, cursor.lastOffset))
696
+ continue;
697
+ collectedTxs.push(tx);
698
+ if (isAfterKey(tx.key, maxTs, maxOffset)) {
699
+ maxTs = tx.key.ts;
700
+ maxOffset = tx.key.offset;
701
+ }
702
+ }
703
+ cursor = {
704
+ ...cursor,
705
+ lastSeq: Math.max(cursor.lastSeq, chunk.last),
706
+ lastTs: maxTs,
707
+ lastOffset: maxOffset,
708
+ lastChunkKey: key,
709
+ };
710
+ changed = true;
711
+ }
712
+ if (chunkRes.more) {
713
+ moreWork = true;
714
+ if (changed)
715
+ updatedCursors.set(p, cursor);
716
+ continue;
717
+ }
718
+ page = await partitionStub(this.env, graph, p).logRows({ after: cursor.lastSeq, limit: ROWS_PER_PARTITION_TICK });
719
+ if (page.archived > cursor.lastSeq)
720
+ moreWork = true;
721
+ }
722
+ let hitFutureEpoch = false;
723
+ for (const row of page.rows) {
724
+ if (row.seq <= cursor.lastSeq)
725
+ continue;
726
+ const rowMaxEpoch = maxEpochOf(row.txs);
727
+ if (rowMaxEpoch > targetWatermark) {
728
+ hitFutureEpoch = true;
729
+ if (minEpochOf(row.txs) <= targetWatermark)
730
+ heldByStraddlingRow = true;
731
+ break;
732
+ }
733
+ let maxTs = cursor.lastTs;
734
+ let maxOffset = cursor.lastOffset;
735
+ for (const tx of row.txs) {
736
+ if (!isAfterKey(tx.key, cursor.lastTs, cursor.lastOffset))
737
+ continue;
738
+ collectedTxs.push(tx);
739
+ if (isAfterKey(tx.key, maxTs, maxOffset)) {
740
+ maxTs = tx.key.ts;
741
+ maxOffset = tx.key.offset;
742
+ }
743
+ }
744
+ cursor = { ...cursor, lastSeq: row.seq, lastTs: maxTs, lastOffset: maxOffset };
745
+ changed = true;
746
+ }
747
+ if (!hitFutureEpoch && page.rows.length === ROWS_PER_PARTITION_TICK) {
748
+ moreWork = true;
749
+ }
750
+ if (changed)
751
+ updatedCursors.set(p, cursor);
752
+ }
753
+ const entities = collectedTxs.length === 0 ? [] : await selectEntitiesFromTxs(this.env, manifest, config.select, collectedTxs);
754
+ // Abort committing stale cursors if replayFromStart() or backfill anchoring reset cursors mid-scan (specs/projection-alarm.spock).
755
+ if (this.generation !== startGen)
756
+ return true;
757
+ const batches = chunkArray(entities, config.batch.maxEntities);
758
+ const now = Date.now();
759
+ // Read fresh `this.meta` after awaits so concurrent `stop()` / `wake()` updates are never overwritten.
760
+ const current = this.requireMeta();
761
+ const nextCursorWatermark = moreWork || heldByStraddlingRow ? current.cursorWatermark : Math.max(current.cursorWatermark, targetWatermark);
762
+ const nextMeta = {
763
+ ...current,
764
+ cursorWatermark: nextCursorWatermark,
765
+ knownWatermark: Math.max(current.knownWatermark, targetWatermark),
766
+ knownPartitions: Math.max(current.knownPartitions, partitions),
767
+ };
768
+ if (updatedCursors.size > 0 || batches.length > 0 || nextMeta.cursorWatermark !== current.cursorWatermark || nextMeta.knownWatermark !== current.knownWatermark) {
769
+ this.ctx.storage.transactionSync(() => {
770
+ for (const c of updatedCursors.values()) {
771
+ this.sql.exec("INSERT INTO partition_cursors (partition, last_seq, last_ts, last_offset, last_chunk_key) VALUES (?, ?, ?, ?, ?) ON CONFLICT (partition) DO UPDATE SET last_seq = excluded.last_seq, last_ts = excluded.last_ts, last_offset = excluded.last_offset, last_chunk_key = excluded.last_chunk_key", c.partition, c.lastSeq, c.lastTs, c.lastOffset, c.lastChunkKey);
772
+ }
773
+ for (const group of batches) {
774
+ this.sql.exec("INSERT INTO pending_batches (delivery_id, watermark, reason, entities, attempts, next_attempt_at, last_error, created_at) VALUES (?, ?, 'live', ?, 0, ?, NULL, ?)", crypto.randomUUID(), targetWatermark, JSON.stringify(group), now, now);
775
+ }
776
+ this.writeMeta(nextMeta);
777
+ });
778
+ for (const [p, c] of updatedCursors)
779
+ this.cursors.set(p, c);
780
+ this.meta = nextMeta;
781
+ if (this.env.SPOCK_TRACE !== undefined) {
782
+ await traceSpock(this.env, nextMeta.graph, "projection.scan", {
783
+ projection: nextMeta.name,
784
+ cursorWatermark: nextMeta.cursorWatermark,
785
+ knownWatermark: nextMeta.knownWatermark,
786
+ batches: batches.length,
787
+ entities: entities.length,
788
+ generation: this.generation,
789
+ status: nextMeta.status,
790
+ });
791
+ }
792
+ }
793
+ return moreWork;
794
+ }
795
+ /** Scans one bounded page of existing matching entities from the R2 index for backfill. */
796
+ async stepBackfill(config) {
797
+ const initial = this.requireMeta();
798
+ const startCursor = initial.backfillCursor;
799
+ const startStartedAt = initial.backfillStartedAt;
800
+ const graph = initial.graph;
801
+ const manifest = await readManifest(this.env, graph, true);
802
+ const now = Date.now();
803
+ if (manifest === null || manifest.watermark === 0) {
804
+ const current = this.requireMeta();
805
+ if (current.backfillStatus !== "running" || current.backfillStartedAt !== startStartedAt)
806
+ return false;
807
+ this.storeMeta({ ...current, backfillStatus: "completed", backfillFinishedAt: now });
808
+ return false;
809
+ }
810
+ const page = await scanBackfillPage(this.env, manifest, config.select, startCursor, config.batch.maxEntities);
811
+ const current = this.requireMeta();
812
+ if (current.backfillStatus !== "running" || current.backfillStartedAt !== startStartedAt)
813
+ return false;
814
+ const lastEntity = page.entities[page.entities.length - 1];
815
+ const nextMeta = {
816
+ ...current,
817
+ backfillCursor: lastEntity ?? current.backfillCursor,
818
+ backfillProcessed: current.backfillProcessed + page.entities.length,
819
+ backfillStatus: page.done ? "completed" : "running",
820
+ backfillFinishedAt: page.done ? now : null,
821
+ };
822
+ this.ctx.storage.transactionSync(() => {
823
+ if (page.entities.length > 0) {
824
+ this.sql.exec("INSERT INTO pending_batches (delivery_id, watermark, reason, entities, attempts, next_attempt_at, last_error, created_at) VALUES (?, ?, 'backfill', ?, 0, ?, NULL, ?)", crypto.randomUUID(), manifest.watermark, JSON.stringify(page.entities), now, now);
825
+ this.recordEvent({
826
+ at: now,
827
+ kind: "backfill_page",
828
+ reason: "backfill",
829
+ watermark: manifest.watermark,
830
+ entityCount: page.entities.length,
831
+ sampleEntities: page.entities,
832
+ });
833
+ }
834
+ if (page.done) {
835
+ this.recordEvent({
836
+ at: now,
837
+ kind: "backfill_completed",
838
+ reason: "backfill",
839
+ watermark: manifest.watermark,
840
+ entityCount: nextMeta.backfillProcessed,
841
+ durationMs: nextMeta.backfillStartedAt === null ? null : Math.max(0, now - nextMeta.backfillStartedAt),
842
+ });
843
+ }
844
+ this.writeMeta(nextMeta);
845
+ });
846
+ this.meta = nextMeta;
847
+ return !page.done;
848
+ }
849
+ /** Delivers due pending batches to the configured Worker RPC sink or built-in R2 exporter. */
850
+ async deliverDueBatches(config) {
851
+ const now = Date.now();
852
+ const due = this.sql.exec("SELECT * FROM pending_batches WHERE next_attempt_at <= ? ORDER BY next_attempt_at, created_at LIMIT ?", now, DELIVERIES_PER_TICK).toArray();
853
+ for (const row of due) {
854
+ const beforeDelivery = this.requireMeta();
855
+ if (beforeDelivery.status !== "running")
856
+ return;
857
+ const entities = parseStringArray(row.entities);
858
+ const delivery = {
859
+ projection: config.name,
860
+ graph: beforeDelivery.graph,
861
+ watermark: row.watermark,
862
+ deliveryId: row.delivery_id,
863
+ reason: row.reason,
864
+ entities,
865
+ };
866
+ const startedAt = Date.now();
867
+ try {
868
+ if (config.sink.kind === "worker") {
869
+ await deliverToWorker(this.env, config.sink.binding, delivery);
870
+ }
871
+ else {
872
+ await deliverToR2(this.env, config.sink, delivery);
873
+ }
874
+ const doneAt = Date.now();
875
+ const fresh = this.requireMeta();
876
+ const nextMeta = {
877
+ ...fresh,
878
+ deliveredBatches: fresh.deliveredBatches + 1,
879
+ deliveredEntities: fresh.deliveredEntities + entities.length,
880
+ lastDeliveryAt: doneAt,
881
+ lastError: null,
882
+ };
883
+ this.ctx.storage.transactionSync(() => {
884
+ this.sql.exec("DELETE FROM pending_batches WHERE delivery_id = ?", row.delivery_id);
885
+ this.writeMeta(nextMeta);
886
+ this.recordEvent({
887
+ at: doneAt,
888
+ kind: "batch_delivered",
889
+ reason: row.reason,
890
+ deliveryId: row.delivery_id,
891
+ watermark: row.watermark,
892
+ entityCount: entities.length,
893
+ sampleEntities: entities,
894
+ durationMs: Math.max(0, doneAt - startedAt),
895
+ attempt: row.attempts + 1,
896
+ });
897
+ });
898
+ this.meta = nextMeta;
899
+ }
900
+ catch (error) {
901
+ const message = error instanceof Error ? error.message : String(error);
902
+ const attempts = row.attempts + 1;
903
+ const failedAt = Date.now();
904
+ const durationMs = Math.max(0, failedAt - startedAt);
905
+ const fresh = this.requireMeta();
906
+ console.error(JSON.stringify({
907
+ event: "projection.delivery_failed",
908
+ graph: fresh.graph,
909
+ projection: config.name,
910
+ deliveryId: row.delivery_id,
911
+ attempts,
912
+ maxAttempts: config.retry.maxAttempts,
913
+ error: message,
914
+ }));
915
+ if (attempts < config.retry.maxAttempts) {
916
+ const backoff = Math.min(config.retry.maxBackoffMs, config.retry.initialBackoffMs * 2 ** (attempts - 1));
917
+ const nextMeta = {
918
+ ...fresh,
919
+ failedDeliveries: fresh.failedDeliveries + 1,
920
+ lastError: message,
921
+ };
922
+ this.ctx.storage.transactionSync(() => {
923
+ this.sql.exec("UPDATE pending_batches SET attempts = ?, next_attempt_at = ?, last_error = ? WHERE delivery_id = ?", attempts, failedAt + backoff, message, row.delivery_id);
924
+ this.writeMeta(nextMeta);
925
+ this.recordEvent({
926
+ at: failedAt,
927
+ kind: "batch_failed",
928
+ reason: row.reason,
929
+ deliveryId: row.delivery_id,
930
+ watermark: row.watermark,
931
+ entityCount: entities.length,
932
+ sampleEntities: entities,
933
+ durationMs,
934
+ attempt: attempts,
935
+ detail: message,
936
+ });
937
+ });
938
+ this.meta = nextMeta;
939
+ }
940
+ else if (config.deadLetter) {
941
+ const nextMeta = {
942
+ ...fresh,
943
+ failedDeliveries: fresh.failedDeliveries + 1,
944
+ lastError: message,
945
+ };
946
+ this.ctx.storage.transactionSync(() => {
947
+ this.sql.exec("INSERT INTO dead_letters (delivery_id, watermark, reason, entities, attempts, last_error, created_at, failed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (delivery_id) DO UPDATE SET attempts = excluded.attempts, last_error = excluded.last_error, failed_at = excluded.failed_at", row.delivery_id, row.watermark, row.reason, row.entities, attempts, message, row.created_at, failedAt);
948
+ this.sql.exec("DELETE FROM pending_batches WHERE delivery_id = ?", row.delivery_id);
949
+ this.writeMeta(nextMeta);
950
+ this.recordEvent({
951
+ at: failedAt,
952
+ kind: "batch_dead_lettered",
953
+ reason: row.reason,
954
+ deliveryId: row.delivery_id,
955
+ watermark: row.watermark,
956
+ entityCount: entities.length,
957
+ sampleEntities: entities,
958
+ durationMs,
959
+ attempt: attempts,
960
+ detail: message,
961
+ });
962
+ });
963
+ this.meta = nextMeta;
964
+ }
965
+ else {
966
+ const nextMeta = {
967
+ ...fresh,
968
+ status: "error",
969
+ failedDeliveries: fresh.failedDeliveries + 1,
970
+ lastError: message,
971
+ };
972
+ this.ctx.storage.transactionSync(() => {
973
+ this.sql.exec("UPDATE pending_batches SET attempts = ?, last_error = ? WHERE delivery_id = ?", attempts, message, row.delivery_id);
974
+ this.writeMeta(nextMeta);
975
+ this.recordEvent({
976
+ at: failedAt,
977
+ kind: "batch_failed",
978
+ reason: row.reason,
979
+ deliveryId: row.delivery_id,
980
+ watermark: row.watermark,
981
+ entityCount: entities.length,
982
+ sampleEntities: entities,
983
+ durationMs,
984
+ attempt: attempts,
985
+ detail: message,
986
+ });
987
+ });
988
+ this.meta = nextMeta;
989
+ return;
990
+ }
991
+ }
992
+ }
993
+ }
994
+ }
995
+ function isAfterKey(key, lastTs, lastOffset) {
996
+ return key.ts > lastTs || (key.ts === lastTs && key.offset > lastOffset);
997
+ }
998
+ function maxEpochOf(txs) {
999
+ let max = 0;
1000
+ for (const tx of txs) {
1001
+ const e = epochOf(tx.key.ts);
1002
+ if (e > max)
1003
+ max = e;
1004
+ }
1005
+ return max;
1006
+ }
1007
+ function minEpochOf(txs) {
1008
+ let min = Infinity;
1009
+ for (const tx of txs) {
1010
+ const e = epochOf(tx.key.ts);
1011
+ if (e < min)
1012
+ min = e;
1013
+ }
1014
+ return min;
1015
+ }
1016
+ function chunkArray(items, size) {
1017
+ const out = [];
1018
+ for (let i = 0; i < items.length; i += size)
1019
+ out.push(items.slice(i, i + size));
1020
+ return out;
1021
+ }
1022
+ function makeSource(env, manifest) {
1023
+ const metrics = { ...emptyReadMetrics(), scans: 0, tuplesRead: 0, segmentsTouched: 0 };
1024
+ return new SegmentFactSource(segmentStore(env), manifest.buckets, manifest.watermark, [], metrics);
1025
+ }
1026
+ function valueAsId(value) {
1027
+ return value.type === "reference" || value.type === "text" ? value.value : null;
1028
+ }
1029
+ /** Resolves the fields that carry entity types for a graph (`typeField`, or `schema:entity:type` + subfields). */
1030
+ async function resolveTypeFields(source, explicit) {
1031
+ if (explicit !== null)
1032
+ return [explicit];
1033
+ const fields = new Set([SCHEMA.type]);
1034
+ const subfields = await source.activeFacts(SCHEMA.subfieldOf);
1035
+ // Follow transitive subfield_of chains back to schema:entity:type.
1036
+ const parents = new Map();
1037
+ for (const fact of subfields) {
1038
+ const parent = valueAsId(fact.value);
1039
+ if (parent === null)
1040
+ continue;
1041
+ const list = parents.get(fact.entity) ?? [];
1042
+ list.push(parent);
1043
+ parents.set(fact.entity, list);
1044
+ }
1045
+ let added = true;
1046
+ while (added) {
1047
+ added = false;
1048
+ for (const [child, list] of parents) {
1049
+ if (fields.has(child))
1050
+ continue;
1051
+ if (list.some((p) => fields.has(p))) {
1052
+ fields.add(child);
1053
+ added = true;
1054
+ }
1055
+ }
1056
+ }
1057
+ return [...fields];
1058
+ }
1059
+ /** Evaluates `select` against a batch of transactions from the durable log, returning deduplicated entity IDs. */
1060
+ async function selectEntitiesFromTxs(env, manifest, select, txs) {
1061
+ const byEntity = new Map();
1062
+ for (const tx of txs) {
1063
+ for (const fact of tx.facts) {
1064
+ let list = byEntity.get(fact.entity);
1065
+ if (list === undefined) {
1066
+ list = [];
1067
+ byEntity.set(fact.entity, list);
1068
+ }
1069
+ list.push(fact);
1070
+ }
1071
+ }
1072
+ let candidates = [...byEntity.keys()];
1073
+ if (candidates.length === 0)
1074
+ return [];
1075
+ if (select.fields.length > 0) {
1076
+ const wantedFields = new Set(select.fields);
1077
+ candidates = candidates.filter((entity) => (byEntity.get(entity) ?? []).some((f) => wantedFields.has(f.field)));
1078
+ if (candidates.length === 0)
1079
+ return [];
1080
+ }
1081
+ if (select.entityKinds.length > 0) {
1082
+ const wantedKinds = new Set(select.entityKinds);
1083
+ const typeFields = await resolveTypeFields(makeSource(env, manifest), select.typeField);
1084
+ const typeFieldSet = new Set(typeFields);
1085
+ const matched = [];
1086
+ for (const entity of candidates) {
1087
+ // Match if a type fact in this batch asserted OR retracted one of the watched kinds.
1088
+ const touchedKind = (byEntity.get(entity) ?? []).some((f) => {
1089
+ if (!typeFieldSet.has(f.field))
1090
+ return false;
1091
+ const id = valueAsId(f.value);
1092
+ return id !== null && wantedKinds.has(id);
1093
+ });
1094
+ if (touchedKind) {
1095
+ matched.push(entity);
1096
+ continue;
1097
+ }
1098
+ // Fresh SegmentFactSource per entity so a large batch never hits a cross-entity tuple budget.
1099
+ const entitySource = makeSource(env, manifest);
1100
+ let hasKind = false;
1101
+ for (const tf of typeFields) {
1102
+ const facts = await entitySource.entityFacts(tf, entity);
1103
+ if (facts.some((f) => {
1104
+ const id = valueAsId(f.value);
1105
+ return id !== null && wantedKinds.has(id);
1106
+ })) {
1107
+ hasKind = true;
1108
+ break;
1109
+ }
1110
+ }
1111
+ if (hasKind)
1112
+ matched.push(entity);
1113
+ }
1114
+ candidates = matched;
1115
+ if (candidates.length === 0)
1116
+ return [];
1117
+ }
1118
+ if (select.where !== null && select.whereEntityVar !== null) {
1119
+ const parsed = parseDatalogQuery(select.where);
1120
+ if (!parsed.ok)
1121
+ throw new Error(`invalid projection where clause: ${parsed.error.message}`);
1122
+ const whereFields = new Set(select.whereFields);
1123
+ const matched = [];
1124
+ for (const entity of candidates) {
1125
+ // If a fact matching one of the where-clause predicates was retracted, still notify so the sink updates.
1126
+ const retractedRelevant = (byEntity.get(entity) ?? []).some((f) => f.retraction && whereFields.has(f.field));
1127
+ if (retractedRelevant) {
1128
+ matched.push(entity);
1129
+ continue;
1130
+ }
1131
+ const boundQuery = bindEntityVar(parsed.value, select.whereEntityVar, entity);
1132
+ for await (const _binding of evaluateDatalog(boundQuery, makeSource(env, manifest), { maxResults: 1 })) {
1133
+ matched.push(entity);
1134
+ break;
1135
+ }
1136
+ }
1137
+ candidates = matched;
1138
+ }
1139
+ return candidates.sort(compareCodeUnits);
1140
+ }
1141
+ function bindEntityVar(query, varName, entity) {
1142
+ const replace = (term) => term.kind === "variable" && term.name === varName
1143
+ ? { kind: "constant", value: { type: "string", value: entity } }
1144
+ : term;
1145
+ const replaceFact = (c) => ({
1146
+ kind: "fact",
1147
+ predicate: c.predicate,
1148
+ entity: replace(c.entity),
1149
+ value: replace(c.value),
1150
+ });
1151
+ const [firstFact, ...restFacts] = query.facts;
1152
+ const facts = [replaceFact(firstFact), ...restFacts.map(replaceFact)];
1153
+ const constraints = query.constraints.map((c) => ({
1154
+ kind: "builtin",
1155
+ name: c.name,
1156
+ left: replace(c.left),
1157
+ right: replace(c.right),
1158
+ }));
1159
+ return { facts, constraints };
1160
+ }
1161
+ /** Collects all distinct field names present in a manifest's segment headers. */
1162
+ async function manifestFields(env, manifest) {
1163
+ const store = segmentStore(env);
1164
+ const metrics = emptyReadMetrics();
1165
+ const refs = Object.values(manifest.buckets).flat();
1166
+ const headers = await Promise.all(refs.map((ref) => readHeader(store, ref, metrics)));
1167
+ const fields = new Set();
1168
+ for (const h of headers) {
1169
+ for (const field of Object.keys(h.schema))
1170
+ fields.add(field);
1171
+ }
1172
+ return [...fields].sort(compareCodeUnits);
1173
+ }
1174
+ /** Scans one lexicographical page of matching active entities from the published R2 index for backfill. */
1175
+ async function scanBackfillPage(env, manifest, select, afterEntity, pageSize) {
1176
+ const source = makeSource(env, manifest);
1177
+ const all = new Set();
1178
+ if (select.where !== null && select.whereEntityVar !== null) {
1179
+ const parsed = parseDatalogQuery(select.where);
1180
+ if (!parsed.ok)
1181
+ throw new Error(`invalid projection where clause: ${parsed.error.message}`);
1182
+ const query = afterEntity === null
1183
+ ? parsed.value
1184
+ : {
1185
+ facts: parsed.value.facts,
1186
+ constraints: [
1187
+ ...parsed.value.constraints,
1188
+ {
1189
+ kind: "builtin",
1190
+ name: ">",
1191
+ left: { kind: "variable", name: select.whereEntityVar },
1192
+ right: { kind: "constant", value: { type: "string", value: afterEntity } },
1193
+ },
1194
+ ],
1195
+ };
1196
+ for await (const binding of evaluateDatalog(query, source, { maxResults: BACKFILL_PAGE_LIMIT })) {
1197
+ const bound = binding.get(select.whereEntityVar);
1198
+ const id = bound === undefined ? null : valueAsId(bound.fact);
1199
+ if (id !== null && (afterEntity === null || id > afterEntity))
1200
+ all.add(id);
1201
+ }
1202
+ // Apply intersection with entityKinds / fields when combined with where.
1203
+ let list = [...all].sort(compareCodeUnits);
1204
+ if (select.entityKinds.length > 0) {
1205
+ const wantedKinds = new Set(select.entityKinds);
1206
+ const typeFields = await resolveTypeFields(makeSource(env, manifest), select.typeField);
1207
+ const filtered = [];
1208
+ for (const e of list) {
1209
+ const entitySource = makeSource(env, manifest);
1210
+ for (const tf of typeFields) {
1211
+ const facts = await entitySource.entityFacts(tf, e);
1212
+ if (facts.some((f) => { const id = valueAsId(f.value); return id !== null && wantedKinds.has(id); })) {
1213
+ filtered.push(e);
1214
+ break;
1215
+ }
1216
+ }
1217
+ if (select.fields.length === 0 && filtered.length > pageSize)
1218
+ break;
1219
+ }
1220
+ list = filtered;
1221
+ }
1222
+ if (select.fields.length > 0) {
1223
+ const filtered = [];
1224
+ for (const e of list) {
1225
+ const entitySource = makeSource(env, manifest);
1226
+ for (const field of select.fields) {
1227
+ if ((await entitySource.entityFacts(field, e)).length > 0) {
1228
+ filtered.push(e);
1229
+ break;
1230
+ }
1231
+ }
1232
+ if (filtered.length > pageSize)
1233
+ break;
1234
+ }
1235
+ list = filtered;
1236
+ }
1237
+ return { entities: list.slice(0, pageSize), done: list.length <= pageSize };
1238
+ }
1239
+ if (select.entityKinds.length > 0) {
1240
+ const typeFields = await resolveTypeFields(makeSource(env, manifest), select.typeField);
1241
+ for (const tf of typeFields) {
1242
+ const parsedTf = parseUri(tf);
1243
+ if (!parsedTf.ok)
1244
+ continue;
1245
+ for (const kind of select.entityKinds) {
1246
+ for await (const tuple of makeSource(env, manifest).scan({ field: parsedTf.value, value: { type: "string", value: kind } })) {
1247
+ const id = tuple.entity.value;
1248
+ if (afterEntity === null || id > afterEntity)
1249
+ all.add(id);
1250
+ }
1251
+ }
1252
+ }
1253
+ let list = [...all].sort(compareCodeUnits);
1254
+ if (select.fields.length > 0) {
1255
+ const filtered = [];
1256
+ for (const e of list) {
1257
+ const entitySource = makeSource(env, manifest);
1258
+ for (const field of select.fields) {
1259
+ if ((await entitySource.entityFacts(field, e)).length > 0) {
1260
+ filtered.push(e);
1261
+ break;
1262
+ }
1263
+ }
1264
+ if (filtered.length > pageSize)
1265
+ break;
1266
+ }
1267
+ list = filtered;
1268
+ }
1269
+ return { entities: list.slice(0, pageSize), done: list.length <= pageSize };
1270
+ }
1271
+ const fieldsToScan = select.fields.length > 0 ? select.fields : await manifestFields(env, manifest);
1272
+ for (const field of fieldsToScan) {
1273
+ const parsedField = parseUri(field);
1274
+ if (!parsedField.ok)
1275
+ continue;
1276
+ for await (const tuple of makeSource(env, manifest).scan({ field: parsedField.value })) {
1277
+ const id = tuple.entity.value;
1278
+ if (afterEntity === null || id > afterEntity)
1279
+ all.add(id);
1280
+ }
1281
+ }
1282
+ const sorted = [...all].sort(compareCodeUnits);
1283
+ return { entities: sorted.slice(0, pageSize), done: sorted.length <= pageSize };
1284
+ }
1285
+ function parseStringArray(raw) {
1286
+ const parsed = JSON.parse(raw);
1287
+ if (!Array.isArray(parsed))
1288
+ return [];
1289
+ return parsed.filter((item) => typeof item === "string");
1290
+ }
1291
+ function lookupBinding(env, name) {
1292
+ return Reflect.get(env, name);
1293
+ }
1294
+ function isProjectionSink(value) {
1295
+ return typeof value === "object" && value !== null && "onProjectionBatch" in value && typeof value.onProjectionBatch === "function";
1296
+ }
1297
+ function isR2BucketBinding(value) {
1298
+ return typeof value === "object" && value !== null && "put" in value && typeof value.put === "function";
1299
+ }
1300
+ async function deliverToWorker(env, binding, delivery) {
1301
+ const target = lookupBinding(env, binding);
1302
+ if (!isProjectionSink(target)) {
1303
+ throw new Error(`projection worker sink binding ${binding} is missing or does not expose onProjectionBatch`);
1304
+ }
1305
+ await target.onProjectionBatch(delivery);
1306
+ }
1307
+ /**
1308
+ * Built-in R2 exporter: reads each entity's current active facts from the latest published manifest
1309
+ * (preventing stale retries/backfills from overwriting newer writes) and writes one JSON file per
1310
+ * entity. Entities with zero active facts still write `{ id, ..., facts: [] }` as a tombstone.
1311
+ */
1312
+ const R2_WRITE_CONCURRENCY = 8;
1313
+ async function deliverToR2(env, sink, delivery) {
1314
+ const bucket = lookupBinding(env, sink.binding);
1315
+ if (!isR2BucketBinding(bucket)) {
1316
+ throw new Error(`projection R2 sink binding ${sink.binding} is not bound`);
1317
+ }
1318
+ const manifest = await readManifest(env, delivery.graph, true);
1319
+ const watermark = Math.max(delivery.watermark, manifest?.watermark ?? 0);
1320
+ const fields = manifest === null ? [] : await manifestFields(env, manifest);
1321
+ for (let i = 0; i < delivery.entities.length; i += R2_WRITE_CONCURRENCY) {
1322
+ const slice = delivery.entities.slice(i, i + R2_WRITE_CONCURRENCY);
1323
+ await Promise.all(slice.map(async (entity) => {
1324
+ const active = [];
1325
+ if (manifest !== null) {
1326
+ // Fresh SegmentFactSource per entity so a large batch never trips a cross-entity tuple budget.
1327
+ const source = makeSource(env, manifest);
1328
+ const perField = await Promise.all(fields.map((field) => source.entityFacts(field, entity)));
1329
+ for (const list of perField)
1330
+ active.push(...list);
1331
+ }
1332
+ active.sort((a, b) => (a.field < b.field ? -1 : a.field > b.field ? 1 : 0)
1333
+ || (a.source < b.source ? -1 : a.source > b.source ? 1 : 0)
1334
+ || compareText(canonicalValue(a.value), canonicalValue(b.value)));
1335
+ const doc = {
1336
+ id: entity,
1337
+ graph: delivery.graph,
1338
+ watermark,
1339
+ updatedAt: Date.now(),
1340
+ facts: active.map((f) => ({ field: f.field, value: f.value, source: f.source })),
1341
+ };
1342
+ const key = projectionEntityKey(sink.prefix, delivery.graph, entity);
1343
+ await bucket.put(key, JSON.stringify(doc), { httpMetadata: { contentType: "application/json" } });
1344
+ }));
1345
+ }
1346
+ }
1347
+ function compareText(a, b) {
1348
+ return a < b ? -1 : a > b ? 1 : 0;
1349
+ }