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,596 @@
1
+ // A graph's root: keeps its layout and publishes its manifest (RFD0008, "Watermark"; RFD0011).
2
+ //
3
+ // The layout. The root makes a graph's first layout when it is first asked for it, and serves it
4
+ // to the Workers that route writes, which cache it. It grows the graph when the partitions' calls
5
+ // outgrow them, or the Workers report partitions refusing calls: it installs the new layout in
6
+ // partition 0 first, which chooses the epoch the new partitions start at, and publishes it after
7
+ // (rule layoutThroughPartitionZero). It splits an index shard that cannot keep up when the shard
8
+ // asks. One change at a time: a split waits for a growth to be published.
9
+ //
10
+ // The manifest. Index shards report their watermark and segments after every flush. At most once
11
+ // a second (the most R2 takes per key) the root writes the manifest: each bucket's segments, from
12
+ // the shard that owns the bucket, or from the shard it was split from until the new one reports,
13
+ // and the graph's watermark, the lowest of its shards'. Then it tells the partitions, which may
14
+ // delete rows the watermark has passed once their token window is over too.
15
+ import { DurableObject } from "cloudflare:workers";
16
+ import { projectionMatchesGraph, readProjectionsConfig } from "../domain/projection.js";
17
+ import { manifestKey, MAX_PARTITIONS, partitionStub, projectionStub, settings, shardStub, traceSpock, } from "./environment.js";
18
+ import { BUCKETS } from "./facts.js";
19
+ import { epochEndMs } from "./keys.js";
20
+ import { initialLayout, isShardCount, isLeaf, MAX_DEPTH, ownerOf, owns, partitionCount, partitionLayout, withEra, withSplit, } from "./layout.js";
21
+ const MANIFEST_GAP_MS = 1_000;
22
+ const NOTIFY_GAP_MS = 2_000;
23
+ const NOTIFY_BATCH = 128;
24
+ /** A graph grows at most every ten seconds, judging partition load over a five-second window. */
25
+ const GROW_EVERY_MS = 10_000;
26
+ const LOAD_WINDOW_MS = 5_000;
27
+ /** Overloaded partitions the Workers report within the load window that make a graph grow, whatever its calls. */
28
+ const GROW_ON_OVERLOADS = 3;
29
+ /** A shard splits at most this often. */
30
+ const SPLIT_EVERY_MS = 10_000;
31
+ const START_SHARDS_EVERY_MS = 5_000;
32
+ const IMMEDIATE_START_EVERY_MS = 500;
33
+ /**
34
+ * The partitions a graph should grow to, or null to stay: when its calls average more than
35
+ * `growAboveCalls` a partition, or partitions refuse calls as overloaded, at least double, and
36
+ * enough for the calls to average half the threshold.
37
+ */
38
+ function isLayout(v) {
39
+ return typeof v === "object" && v !== null && "version" in v && "eras" in v && "shards" in v && Array.isArray(v.eras) && Array.isArray(v.shards);
40
+ }
41
+ function parseStoredLayout(raw) {
42
+ const parsed = JSON.parse(raw);
43
+ if (!isLayout(parsed))
44
+ throw new Error("stored root layout is invalid");
45
+ return parsed;
46
+ }
47
+ export function growthTarget(input) {
48
+ const { partitions: n, callsPerSecond: rate, overloaded, growAboveCalls: above } = input;
49
+ if (n >= MAX_PARTITIONS)
50
+ return null;
51
+ if (!overloaded && (rate === null || rate <= above * n))
52
+ return null;
53
+ return Math.min(MAX_PARTITIONS, Math.max(2 * n, rate === null ? 0 : Math.ceil(rate / (above / 2))));
54
+ }
55
+ export class GraphRootDO extends DurableObject {
56
+ sql = this.ctx.storage.sql;
57
+ graph = null;
58
+ current = null;
59
+ shards = new Map();
60
+ publish = {
61
+ manifestedSeq: new Map(),
62
+ published: 0,
63
+ r2Synced: false,
64
+ notified: 0,
65
+ projectionNotified: new Map(),
66
+ lastNotifyAt: 0,
67
+ manifests: 0,
68
+ lastManifestAt: 0,
69
+ scheduled: false,
70
+ running: null,
71
+ notifying: false,
72
+ };
73
+ scaling = {
74
+ pending: null,
75
+ installing: null,
76
+ lastGrewAt: 0,
77
+ lastStartAt: 0,
78
+ callsPerSecond: null,
79
+ overloads: [],
80
+ splitAt: new Map(),
81
+ };
82
+ counters = { reports: 0, alarms: 0, lastAlarmMs: 0, maxAlarmMs: 0, notifyRounds: 0, lastNotifyMs: 0, skippedNotifies: 0 };
83
+ errors = [];
84
+ /** Why this root cannot take calls: a layout of 0.1 that no layout here can hold. */
85
+ unreadable = null;
86
+ constructor(ctx, env) {
87
+ super(ctx, env);
88
+ void ctx.blockConcurrencyWhile(async () => this.load());
89
+ }
90
+ load() {
91
+ this.sql.exec("CREATE TABLE IF NOT EXISTS root (id INTEGER PRIMARY KEY CHECK (id = 1), graph TEXT NOT NULL, layout TEXT NOT NULL, pending TEXT, published INTEGER NOT NULL)");
92
+ this.sql.exec("CREATE TABLE IF NOT EXISTS shard_reports (prefix INTEGER PRIMARY KEY, depth INTEGER NOT NULL, watermark INTEGER NOT NULL, facts INTEGER NOT NULL, buckets TEXT NOT NULL, seq INTEGER NOT NULL DEFAULT 0)");
93
+ const reportCols = new Set(this.sql.exec("PRAGMA table_info(shard_reports)").toArray().map((c) => c.name));
94
+ if (!reportCols.has("seq"))
95
+ this.sql.exec("ALTER TABLE shard_reports ADD COLUMN seq INTEGER NOT NULL DEFAULT 0");
96
+ this.adoptFixedLayout();
97
+ const row = this.sql.exec("SELECT graph, layout, pending, published FROM root").toArray()[0];
98
+ if (row) {
99
+ this.graph = row.graph;
100
+ this.current = parseStoredLayout(row.layout);
101
+ this.scaling.pending = row.pending === null ? null : parseStoredLayout(row.pending);
102
+ this.publish.published = row.published;
103
+ }
104
+ for (const r of this.sql.exec("SELECT prefix, depth, watermark, facts, seq, buckets FROM shard_reports")) {
105
+ this.shards.set(r.prefix, { depth: r.depth, watermark: r.watermark, facts: r.facts, seq: r.seq, buckets: JSON.parse(r.buckets) });
106
+ }
107
+ }
108
+ /**
109
+ * A root written before layouts could change kept a fixed one, `layout`, and its shards' reports
110
+ * by shard number, `shards`: their layout is the first of the graph's, and their shards the
111
+ * leaves of a full tree (layout.ts), so the graph keeps its data.
112
+ */
113
+ adoptFixedLayout() {
114
+ const tables = new Set(this.sql.exec("SELECT name FROM sqlite_master WHERE type = 'table'").toArray().map((t) => t.name));
115
+ if (!tables.has("layout"))
116
+ return;
117
+ this.ctx.storage.transactionSync(() => {
118
+ const old = this.sql.exec("SELECT graph, partitions, shards, published FROM layout").toArray()[0];
119
+ if (old && !isShardCount(old.shards)) {
120
+ // 0.1 gave a shard the buckets b with b % shards === shard; only a power of two is a tree of them.
121
+ this.unreadable = `graph ${old.graph} was laid out by FateDB 0.1 with ${old.shards} index shards; 0.2 adopts only a power of two, so the graph can be read but not written`;
122
+ return;
123
+ }
124
+ if (old) {
125
+ const layout = initialLayout(old.partitions, old.shards, 0);
126
+ this.sql.exec("INSERT INTO root (id, graph, layout, pending, published) VALUES (1, ?, ?, NULL, ?)", old.graph, JSON.stringify(layout), old.published);
127
+ const depth = layout.shards[0]?.depth ?? 0;
128
+ if (tables.has("shards")) {
129
+ for (const r of this.sql.exec("SELECT shard, watermark, facts, buckets FROM shards").toArray()) {
130
+ this.sql.exec("INSERT INTO shard_reports (prefix, depth, watermark, facts, buckets) VALUES (?, ?, ?, ?, ?)", r.shard, depth, r.watermark, r.facts, r.buckets);
131
+ }
132
+ }
133
+ }
134
+ this.sql.exec("DROP TABLE layout");
135
+ if (tables.has("shards"))
136
+ this.sql.exec("DROP TABLE shards");
137
+ });
138
+ }
139
+ remember(graph) {
140
+ if (this.unreadable !== null)
141
+ throw new Error(this.unreadable);
142
+ if (this.graph === graph)
143
+ return;
144
+ if (this.graph !== null)
145
+ throw new Error(`root of ${this.graph} was called for ${graph}`);
146
+ this.graph = graph;
147
+ }
148
+ /**
149
+ * Stores the root's state with these changes, then takes them: what the root acts on is always
150
+ * what it stored, so a write storage refuses changes nothing a restart would undo.
151
+ */
152
+ requireGraph() {
153
+ if (this.graph === null)
154
+ throw new Error("root graph is not initialized");
155
+ return this.graph;
156
+ }
157
+ requireLayout() {
158
+ if (this.current === null)
159
+ throw new Error("root layout is not initialized");
160
+ return this.current;
161
+ }
162
+ store(changes) {
163
+ const current = changes.current ?? this.requireLayout();
164
+ const pending = changes.pending === undefined ? this.scaling.pending : changes.pending;
165
+ this.sql.exec("INSERT INTO root (id, graph, layout, pending, published) VALUES (1, ?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET graph = excluded.graph, layout = excluded.layout, pending = excluded.pending, published = excluded.published", this.graph, JSON.stringify(current), pending === null ? null : JSON.stringify(pending), this.publish.published);
166
+ this.current = current;
167
+ this.scaling.pending = pending;
168
+ return current;
169
+ }
170
+ /** The graph's layout, made on first use with the instance's initial partitions and one index shard, or the counts given. */
171
+ async layout(input) {
172
+ this.remember(input.graph);
173
+ let current = this.current;
174
+ if (current === null) {
175
+ const partitions = input.partitions ?? settings(this.env).initialPartitions;
176
+ if (!Number.isSafeInteger(partitions) || partitions < 1 || partitions > MAX_PARTITIONS)
177
+ throw new RangeError(`a graph has 1 to ${MAX_PARTITIONS} partitions`);
178
+ current = this.store({ current: initialLayout(partitions, input.shards ?? 1, Date.now()) });
179
+ }
180
+ if (this.scaling.pending !== null && this.scaling.installing === null)
181
+ this.ctx.waitUntil(this.publishGrowth().catch((error) => this.fail("grow", error)));
182
+ return current;
183
+ }
184
+ /**
185
+ * Makes the graph's layout, and an empty manifest so the graph is listed before its first write.
186
+ * An operator who knows the load to come may give it more partitions or shards to start with.
187
+ */
188
+ async create(input) {
189
+ const created = this.current === null;
190
+ const layout = await this.layout(input);
191
+ if ((await this.env.INDEX.head(manifestKey(input.graph))) === null)
192
+ await this.putManifest(layout, 0);
193
+ return { layout, created };
194
+ }
195
+ async report(input) {
196
+ this.remember(input.graph);
197
+ const layout = this.current;
198
+ if (layout === null)
199
+ throw new Error(`root of ${input.graph} was reported to before it had a layout`);
200
+ const prior = this.shards.get(input.leaf.prefix);
201
+ const seq = input.seq ?? 0;
202
+ // A late report: from before a split, or older than the last.
203
+ const late = prior !== undefined && (prior.depth > input.leaf.depth || prior.watermark > input.watermark || (prior.depth === input.leaf.depth && prior.watermark === input.watermark && prior.seq > seq));
204
+ const unchanged = prior !== undefined
205
+ && prior.depth === input.leaf.depth
206
+ && prior.watermark === input.watermark
207
+ && prior.facts === input.facts
208
+ && prior.seq === seq;
209
+ if (!late && !unchanged) {
210
+ // Persist before taking in memory so a refused SQL write never leaks unpersisted shard state into manifests.
211
+ this.sql.exec("INSERT INTO shard_reports (prefix, depth, watermark, facts, seq, buckets) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (prefix) DO UPDATE SET depth = excluded.depth, watermark = excluded.watermark, facts = excluded.facts, seq = excluded.seq, buckets = excluded.buckets", input.leaf.prefix, input.leaf.depth, input.watermark, input.facts, seq, JSON.stringify(input.buckets));
212
+ this.shards.set(input.leaf.prefix, { depth: input.leaf.depth, watermark: input.watermark, facts: input.facts, seq, buckets: input.buckets });
213
+ }
214
+ this.counters.reports++;
215
+ if (input.load !== undefined)
216
+ this.considerGrowth(input.load);
217
+ if (input.split === true)
218
+ this.considerSplit(input.leaf);
219
+ const needsPublish = !unchanged
220
+ || this.publish.manifests === 0
221
+ || (this.publish.manifestedSeq.get(input.leaf.prefix) ?? 0) < seq
222
+ || this.graphWatermark(layout) > this.publish.published;
223
+ if (needsPublish) {
224
+ if (this.publish.running !== null)
225
+ this.publish.running.reported = true;
226
+ else if (!this.publish.scheduled)
227
+ await this.schedule(Math.max(Date.now(), this.publish.lastManifestAt + MANIFEST_GAP_MS));
228
+ }
229
+ if (this.env.SPOCK_TRACE !== undefined) {
230
+ await traceSpock(this.env, input.graph, "root.report", {
231
+ shard: input.leaf.prefix,
232
+ depth: input.leaf.depth,
233
+ watermark: input.watermark,
234
+ seq,
235
+ published: this.publish.published,
236
+ scheduled: this.publish.scheduled,
237
+ });
238
+ }
239
+ return { watermark: this.publish.published, layout: this.requireLayout(), publishedSeq: this.publish.manifestedSeq.get(input.leaf.prefix) ?? 0 };
240
+ }
241
+ /**
242
+ * Sets the alarm that writes the next manifest. It counts as set from the call on, so reports
243
+ * meanwhile do not set it again, and is forgotten if storage refuses it: a report or an alarm
244
+ * retry sets it again, instead of every later report taking it as set.
245
+ */
246
+ async schedule(at) {
247
+ this.publish.scheduled = true;
248
+ try {
249
+ await this.ctx.storage.setAlarm(at);
250
+ }
251
+ catch (error) {
252
+ this.publish.scheduled = false;
253
+ throw error;
254
+ }
255
+ }
256
+ /** A Worker saw a partition refuse a call because it was overloaded. */
257
+ async overloaded(input) {
258
+ this.remember(input.graph);
259
+ const now = Date.now();
260
+ this.scaling.overloads = [...this.scaling.overloads.filter((at) => now - at < LOAD_WINDOW_MS), now];
261
+ if (this.scaling.overloads.length >= GROW_ON_OVERLOADS)
262
+ this.considerGrowth(null);
263
+ }
264
+ /**
265
+ * Starts the index shards and answers the published watermark so restarted partitions can trim.
266
+ * Publishing a manifest clears the start throttle (specs/shard-idle-wake.spock), so a write
267
+ * arriving right after a shard stops on a clean confirm tick immediately wakes it.
268
+ */
269
+ async ensureIndexing(input) {
270
+ this.remember(input.graph);
271
+ const now = Date.now();
272
+ const immediate = input.immediate === true;
273
+ const publishedSinceStart = this.publish.lastManifestAt > this.scaling.lastStartAt;
274
+ const elapsed = now - this.scaling.lastStartAt;
275
+ const due = input.force === true
276
+ ? true
277
+ : immediate
278
+ ? elapsed >= IMMEDIATE_START_EVERY_MS || publishedSinceStart
279
+ : elapsed >= START_SHARDS_EVERY_MS || publishedSinceStart;
280
+ if (this.current !== null && due) {
281
+ this.scaling.lastStartAt = now;
282
+ await this.startShards(this.current, immediate);
283
+ }
284
+ return { watermark: this.publish.published };
285
+ }
286
+ async startShards(layout, immediate = false) {
287
+ const graph = this.requireGraph();
288
+ await Promise.allSettled(layout.shards.map((leaf) => shardStub(this.env, graph, leaf.prefix).start({
289
+ graph, leaf, layout, ...(immediate ? { immediate: true } : {}),
290
+ }).catch((error) => {
291
+ this.scaling.lastStartAt = 0;
292
+ console.error(JSON.stringify({ event: "root.shard_start_failed", shard: leaf.prefix, error: String(error) }));
293
+ })));
294
+ }
295
+ /** Grows the graph to `partitions` now, as its load would. For operators and tests. */
296
+ async resize(input) {
297
+ await this.layout({ graph: input.graph });
298
+ if (!Number.isSafeInteger(input.partitions) || input.partitions > MAX_PARTITIONS)
299
+ throw new RangeError(`a graph has at most ${MAX_PARTITIONS} partitions`);
300
+ if (this.scaling.pending !== null)
301
+ await this.publishGrowth();
302
+ const current = this.requireLayout();
303
+ if (input.partitions <= partitionCount(current))
304
+ return current;
305
+ return this.grow(input.partitions);
306
+ }
307
+ /** Splits an index shard now, as its asking would. For operators and tests. */
308
+ async split(input) {
309
+ await this.layout({ graph: input.graph });
310
+ if (this.scaling.pending !== null)
311
+ await this.publishGrowth();
312
+ const current = this.requireLayout();
313
+ const leaf = current.shards.find((l) => l.prefix === input.prefix);
314
+ if (leaf === undefined)
315
+ throw new RangeError(`the graph has no index shard ${input.prefix}`);
316
+ // Its half is made from what it hands over, so it must exist: a shard that never reported may never have started.
317
+ if (!this.shards.has(leaf.prefix))
318
+ throw new RangeError(`index shard ${input.prefix} has not reported yet`);
319
+ const split = this.store({ current: withSplit(current, leaf) });
320
+ this.scaling.splitAt.set(leaf.prefix, Date.now());
321
+ if (this.env.SPOCK_TRACE !== undefined) {
322
+ await traceSpock(this.env, input.graph, "root.split", {
323
+ version: split.version,
324
+ shards: split.shards.length,
325
+ prefix: leaf.prefix,
326
+ });
327
+ }
328
+ await this.startShards(split);
329
+ return split;
330
+ }
331
+ considerGrowth(load) {
332
+ const layout = this.current;
333
+ if (layout === null || this.scaling.installing !== null || this.scaling.pending !== null)
334
+ return;
335
+ const now = Date.now();
336
+ const n = partitionCount(layout);
337
+ const rate = load === null ? null : load.calls / Math.max(1, load.windowMs / 1_000);
338
+ if (rate !== null)
339
+ this.scaling.callsPerSecond = rate;
340
+ if (now - this.scaling.lastGrewAt < GROW_EVERY_MS)
341
+ return;
342
+ const overloaded = this.scaling.overloads.filter((at) => now - at < LOAD_WINDOW_MS).length >= GROW_ON_OVERLOADS;
343
+ const target = growthTarget({ partitions: n, callsPerSecond: rate, overloaded, growAboveCalls: settings(this.env).growAboveCalls });
344
+ if (target === null)
345
+ return;
346
+ this.scaling.lastGrewAt = now;
347
+ console.info(JSON.stringify({ event: "root.grow", graph: this.graph, from: n, to: target, callsPerSecond: rate, overloads: this.scaling.overloads.length }));
348
+ this.ctx.waitUntil(this.grow(target).catch((error) => this.fail("grow", error)));
349
+ }
350
+ considerSplit(leaf) {
351
+ const layout = this.current;
352
+ if (layout === null || this.scaling.installing !== null || this.scaling.pending !== null || !isLeaf(layout, leaf) || leaf.depth >= MAX_DEPTH)
353
+ return;
354
+ const now = Date.now();
355
+ if (now - (this.scaling.splitAt.get(leaf.prefix) ?? 0) < SPLIT_EVERY_MS)
356
+ return;
357
+ this.store({ current: withSplit(layout, leaf) });
358
+ this.scaling.splitAt.set(leaf.prefix, now);
359
+ console.info(JSON.stringify({ event: "root.split", graph: this.graph, shard: leaf.prefix, depth: leaf.depth }));
360
+ }
361
+ /** Installs a layout with more partitions in partition 0, then publishes it with the epoch partition 0 chose. */
362
+ async grow(partitions) {
363
+ this.store({ pending: withEra(this.requireLayout(), partitions, Date.now()) });
364
+ return this.publishGrowth();
365
+ }
366
+ publishGrowth() {
367
+ this.scaling.installing ??= (async () => {
368
+ const next = this.scaling.pending;
369
+ if (next === null)
370
+ throw new Error("publishGrowth called without a pending layout");
371
+ const graph = this.requireGraph();
372
+ // Stamp `at` when installing/publishing, so earlierHomes covers the full token window from publish time
373
+ // and partition 0 and the root hold the exact same era record.
374
+ const attemptAt = Date.now();
375
+ const stamped = { ...next, eras: next.eras.map((era, i) => (i === next.eras.length - 1 ? { ...era, at: attemptAt } : era)) };
376
+ const { since, at } = await partitionStub(this.env, graph, 0).install({ graph, partition: 0, layout: partitionLayout(stamped) });
377
+ const eras = next.eras.map((era, i) => (i === next.eras.length - 1 ? { ...era, since, at } : era));
378
+ // A split never lands while a growth is pending, so the shards are the current layout's.
379
+ const grown = this.store({ current: { ...this.requireLayout(), version: next.version, eras }, pending: null });
380
+ this.scaling.lastGrewAt = Date.now();
381
+ if (this.env.SPOCK_TRACE !== undefined) {
382
+ await traceSpock(this.env, graph, "root.grow", {
383
+ version: grown.version,
384
+ partitions: partitionCount(grown),
385
+ shards: grown.shards.length,
386
+ since,
387
+ at,
388
+ });
389
+ }
390
+ this.ctx.waitUntil(this.startShards(grown).catch(() => undefined));
391
+ return grown;
392
+ })().finally(() => (this.scaling.installing = null));
393
+ return this.scaling.installing;
394
+ }
395
+ fail(what, error) {
396
+ this.errors.push(`${new Date().toISOString()} ${what}: ${String(error)}`);
397
+ if (this.errors.length > 20)
398
+ this.errors.shift();
399
+ console.error(JSON.stringify({ event: `root.${what}_failed`, graph: this.graph, error: String(error) }));
400
+ }
401
+ /** The lowest watermark of the layout's shards, once each has reported; until then, what was published. */
402
+ graphWatermark(layout) {
403
+ let lowest = Infinity;
404
+ for (const leaf of layout.shards) {
405
+ const state = this.shards.get(leaf.prefix);
406
+ if (state === undefined)
407
+ return this.publish.published;
408
+ lowest = Math.min(lowest, state.watermark);
409
+ }
410
+ return Math.max(this.publish.published, lowest === Infinity ? 0 : lowest);
411
+ }
412
+ /**
413
+ * Each bucket's segments, from the shard that owns it, or from the deepest ancestor that still
414
+ * owns it when the new half has never reported yet. Once the owning shard has reported, its
415
+ * bucket list is authoritative (an omitted bucket was compacted to empty and must not fall back).
416
+ */
417
+ manifestBuckets(layout) {
418
+ const buckets = {};
419
+ for (let b = 0; b < BUCKETS; b++) {
420
+ const owner = ownerOf(layout, b);
421
+ const ownerState = this.shards.get(owner.prefix);
422
+ let refs = ownerState?.buckets[b];
423
+ if (ownerState === undefined) {
424
+ let bestDepth = -1;
425
+ for (const [prefix, state] of this.shards) {
426
+ if (state.depth <= bestDepth || !owns({ depth: state.depth, prefix }, b))
427
+ continue;
428
+ const held = state.buckets[b];
429
+ if (held !== undefined) {
430
+ bestDepth = state.depth;
431
+ refs = held;
432
+ }
433
+ }
434
+ }
435
+ if (refs !== undefined)
436
+ buckets[b] = refs;
437
+ }
438
+ return buckets;
439
+ }
440
+ async putManifest(layout, watermark) {
441
+ const included = new Map();
442
+ for (const leaf of layout.shards) {
443
+ const state = this.shards.get(leaf.prefix);
444
+ if (state !== undefined)
445
+ included.set(leaf.prefix, state.seq);
446
+ }
447
+ const graph = this.requireGraph();
448
+ const manifest = {
449
+ graph, partitions: partitionCount(layout), shards: layout.shards.length, watermark,
450
+ buckets: this.manifestBuckets(layout), updatedAt: Date.now(),
451
+ };
452
+ await this.env.INDEX.put(manifestKey(graph), JSON.stringify(manifest), { httpMetadata: { contentType: "application/json" } });
453
+ for (const [prefix, seq] of included) {
454
+ this.publish.manifestedSeq.set(prefix, Math.max(this.publish.manifestedSeq.get(prefix) ?? 0, seq));
455
+ }
456
+ }
457
+ /**
458
+ * Syncs `published` from R2 once after boot or a failed SQL update so a restart or split never
459
+ * overwrites R2's manifest with a lower watermark.
460
+ */
461
+ async syncPublishedFromR2() {
462
+ if (this.publish.r2Synced || this.graph === null)
463
+ return;
464
+ const object = await this.env.INDEX.get(manifestKey(this.graph));
465
+ if (object !== null) {
466
+ const existing = await object.json();
467
+ const wm = typeof existing === "object" && existing !== null && "watermark" in existing ? existing.watermark : undefined;
468
+ if (typeof wm === "number" && Number.isSafeInteger(wm) && wm > this.publish.published) {
469
+ this.sql.exec("UPDATE root SET published = ? WHERE id = 1", wm);
470
+ this.publish.published = wm;
471
+ }
472
+ }
473
+ this.publish.r2Synced = true;
474
+ }
475
+ async alarm() {
476
+ // Writes what has been reported so far, then sets the next alarm if a shard reported meanwhile.
477
+ this.publish.scheduled = false;
478
+ const layout = this.current;
479
+ if (layout === null || this.graph === null)
480
+ return;
481
+ if (this.scaling.pending !== null && this.scaling.installing === null)
482
+ this.ctx.waitUntil(this.publishGrowth().catch((error) => this.fail("grow", error)));
483
+ const started = Date.now();
484
+ this.counters.alarms++;
485
+ const run = { reported: false };
486
+ this.publish.running = run;
487
+ let putDone = false;
488
+ try {
489
+ await this.syncPublishedFromR2();
490
+ const watermark = this.graphWatermark(layout);
491
+ await this.putManifest(layout, watermark);
492
+ putDone = true;
493
+ this.publish.lastManifestAt = Date.now();
494
+ this.publish.manifests++;
495
+ if (watermark > this.publish.published) {
496
+ this.sql.exec("UPDATE root SET published = ? WHERE id = 1", watermark);
497
+ this.publish.published = watermark;
498
+ }
499
+ if (this.env.SPOCK_TRACE !== undefined && this.graph !== null) {
500
+ await traceSpock(this.env, this.graph, "root.manifest", {
501
+ watermark: this.publish.published,
502
+ layoutVersion: layout.version,
503
+ shards: layout.shards.length,
504
+ manifests: this.publish.manifests,
505
+ });
506
+ }
507
+ }
508
+ catch (error) {
509
+ if (putDone)
510
+ this.publish.r2Synced = false;
511
+ this.fail("manifest", error);
512
+ await this.schedule(Date.now() + MANIFEST_GAP_MS);
513
+ return;
514
+ }
515
+ finally {
516
+ this.publish.running = null;
517
+ this.counters.lastAlarmMs = Date.now() - started;
518
+ this.counters.maxAlarmMs = Math.max(this.counters.maxAlarmMs, this.counters.lastAlarmMs);
519
+ }
520
+ // Wake every configured projection for this graph; retry via the root alarm if any wake fails.
521
+ const projectionRetry = await this.notifyProjections(layout);
522
+ // R2 takes one write a second to a key, so the next manifest waits that long after this one.
523
+ if ((run.reported || projectionRetry) && !this.publish.scheduled) {
524
+ await this.schedule(Math.max(Date.now() + 100, this.publish.lastManifestAt + MANIFEST_GAP_MS));
525
+ }
526
+ this.notifyPartitions(layout);
527
+ }
528
+ /**
529
+ * Wakes every configured projection matching this graph once the manifest passes what it was last
530
+ * woken for. Returns whether any wake failed so the root schedules a retry alarm (RFD0016,
531
+ * specs/projection-delivery.spock).
532
+ */
533
+ async notifyProjections(layout) {
534
+ if (this.env.PROJECTIONS === undefined || this.publish.published === 0 || this.graph === null)
535
+ return false;
536
+ const graph = this.graph;
537
+ const matching = readProjectionsConfig(this.env.PROJECTIONS_CONFIG).filter((c) => projectionMatchesGraph(c, graph));
538
+ if (matching.length === 0)
539
+ return false;
540
+ const w = this.publish.published;
541
+ const partitions = partitionCount(layout);
542
+ let anyFailed = false;
543
+ await Promise.all(matching.map(async (config) => {
544
+ if ((this.publish.projectionNotified.get(config.name) ?? 0) >= w)
545
+ return;
546
+ try {
547
+ await projectionStub(this.env, graph, config.name).wake({ graph, projection: config.name, watermark: w, partitions });
548
+ this.publish.projectionNotified.set(config.name, Math.max(this.publish.projectionNotified.get(config.name) ?? 0, w));
549
+ if (this.env.SPOCK_TRACE !== undefined) {
550
+ await traceSpock(this.env, graph, "root.wake_projection", { projection: config.name, watermark: w, ok: true });
551
+ }
552
+ }
553
+ catch (error) {
554
+ anyFailed = true;
555
+ if (this.env.SPOCK_TRACE !== undefined) {
556
+ await traceSpock(this.env, graph, "root.wake_projection", { projection: config.name, watermark: w, ok: false });
557
+ }
558
+ this.fail(`projection:${config.name}`, error);
559
+ }
560
+ }));
561
+ return anyFailed;
562
+ }
563
+ /** Partitions only need the watermark to trim, so a slow partition must not hold up the next manifest. */
564
+ notifyPartitions(layout) {
565
+ if (this.publish.published <= this.publish.notified || Date.now() - this.publish.lastNotifyAt < NOTIFY_GAP_MS)
566
+ return;
567
+ if (this.publish.notifying) {
568
+ this.counters.skippedNotifies++;
569
+ return;
570
+ }
571
+ const w = this.publish.published, graph = this.requireGraph(), n = partitionCount(layout);
572
+ this.publish.notifying = true;
573
+ this.publish.lastNotifyAt = Date.now();
574
+ const t0 = Date.now();
575
+ this.ctx.waitUntil((async () => {
576
+ for (let from = 0; from < n; from += NOTIFY_BATCH) {
577
+ await Promise.allSettled(Array.from({ length: Math.min(NOTIFY_BATCH, n - from) }, (_, i) => partitionStub(this.env, graph, from + i).watermark({ watermark: w })));
578
+ }
579
+ this.publish.notified = Math.max(this.publish.notified, w);
580
+ this.counters.notifyRounds++;
581
+ this.counters.lastNotifyMs = Date.now() - t0;
582
+ })().finally(() => (this.publish.notifying = false)));
583
+ }
584
+ async status() {
585
+ const l = this.current;
586
+ return {
587
+ graph: this.graph, layout: l, partitions: l === null ? 0 : partitionCount(l), shards: l?.shards.length ?? 0, watermark: this.publish.published,
588
+ stalenessMs: this.publish.published > 0 ? Date.now() - epochEndMs(this.publish.published) : 0,
589
+ shardWatermarks: Object.fromEntries((l?.shards ?? []).map((leaf) => [String(leaf.prefix), this.shards.get(leaf.prefix)?.watermark ?? 0])),
590
+ indexed: { facts: (l?.shards ?? []).reduce((n, leaf) => n + (this.shards.get(leaf.prefix)?.facts ?? 0), 0) },
591
+ manifests: this.publish.manifests, lastManifestAt: this.publish.lastManifestAt,
592
+ growth: { installing: this.scaling.installing !== null || this.scaling.pending !== null, lastGrewAt: this.scaling.lastGrewAt, callsPerSecond: this.scaling.callsPerSecond, overloads: this.scaling.overloads.length },
593
+ counters: { ...this.counters }, errors: this.errors,
594
+ };
595
+ }
596
+ }