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,710 @@
1
+ // An index shard: indexes the field buckets it owns (RFD0008, "Index shards and R2").
2
+ //
3
+ // Once a second it asks every partition to close its past epochs and hand over the facts in its
4
+ // buckets above its watermark. Its next watermark is the lowest epoch every partition has fully
5
+ // handed over. It writes those facts as one segment per bucket, stores what it wrote, and reports
6
+ // its watermark and segments to the graph's root, which publishes the manifest.
7
+ //
8
+ // A shard is a leaf of the graph's layout (layout.ts): it owns the buckets b with b mod 2^depth =
9
+ // prefix, so a hot field stays on one shard. It reads the partitions of the layout it knows, and
10
+ // learns a newer one from partition 0, which holds its watermark below the partitions it does not
11
+ // read yet, or from the root's answer to its report (RFD0011). A shard that cannot keep up asks the
12
+ // root to split it; once the root has, the shard hands the buckets of its new half, with their
13
+ // segments and its watermark, to that half's object, and keeps the rest.
14
+ import { DurableObject } from "cloudflare:workers";
15
+ import { partitionStub, rootStub, settings, shardStub, traceSpock, } from "./environment.js";
16
+ import { BUCKETS, bucketOf, compareFacts, fromWire, lastWrites, resolveActive } from "./facts.js";
17
+ import { epochEndMs, epochOf } from "./keys.js";
18
+ import { halves, initialLayout, isShardCount, isLeaf, MAX_DEPTH, newer, owns, partitionCount, partitionLayout } from "./layout.js";
19
+ import { encodeSegment, readEavFacts } from "./segment.js";
20
+ const WAKE_FLUSH_MS = 1_000;
21
+ const IMMEDIATE_WAKE_MS = 50;
22
+ /** Cap on the confirm tick after a flush so lazy flushMs (e.g. 60–300 s) still confirms & sleeps quickly. */
23
+ const CONFIRM_SYNC_CAP_MS = 1_500;
24
+ // What a flush reads, split across the partitions: FACTS_PER_FLUSH bounds the facts partitions parse
25
+ // (one transaction holds up to 1,000), FLUSH_BYTES the bytes of the shard's own facts they hand
26
+ // over, which is what the shard holds in memory. Durable Objects have 128 MB, shared with the other
27
+ // objects in their isolate, and a fact takes a few times its wire size once parsed and encoded.
28
+ const FACTS_PER_FLUSH = 120_000;
29
+ const MAX_FACTS_PER_HANDOFF = 30_000;
30
+ const FLUSH_BYTES = 8 * 2 ** 20;
31
+ const MIN_HANDOFF_BYTES = 64 * 2 ** 10;
32
+ // Compaction by size ratio: a run of segments merges while each older one holds fewer than RATIO
33
+ // times the bytes of the newer ones it joins. Sizes then grow geometrically from newest to oldest,
34
+ // so a bucket keeps about log2 of its bytes in segments, whatever sizes its flushes happened to have,
35
+ // up to MAX_MERGED_BYTES a segment. A merge runs after its flush, one at a time in an isolate (see
36
+ // `merging`), and holds about four times its bytes at its peak.
37
+ const RATIO = 2;
38
+ const MAX_MERGED_BYTES = 16 * 2 ** 20;
39
+ /** Multi-bucket flushes up to this size pack into a single L0 R2 segment (1 Class A PUT instead of N). */
40
+ const PACKED_FLUSH_BYTES = 1 * 2 ** 20;
41
+ const PACKED_FLUSH_FACTS = 8_000;
42
+ const RETIRE_AFTER_MS = 60_000; // readers holding an older manifest may still read retired segments
43
+ /** Flushes in a row that held a partition back, after which a shard asks to be split. */
44
+ const SPLIT_AFTER_BEHIND = 5;
45
+ const posKey = (bucket, name) => `${bucket}\u0000${name}`;
46
+ /** Durable Objects in one isolate share its memory: one merge at a time among them. */
47
+ let merging = false;
48
+ export class IndexShardDO extends DurableObject {
49
+ sql = this.ctx.storage.sql;
50
+ meta = null;
51
+ buckets = new Map();
52
+ /** Each live segment's place in its bucket: appended ones take their seq, a merge takes the place of the first segment it replaces. */
53
+ positions = new Map();
54
+ graphWatermark = 0;
55
+ reportPending = true;
56
+ flushes = [];
57
+ errors = [];
58
+ compactions = { runs: 0, segmentsIn: 0, bytesIn: 0, lastMs: 0, maxMs: 0 };
59
+ behindStreak = 0;
60
+ partitionLoad = null;
61
+ /** The root's layout, once it shows this shard split. */
62
+ splitDue = null;
63
+ constructor(ctx, env) {
64
+ super(ctx, env);
65
+ void ctx.blockConcurrencyWhile(async () => this.load());
66
+ }
67
+ load() {
68
+ this.sql.exec(`CREATE TABLE IF NOT EXISTS shard (id INTEGER PRIMARY KEY CHECK (id = 1), graph TEXT NOT NULL, depth INTEGER NOT NULL,
69
+ prefix INTEGER NOT NULL, layout TEXT NOT NULL, watermark INTEGER NOT NULL, seq INTEGER NOT NULL, facts INTEGER NOT NULL)`);
70
+ this.sql.exec(`CREATE TABLE IF NOT EXISTS segments (name TEXT NOT NULL, bucket INTEGER NOT NULL, seq INTEGER NOT NULL, position REAL NOT NULL,
71
+ ref TEXT NOT NULL, retired_at INTEGER, retired_seq INTEGER, PRIMARY KEY (name, bucket))`);
72
+ const segCols = this.sql.exec("PRAGMA table_info(segments)").toArray();
73
+ const colNames = new Set(segCols.map((c) => c.name));
74
+ if (!colNames.has("retired_seq"))
75
+ this.sql.exec("ALTER TABLE segments ADD COLUMN retired_seq INTEGER");
76
+ const bucketPk = segCols.find((c) => c.name === "bucket")?.pk ?? 0;
77
+ if (bucketPk === 0) {
78
+ // Upgrade pre-packed segments table (PRIMARY KEY (name)) to composite PRIMARY KEY (name, bucket).
79
+ this.ctx.storage.transactionSync(() => {
80
+ this.sql.exec(`CREATE TABLE segments_v2 (name TEXT NOT NULL, bucket INTEGER NOT NULL, seq INTEGER NOT NULL, position REAL NOT NULL,
81
+ ref TEXT NOT NULL, retired_at INTEGER, retired_seq INTEGER, PRIMARY KEY (name, bucket))`);
82
+ this.sql.exec("INSERT INTO segments_v2 (name, bucket, seq, position, ref, retired_at, retired_seq) SELECT name, bucket, seq, position, ref, retired_at, retired_seq FROM segments");
83
+ this.sql.exec("DROP TABLE segments");
84
+ this.sql.exec("ALTER TABLE segments_v2 RENAME TO segments");
85
+ });
86
+ }
87
+ this.adoptFixedLayout();
88
+ const row = this.sql.exec("SELECT graph, depth, prefix, layout, watermark, seq, facts FROM shard").toArray()[0];
89
+ this.meta = row === undefined ? null : { ...row, layout: parsePartitionLayoutJson(row.layout) };
90
+ for (const row of this.sql.exec("SELECT bucket, ref, position FROM segments WHERE retired_at IS NULL AND retired_seq IS NULL ORDER BY bucket, position")) {
91
+ const list = this.buckets.get(row.bucket) ?? [];
92
+ const ref = parseSegmentRefJson(row.ref);
93
+ list.push(ref);
94
+ this.positions.set(posKey(row.bucket, ref.name), row.position);
95
+ this.buckets.set(row.bucket, list);
96
+ }
97
+ }
98
+ /**
99
+ * A shard written before layouts could change kept its graph's fixed partitions and shard count
100
+ * in `meta`: its leaf is its number in a full tree of that many shards (layout.ts), and its
101
+ * layout the graph's first.
102
+ */
103
+ adoptFixedLayout() {
104
+ const tables = new Set(this.sql.exec("SELECT name FROM sqlite_master WHERE type = 'table'").toArray().map((t) => t.name));
105
+ if (!tables.has("meta"))
106
+ return;
107
+ this.ctx.storage.transactionSync(() => {
108
+ const old = this.sql.exec("SELECT graph, partitions, shards, shard, watermark, seq, facts FROM meta").toArray()[0];
109
+ // Its root refuses the graph (root.ts); the shard keeps what it holds, and is never started.
110
+ if (old && !isShardCount(old.shards))
111
+ return;
112
+ if (old) {
113
+ const layout = initialLayout(old.partitions, old.shards, 0);
114
+ this.sql.exec("INSERT INTO shard (id, graph, depth, prefix, layout, watermark, seq, facts) VALUES (1, ?, ?, ?, ?, ?, ?, ?)", old.graph, layout.firstDepth, old.shard, JSON.stringify(partitionLayout(layout)), old.watermark, old.seq, old.facts);
115
+ }
116
+ this.sql.exec("DROP TABLE meta");
117
+ });
118
+ }
119
+ /** Stores the shard's metadata, then takes it: what the shard acts on is always what it stored. */
120
+ storeMeta(meta) {
121
+ this.writeMeta(meta);
122
+ this.meta = meta;
123
+ }
124
+ /**
125
+ * Writes the metadata inside a transaction, whose caller takes it once the transaction commits:
126
+ * a rolled-back flush that had already taken its watermark would hand off from past the facts it
127
+ * never stored, and they would be missing from the index for good.
128
+ */
129
+ writeMeta(meta) {
130
+ this.sql.exec("INSERT INTO shard (id, graph, depth, prefix, layout, watermark, seq, facts) VALUES (1, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET graph = excluded.graph, depth = excluded.depth, prefix = excluded.prefix, layout = excluded.layout, watermark = excluded.watermark, seq = excluded.seq, facts = excluded.facts", meta.graph, meta.depth, meta.prefix, JSON.stringify(meta.layout), meta.watermark, meta.seq, meta.facts);
131
+ }
132
+ /**
133
+ * The root starts the shards of its layout. A shard of the graph's first layout starts empty; a
134
+ * half made by a split has nothing until the shard it split from hands it its buckets (adopt).
135
+ */
136
+ async start(input) {
137
+ if (this.meta === null) {
138
+ if (input.leaf.depth !== input.layout.firstDepth)
139
+ return;
140
+ this.storeMeta({ graph: input.graph, depth: input.leaf.depth, prefix: input.leaf.prefix, layout: partitionLayout(input.layout), watermark: 0, seq: 0, facts: 0 });
141
+ }
142
+ else if (this.meta.graph !== input.graph || this.meta.prefix !== input.leaf.prefix) {
143
+ throw new Error(`shard ${this.meta.prefix} of ${this.meta.graph} was started as ${JSON.stringify(input.leaf)} of ${input.graph}`);
144
+ }
145
+ this.takeLayout(input.layout);
146
+ const now = Date.now();
147
+ const flushMs = settings(this.env).flushMs;
148
+ const delay = input.immediate === true
149
+ ? IMMEDIATE_WAKE_MS
150
+ : flushMs <= 2_000
151
+ ? Math.min(WAKE_FLUSH_MS, flushMs)
152
+ : flushMs;
153
+ const alarm = await this.ctx.storage.getAlarm();
154
+ if (alarm === null || alarm > now + delay)
155
+ await this.ctx.storage.setAlarm(now + delay);
156
+ }
157
+ requireMeta() {
158
+ if (this.meta === null)
159
+ throw new Error("shard meta is not initialized");
160
+ return this.meta;
161
+ }
162
+ /** Takes the partitions of a newer layout for the next flush, and notes when it shows this shard split. */
163
+ takeLayout(layout) {
164
+ const meta = this.requireMeta();
165
+ const next = newer(meta.layout, partitionLayout(layout));
166
+ if (next !== meta.layout)
167
+ this.storeMeta({ ...meta, layout: next });
168
+ if (!isLeaf(layout, { depth: meta.depth, prefix: meta.prefix }) && layout.shards.some((l) => l.prefix === meta.prefix && l.depth > meta.depth))
169
+ this.splitDue = layout;
170
+ }
171
+ /**
172
+ * The half of a split shard takes over its buckets, once: a repeated call, from a shard whose
173
+ * call failed or that restarted mid-split, takes nothing again. Every call reports before it
174
+ * answers, since the root must name these buckets' segments from this shard before the one it
175
+ * split from stops reporting them: that one drops them as soon as this answers.
176
+ */
177
+ async adopt(input) {
178
+ if (this.meta === null) {
179
+ const adopted = { graph: input.graph, depth: input.leaf.depth, prefix: input.leaf.prefix, layout: input.layout, watermark: input.watermark, seq: input.seq, facts: input.facts };
180
+ this.ctx.storage.transactionSync(() => {
181
+ for (const [bucket, refs] of Object.entries(input.buckets)) {
182
+ refs.forEach((ref, i) => this.sql.exec("INSERT INTO segments (name, bucket, seq, position, ref) VALUES (?, ?, ?, ?, ?)", ref.name, Number(bucket), input.seq, i, JSON.stringify(ref)));
183
+ }
184
+ this.writeMeta(adopted);
185
+ });
186
+ this.meta = adopted;
187
+ for (const [bucket, refs] of Object.entries(input.buckets)) {
188
+ const b = Number(bucket);
189
+ this.buckets.set(b, [...refs]);
190
+ refs.forEach((ref, i) => this.positions.set(posKey(b, ref.name), i));
191
+ }
192
+ }
193
+ else if (this.meta.graph !== input.graph || this.meta.prefix !== input.leaf.prefix) {
194
+ throw new Error(`shard ${this.meta.prefix} of ${this.meta.graph} was handed ${JSON.stringify(input.leaf)} of ${input.graph}`);
195
+ }
196
+ this.reportPending = true;
197
+ await this.report();
198
+ await this.ctx.storage.setAlarm(Date.now() + Math.min(WAKE_FLUSH_MS, settings(this.env).flushMs));
199
+ if (this.env.SPOCK_TRACE !== undefined) {
200
+ await traceSpock(this.env, input.graph, "shard.adopt", {
201
+ shard: input.leaf.prefix,
202
+ depth: input.leaf.depth,
203
+ watermark: input.watermark,
204
+ buckets: Object.keys(input.buckets).length,
205
+ });
206
+ }
207
+ }
208
+ /**
209
+ * Splits any packed L0 segment shared between kept and moved buckets during a shard split so
210
+ * each shard owns disjoint R2 objects and can garbage-collect retired segments locally.
211
+ */
212
+ async isolateMovedBuckets(meta, movedEntries, keptNames) {
213
+ const sharedRefs = new Map();
214
+ for (const [, refs] of movedEntries) {
215
+ for (const ref of refs)
216
+ if (keptNames.has(ref.name))
217
+ sharedRefs.set(ref.name, ref);
218
+ }
219
+ const decoded = new Map();
220
+ if (sharedRefs.size > 0) {
221
+ const pairs = await Promise.all([...sharedRefs.values()].map(async (ref) => [ref.name, await readEavFacts(this.env.INDEX, ref)]));
222
+ for (const [name, facts] of pairs)
223
+ decoded.set(name, facts);
224
+ }
225
+ let seq = meta.seq;
226
+ const writes = [];
227
+ const moved = movedEntries.map(([bucket, refs]) => {
228
+ const out = [];
229
+ for (const ref of refs) {
230
+ if (!keptNames.has(ref.name)) {
231
+ out.push(ref);
232
+ continue;
233
+ }
234
+ const bucketFacts = (decoded.get(ref.name) ?? []).filter((f) => bucketOf(f.field, BUCKETS) === bucket);
235
+ if (bucketFacts.length === 0)
236
+ continue;
237
+ const slot = out.length;
238
+ out.push(ref);
239
+ const s = ++seq;
240
+ writes.push(this.put(meta, bucket, ref.maxEpoch, s, "flush", bucketFacts).then((isolated) => [bucket, slot, isolated]));
241
+ }
242
+ return [bucket, out];
243
+ });
244
+ if (writes.length > 0) {
245
+ const byBucket = new Map(moved);
246
+ for (const [bucket, slot, isolated] of await Promise.all(writes)) {
247
+ const list = byBucket.get(bucket);
248
+ if (list !== undefined)
249
+ list[slot] = isolated;
250
+ }
251
+ }
252
+ return { moved, seq };
253
+ }
254
+ /** Hands one half of this shard's buckets to its new sibling object and commits the new depth. */
255
+ async splitHalf(meta, give) {
256
+ const keptNames = new Set();
257
+ for (const [bucket, refs] of this.buckets) {
258
+ if (!owns(give, bucket))
259
+ for (const ref of refs)
260
+ keptNames.add(ref.name);
261
+ }
262
+ // Any retired row still tracked on this shard will be garbage-collected by deleteRetired()
263
+ // once its grace window expires; isolate moved buckets referencing the same R2 object so a
264
+ // sibling shard never loses a live packed segment to this shard's local GC.
265
+ for (const row of this.sql.exec("SELECT DISTINCT name FROM segments WHERE retired_at IS NOT NULL OR retired_seq IS NOT NULL")) {
266
+ keptNames.add(row.name);
267
+ }
268
+ const movedEntries = [...this.buckets].filter(([bucket]) => owns(give, bucket));
269
+ const { moved, seq } = await this.isolateMovedBuckets(meta, movedEntries, keptNames);
270
+ const movedFacts = moved.reduce((n, [, refs]) => n + refs.reduce((m, r) => m + r.facts, 0), 0);
271
+ await shardStub(this.env, meta.graph, give.prefix).adopt({
272
+ graph: meta.graph, leaf: give, layout: meta.layout, watermark: meta.watermark, seq, facts: movedFacts,
273
+ buckets: Object.fromEntries(moved.map(([bucket, refs]) => [String(bucket), refs])),
274
+ });
275
+ const next = { ...meta, depth: meta.depth + 1, seq, facts: Math.max(0, meta.facts - movedFacts) };
276
+ this.ctx.storage.transactionSync(() => {
277
+ for (const [bucket] of moved)
278
+ this.sql.exec("DELETE FROM segments WHERE bucket = ? AND retired_at IS NULL AND retired_seq IS NULL", bucket);
279
+ this.writeMeta(next);
280
+ });
281
+ this.meta = next;
282
+ for (const [bucket, refs] of movedEntries) {
283
+ this.buckets.delete(bucket);
284
+ for (const ref of refs)
285
+ this.positions.delete(posKey(bucket, ref.name));
286
+ }
287
+ return next;
288
+ }
289
+ /** Hands the buckets of each new half to its object, until this shard is a leaf of the root's layout. */
290
+ async split(layout) {
291
+ const step = async (meta) => {
292
+ if (isLeaf(layout, { depth: meta.depth, prefix: meta.prefix }))
293
+ return meta;
294
+ const [, give] = halves({ depth: meta.depth, prefix: meta.prefix });
295
+ return step(await this.splitHalf(meta, give));
296
+ };
297
+ const meta = await step(this.requireMeta());
298
+ this.splitDue = null;
299
+ this.reportPending = true;
300
+ if (this.env.SPOCK_TRACE !== undefined) {
301
+ await traceSpock(this.env, meta.graph, "shard.split", {
302
+ shard: meta.prefix,
303
+ depth: meta.depth,
304
+ buckets: this.buckets.size,
305
+ });
306
+ }
307
+ await this.report();
308
+ }
309
+ async alarm() {
310
+ const started = Date.now();
311
+ let behind = false;
312
+ let open = false;
313
+ let txs = 0;
314
+ let failed = false;
315
+ try {
316
+ const outcome = await this.flush();
317
+ behind = outcome.behind;
318
+ open = outcome.open;
319
+ txs = outcome.txs;
320
+ if (this.splitDue !== null)
321
+ await this.split(this.splitDue);
322
+ // Apart from the flush, so the two never hold their memory at once; not while behind.
323
+ else if (!behind)
324
+ await this.compactOnce();
325
+ }
326
+ catch (error) {
327
+ failed = true;
328
+ this.errors.push(`${new Date().toISOString()} ${String(error)}`);
329
+ if (this.errors.length > 20)
330
+ this.errors.shift();
331
+ console.error(JSON.stringify({ event: "shard.flush_failed", shard: this.meta?.prefix, error: String(error) }));
332
+ }
333
+ const now = Date.now();
334
+ const needsSync = this.reportPending || this.hasUnconfirmedRetired()
335
+ || (this.meta !== null && this.graphWatermark < this.meta.watermark);
336
+ // 1-tick idle stop (specs/shard-idle-wake.spock): once a tick finds zero unindexed txs,
337
+ // no open epoch, no failure, and the root has confirmed our watermark & retired segments,
338
+ // sleep immediately (or directly until the next retired-segment GC deadline).
339
+ if (!failed && !behind && !open && txs === 0 && !needsSync && this.splitDue === null) {
340
+ const nextRetire = this.nextRetiredDeleteAt();
341
+ if (nextRetire !== null) {
342
+ await this.ctx.storage.setAlarm(Math.max(now + 50, nextRetire));
343
+ }
344
+ if (this.env.SPOCK_TRACE !== undefined && this.meta !== null) {
345
+ await traceSpock(this.env, this.meta.graph, "shard.alarm", {
346
+ shard: this.meta.prefix,
347
+ watermark: this.meta.watermark,
348
+ graphWatermark: this.graphWatermark,
349
+ txs,
350
+ alarmSet: nextRetire !== null,
351
+ });
352
+ }
353
+ return;
354
+ }
355
+ const flushMs = settings(this.env).flushMs;
356
+ const baseNext = Math.max(now + 50, started + flushMs);
357
+ const nextAt = behind
358
+ ? now + 50
359
+ : open
360
+ ? now + 100
361
+ : needsSync
362
+ ? Math.min(baseNext, now + CONFIRM_SYNC_CAP_MS)
363
+ : baseNext;
364
+ await this.ctx.storage.setAlarm(nextAt);
365
+ if (this.env.SPOCK_TRACE !== undefined && this.meta !== null) {
366
+ await traceSpock(this.env, this.meta.graph, "shard.alarm", {
367
+ shard: this.meta.prefix,
368
+ watermark: this.meta.watermark,
369
+ graphWatermark: this.graphWatermark,
370
+ txs,
371
+ alarmSet: true,
372
+ });
373
+ }
374
+ }
375
+ /** Returns whether a partition held back more than one flush takes, holds rows in an open epoch, and how many txs flushed. */
376
+ async flush() {
377
+ const meta = this.meta;
378
+ if (meta === null)
379
+ return { behind: false, open: false, txs: 0 };
380
+ const t0 = Date.now();
381
+ const partitions = partitionCount(meta.layout);
382
+ const parts = Array.from({ length: partitions }, (_, p) => p);
383
+ const shards = 2 ** meta.depth;
384
+ // A partition hands this shard about 1/2^depth of what it reads, so this keeps the flush near FACTS_PER_FLUSH.
385
+ const maxFacts = Math.min(MAX_FACTS_PER_HANDOFF, Math.max(1_000, Math.floor((FACTS_PER_FLUSH * shards) / partitions)));
386
+ const maxBytes = Math.max(MIN_HANDOFF_BYTES, Math.floor(FLUSH_BYTES / partitions));
387
+ const handoffs = await Promise.all(parts.map((p) => partitionStub(this.env, meta.graph, p).handoff({
388
+ partition: p, from: meta.watermark, maxFacts, maxBytes, shard: meta.prefix, shards, layout: meta.layout, forceClose: false,
389
+ })));
390
+ // If any partition handed off transactions, ask lagging quiet partitions to close up to that
391
+ // epoch so the graph watermark advances without wasting SQLite writes on fully idle ticks.
392
+ const anyTxs = handoffs.some((h) => h.txs > 0);
393
+ if (anyTxs && partitions > 1) {
394
+ const targetEpoch = Math.max(...handoffs.filter((h) => h.txs > 0).map((h) => h.covered));
395
+ const lagging = parts.filter((p) => {
396
+ const h = handoffs[p];
397
+ return h !== undefined && h.covered < targetEpoch;
398
+ });
399
+ if (lagging.length > 0) {
400
+ const closed = await Promise.all(lagging.map((p) => partitionStub(this.env, meta.graph, p).handoff({
401
+ partition: p, from: meta.watermark, maxFacts, maxBytes, shard: meta.prefix, shards, layout: meta.layout, forceClose: true,
402
+ })));
403
+ lagging.forEach((p, idx) => {
404
+ const updated = closed[idx];
405
+ if (updated !== undefined)
406
+ handoffs[p] = updated;
407
+ });
408
+ }
409
+ }
410
+ const t1 = Date.now();
411
+ const next = Math.min(...handoffs.map((h) => h.covered));
412
+ const behind = handoffs.some((h) => h.covered < h.closed);
413
+ const open = handoffs.some((h) => h.open === true);
414
+ this.behindStreak = behind ? this.behindStreak + 1 : 0;
415
+ // The partitions' calls, for the root to grow the graph by: one shard sends them when non-zero.
416
+ const totalCalls = handoffs.reduce((n, h) => n + h.calls, 0);
417
+ const totalPending = handoffs.reduce((n, h) => n + h.pending, 0);
418
+ this.partitionLoad = meta.prefix === 0 && (totalCalls > 0 || totalPending > 0)
419
+ ? { calls: totalCalls, windowMs: handoffs[0]?.windowMs ?? 0, pending: totalPending, partitions }
420
+ : null;
421
+ // Partition 0 tells a shard of a layout it does not read yet, and held its watermark below it: read it from the next flush.
422
+ const learned = handoffs.reduce((l, h) => newer(l, h.layout), meta.layout);
423
+ const txs = handoffs.reduce((n, h) => n + h.txs, 0);
424
+ if (txs === 0 || next <= meta.watermark) {
425
+ if (learned !== meta.layout)
426
+ this.storeMeta({ ...meta, layout: learned });
427
+ const needsReport = this.reportPending
428
+ || this.hasUnconfirmedRetired()
429
+ || this.graphWatermark < meta.watermark
430
+ || (this.partitionLoad !== null && this.partitionLoad.calls > 0);
431
+ if (needsReport)
432
+ await this.report();
433
+ if (this.hasRetired())
434
+ await this.deleteRetired();
435
+ return { behind, open, txs: 0 };
436
+ }
437
+ const facts = handoffs.flatMap((h) => h.facts.map(fromWire)).filter((f) => epochOf(f.ts) <= next);
438
+ const byBucket = new Map();
439
+ for (const f of facts) {
440
+ const b = bucketOf(f.field, BUCKETS);
441
+ const list = byBucket.get(b) ?? [];
442
+ list.push(f);
443
+ byBucket.set(b, list);
444
+ }
445
+ let seq = meta.seq;
446
+ const compacted = 0;
447
+ const buckets = new Map([...this.buckets].map(([b, refs]) => [b, [...refs]]));
448
+ const added = [];
449
+ const retired = [];
450
+ let packed = false;
451
+ if (byBucket.size > 1 && facts.length <= PACKED_FLUSH_FACTS) {
452
+ const encoded = encodeSegment(facts, next);
453
+ if (encoded.bytes.byteLength <= PACKED_FLUSH_BYTES) {
454
+ const s = ++seq;
455
+ const name = `graphs/${meta.graph}/segments/l0/${String(next).padStart(14, "0")}-${meta.prefix}-${s}-flush.seg`;
456
+ await this.env.INDEX.put(name, encoded.bytes);
457
+ const ref = { name, ...encoded.ref };
458
+ for (const b of byBucket.keys()) {
459
+ buckets.set(b, [...(buckets.get(b) ?? []), ref]);
460
+ added.push({ bucket: b, ref, seq: s, position: s });
461
+ }
462
+ packed = true;
463
+ }
464
+ }
465
+ if (!packed) {
466
+ await Promise.all([...byBucket].map(async ([b, list]) => {
467
+ const s = ++seq;
468
+ const ref = await this.put(meta, b, next, s, "flush", list);
469
+ buckets.set(b, [...(buckets.get(b) ?? []), ref]);
470
+ added.push({ bucket: b, ref, seq: s, position: s });
471
+ }));
472
+ }
473
+ // Store what the root will publish before reporting it, so a restart never forgets a segment.
474
+ const now = Date.now();
475
+ const flushed = { ...meta, layout: learned, watermark: next, seq, facts: meta.facts + facts.length };
476
+ this.ctx.storage.transactionSync(() => {
477
+ for (const a of added)
478
+ this.sql.exec("INSERT INTO segments (name, bucket, seq, position, ref) VALUES (?, ?, ?, ?, ?)", a.ref.name, a.bucket, a.seq, a.position, JSON.stringify(a.ref));
479
+ for (const name of retired)
480
+ this.sql.exec("UPDATE segments SET retired_at = ? WHERE name = ?", now, name);
481
+ this.writeMeta(flushed);
482
+ });
483
+ this.meta = flushed;
484
+ this.buckets = buckets;
485
+ for (const a of added)
486
+ this.positions.set(posKey(a.bucket, a.ref.name), a.position);
487
+ if (this.env.SPOCK_TRACE !== undefined) {
488
+ await traceSpock(this.env, flushed.graph, "shard.flush", {
489
+ shard: flushed.prefix,
490
+ depth: flushed.depth,
491
+ watermark: flushed.watermark,
492
+ seq: flushed.seq,
493
+ txs,
494
+ segments: packed ? 1 : added.length,
495
+ retired: retired.length,
496
+ });
497
+ }
498
+ const t2 = Date.now();
499
+ await this.report();
500
+ const t3 = Date.now();
501
+ await this.deleteRetired();
502
+ this.flushes.push({
503
+ at: t3, watermark: next, stalenessMs: t3 - epochEndMs(next), txs, facts: facts.length, segments: packed ? 1 : byBucket.size, compacted,
504
+ handoffMs: t1 - t0, r2Ms: t2 - t1, reportMs: t3 - t2, totalMs: Date.now() - t0, behind,
505
+ });
506
+ if (this.flushes.length > 600)
507
+ this.flushes.shift();
508
+ return { behind, open, txs };
509
+ }
510
+ /**
511
+ * Merges one run of segments, in the bucket with the most of them, if any bucket has a run, and
512
+ * reports it. The merged segment takes the place of the first one it replaces; the replaced ones
513
+ * are deleted RETIRE_AFTER_MS later, once readers holding an older manifest are done with them.
514
+ */
515
+ async compactOnce() {
516
+ const meta = this.meta;
517
+ if (meta === null || merging)
518
+ return;
519
+ let pick = null;
520
+ for (const [bucket, refs] of this.buckets) {
521
+ const run = compactionRun(refs, this.graphWatermark);
522
+ if (run !== null && (pick === null || refs.length > pick.refs.length))
523
+ pick = { bucket, refs, run };
524
+ }
525
+ if (pick === null)
526
+ return;
527
+ const { bucket, refs, run } = pick;
528
+ const inputs = refs.slice(run.start, run.end);
529
+ const started = Date.now();
530
+ merging = true;
531
+ let ref;
532
+ const s = meta.seq + 1;
533
+ try {
534
+ const chunks = await Promise.all(inputs.map((r) => readEavFacts(this.env.INDEX, r)));
535
+ // Packed L0 segments hold multiple buckets: keep only this bucket's facts when compacting it.
536
+ const all = chunks.flat().filter((f) => bucketOf(f.field, BUCKETS) === bucket);
537
+ // Only a run reaching back to the first segment may drop retractions: otherwise an older
538
+ // segment may hold the fact they retract.
539
+ const merged = (run.start === 0 ? resolveActive(all) : lastWrites(all)).sort(compareFacts);
540
+ ref = merged.length === 0 ? null : await this.put(meta, bucket, meta.watermark, s, "compacted", merged);
541
+ }
542
+ finally {
543
+ merging = false;
544
+ }
545
+ const retired = inputs.map((r) => r.name);
546
+ const firstInput = inputs[0];
547
+ const position = (firstInput === undefined ? undefined : this.positions.get(posKey(bucket, firstInput.name))) ?? s;
548
+ const compacted = { ...this.requireMeta(), seq: s };
549
+ this.ctx.storage.transactionSync(() => {
550
+ if (ref)
551
+ this.sql.exec("INSERT INTO segments (name, bucket, seq, position, ref) VALUES (?, ?, ?, ?, ?)", ref.name, bucket, s, position, JSON.stringify(ref));
552
+ // Record retired_seq without arming retired_at yet: the grace timer starts only once the
553
+ // root confirms a manifest at seq >= s has been written to R2 (specs/compaction-gc.spock).
554
+ for (const name of retired)
555
+ this.sql.exec("UPDATE segments SET retired_seq = ?, retired_at = NULL WHERE name = ? AND bucket = ?", s, name, bucket);
556
+ this.writeMeta(compacted);
557
+ });
558
+ this.meta = compacted;
559
+ this.buckets.set(bucket, [...refs.slice(0, run.start), ...(ref ? [ref] : []), ...refs.slice(run.end)]);
560
+ if (ref)
561
+ this.positions.set(posKey(bucket, ref.name), position);
562
+ for (const name of retired)
563
+ this.positions.delete(posKey(bucket, name));
564
+ const ms = Date.now() - started;
565
+ Object.assign(this.compactions, {
566
+ runs: this.compactions.runs + 1, segmentsIn: this.compactions.segmentsIn + inputs.length,
567
+ bytesIn: this.compactions.bytesIn + inputs.reduce((n, r) => n + r.bytes, 0), lastMs: ms, maxMs: Math.max(this.compactions.maxMs, ms),
568
+ });
569
+ // Report now: the replaced segments are deleted RETIRE_AFTER_MS after this, so the manifest must stop naming them first.
570
+ this.reportPending = true;
571
+ if (this.env.SPOCK_TRACE !== undefined) {
572
+ await traceSpock(this.env, compacted.graph, "shard.compact", {
573
+ shard: compacted.prefix,
574
+ bucket,
575
+ seq: compacted.seq,
576
+ full: run.start === 0,
577
+ mergedCount: inputs.length,
578
+ retiredCount: retired.length,
579
+ remainingInBucket: (this.buckets.get(bucket) ?? []).length,
580
+ graphWatermark: this.graphWatermark,
581
+ });
582
+ }
583
+ await this.report();
584
+ }
585
+ async put(meta, bucket, watermark, seq, kind, facts) {
586
+ const name = `graphs/${meta.graph}/segments/${bucket}/${String(watermark).padStart(14, "0")}-${meta.prefix}-${seq}-${kind}.seg`;
587
+ const { bytes, ref } = encodeSegment(facts, watermark);
588
+ await this.env.INDEX.put(name, bytes);
589
+ return { name, ...ref };
590
+ }
591
+ /** Tells the root this shard's watermark and segments; it answers with the graph's watermark and its layout. */
592
+ async report() {
593
+ const meta = this.requireMeta();
594
+ const wantsSplit = this.behindStreak >= SPLIT_AFTER_BEHIND && meta.depth < MAX_DEPTH && this.buckets.size > 1;
595
+ try {
596
+ const answer = await rootStub(this.env, meta.graph).report({
597
+ graph: meta.graph, leaf: { depth: meta.depth, prefix: meta.prefix },
598
+ watermark: meta.watermark, facts: meta.facts, seq: meta.seq, buckets: Object.fromEntries([...this.buckets].map(([b, refs]) => [String(b), refs])),
599
+ ...(this.partitionLoad === null ? {} : { load: this.partitionLoad }), ...(wantsSplit ? { split: true } : {}),
600
+ });
601
+ this.graphWatermark = Math.max(this.graphWatermark, answer.watermark);
602
+ this.takeLayout(answer.layout);
603
+ if (answer.publishedSeq > 0) {
604
+ this.sql.exec("UPDATE segments SET retired_at = ? WHERE retired_seq IS NOT NULL AND retired_seq <= ? AND retired_at IS NULL", Date.now(), answer.publishedSeq);
605
+ }
606
+ this.reportPending = false;
607
+ }
608
+ catch (error) {
609
+ this.reportPending = true;
610
+ throw error;
611
+ }
612
+ }
613
+ hasUnconfirmedRetired() {
614
+ return this.sql.exec("SELECT 1 AS n FROM segments WHERE retired_seq IS NOT NULL AND retired_at IS NULL LIMIT 1").toArray().length > 0;
615
+ }
616
+ hasRetired() {
617
+ return this.sql.exec("SELECT 1 AS n FROM segments WHERE retired_seq IS NOT NULL OR retired_at IS NOT NULL LIMIT 1").toArray().length > 0;
618
+ }
619
+ /** Earliest wall time at which a retired segment becomes eligible for R2 deletion, or null. */
620
+ nextRetiredDeleteAt() {
621
+ const row = this.sql.exec("SELECT MIN(retired_at) AS earliest FROM segments WHERE retired_at IS NOT NULL").one();
622
+ return row.earliest === null ? null : row.earliest + RETIRE_AFTER_MS;
623
+ }
624
+ async deleteRetired() {
625
+ const cutoff = Date.now() - RETIRE_AFTER_MS;
626
+ // Only delete an R2 segment once EVERY bucket referencing it on this shard has been retired
627
+ // and past the grace window (packed L0 segments may stay live in other buckets).
628
+ const due = this.sql.exec(`SELECT name FROM segments
629
+ WHERE name IN (SELECT DISTINCT name FROM segments WHERE retired_at IS NOT NULL AND retired_at < ?)
630
+ GROUP BY name
631
+ HAVING SUM(CASE WHEN retired_at IS NULL OR retired_at >= ? THEN 1 ELSE 0 END) = 0
632
+ LIMIT 1000`, cutoff, cutoff).toArray().map((r) => r.name);
633
+ if (due.length === 0)
634
+ return;
635
+ await this.env.INDEX.delete(due);
636
+ for (const name of due)
637
+ this.sql.exec("DELETE FROM segments WHERE name = ?", name);
638
+ if (this.env.SPOCK_TRACE !== undefined && this.meta !== null) {
639
+ await traceSpock(this.env, this.meta.graph, "shard.retire_delete", {
640
+ shard: this.meta.prefix,
641
+ deletedCount: due.length,
642
+ hasRetired: this.hasRetired(),
643
+ });
644
+ }
645
+ }
646
+ async status(brief = false) {
647
+ const m = this.meta;
648
+ const unique = new Map();
649
+ for (const refs of this.buckets.values())
650
+ for (const ref of refs)
651
+ unique.set(ref.name, ref);
652
+ const live = [...unique.values()];
653
+ return {
654
+ shard: m?.prefix ?? -1, depth: m?.depth ?? 0, layoutVersion: m?.layout.version ?? 0, watermark: m?.watermark ?? 0, graphWatermark: this.graphWatermark, facts: m?.facts ?? 0,
655
+ segments: live.length,
656
+ liveFacts: live.reduce((f, ref) => f + ref.facts, 0),
657
+ bytes: live.reduce((b, ref) => b + ref.bytes, 0), compactions: { ...this.compactions },
658
+ flushes: brief ? [] : this.flushes.slice(-120), errors: this.errors,
659
+ };
660
+ }
661
+ }
662
+ /**
663
+ * The run to merge in a bucket, if there is one: the newest run of two or more consecutive
664
+ * segments where each older one holds fewer than RATIO times the bytes of the newer ones, none
665
+ * holding a write above the graph's watermark, within MAX_MERGED_BYTES. Merging above the
666
+ * watermark would drop writes a reader at an older watermark still needs.
667
+ */
668
+ function isPartitionLayout(v) {
669
+ return typeof v === "object" && v !== null && "version" in v && "eras" in v && Array.isArray(v.eras);
670
+ }
671
+ function parsePartitionLayoutJson(raw) {
672
+ const parsed = JSON.parse(raw);
673
+ if (!isPartitionLayout(parsed))
674
+ throw new Error("stored shard layout is invalid");
675
+ return parsed;
676
+ }
677
+ function isSegmentRef(v) {
678
+ return typeof v === "object" && v !== null && "name" in v && typeof v.name === "string";
679
+ }
680
+ function parseSegmentRefJson(raw) {
681
+ const parsed = JSON.parse(raw);
682
+ if (!isSegmentRef(parsed))
683
+ throw new Error("stored segment ref is invalid");
684
+ return parsed;
685
+ }
686
+ export function compactionRun(refs, graphWatermark) {
687
+ let end = refs.length;
688
+ while (end > 0) {
689
+ const ref = refs[end - 1];
690
+ if (ref === undefined || ref.maxEpoch <= graphWatermark)
691
+ break;
692
+ end--;
693
+ }
694
+ for (let i = end; i >= 2; i--) {
695
+ const seed = refs[i - 1];
696
+ if (seed === undefined)
697
+ continue;
698
+ let start = i - 1, total = seed.bytes;
699
+ while (start > 0) {
700
+ const prev = refs[start - 1];
701
+ if (prev === undefined || prev.bytes >= RATIO * total || total + prev.bytes > MAX_MERGED_BYTES)
702
+ break;
703
+ total += prev.bytes;
704
+ start--;
705
+ }
706
+ if (i - start >= 2)
707
+ return { start, end: i };
708
+ }
709
+ return null;
710
+ }