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,816 @@
1
+ // One partition of a graph: a short log of whole transactions (RFD0008, "Partitions").
2
+ //
3
+ // A write is stamped with a key and stored in one SQLite row with the other calls that arrived
4
+ // while the previous commit was in flight (group commit). The partition reads nothing to answer a
5
+ // write: client request tokens are looked up in memory, in a map rebuilt from the rows it still
6
+ // holds when it starts. Once the watermark has passed a row and the token window has too, the
7
+ // partition writes it to the graph's log in R2 (log.ts), and only then deletes it.
8
+ //
9
+ // While it holds rows the index has not reached, a partition checks every INDEX_CHECK_MS that the
10
+ // index shards run, and has the root start them: a shard stops when idle and may fail, and with no
11
+ // new writes nothing else would start it again.
12
+ //
13
+ // A graph grows by adding partitions (RFD0011, specs/growing-partitions.ts). Every call that may be
14
+ // a partition's first carries the caller's layout, so a partition the layout added knows the epoch
15
+ // it starts at before it stamps or closes anything. A write with a client request token goes to the
16
+ // token's home; a home that the token moved to within the token window claims it from its earlier
17
+ // homes first, and a partition that knows a layout refuses tokens whose home it no longer is. Partition 0
18
+ // holds the layout before it is published, and caps the covered epoch of a shard that reads an
19
+ // older one.
20
+ import { DurableObject } from "cloudflare:workers";
21
+ import { newTransactionId } from "../domain/identifiers.js";
22
+ import { partitionStub, rootStub, settings, traceSpock, } from "./environment.js";
23
+ import { BUCKETS, bucketOf } from "./facts.js";
24
+ import { Histogram } from "../domain/histogram.js";
25
+ import { epochOf, hash32, stampTs, wallEpoch } from "./keys.js";
26
+ import { capFor, earlierHomes, floorOf, homeOf, newer, partitionCount } from "./layout.js";
27
+ import { MAX_CHUNK_BYTES, writeLogChunk } from "./log.js";
28
+ const MAX_ROW_BYTES = 1_500_000; // under SQLite's 2 MB per value
29
+ const TRIM_EVERY_MS = 10_000;
30
+ /** Coalesce small indexed log chunks up to this size/count or age backstop before writing an R2 archive object. */
31
+ const MIN_ARCHIVE_BYTES = 1 * 2 ** 20;
32
+ const MIN_ARCHIVE_ROWS = 128;
33
+ const ARCHIVE_COALESCE_MS = 5 * 60_000;
34
+ const START_INDEXER_EVERY_MS = 5_000;
35
+ const IMMEDIATE_INDEXER_EVERY_MS = 1_000;
36
+ /** Unindexed fact/byte thresholds that trigger an immediate flush even under lazy flushMs (e.g. 60–300 s). */
37
+ const EARLY_FLUSH_FACTS = 500;
38
+ const EARLY_FLUSH_BYTES = 256 * 1024;
39
+ /** How far back the calls a partition reports for its graph's growth reach. */
40
+ const LOAD_WINDOW_MS = 5_000;
41
+ /** Clocks of the root and the partitions differ a little, and Workers cache layouts for 10 s: an era that ended this much past the token window is still claimed from. */
42
+ const CLOCK_SLACK_MS = 45_000;
43
+ /** Durable Objects in one isolate share its thread; partitions report this to show how they were packed. */
44
+ let isolate;
45
+ // Random values are not allowed at global scope, so the id is made on first use, inside a handler.
46
+ const isolateId = () => (isolate ??= crypto.randomUUID().slice(0, 8));
47
+ // Recent rows, parsed: every index shard reads them each second. Counted in facts, since one
48
+ // transaction holds up to 1,000 of them and the object has 128 MB.
49
+ const PARSED_CACHE_FACTS = 50_000;
50
+ function isPartitionLayout(v) {
51
+ return typeof v === "object" && v !== null && "version" in v && "eras" in v && Array.isArray(v.eras);
52
+ }
53
+ function parsePartitionLayout(raw) {
54
+ const parsed = JSON.parse(raw);
55
+ if (!isPartitionLayout(parsed))
56
+ throw new Error("stored partition layout is invalid");
57
+ return parsed;
58
+ }
59
+ function isTokenEntryArray(v) {
60
+ return Array.isArray(v);
61
+ }
62
+ function parseTokenEntries(raw) {
63
+ const parsed = JSON.parse(raw);
64
+ if (!isTokenEntryArray(parsed))
65
+ throw new Error("stored partition tokens are invalid");
66
+ return parsed;
67
+ }
68
+ function isStoredTxArray(v) {
69
+ return Array.isArray(v);
70
+ }
71
+ function parseStoredTxs(raw) {
72
+ const parsed = JSON.parse(raw);
73
+ if (!isStoredTxArray(parsed))
74
+ throw new Error("stored partition batch is invalid");
75
+ return parsed;
76
+ }
77
+ export class PartitionDO extends DurableObject {
78
+ sql = this.ctx.storage.sql;
79
+ rows = [];
80
+ known = null;
81
+ lastIndexerStart = 0;
82
+ lastImmediateStart = 0;
83
+ state = {
84
+ partition: -1,
85
+ graph: null,
86
+ lastTs: 0,
87
+ nextOffset: 0,
88
+ closed: 0,
89
+ floor: 0,
90
+ indexed: 0,
91
+ unindexedFacts: 0,
92
+ unindexedBytes: 0,
93
+ archived: 0,
94
+ boots: 0,
95
+ parsed: new Map(),
96
+ parsedFacts: 0,
97
+ colo: null,
98
+ coloAsked: false,
99
+ };
100
+ work = {
101
+ tokens: new Map(),
102
+ claimed: new Map(),
103
+ inFlightTokens: new Map(),
104
+ calls: new Map(),
105
+ pending: [],
106
+ flushing: false,
107
+ lingerTimer: null,
108
+ trimming: null,
109
+ lastTrim: 0,
110
+ checkScheduled: false,
111
+ };
112
+ service = new Histogram();
113
+ counters = { commits: 0, txs: 0, replays: 0, conflicts: 0, maxBatch: 0, startedAt: Date.now() };
114
+ constructor(ctx, env) {
115
+ super(ctx, env);
116
+ void ctx.blockConcurrencyWhile(async () => this.load());
117
+ }
118
+ load() {
119
+ // AUTOINCREMENT: a row number is never reused, even once every row has been deleted, since the
120
+ // graph's log in R2 names its chunks by them.
121
+ this.sql.exec(`CREATE TABLE IF NOT EXISTS log (
122
+ seq INTEGER PRIMARY KEY AUTOINCREMENT, epoch_max INTEGER NOT NULL, ts_max INTEGER NOT NULL, offset_max INTEGER NOT NULL,
123
+ created_at INTEGER NOT NULL, tokens TEXT NOT NULL, batch TEXT NOT NULL)`);
124
+ this.sql.exec("CREATE TABLE IF NOT EXISTS state (name TEXT PRIMARY KEY, value INTEGER NOT NULL)");
125
+ this.sql.exec("CREATE TABLE IF NOT EXISTS graph (id INTEGER PRIMARY KEY CHECK (id = 1), name TEXT NOT NULL)");
126
+ this.sql.exec("CREATE TABLE IF NOT EXISTS layout (id INTEGER PRIMARY KEY CHECK (id = 1), layout TEXT NOT NULL)");
127
+ this.state.graph = this.sql.exec("SELECT name FROM graph").toArray()[0]?.name ?? null;
128
+ const layout = this.sql.exec("SELECT layout FROM layout").toArray()[0];
129
+ this.known = layout === undefined ? null : parsePartitionLayout(layout.layout);
130
+ for (const row of this.sql.exec("SELECT name, value FROM state")) {
131
+ if (row.name === "closed")
132
+ this.state.closed = row.value;
133
+ if (row.name === "floor")
134
+ this.state.floor = row.value;
135
+ if (row.name === "partition")
136
+ this.state.partition = row.value;
137
+ if (row.name === "boots")
138
+ this.state.boots = row.value;
139
+ if (row.name === "archived")
140
+ this.state.archived = row.value;
141
+ }
142
+ this.state.boots++;
143
+ // Rebuild the token map from the rows' small `tokens` column; `batch` is not read.
144
+ for (const row of this.sql.exec("SELECT seq, epoch_max, ts_max, offset_max, created_at, tokens, length(batch) AS bytes FROM log ORDER BY seq")) {
145
+ // The partition wrote these rows itself, so their ids are its own TransactionIds.
146
+ const entries = parseTokenEntries(row.tokens);
147
+ for (const entry of entries)
148
+ this.rememberToken(entry);
149
+ this.rows.push({ seq: row.seq, epochMax: row.epoch_max, createdAt: row.created_at, bytes: row.bytes, tokens: entries.map((e) => [e[0], e[1]]) });
150
+ this.state.lastTs = Math.max(this.state.lastTs, row.ts_max);
151
+ this.state.nextOffset = Math.max(this.state.nextOffset, row.offset_max + 1);
152
+ }
153
+ }
154
+ remember(partition) {
155
+ if (this.state.partition === partition)
156
+ return;
157
+ if (this.state.partition !== -1)
158
+ throw new Error(`partition ${this.state.partition} was called as ${partition}`);
159
+ this.setState("partition", partition);
160
+ this.state.partition = partition;
161
+ }
162
+ rememberGraph(graph) {
163
+ if (this.state.graph === graph)
164
+ return;
165
+ if (this.state.graph !== null)
166
+ throw new Error(`partition of ${this.state.graph} was called for ${graph}`);
167
+ this.sql.exec("INSERT INTO graph (id, name) VALUES (1, ?)", graph);
168
+ this.state.graph = graph;
169
+ }
170
+ /**
171
+ * Takes a newer layout, and keeps it before answering: a partition that knows a layout refuses
172
+ * tokens whose home it is not (rule claimsFence). A partition the layout added closes the epochs
173
+ * before its era (rule newPartitionsStartAtTheirEpoch).
174
+ */
175
+ learn(layout) {
176
+ const next = this.known === null ? layout : newer(this.known, layout);
177
+ if (next === this.known)
178
+ return;
179
+ const closed = Math.max(this.state.closed, floorOf(next, this.state.partition) - 1);
180
+ // Stored together, and taken only once stored: partition 0 answers a repeated install from the
181
+ // layout it knows, so a layout known but never stored would answer an era a restart forgets.
182
+ this.ctx.storage.transactionSync(() => {
183
+ this.sql.exec("INSERT INTO layout (id, layout) VALUES (1, ?) ON CONFLICT (id) DO UPDATE SET layout = excluded.layout", JSON.stringify(next));
184
+ if (closed > this.state.closed)
185
+ this.setState("closed", closed);
186
+ });
187
+ this.known = next;
188
+ this.state.closed = closed;
189
+ }
190
+ /** Index shards keep themselves scheduled; partitions ask the root to start them and learn its published watermark. */
191
+ ensureIndexer(graph, options = {}) {
192
+ const now = Date.now();
193
+ const immediate = options.immediate === true;
194
+ if (immediate) {
195
+ if (now - this.lastImmediateStart < IMMEDIATE_INDEXER_EVERY_MS)
196
+ return Promise.resolve();
197
+ this.lastImmediateStart = now;
198
+ this.lastIndexerStart = now;
199
+ }
200
+ else if (!options.force && now - this.lastIndexerStart < START_INDEXER_EVERY_MS) {
201
+ return Promise.resolve();
202
+ }
203
+ else {
204
+ this.lastIndexerStart = now;
205
+ }
206
+ return rootStub(this.env, graph).ensureIndexing({
207
+ graph,
208
+ ...(immediate ? { immediate: true } : {}),
209
+ ...(options.forceRoot ? { force: true } : {}),
210
+ }).then((answer) => {
211
+ if (answer && typeof answer.watermark === "number")
212
+ this.noteIndexed(answer.watermark);
213
+ }).catch((error) => {
214
+ this.lastIndexerStart = 0;
215
+ if (immediate)
216
+ this.lastImmediateStart = 0;
217
+ console.error(JSON.stringify({ event: "partition.indexing_start_failed", partition: this.state.partition, error: String(error) }));
218
+ });
219
+ }
220
+ noteIndexed(watermark) {
221
+ if (watermark <= this.state.indexed)
222
+ return;
223
+ this.state.indexed = watermark;
224
+ const lastRow = this.rows[this.rows.length - 1];
225
+ if (lastRow === undefined || lastRow.epochMax <= this.state.indexed) {
226
+ this.state.unindexedFacts = 0;
227
+ this.state.unindexedBytes = 0;
228
+ }
229
+ }
230
+ countCall(now) {
231
+ const second = Math.floor(now / 1_000);
232
+ this.work.calls.set(second, (this.work.calls.get(second) ?? 0) + 1);
233
+ if (this.work.calls.size > LOAD_WINDOW_MS / 1_000 + 1) {
234
+ for (const at of this.work.calls.keys())
235
+ if (at <= second - LOAD_WINDOW_MS / 1_000)
236
+ this.work.calls.delete(at);
237
+ }
238
+ }
239
+ callsIn(now) {
240
+ const second = Math.floor(now / 1_000);
241
+ let n = 0;
242
+ for (const [at, count] of this.work.calls)
243
+ if (at > second - LOAD_WINDOW_MS / 1_000)
244
+ n += count;
245
+ return n;
246
+ }
247
+ async scheduleCheck() {
248
+ if (this.work.checkScheduled)
249
+ return;
250
+ this.work.checkScheduled = true;
251
+ try {
252
+ await this.ctx.storage.setAlarm(Date.now() + settings(this.env).indexCheckMs);
253
+ }
254
+ catch (error) {
255
+ this.work.checkScheduled = false;
256
+ throw error;
257
+ }
258
+ }
259
+ /** The index check: starts the shards if the index has not reached every row held, trims, and stays set while rows are held. */
260
+ async alarm() {
261
+ this.work.checkScheduled = false;
262
+ const lastRow = this.rows[this.rows.length - 1];
263
+ if (this.state.graph === null || lastRow === undefined)
264
+ return;
265
+ if (lastRow.epochMax > this.state.indexed) {
266
+ this.lastIndexerStart = 0;
267
+ await this.ensureIndexer(this.state.graph, { force: true, forceRoot: true });
268
+ }
269
+ try {
270
+ await this.trim(Date.now());
271
+ }
272
+ catch (error) {
273
+ // The rows stay until a later trim archives them; the check must stay set to try again.
274
+ console.error(JSON.stringify({ event: "partition.trim_failed", partition: this.state.partition, error: String(error) }));
275
+ }
276
+ if (this.rows.length > 0)
277
+ await this.scheduleCheck();
278
+ if (this.env.SPOCK_TRACE !== undefined) {
279
+ await traceSpock(this.env, this.state.graph, "partition.alarm", {
280
+ partition: this.state.partition,
281
+ hasRows: this.rows.length > 0,
282
+ indexed: this.state.indexed,
283
+ alarmSet: this.work.checkScheduled,
284
+ });
285
+ }
286
+ }
287
+ setState(name, value) {
288
+ this.sql.exec("INSERT INTO state (name, value) VALUES (?, ?) ON CONFLICT (name) DO UPDATE SET value = excluded.value", name, value);
289
+ }
290
+ async append(input) {
291
+ this.remember(input.partition);
292
+ this.rememberGraph(input.graph);
293
+ this.learn(input.layout);
294
+ const lastRow = this.rows[this.rows.length - 1];
295
+ const wasIdle = lastRow === undefined || lastRow.epochMax <= this.state.indexed;
296
+ this.ctx.waitUntil(this.ensureIndexer(input.graph, { force: wasIdle }));
297
+ this.ctx.waitUntil(this.scheduleCheck().catch(() => undefined));
298
+ if (!this.state.coloAsked) {
299
+ this.state.coloAsked = true;
300
+ void fetch("https://cloudflare.com/cdn-cgi/trace", { signal: AbortSignal.timeout(3_000) }).then((r) => r.text()).then((t) => (this.state.colo = /^colo=(\w+)$/m.exec(t)?.[1] ?? null)).catch(() => undefined);
301
+ }
302
+ const now = Date.now();
303
+ this.countCall(now);
304
+ if (input.tokenHash === null)
305
+ return this.enqueue(input, now);
306
+ const hash = input.tokenHash;
307
+ const prior = this.work.tokens.get(hash) ?? this.work.claimed.get(hash)?.record;
308
+ if (prior)
309
+ return this.replay(prior, input);
310
+ const inFlight = this.work.inFlightTokens.get(hash);
311
+ if (inFlight) {
312
+ const first = await inFlight;
313
+ const record = this.work.tokens.get(hash) ?? this.work.claimed.get(hash)?.record;
314
+ if (first.kind === "conflict" || first.kind === "moved" || !record)
315
+ return first;
316
+ return this.replay(record, input);
317
+ }
318
+ const layout = this.known ?? input.layout;
319
+ const seed = hash32(hash);
320
+ if (homeOf(seed, partitionCount(layout)) !== this.state.partition)
321
+ return { kind: "moved", layout };
322
+ const earlier = earlierHomes(layout, seed, now, settings(this.env).tokenWindowMs + CLOCK_SLACK_MS);
323
+ const result = earlier.length === 0 ? this.enqueue(input, now) : this.claimThenStore(input, earlier, now);
324
+ this.work.inFlightTokens.set(hash, result);
325
+ void result.finally(() => this.work.inFlightTokens.delete(hash)).catch(() => { });
326
+ return result;
327
+ }
328
+ /** Stores the write with the next group commit, briefly coalescing under sustained load to cut SQLite row writes. */
329
+ enqueue(input, arrived) {
330
+ return new Promise((resolve, reject) => {
331
+ this.work.pending.push({ input, resolve: (r) => {
332
+ this.service.record(Date.now() - arrived);
333
+ resolve(r);
334
+ }, reject });
335
+ if (this.work.flushing)
336
+ return;
337
+ const lingerMs = settings(this.env).commitLingerMs;
338
+ // Engage adaptive linger above 10 writes/s (50 calls in LOAD_WINDOW_MS = 5 s), leaving low-rate writes at 0 ms.
339
+ const shouldLinger = lingerMs > 0 && this.work.pending.length < 64 && this.callsIn(arrived) >= 50;
340
+ if (shouldLinger) {
341
+ if (this.work.lingerTimer === null) {
342
+ this.work.lingerTimer = setTimeout(() => {
343
+ this.work.lingerTimer = null;
344
+ if (!this.work.flushing && this.work.pending.length > 0)
345
+ void this.flush();
346
+ }, lingerMs);
347
+ }
348
+ return;
349
+ }
350
+ if (this.work.lingerTimer !== null) {
351
+ clearTimeout(this.work.lingerTimer);
352
+ this.work.lingerTimer = null;
353
+ }
354
+ void this.flush();
355
+ });
356
+ }
357
+ /**
358
+ * The token moved here within the token window: asks its earlier homes first (rule
359
+ * movedTokensAreClaimed). One that holds it answers the write; otherwise none of them will store
360
+ * it from now on, and it is stored here.
361
+ */
362
+ async claimThenStore(input, earlier, arrived) {
363
+ const hash = input.tokenHash;
364
+ if (hash === null)
365
+ return this.enqueue(input, arrived);
366
+ const currentLayout = this.known ?? input.layout;
367
+ const answers = await Promise.all(earlier.map((p) => partitionStub(this.env, input.graph, p).claim({ graph: input.graph, partition: p, tokenHash: hash, layout: currentLayout })));
368
+ const found = answers.find((a) => a.record !== null)?.record;
369
+ if (found) {
370
+ this.work.claimed.set(hash, { record: found, at: Date.now() });
371
+ return this.replay(found, input);
372
+ }
373
+ // If this partition learned a newer layout while awaiting claims, defer to the new home.
374
+ const layout = this.known ?? currentLayout;
375
+ if (homeOf(hash32(hash), partitionCount(layout)) !== this.state.partition)
376
+ return { kind: "moved", layout };
377
+ return this.enqueue(input, arrived);
378
+ }
379
+ /**
380
+ * Another partition, now the token's home, asks whether this one holds it. Keeps the asker's
381
+ * layout first, so from now on this partition refuses the token (rule claimsFence), and waits for
382
+ * a write of the token it is storing.
383
+ */
384
+ async claim(input) {
385
+ this.remember(input.partition);
386
+ this.rememberGraph(input.graph);
387
+ this.learn(input.layout);
388
+ const inFlight = this.work.inFlightTokens.get(input.tokenHash);
389
+ if (inFlight)
390
+ await inFlight.catch(() => undefined);
391
+ const record = this.work.tokens.get(input.tokenHash) ?? this.work.claimed.get(input.tokenHash)?.record ?? null;
392
+ if (this.env.SPOCK_TRACE !== undefined) {
393
+ await traceSpock(this.env, input.graph, "partition.claim", {
394
+ partition: this.state.partition,
395
+ found: record !== null,
396
+ fenced: record === null,
397
+ });
398
+ }
399
+ return { record };
400
+ }
401
+ /**
402
+ * Partition 0 only: keeps a layout the root is about to publish, starting its newest era one past
403
+ * the last epoch this partition closed (rule layoutThroughPartitionZero). No shard's watermark
404
+ * is past that epoch, since every shard reads this partition on every flush. Called again with
405
+ * the same version, as a root that restarted does, it answers the epoch it chose.
406
+ */
407
+ async install(input) {
408
+ this.remember(input.partition);
409
+ this.rememberGraph(input.graph);
410
+ if (this.state.partition !== 0)
411
+ throw new Error(`partition ${this.state.partition} was asked to install a layout; only partition 0 is`);
412
+ const era = input.layout.eras[input.layout.eras.length - 1];
413
+ if (era === undefined)
414
+ throw new Error("layout has no eras");
415
+ if (this.known !== null && this.known.version >= input.layout.version) {
416
+ const held = this.known.eras.find((e) => e.version === era.version);
417
+ if (held === undefined)
418
+ throw new Error(`partition 0 knows layout ${this.known.version} and has no era of version ${era.version}`);
419
+ return { since: held.since, at: held.at };
420
+ }
421
+ const since = this.state.closed + 1;
422
+ this.learn({ version: input.layout.version, eras: input.layout.eras.map((e) => (e === era ? { ...e, since } : e)) });
423
+ if (this.env.SPOCK_TRACE !== undefined) {
424
+ await traceSpock(this.env, input.graph, "partition.install", {
425
+ version: input.layout.version,
426
+ since,
427
+ at: era.at,
428
+ });
429
+ }
430
+ return { since, at: era.at };
431
+ }
432
+ /** The answer to a write whose client request token is already stored: the first write, or a conflict. */
433
+ replay(record, input) {
434
+ if (record.payloadHash !== input.payloadHash) {
435
+ this.counters.conflicts++;
436
+ return { kind: "conflict" };
437
+ }
438
+ this.counters.replays++;
439
+ return { kind: "replayed", txId: record.txId, key: record.key, sameSession: record.session === input.session };
440
+ }
441
+ rememberToken([hash, txId, ts, partition, offset, payloadHash, session]) {
442
+ this.work.tokens.set(hash, { txId, key: { ts, partition, offset }, payloadHash, session });
443
+ }
444
+ /** Commits what is pending as one atomic SQLite transaction, waits until durable, then takes what arrived meanwhile. */
445
+ async flush() {
446
+ this.work.flushing = true;
447
+ try {
448
+ while (this.work.pending.length > 0) {
449
+ const batch = this.work.pending.splice(0, this.work.pending.length);
450
+ const now = Date.now();
451
+ let lastTs = this.state.lastTs;
452
+ let nextOffset = this.state.nextOffset;
453
+ const entries = batch.map(({ input }) => {
454
+ const ts = stampTs({ lastTs, nowMs: now, after: input.after, closedEpoch: this.state.closed });
455
+ lastTs = ts;
456
+ return { txId: newTransactionId(), key: { ts, partition: this.state.partition, offset: nextOffset++ }, session: input.session, facts: input.facts, tokenHash: input.tokenHash, payloadHash: input.payloadHash, bytes: input.bytes };
457
+ });
458
+ const inserted = [];
459
+ try {
460
+ // Commit every row of the batch together, and adopt into memory only after commit
461
+ // (specs/partition-commit.spock).
462
+ this.ctx.storage.transactionSync(() => {
463
+ for (const group of byRowSize(entries))
464
+ inserted.push(this.insertRow(group, now));
465
+ });
466
+ }
467
+ catch (error) {
468
+ for (const w of batch)
469
+ w.reject(error);
470
+ continue;
471
+ }
472
+ this.state.lastTs = lastTs;
473
+ this.state.nextOffset = nextOffset;
474
+ let addedFacts = 0;
475
+ let addedBytes = 0;
476
+ for (const row of inserted) {
477
+ this.rememberParsed(row.seq, row.batch);
478
+ this.rows.push(row.meta);
479
+ addedBytes += row.meta.bytes;
480
+ for (const tx of row.batch)
481
+ addedFacts += tx.facts.length;
482
+ for (const entry of row.tokens)
483
+ this.rememberToken(entry);
484
+ }
485
+ this.state.unindexedFacts += addedFacts;
486
+ this.state.unindexedBytes += addedBytes;
487
+ if (this.state.graph !== null && (this.state.unindexedFacts >= EARLY_FLUSH_FACTS || this.state.unindexedBytes >= EARLY_FLUSH_BYTES)) {
488
+ this.ctx.waitUntil(this.ensureIndexer(this.state.graph, { immediate: true }));
489
+ }
490
+ try {
491
+ await this.ctx.storage.sync();
492
+ }
493
+ catch (error) {
494
+ for (const w of batch)
495
+ w.reject(error);
496
+ for (const w of this.work.pending.splice(0))
497
+ w.reject(error);
498
+ // In-memory state already includes this batch; abort the DO so uncommitted state cannot survive.
499
+ this.ctx.abort("storage.sync failed");
500
+ return;
501
+ }
502
+ this.counters.commits++;
503
+ this.counters.txs += entries.length;
504
+ this.counters.maxBatch = Math.max(this.counters.maxBatch, entries.length);
505
+ batch.forEach((w, i) => {
506
+ const entry = entries[i];
507
+ if (entry !== undefined)
508
+ w.resolve({ kind: "stored", txId: entry.txId, key: entry.key });
509
+ });
510
+ }
511
+ }
512
+ finally {
513
+ this.work.flushing = false;
514
+ }
515
+ if (this.env.SPOCK_TRACE !== undefined && this.state.graph !== null) {
516
+ const last = this.rows[this.rows.length - 1];
517
+ await traceSpock(this.env, this.state.graph, "partition.commit", {
518
+ partition: this.state.partition,
519
+ rows: this.rows.length,
520
+ commits: this.counters.commits,
521
+ txs: this.counters.txs,
522
+ lastEpoch: last?.epochMax ?? 0,
523
+ lastSeq: last?.seq ?? 0,
524
+ });
525
+ }
526
+ }
527
+ insertRow(group, now) {
528
+ const last = group[group.length - 1];
529
+ if (last === undefined)
530
+ throw new Error("insertRow called with empty group");
531
+ const tokens = [];
532
+ for (const e of group) {
533
+ if (e.tokenHash !== null)
534
+ tokens.push([e.tokenHash, e.txId, e.key.ts, e.key.partition, e.key.offset, e.payloadHash, e.session]);
535
+ }
536
+ const batch = group.map(({ txId, key, session, facts }) => ({ txId, key, session, facts }));
537
+ const epochMax = epochOf(last.key.ts);
538
+ const text = JSON.stringify(batch);
539
+ const cursor = this.sql.exec("INSERT INTO log (epoch_max, ts_max, offset_max, created_at, tokens, batch) VALUES (?, ?, ?, ?, ?, ?) RETURNING seq", epochMax, last.key.ts, last.key.offset, now, JSON.stringify(tokens), text);
540
+ const seq = cursor.one().seq;
541
+ return { seq, batch, meta: { seq, epochMax, createdAt: now, bytes: text.length, tokens: tokens.map((t) => [t[0], t[1]]) }, tokens };
542
+ }
543
+ /**
544
+ * Closes the epochs before the current one and hands an index shard the facts in its buckets
545
+ * above `from`, whole epochs at a time, until it has read about `maxFacts` facts or handed about
546
+ * `maxBytes` bytes of them: a shard that falls behind catches up in steps both sides can hold,
547
+ * instead of asking for everything at once. The closed epoch is stored before it is reported (rule
548
+ * closedEpochsStayClosed), and later writes are stamped above it.
549
+ */
550
+ async handoff(input) {
551
+ this.remember(input.partition);
552
+ this.learn(input.layout);
553
+ const now = Date.now();
554
+ const lastRow = this.rows[this.rows.length - 1];
555
+ const hasUnindexed = lastRow !== undefined && lastRow.epochMax > input.from;
556
+ const layout = this.known !== null && this.known.version > input.layout.version ? this.known : null;
557
+ const shouldClose = hasUnindexed || input.forceClose !== false;
558
+ const closed = shouldClose ? Math.max(this.state.closed, wallEpoch(now) - 1) : this.state.closed;
559
+ if (shouldClose && closed > this.state.closed) {
560
+ this.setState("closed", closed);
561
+ this.state.closed = closed;
562
+ }
563
+ // A shard that reads an older layout than partition 0 knows stays below the partitions it does not read yet.
564
+ const limit = this.state.partition === 0 && this.known !== null ? Math.min(closed, capFor(this.known, input.layout.version)) : closed;
565
+ const facts = [];
566
+ let read = 0, bytes = 0, txs = 0, current = -1, covered = limit;
567
+ if (hasUnindexed) {
568
+ for (const tx of this.txsAbove(input.from)) {
569
+ const epoch = epochOf(tx.key.ts);
570
+ if (epoch > limit)
571
+ break;
572
+ if (epoch !== current) {
573
+ // Whole epochs only, and always at least one, so a shard that is behind still moves.
574
+ if (current !== -1 && (read >= input.maxFacts || bytes >= input.maxBytes)) {
575
+ covered = current;
576
+ break;
577
+ }
578
+ current = epoch;
579
+ }
580
+ txs++;
581
+ read += tx.facts.length;
582
+ tx.facts.forEach((f, index) => {
583
+ if (bucketOf(f.field, BUCKETS) % input.shards !== input.shard)
584
+ return;
585
+ facts.push([tx.key.ts, tx.key.partition, tx.key.offset, index, f.source, f.entity, f.field, f.value, f.retraction ? 1 : 0]);
586
+ bytes += factBytes(f);
587
+ });
588
+ }
589
+ }
590
+ const open = lastRow !== undefined && lastRow.epochMax > covered;
591
+ if (this.env.SPOCK_TRACE !== undefined && this.state.graph !== null) {
592
+ await traceSpock(this.env, this.state.graph, "partition.handoff", {
593
+ partition: this.state.partition,
594
+ from: input.from,
595
+ closed,
596
+ covered,
597
+ txs,
598
+ layoutVersion: layout?.version ?? input.layout.version,
599
+ open,
600
+ });
601
+ }
602
+ return { closed, covered, txs, facts, layout, calls: this.callsIn(now), windowMs: LOAD_WINDOW_MS, pending: this.work.pending.length, ...(open ? { open: true } : {}) };
603
+ }
604
+ /** The session's transactions above the reader's watermark, and how far rows are deleted. (Not `tail`: Workers reserve that name for Tail Workers.) */
605
+ async sessionTail(input) {
606
+ const txs = [];
607
+ for (const tx of this.txsAbove(input.watermark))
608
+ if (tx.session === input.session)
609
+ txs.push(tx);
610
+ return { txs, floor: this.state.floor };
611
+ }
612
+ /** Transactions in epochs above `epoch`, in key order, parsing rows only as they are reached. */
613
+ *txsAbove(epoch) {
614
+ // Stamps never go down, so rows are sorted by epochMax and transactions by key.
615
+ let lo = 0, hi = this.rows.length;
616
+ while (lo < hi) {
617
+ const mid = (lo + hi) >>> 1;
618
+ const row = this.rows[mid];
619
+ if (row !== undefined && row.epochMax > epoch)
620
+ hi = mid;
621
+ else
622
+ lo = mid + 1;
623
+ }
624
+ for (let i = lo; i < this.rows.length; i++) {
625
+ const row = this.rows[i];
626
+ if (row === undefined)
627
+ continue;
628
+ const seq = row.seq;
629
+ let batch = this.state.parsed.get(seq);
630
+ if (batch === undefined) {
631
+ batch = parseStoredTxs(this.sql.exec("SELECT batch FROM log WHERE seq = ?", seq).one().batch);
632
+ this.rememberParsed(seq, batch);
633
+ }
634
+ for (const tx of batch)
635
+ if (epochOf(tx.key.ts) > epoch)
636
+ yield tx;
637
+ }
638
+ }
639
+ rememberParsed(seq, batch) {
640
+ this.state.parsed.set(seq, batch);
641
+ this.state.parsedFacts += factCount(batch);
642
+ while (this.state.parsedFacts > PARSED_CACHE_FACTS && this.state.parsed.size > 1) {
643
+ const first = this.state.parsed.entries().next();
644
+ if (first.done)
645
+ break;
646
+ const [oldest, held] = first.value;
647
+ this.state.parsed.delete(oldest);
648
+ this.state.parsedFacts -= factCount(held);
649
+ }
650
+ }
651
+ async watermark(input) {
652
+ this.noteIndexed(input.watermark);
653
+ if (this.rows.length > 0)
654
+ this.ctx.waitUntil(this.scheduleCheck().catch(() => undefined));
655
+ const now = Date.now();
656
+ if (now - this.work.lastTrim >= TRIM_EVERY_MS) {
657
+ this.work.lastTrim = now;
658
+ // The root does not wait for the archive: a slow PUT must not hold up its next manifest.
659
+ this.ctx.waitUntil(this.trim(now).catch((error) => console.error(JSON.stringify({ event: "partition.trim_failed", partition: this.state.partition, error: String(error) }))));
660
+ }
661
+ }
662
+ /** The rows above `after`, as the graph's log reader reads them, and how far rows are archived. */
663
+ async logRows(input) {
664
+ const limit = Math.max(1, Math.min(256, Math.floor(input.limit)));
665
+ const rows = this.sql.exec("SELECT seq, batch FROM log WHERE seq > ? ORDER BY seq LIMIT ?", input.after, limit)
666
+ .toArray().map((row) => ({ seq: row.seq, txs: parseStoredTxs(row.batch) }));
667
+ return { archived: this.state.archived, rows };
668
+ }
669
+ /**
670
+ * The highest row whose transactions are all at or below `watermark`, so a backfill can anchor
671
+ * live log tailing at `watermark` without scanning earlier history.
672
+ */
673
+ async logHead(input) {
674
+ const row = this.sql.exec("SELECT seq, ts_max, offset_max FROM log WHERE epoch_max <= ? ORDER BY seq DESC LIMIT 1", input.watermark).toArray()[0];
675
+ if (row !== undefined)
676
+ return { seq: row.seq, ts: row.ts_max, offset: row.offset_max, archived: this.state.archived };
677
+ // Every row <= watermark was already archived (or none exists yet): archived rows all had epochMax <= indexed.
678
+ return { seq: this.state.archived, ts: 0, offset: 0, archived: this.state.archived };
679
+ }
680
+ /** One trim at a time: the index check and the root's watermark both start one. */
681
+ trim(now) {
682
+ this.work.trimming ??= this.archiveAndTrim(now).finally(() => (this.work.trimming = null));
683
+ return this.work.trimming;
684
+ }
685
+ /**
686
+ * Writes the rows the index holds and the token window has passed to the graph's log, in chunks
687
+ * of at most MAX_CHUNK_BYTES, then deletes them. Small chunks coalesce until MIN_ARCHIVE_BYTES,
688
+ * MIN_ARCHIVE_ROWS, or the coalesce age backstop to avoid tiny R2 Class A PUTs. A chunk starts
689
+ * after the last row archived, which is stored only once its PUT succeeded: a retry after a
690
+ * crash writes the same key again, with at least the rows it had, so chunks never overlap.
691
+ */
692
+ async archiveAndTrim(now) {
693
+ const graph = this.state.graph;
694
+ if (graph === null)
695
+ return;
696
+ const tokenWindowMs = settings(this.env).tokenWindowMs;
697
+ const cutoff = now - tokenWindowMs;
698
+ for (const [hash, held] of this.work.claimed)
699
+ if (held.at < cutoff)
700
+ this.work.claimed.delete(hash);
701
+ let n = 0;
702
+ let dueBytes = 0;
703
+ while (n < this.rows.length) {
704
+ const row = this.rows[n];
705
+ if (row === undefined || row.epochMax > this.state.indexed || row.createdAt >= cutoff)
706
+ break;
707
+ dueBytes += row.bytes;
708
+ n++;
709
+ }
710
+ if (n === 0)
711
+ return;
712
+ const oldest = this.rows[0];
713
+ // Coalesce small archive chunks in production (tokenWindowMs >= 60 s) until MIN_ARCHIVE_BYTES,
714
+ // MIN_ARCHIVE_ROWS, or an extra ARCHIVE_COALESCE_MS window passes.
715
+ const coalesceLimit = tokenWindowMs + (tokenWindowMs >= 60_000 ? ARCHIVE_COALESCE_MS : 0);
716
+ if (dueBytes < MIN_ARCHIVE_BYTES && n < MIN_ARCHIVE_ROWS && oldest !== undefined && now - oldest.createdAt < coalesceLimit) {
717
+ return;
718
+ }
719
+ const due = this.rows.slice(0, n).filter((row) => row.seq > this.state.archived);
720
+ for (let i = 0; i < due.length;) {
721
+ const firstRow = due[i];
722
+ if (firstRow === undefined)
723
+ break;
724
+ let j = i + 1, bytes = firstRow.bytes;
725
+ while (j < due.length) {
726
+ const nextRow = due[j];
727
+ if (nextRow === undefined || bytes + nextRow.bytes > MAX_CHUNK_BYTES)
728
+ break;
729
+ bytes += nextRow.bytes;
730
+ j++;
731
+ }
732
+ const lastRow = due[j - 1] ?? firstRow;
733
+ const first = firstRow.seq, last = lastRow.seq;
734
+ const batches = this.sql.exec("SELECT batch FROM log WHERE seq >= ? AND seq <= ? ORDER BY seq", first, last).toArray().map((r) => r.batch);
735
+ await writeLogChunk(this.env.INDEX, { graph, partition: this.state.partition, first, last, batches });
736
+ this.setState("archived", last);
737
+ this.state.archived = last;
738
+ i = j;
739
+ }
740
+ // The rows go with the floor that marks them deleted: a floor below deleted rows would pass a
741
+ // read whose tail lacks them as complete (rule trimmedTailsRestartReads).
742
+ const last = this.rows[n - 1];
743
+ if (last === undefined)
744
+ return;
745
+ const floor = Math.max(this.state.floor, last.epochMax);
746
+ this.ctx.storage.transactionSync(() => {
747
+ this.sql.exec("DELETE FROM log WHERE seq <= ?", last.seq);
748
+ this.setState("floor", floor);
749
+ });
750
+ const gone = this.rows.splice(0, n);
751
+ this.state.floor = floor;
752
+ // A token reused after the window maps to a newer row; keep that mapping.
753
+ for (const row of gone) {
754
+ for (const [hash, txId] of row.tokens)
755
+ if (this.work.tokens.get(hash)?.txId === txId)
756
+ this.work.tokens.delete(hash);
757
+ const held = this.state.parsed.get(row.seq);
758
+ if (held) {
759
+ this.state.parsed.delete(row.seq);
760
+ this.state.parsedFacts -= factCount(held);
761
+ }
762
+ }
763
+ if (this.env.SPOCK_TRACE !== undefined && this.state.graph !== null) {
764
+ await traceSpock(this.env, this.state.graph, "partition.trim", {
765
+ partition: this.state.partition,
766
+ archived: this.state.archived,
767
+ floor: this.state.floor,
768
+ remainingRows: this.rows.length,
769
+ });
770
+ }
771
+ }
772
+ async stats() {
773
+ return {
774
+ partition: this.state.partition, ...this.counters, rows: this.rows.length, tokens: this.work.tokens.size, closed: this.state.closed,
775
+ floor: this.state.floor, indexed: this.state.indexed, archived: this.state.archived, lastEpoch: epochOf(this.state.lastTs), pending: this.work.pending.length, boots: this.state.boots, isolate: isolateId(), colo: this.state.colo, service: this.service.toData(),
776
+ layoutVersion: this.known?.version ?? 0, calls: this.callsIn(Date.now()),
777
+ };
778
+ }
779
+ }
780
+ function byRowSize(entries) {
781
+ const groups = [];
782
+ let group = [], bytes = 0;
783
+ for (const e of entries) {
784
+ const size = e.bytes + 200;
785
+ if (group.length > 0 && bytes + size > MAX_ROW_BYTES) {
786
+ groups.push(group);
787
+ group = [];
788
+ bytes = 0;
789
+ }
790
+ group.push(e);
791
+ bytes += size;
792
+ }
793
+ if (group.length > 0)
794
+ groups.push(group);
795
+ return groups;
796
+ }
797
+ /** About how many bytes a fact takes as a WireFact in JSON: what bounds a handoff, and the shard's memory with it. */
798
+ export function factBytes(f) {
799
+ return 48 + f.source.length + f.entity.length + f.field.length + valueBytes(f.value);
800
+ }
801
+ function valueBytes(v) {
802
+ switch (v.type) {
803
+ case "null":
804
+ case "boolean": return 24;
805
+ case "bytes": return 24 + 4 * v.value.length;
806
+ case "list":
807
+ case "map": return JSON.stringify(v).length;
808
+ default: return 24 + v.value.length;
809
+ }
810
+ }
811
+ function factCount(batch) {
812
+ let n = 0;
813
+ for (const tx of batch)
814
+ n += tx.facts.length;
815
+ return n;
816
+ }