@volter/world-core 3.0.155 → 3.0.157

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 (150) hide show
  1. package/attach.cjs +2 -0
  2. package/capability-decision.cjs +6 -4
  3. package/dist/attach.cjs +2 -0
  4. package/dist/capability-decision.cjs +6 -4
  5. package/dist/generated/pack-facts.json +204 -4
  6. package/dist/inject.cjs +150 -86
  7. package/dist/network-policy.cjs +11 -1
  8. package/dist/network-policy.d.cts +1 -0
  9. package/dist/pack-facts.d.cts +3 -0
  10. package/dist/required-credential-transport.cjs +29 -0
  11. package/dist/required-credential-transport.d.cts +3 -0
  12. package/dist/src/actions.d.ts +15 -0
  13. package/dist/src/actions.js +82 -21
  14. package/dist/src/ancestry.d.ts +5 -4
  15. package/dist/src/ancestry.js +53 -28
  16. package/dist/src/blob-store.d.ts +16 -0
  17. package/dist/src/blob-store.js +76 -1
  18. package/dist/src/changeset.js +1 -1
  19. package/dist/src/clickhouse/compression.d.ts +28 -0
  20. package/dist/src/clickhouse/compression.js +281 -0
  21. package/dist/src/clickhouse/index.d.ts +1 -0
  22. package/dist/src/clickhouse/index.js +1 -0
  23. package/dist/src/derived-core.d.ts +84 -7
  24. package/dist/src/derived-core.js +336 -61
  25. package/dist/src/derived-real.js +97 -15
  26. package/dist/src/derived.d.ts +5 -0
  27. package/dist/src/derived.js +3 -0
  28. package/dist/src/executor.d.ts +7 -0
  29. package/dist/src/executor.js +15 -1
  30. package/dist/src/fork.js +1 -1
  31. package/dist/src/git/lfs.d.ts +13 -3
  32. package/dist/src/git/lfs.js +41 -9
  33. package/dist/src/grpc-wire.js +2 -1
  34. package/dist/src/h2.js +63 -10
  35. package/dist/src/head.d.ts +5 -0
  36. package/dist/src/head.js +15 -0
  37. package/dist/src/history.d.ts +1 -1
  38. package/dist/src/history.js +7 -7
  39. package/dist/src/index.d.ts +5 -1
  40. package/dist/src/index.js +6 -1
  41. package/dist/src/live/ingest.js +9 -13
  42. package/dist/src/live/rtmp.js +7 -5
  43. package/dist/src/live/segmenter.js +7 -1
  44. package/dist/src/log.d.ts +23 -3
  45. package/dist/src/log.js +160 -37
  46. package/dist/src/machines.js +5 -1
  47. package/dist/src/managed-go-programs.d.ts +55 -0
  48. package/dist/src/managed-go-programs.js +133 -0
  49. package/dist/src/managed-original-inputs.d.ts +101 -0
  50. package/dist/src/managed-original-inputs.js +125 -0
  51. package/dist/src/mongodb/client.d.ts +8 -0
  52. package/dist/src/mongodb/client.js +27 -0
  53. package/dist/src/mongodb/index.d.ts +2 -0
  54. package/dist/src/mongodb/index.js +5 -0
  55. package/dist/src/mongodb/stream.d.ts +97 -0
  56. package/dist/src/mongodb/stream.js +206 -0
  57. package/dist/src/observe.js +1 -1
  58. package/dist/src/pack-fetch.d.ts +6 -1
  59. package/dist/src/pack-fetch.js +69 -14
  60. package/dist/src/pack-paths.d.ts +2 -1
  61. package/dist/src/pack-paths.js +6 -1
  62. package/dist/src/packRegistry.d.ts +10 -14
  63. package/dist/src/packRegistry.js +2 -13
  64. package/dist/src/protocol.d.ts +13 -0
  65. package/dist/src/protocol.js +13 -0
  66. package/dist/src/redis/engine.d.ts +10 -4
  67. package/dist/src/redis/engine.js +103 -32
  68. package/dist/src/redis/member-storage.js +20 -8
  69. package/dist/src/redis/service-times.d.ts +25 -0
  70. package/dist/src/redis/service-times.js +87 -0
  71. package/dist/src/redis/stream.d.ts +2 -1
  72. package/dist/src/redis/stream.js +109 -20
  73. package/dist/src/resource-blob.d.ts +4 -0
  74. package/dist/src/resource-blob.js +8 -1
  75. package/dist/src/runtime-state.d.ts +11 -0
  76. package/dist/src/runtime-state.js +13 -0
  77. package/dist/src/runtime.d.ts +7 -5
  78. package/dist/src/runtime.js +7 -4
  79. package/dist/src/serve-http.d.ts +2 -0
  80. package/dist/src/serve-http.js +73 -6
  81. package/dist/src/serve.d.ts +10 -0
  82. package/dist/src/serve.js +43 -3
  83. package/dist/src/sockets.d.ts +4 -1
  84. package/dist/src/sockets.js +59 -6
  85. package/dist/src/storage.d.ts +2 -1
  86. package/dist/src/storage.js +6 -3
  87. package/dist/src/vendor-call.js +58 -0
  88. package/dist/src/world-boot.d.ts +1 -0
  89. package/dist/src/world-boot.js +6 -0
  90. package/dist/src/world-clock.js +6 -2
  91. package/dist/src/world-store.d.ts +122 -7
  92. package/dist/src/world-store.js +959 -103
  93. package/dist/src/xml.d.ts +30 -0
  94. package/dist/src/xml.js +74 -0
  95. package/generated/pack-facts.json +204 -4
  96. package/inject.cjs +150 -86
  97. package/network-policy.cjs +11 -1
  98. package/network-policy.d.cts +1 -0
  99. package/pack-facts.d.cts +3 -0
  100. package/package.json +27 -1
  101. package/required-credential-transport.cjs +29 -0
  102. package/required-credential-transport.d.cts +3 -0
  103. package/src/actions.ts +78 -21
  104. package/src/ancestry.ts +46 -24
  105. package/src/blob-store.ts +59 -1
  106. package/src/changeset.ts +1 -1
  107. package/src/clickhouse/compression.ts +172 -0
  108. package/src/clickhouse/index.ts +2 -0
  109. package/src/derived-core.ts +356 -61
  110. package/src/derived-real.ts +80 -14
  111. package/src/derived.ts +9 -1
  112. package/src/executor.ts +17 -3
  113. package/src/fork.ts +1 -1
  114. package/src/git/lfs.ts +40 -9
  115. package/src/grpc-wire.ts +2 -1
  116. package/src/h2.ts +46 -5
  117. package/src/head.ts +15 -0
  118. package/src/history.ts +7 -7
  119. package/src/index.ts +7 -1
  120. package/src/live/ingest.ts +7 -3
  121. package/src/live/rtmp.ts +7 -5
  122. package/src/live/segmenter.ts +7 -1
  123. package/src/log.ts +147 -32
  124. package/src/machines.ts +5 -1
  125. package/src/managed-go-programs.ts +146 -0
  126. package/src/managed-original-inputs.ts +163 -0
  127. package/src/mongodb/client.ts +27 -0
  128. package/src/mongodb/index.ts +5 -0
  129. package/src/mongodb/stream.ts +223 -0
  130. package/src/observe.ts +1 -1
  131. package/src/pack-fetch.ts +66 -16
  132. package/src/pack-paths.ts +5 -1
  133. package/src/packRegistry.ts +3 -15
  134. package/src/protocol.ts +13 -0
  135. package/src/redis/engine.ts +100 -57
  136. package/src/redis/member-storage.ts +17 -9
  137. package/src/redis/service-times.ts +81 -0
  138. package/src/redis/stream.ts +66 -14
  139. package/src/resource-blob.ts +9 -1
  140. package/src/runtime-state.ts +14 -0
  141. package/src/runtime.ts +10 -3
  142. package/src/serve-http.ts +65 -6
  143. package/src/serve.ts +45 -3
  144. package/src/sockets.ts +39 -8
  145. package/src/storage.ts +5 -3
  146. package/src/vendor-call.ts +54 -0
  147. package/src/world-boot.ts +6 -0
  148. package/src/world-clock.ts +6 -2
  149. package/src/world-store.ts +768 -91
  150. package/src/xml.ts +71 -0
@@ -4,7 +4,7 @@ import { createHash, randomUUID } from 'node:crypto';
4
4
  import { volterHome } from "./volter-home.js";
5
5
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
6
6
  import { stateDirName } from "./storage.js";
7
- import { getActiveWorldStore } from "./world-store.js";
7
+ import { getActiveWorldStore, storageLockScope, withStorageLockOperation } from "./world-store.js";
8
8
  let entered;
9
9
  export const canonicalStatePath = (path) => getActiveWorldStore().canonicalPath?.(path) ?? resolve(path);
10
10
  const metaPath = (dir) => join(dir, 'ancestry.json');
@@ -14,7 +14,8 @@ const inside = (base, path) => { const rel = relative(canonicalStatePath(base),
14
14
  * bookkeeping (generations, pins, branch pointers, removal receipts) and the not-being-removed check: every World
15
15
  * sharing the VOLTER_HOME waits on it, so no append, fold or caller's critical section runs inside it, and no state lock
16
16
  * is taken inside it (`withStateLock` takes its lock first). */
17
- export function withAncestryLock(fn) {
17
+ export function withAncestryLock(fn, options = {}) {
18
+ const scope = storageLockScope(options);
18
19
  const store = getActiveWorldStore();
19
20
  const active = entered ??= new WeakSet();
20
21
  if (active.has(store))
@@ -23,13 +24,13 @@ export function withAncestryLock(fn) {
23
24
  return store.withLock(path, () => {
24
25
  active.add(store);
25
26
  try {
26
- recoverRemovals();
27
+ recoverRemovals(path);
27
28
  return fn();
28
29
  }
29
30
  finally {
30
31
  active.delete(store);
31
32
  }
32
- }, { retainLiveOwner: true });
33
+ }, { ...scope, retainLiveOwner: true });
33
34
  }
34
35
  /** The state locks this process holds, per store: taken again inside one, a lock is already ours. */
35
36
  let heldLocks;
@@ -39,15 +40,27 @@ const heldBy = (store) => { const map = heldLocks ??= new WeakMap(); let set = m
39
40
  } return set; };
40
41
  /** Run `fn` holding the cross-process lock at `lockPath`, a lock of the directory it sits in: taken first, then the
41
42
  * coordinator only to check that the directory is not being removed. Re-entrant within a process. */
42
- export function withStateLock(lockPath, fn) {
43
+ export function withStateLock(lockPath, fn, options = {}) {
44
+ const scope = storageLockScope(options);
43
45
  const store = getActiveWorldStore();
44
46
  const held = heldBy(store);
45
47
  if (held.has(lockPath))
46
48
  return fn();
47
49
  if (entered?.has(store))
48
50
  throw new Error(`State lock ${lockPath} taken inside the ancestry coordinator: a state lock is taken before it, never inside it`);
51
+ // A lock taken inside a held lock of the SAME directory asks the coordinator nothing: the outer take checked that
52
+ // the directory is not being removed, and a removal recorded since waits on that outer lock before it deletes
53
+ // anything, so this operation finishes first, as a holder that checked before the receipt does. Asked again, each
54
+ // write took the machine-wide coordinator three times for one directory.
55
+ const directory = dirname(lockPath);
56
+ const nested = [...held].some((path) => dirname(path) === directory);
49
57
  return store.withLock(lockPath, () => {
50
- withAncestryLock(() => assertNotBeingRemoved(dirname(lockPath)));
58
+ // The removal check reads the receipts without the coordinator, and takes it only where one is there (S2 R17;
59
+ // architecture, the history lock): this holder already has the directory's lock, and a removal writes its receipt
60
+ // under the coordinator before it waits on every lock inside the tree, so a receipt not yet visible here belongs to
61
+ // a removal that waits for this holder, which finishes first. A visible receipt is checked, recovered, as before.
62
+ if (!nested && removalRecorded())
63
+ withAncestryLock(() => assertNotBeingRemoved(directory), { operation: 'removal preflight' });
51
64
  held.add(lockPath);
52
65
  try {
53
66
  return fn();
@@ -55,12 +68,12 @@ export function withStateLock(lockPath, fn) {
55
68
  finally {
56
69
  held.delete(lockPath);
57
70
  }
58
- });
71
+ }, scope);
59
72
  }
60
73
  /** A state directory's history lock: its appends, captures, observation batches and folds. A branch's is taken before
61
74
  * its ancestors'. */
62
- export function withHistoryLock(directory, fn) {
63
- return withStateLock(join(canonicalStatePath(directory), 'history.lock'), fn);
75
+ export function withHistoryLock(directory, fn, options = {}) {
76
+ return withStateLock(join(canonicalStatePath(directory), 'history.lock'), fn, storageLockScope(options));
64
77
  }
65
78
  /** A lock file a holder has recorded itself in (`{pid, hostname}`, written before the holder runs anything): a file
66
79
  * that only ends in `.lock` (a yarn.lock) is not one. */
@@ -74,9 +87,10 @@ function isHeldLock(text) {
74
87
  }
75
88
  }
76
89
  /** Several sibling directories' history locks at once (a World's services, a changeset's targets), in one order. */
77
- export function withHistoryLocks(directories, fn) {
90
+ export function withHistoryLocks(directories, fn, options = {}) {
91
+ const scope = storageLockScope(options);
78
92
  const sorted = [...new Set(directories.map((d) => canonicalStatePath(d)))].sort();
79
- const take = (i) => (i === sorted.length ? fn() : withHistoryLock(sorted[i], () => take(i + 1)));
93
+ const take = (i) => (i === sorted.length ? fn() : withHistoryLock(sorted[i], () => take(i + 1), scope));
80
94
  return take(0);
81
95
  }
82
96
  /** The locks inside a tree a removal waits on before deleting it. */
@@ -125,7 +139,7 @@ export function stateGeneration(dir) {
125
139
  store.writeAtomic(metaPath(dir), JSON.stringify(meta));
126
140
  }
127
141
  return meta.generation;
128
- });
142
+ }, { operation: 'state generation' });
129
143
  }
130
144
  /** Must be called in the same critical section as child pointer publication. A crash before
131
145
  * publication leaves a pending pin; it can be ignored only once its writer is provably dead. */
@@ -254,23 +268,34 @@ function releaseOutgoing(removal) {
254
268
  }
255
269
  /** A crash after deleting files cannot strand committed child pins. Receipts are replayed
256
270
  * before any subsequent ancestry publication, so path reuse cannot hide completed removal. */
257
- function recoverRemovals() {
271
+ function recoverRemovals(lockPath) {
258
272
  const store = getActiveWorldStore();
273
+ const receipts = store.list(removalDir()).filter(n => n.endsWith('.json'));
274
+ if (!receipts.length) {
275
+ beingRemoved = [];
276
+ return;
277
+ }
259
278
  const pending = [];
260
- for (const name of store.list(removalDir()).filter(n => n.endsWith('.json'))) {
261
- const file = join(removalDir(), name);
262
- const removal = JSON.parse(store.read(file));
263
- if (typeof removal.path !== 'string' || !Array.isArray(removal.outgoing))
264
- throw new Error('Invalid branch removal receipt; retained');
265
- if (!store.exists(removal.path)) {
266
- releaseOutgoing(removal);
267
- store.remove(file);
279
+ withStorageLockOperation(lockPath, 'ancestry removal recovery', () => {
280
+ for (const name of receipts) {
281
+ const file = join(removalDir(), name);
282
+ const removal = JSON.parse(store.read(file));
283
+ if (typeof removal.path !== 'string' || !Array.isArray(removal.outgoing))
284
+ throw new Error('Invalid branch removal receipt; retained');
285
+ if (!store.exists(removal.path)) {
286
+ releaseOutgoing(removal);
287
+ store.remove(file);
288
+ }
289
+ else
290
+ pending.push(removal.path);
268
291
  }
269
- else
270
- pending.push(removal.path);
271
- }
292
+ });
272
293
  beingRemoved = pending;
273
294
  }
295
+ /** Whether any removal receipt is recorded now: read without the coordinator (withStateLock). */
296
+ function removalRecorded() {
297
+ return getActiveWorldStore().list(removalDir()).some((name) => name.endsWith('.json'));
298
+ }
274
299
  /** State whose removal is recorded and not yet complete: its deletion runs outside the coordinator, so nothing may pin
275
300
  * it as a parent or write into it meanwhile. Read under the coordinator, where recoverRemovals has just refreshed it. */
276
301
  let beingRemoved = [];
@@ -298,21 +323,21 @@ export function withStateRemoval(path, remove, check) {
298
323
  store.writeAtomic(receipt, JSON.stringify(removal));
299
324
  beingRemoved = [...beingRemoved, removal.path];
300
325
  return { removal, receipt };
301
- });
326
+ }, { operation: 'removal preflight' });
302
327
  // Each lock is waited on alone, taken and let go: a holder that checked before the receipt finishes, and a taker
303
328
  // after it refuses once it holds the lock (withStateLock), so the removal never holds one lock while waiting on
304
329
  // another and no lock order can deadlock it. A wait that fails leaves nothing deleted: the receipt is released.
305
330
  const held = heldBy(store);
306
331
  try {
307
332
  for (const lock of locksUnder(path).filter((l) => !held.has(l)))
308
- store.withLock(lock, () => undefined);
333
+ store.withLock(lock, () => undefined, { operation: 'removal preflight' });
309
334
  }
310
335
  catch (error) {
311
336
  withAncestryLock(() => {
312
337
  if (store.exists(receipt))
313
338
  store.remove(receipt);
314
339
  beingRemoved = beingRemoved.filter((p) => p !== removal.path);
315
- });
340
+ }, { operation: 'ancestry removal recovery' });
316
341
  throw error;
317
342
  }
318
343
  const result = remove();
@@ -323,6 +348,6 @@ export function withStateRemoval(path, remove, check) {
323
348
  releaseOutgoing(removal);
324
349
  if (store.exists(receipt))
325
350
  store.remove(receipt);
326
- });
351
+ }, { operation: 'ancestry removal recovery' });
327
352
  return result;
328
353
  }
@@ -19,7 +19,22 @@ export interface BlobStore {
19
19
  * whole. Optional: `readBlobRange` falls back to `get` (a whole read) for a backend without it —
20
20
  * the hosted World's R2 store today. */
21
21
  getRange?(key: string, start: number, endInclusive: number): Promise<Uint8Array | null>;
22
+ /** A body's chunks written to `key` as they arrive and hashed as they are written, kept (atomically, as `put`)
23
+ * only when `accept` holds for their size and SHA-256; otherwise nothing is kept. True when kept. So an upload
24
+ * of a large object (a model's weights) never holds more than a chunk. Optional: `writeBlobStream` collects
25
+ * the chunks and `put`s them for a backend without it. */
26
+ putStream?(key: string, chunks: AsyncIterable<Uint8Array>, accept: (written: BlobWritten) => boolean): Promise<boolean>;
22
27
  }
28
+ /** What a streamed write wrote: its byte length and its SHA-256 (hex). */
29
+ export type BlobWritten = {
30
+ size: number;
31
+ sha256: string;
32
+ };
33
+ /** A body's chunks to `key` through the active store, kept when `accept` holds for what was written (the store's
34
+ * own streamed write where it has one, else the chunks collected and `put`). True when kept. */
35
+ export declare function writeBlobStream(key: string, chunks: AsyncIterable<Uint8Array>, accept: (written: BlobWritten) => boolean): Promise<boolean>;
36
+ /** A web stream's chunks, read by its reader (a browser's ReadableStream need not be async-iterable). */
37
+ export declare function streamChunks(body: ReadableStream<Uint8Array>): AsyncGenerator<Uint8Array>;
23
38
  /** A range of the blob at `key` through the active store: native when the store has it, else sliced. */
24
39
  export declare function readBlobRange(key: string, start: number, endInclusive: number): Promise<Uint8Array | null>;
25
40
  /** Today's layout, verbatim: keys are filesystem paths. */
@@ -30,6 +45,7 @@ export declare class FsBlobStore implements BlobStore {
30
45
  });
31
46
  get(key: string): Promise<Uint8Array | null>;
32
47
  put(key: string, bytes: Uint8Array): Promise<void>;
48
+ putStream(key: string, chunks: AsyncIterable<Uint8Array>, accept: (written: BlobWritten) => boolean): Promise<boolean>;
33
49
  exists(key: string): Promise<boolean>;
34
50
  remove(key: string): Promise<void>;
35
51
  list(prefix: string): Promise<string[]>;
@@ -19,11 +19,50 @@
19
19
  // local worlds change NOTHING — scrub, backup, and inspection all still see the same tree.
20
20
  // A remote adapter maps the path to an object key (namespace prefix + path).
21
21
  import { createHash, randomUUID } from 'node:crypto';
22
- import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
22
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs';
23
23
  import { dirname, join } from 'node:path';
24
24
  import { volterHome } from "./volter-home.js";
25
25
  import { sharedBlobIndex } from "./shared-blob-index.js";
26
26
  import { refuseReadOnlyWrite, writesRefused } from "./request-scope.js";
27
+ /** A body's chunks to `key` through the active store, kept when `accept` holds for what was written (the store's
28
+ * own streamed write where it has one, else the chunks collected and `put`). True when kept. */
29
+ export async function writeBlobStream(key, chunks, accept) {
30
+ const store = getActiveBlobStore();
31
+ if (store.putStream)
32
+ return store.putStream(key, chunks, accept);
33
+ const parts = [];
34
+ let size = 0;
35
+ for await (const chunk of chunks) {
36
+ parts.push(chunk);
37
+ size += chunk.byteLength;
38
+ }
39
+ const bytes = new Uint8Array(size);
40
+ let at = 0;
41
+ for (const part of parts) {
42
+ bytes.set(part, at);
43
+ at += part.byteLength;
44
+ }
45
+ if (!accept({ size, sha256: blobDigest(bytes) }))
46
+ return false;
47
+ await store.put(key, bytes);
48
+ return true;
49
+ }
50
+ /** A web stream's chunks, read by its reader (a browser's ReadableStream need not be async-iterable). */
51
+ export async function* streamChunks(body) {
52
+ const reader = body.getReader();
53
+ try {
54
+ for (;;) {
55
+ const { done, value } = await reader.read();
56
+ if (done)
57
+ return;
58
+ if (value)
59
+ yield value;
60
+ }
61
+ }
62
+ finally {
63
+ reader.releaseLock();
64
+ }
65
+ }
27
66
  /** A range of the blob at `key` through the active store: native when the store has it, else sliced. */
28
67
  export async function readBlobRange(key, start, endInclusive) {
29
68
  // one clamping for every backend: a negative or non-finite start reads from 0, a range that ends
@@ -72,6 +111,40 @@ export class FsBlobStore {
72
111
  rmSync(tmp, { force: true });
73
112
  }
74
113
  }
114
+ async putStream(key, chunks, accept) {
115
+ mkdirSync(dirname(key), { recursive: true });
116
+ const tmp = `${key}.tmp.${randomUUID()}`;
117
+ const hash = createHash('sha256');
118
+ let size = 0;
119
+ try {
120
+ const fd = openSync(tmp, 'wx');
121
+ try {
122
+ for await (const chunk of chunks) {
123
+ hash.update(chunk);
124
+ size += chunk.byteLength;
125
+ for (let at = 0; at < chunk.byteLength;)
126
+ at += writeSync(fd, chunk, at, chunk.byteLength - at);
127
+ }
128
+ }
129
+ finally {
130
+ closeSync(fd);
131
+ }
132
+ const sha256 = hash.digest('hex');
133
+ if (!accept({ size, sha256 }))
134
+ return false;
135
+ renameSync(tmp, key);
136
+ if (this.options.sharedIndexRoot !== false) {
137
+ try {
138
+ sharedBlobIndex(this.options.sharedIndexRoot ?? join(volterHome(), 'blob-index-v1'), statSync(dirname(key)).dev, sha256).record(key);
139
+ }
140
+ catch { /* The index is an optimization, never a prerequisite for a blob write. */ }
141
+ }
142
+ return true;
143
+ }
144
+ finally {
145
+ rmSync(tmp, { force: true });
146
+ }
147
+ }
75
148
  async exists(key) {
76
149
  return existsSync(key);
77
150
  }
@@ -180,7 +253,9 @@ function readOnlyBlobs(store) {
180
253
  exists: (key) => store.exists(key),
181
254
  list: (prefix) => store.list(prefix),
182
255
  size: (key) => store.size(key),
256
+ ...(store.getRange ? { getRange: (key, start, endInclusive) => store.getRange(key, start, endInclusive) } : {}),
183
257
  put: async () => { refuseReadOnlyWrite('blobs'); },
258
+ putStream: async () => { refuseReadOnlyWrite('blobs'); return false; },
184
259
  remove: async () => { refuseReadOnlyWrite('blobs'); },
185
260
  };
186
261
  }
@@ -727,7 +727,7 @@ export function narrationDrift(changeset) {
727
727
  return expected === changeset.narration ? null : { recorded: changeset.narration, expected };
728
728
  }
729
729
  export function rebaseChangeset(changeset, opts) {
730
- return withHistoryLocks(opts.targets.map((t) => worldPaths(t.stateService, t.controlRoot).dir), () => rebaseChangesetLocked(changeset, opts));
730
+ return withHistoryLocks(opts.targets.map((t) => worldPaths(t.stateService, t.controlRoot).dir), () => rebaseChangesetLocked(changeset, opts), { operation: 'branch-pointer adjustment' });
731
731
  }
732
732
  function rebaseChangesetLocked(changeset, opts) {
733
733
  const at = opts.at ?? new Date().toISOString();
@@ -0,0 +1,28 @@
1
+ type Pair = [bigint, bigint];
2
+ /** The CityHash 1.0.2 checksum used by ClickHouse native compression frames. */
3
+ export declare function cityHash128(bytes: Uint8Array): Pair;
4
+ export declare const MAX_COMPRESSED_BLOCK_SIZE = 1073741824;
5
+ export declare const MAX_DECOMPRESSED_BLOCK_SIZE = 1073741824;
6
+ /** LZ4 block sequences. Validate all lengths before allocating the output buffer. */
7
+ export declare function decodeLz4Block(input: Uint8Array, size: number): Uint8Array;
8
+ /** A valid literal-only LZ4 block. */
9
+ export declare function encodeLz4Literals(input: Uint8Array): Uint8Array;
10
+ export declare class ClickHouseCompressionError extends Error {
11
+ readonly code: number;
12
+ constructor(code: number, message: string);
13
+ }
14
+ /** ClickHouse compressed frame, including its sixteen-byte checksum.
15
+ * ICompressionCodec.cpp:62–69,102–116 (SHA2562cfbdbd7…) writes the9-byte header.
16
+ * CompressedReadBufferBase.cpp:193–194,255–256 (SHA2566f5af3a8…) reads low/high
17
+ * little-endian checksum words and verifies the complete header+payload before decompressing.
18
+ */
19
+ export declare function encodeFrame(input: Uint8Array, method?: 0x82 | 0x02): Uint8Array;
20
+ /** Decode one frame; undefined means the input has not yet supplied the whole frame.
21
+ * Sizes are validated from the header before waiting for its body, and the checksum
22
+ * precedes decompression. bytesRead allows the caller to retain subsequent frames.
23
+ */
24
+ export declare function decodeFrame(input: Uint8Array): {
25
+ data: Uint8Array;
26
+ bytesRead: number;
27
+ } | undefined;
28
+ export {};
@@ -0,0 +1,281 @@
1
+ // CityHashv1.0.2 arithmetic, ported from the vendor-carried Google source.
2
+ // Source: ClickHouse/ClickHouse contrib/cityhash102/src/city.cc, SHA256
3
+ // 4bcc8f0c09e3ef38210a0c568efc0550e4cb426719d8ad74a466f152296d0df7.
4
+ // Copyright (c) 2011 Google, Inc.
5
+ //
6
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ // of this software and associated documentation files (the "Software"), to deal
8
+ // in the Software without restriction, including without limitation the rights
9
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ // copies of the Software, and to permit persons to whom the Software is
11
+ // furnished to do so, subject to the following conditions:
12
+ //
13
+ // The above copyright notice and this permission notice shall be included in
14
+ // all copies or substantial portions of the Software.
15
+ //
16
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ // THE SOFTWARE.
23
+ const k0 = 0xc3a5c85c97cb3127n, k1 = 0xb492b66fbe98f273n, k2 = 0x9ae16a3b2f90404fn, k3 = 0xc949d7c7509e6557n;
24
+ const u = (value) => BigInt.asUintN(64, value);
25
+ const rotate = (value, shift) => shift === 0 ? u(value) : u((u(value) >> BigInt(shift)) | (u(value) << BigInt(64 - shift)));
26
+ const mix = (value) => u(value) ^ (u(value) >> 47n);
27
+ function hash16(first, second) {
28
+ const mul = 0x9ddfea08eb382d69n;
29
+ let a = u((u(first) ^ u(second)) * mul);
30
+ a ^= a >> 47n;
31
+ let b = u((u(second) ^ a) * mul);
32
+ b ^= b >> 47n;
33
+ return u(b * mul);
34
+ }
35
+ /** The CityHash 1.0.2 checksum used by ClickHouse native compression frames. */
36
+ export function cityHash128(bytes) {
37
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
38
+ const fetch = (at) => view.getBigUint64(at, true);
39
+ const short = (at, length) => {
40
+ if (length > 8) {
41
+ const a = fetch(at), b = fetch(at + length - 8);
42
+ return hash16(a, rotate(u(b + BigInt(length)), length)) ^ b;
43
+ }
44
+ if (length >= 4)
45
+ return hash16(BigInt(length) + (BigInt(view.getUint32(at, true)) << 3n), BigInt(view.getUint32(at + length - 4, true)));
46
+ if (length) {
47
+ const a = bytes[at], b = bytes[at + (length >> 1)], c = bytes[at + length - 1];
48
+ return u(mix(u(BigInt(a + (b << 8)) * k2) ^ u(BigInt(length + (c << 2)) * k3)) * k2);
49
+ }
50
+ return k2;
51
+ };
52
+ const weak = (at, first, second) => {
53
+ const w = fetch(at), x = fetch(at + 8), y = fetch(at + 16), z = fetch(at + 24);
54
+ let a = u(first + w), b = rotate(u(second + a + z), 21);
55
+ const c = a;
56
+ a = u(a + x + y);
57
+ b = u(b + rotate(a, 44));
58
+ return [u(a + z), u(b + c)];
59
+ };
60
+ const murmur = (at, length, seed) => {
61
+ let [a, b] = seed, c = 0n, d = 0n, left = length - 16;
62
+ if (left <= 0) {
63
+ a = u(mix(u(a * k1)) * k1);
64
+ c = u(b * k1 + short(at, length));
65
+ d = mix(u(a + (length >= 8 ? fetch(at) : c)));
66
+ }
67
+ else {
68
+ c = hash16(u(fetch(at + length - 8) + k1), a);
69
+ d = hash16(u(b + BigInt(length)), u(c + fetch(at + length - 16)));
70
+ a = u(a + d);
71
+ do {
72
+ a ^= u(mix(u(fetch(at) * k1)) * k1);
73
+ a = u(a * k1);
74
+ b ^= a;
75
+ c ^= u(mix(u(fetch(at + 8) * k1)) * k1);
76
+ c = u(c * k1);
77
+ d ^= c;
78
+ at += 16;
79
+ left -= 16;
80
+ } while (left > 0);
81
+ }
82
+ a = hash16(a, c);
83
+ b = hash16(d, b);
84
+ return [a ^ b, hash16(b, a)];
85
+ };
86
+ const seeded = (at, length, seed) => {
87
+ if (length < 128)
88
+ return murmur(at, length, seed);
89
+ let [x, y] = seed, z = u(BigInt(length) * k1);
90
+ let v = [u(rotate(y ^ k1, 49) * k1 + fetch(at)), 0n];
91
+ v[1] = u(rotate(v[0], 42) * k1 + fetch(at + 8));
92
+ let w = [u(rotate(u(y + z), 35) * k1 + x), u(rotate(u(x + fetch(at + 88)), 53) * k1)];
93
+ const round = () => {
94
+ x = u(rotate(u(x + y + v[0] + fetch(at + 16)), 37) * k1);
95
+ y = u(rotate(u(y + v[1] + fetch(at + 48)), 42) * k1);
96
+ x ^= w[1];
97
+ y ^= v[0];
98
+ z = rotate(z ^ w[0], 33);
99
+ v = weak(at, u(v[1] * k1), u(x + w[0]));
100
+ w = weak(at + 32, u(z + w[1]), y);
101
+ [z, x] = [x, z];
102
+ at += 64;
103
+ };
104
+ do {
105
+ round();
106
+ round();
107
+ length -= 128;
108
+ } while (length >= 128);
109
+ y = u(y + rotate(w[0], 37) * k0 + z);
110
+ x = u(x + rotate(u(v[0] + z), 49) * k0);
111
+ for (let done = 0; done < length;) {
112
+ done += 32;
113
+ y = u(rotate(u(y - x), 42) * k0 + v[1]);
114
+ w[0] = u(w[0] + fetch(at + length - done + 16));
115
+ x = u(rotate(x, 49) * k0 + w[0]);
116
+ w[0] = u(w[0] + v[0]);
117
+ v = weak(at + length - done, v[0], v[1]);
118
+ }
119
+ x = hash16(x, v[0]);
120
+ y = hash16(y, w[0]);
121
+ return [u(hash16(u(x + v[1]), w[1]) + y), hash16(u(x + w[1]), u(y + v[1]))];
122
+ };
123
+ const length = bytes.length;
124
+ if (length >= 16)
125
+ return seeded(16, length - 16, [fetch(0) ^ k3, fetch(8)]);
126
+ if (length >= 8)
127
+ return seeded(0, 0, [fetch(0) ^ u(BigInt(length) * k0), fetch(length - 8) ^ k1]);
128
+ return seeded(0, length, [k0, k1]);
129
+ }
130
+ // ClickHouse src/Compression/CompressionInfo.h:7,14 (SHA25614b39ae2…): both limits are1GiB.
131
+ export const MAX_COMPRESSED_BLOCK_SIZE = 0x40000000;
132
+ export const MAX_DECOMPRESSED_BLOCK_SIZE = 0x40000000;
133
+ /** LZ4 block sequences. Validate all lengths before allocating the output buffer. */
134
+ export function decodeLz4Block(input, size) {
135
+ if (!Number.isSafeInteger(size) || size < 0 || size > MAX_DECOMPRESSED_BLOCK_SIZE || input.length > MAX_COMPRESSED_BLOCK_SIZE)
136
+ throw new RangeError('Invalid LZ4 block size');
137
+ // lz4_Block_format.md:114–126 requires a final literal sequence, five final literals
138
+ // (except a short all-literal block), and the last match at least12 bytes before its end.
139
+ // This is the format specification's strictness; ClickHouse's decoder is not retained
140
+ // here and may accept malformed end sequences that this decoder rejects.
141
+ const walk = (output) => {
142
+ let source = 0, target = 0, sequences = 0, finalLiterals = -1, lastMatchStart = -1;
143
+ const length = (initial) => {
144
+ let result = initial;
145
+ if (initial === 15) {
146
+ let value;
147
+ do {
148
+ if (source >= input.length)
149
+ throw new RangeError('Truncated LZ4 length');
150
+ value = input[source++];
151
+ result += value;
152
+ } while (value === 255);
153
+ }
154
+ return result;
155
+ };
156
+ while (source < input.length) {
157
+ sequences++;
158
+ const token = input[source++], literals = length(token >> 4);
159
+ if (literals > input.length - source || literals > size - target)
160
+ throw new RangeError('Invalid LZ4 literal range');
161
+ output?.set(input.subarray(source, source + literals), target);
162
+ source += literals;
163
+ target += literals;
164
+ if (source === input.length) {
165
+ finalLiterals = literals;
166
+ break;
167
+ }
168
+ if (source + 2 > input.length)
169
+ throw new RangeError('Truncated LZ4 offset');
170
+ const offset = input[source++] | (input[source++] << 8);
171
+ if (!offset || offset > target)
172
+ throw new RangeError('Invalid LZ4 offset');
173
+ const match = length(token & 15) + 4;
174
+ if (match > size - target)
175
+ throw new RangeError('Invalid LZ4 match range');
176
+ lastMatchStart = target;
177
+ if (output)
178
+ for (let i = 0; i < match; i++) {
179
+ output[target] = output[target - offset];
180
+ target++;
181
+ }
182
+ else
183
+ target += match;
184
+ }
185
+ if (finalLiterals < 0 || (size >= 5 && finalLiterals < 5) || (size < 5 && sequences !== 1) || (lastMatchStart >= 0 && size - lastMatchStart < 12))
186
+ throw new RangeError('Invalid LZ4 end sequence');
187
+ if (target !== size)
188
+ throw new RangeError('LZ4 decoded size differs');
189
+ };
190
+ walk();
191
+ const output = new Uint8Array(size);
192
+ walk(output);
193
+ return output;
194
+ }
195
+ /** A valid literal-only LZ4 block. */
196
+ export function encodeLz4Literals(input) {
197
+ if (input.length > MAX_DECOMPRESSED_BLOCK_SIZE)
198
+ throw new RangeError('LZ4 block is too large');
199
+ const extension = input.length >= 15 ? Math.floor((input.length - 15) / 255) + 1 : 0;
200
+ const output = new Uint8Array(1 + extension + input.length);
201
+ let at = 0;
202
+ output[at++] = Math.min(input.length, 15) << 4;
203
+ if (extension) {
204
+ let left = input.length - 15;
205
+ while (left >= 255) {
206
+ output[at++] = 255;
207
+ left -= 255;
208
+ }
209
+ output[at++] = left;
210
+ }
211
+ output.set(input, at);
212
+ return output;
213
+ }
214
+ export class ClickHouseCompressionError extends Error {
215
+ code;
216
+ constructor(code, message) {
217
+ super(message);
218
+ this.code = code;
219
+ this.name = 'ClickHouseCompressionError';
220
+ }
221
+ }
222
+ /** ClickHouse compressed frame, including its sixteen-byte checksum.
223
+ * ICompressionCodec.cpp:62–69,102–116 (SHA2562cfbdbd7…) writes the9-byte header.
224
+ * CompressedReadBufferBase.cpp:193–194,255–256 (SHA2566f5af3a8…) reads low/high
225
+ * little-endian checksum words and verifies the complete header+payload before decompressing.
226
+ */
227
+ export function encodeFrame(input, method = 0x82) {
228
+ if (!input.length || input.length > MAX_DECOMPRESSED_BLOCK_SIZE)
229
+ throw new ClickHouseCompressionError(39, 'Invalid decompressed block size');
230
+ if (method !== 0x82 && method !== 0x02)
231
+ throw new ClickHouseCompressionError(89, 'Unknown compression method');
232
+ const bodyLength = method === 0x82 ? 1 + (input.length >= 15 ? Math.floor((input.length - 15) / 255) + 1 : 0) + input.length : input.length;
233
+ if (bodyLength + 9 > MAX_COMPRESSED_BLOCK_SIZE)
234
+ throw new ClickHouseCompressionError(39, 'Compressed block is too large');
235
+ const body = method === 0x82 ? encodeLz4Literals(input) : input;
236
+ const output = new Uint8Array(25 + body.length), view = new DataView(output.buffer);
237
+ output[16] = method;
238
+ view.setUint32(17, 9 + body.length, true);
239
+ view.setUint32(21, input.length, true);
240
+ output.set(body, 25);
241
+ const [low, high] = cityHash128(output.subarray(16));
242
+ view.setBigUint64(0, low, true);
243
+ view.setBigUint64(8, high, true);
244
+ return output;
245
+ }
246
+ /** Decode one frame; undefined means the input has not yet supplied the whole frame.
247
+ * Sizes are validated from the header before waiting for its body, and the checksum
248
+ * precedes decompression. bytesRead allows the caller to retain subsequent frames.
249
+ */
250
+ export function decodeFrame(input) {
251
+ if (input.length < 25)
252
+ return undefined;
253
+ const view = new DataView(input.buffer, input.byteOffset, input.byteLength), method = input[16];
254
+ // CompressedReadBufferBase.cpp:134–138 selects/refuses the codec before header sizes.
255
+ if (method !== 0x82 && method !== 0x02)
256
+ throw new ClickHouseCompressionError(89, 'Unknown compression method');
257
+ const compressed = view.getUint32(17, true), size = view.getUint32(21, true);
258
+ if (compressed > MAX_COMPRESSED_BLOCK_SIZE || size > MAX_DECOMPRESSED_BLOCK_SIZE)
259
+ throw new ClickHouseCompressionError(39, 'Compressed block size exceeds the vendor limit');
260
+ if (compressed < 9 || !size)
261
+ throw new ClickHouseCompressionError(246, 'Corrupt compressed block header');
262
+ const bytesRead = 16 + compressed;
263
+ if (input.length < bytesRead)
264
+ return undefined;
265
+ const frame = input.subarray(16, bytesRead), [low, high] = cityHash128(frame);
266
+ if (low !== view.getBigUint64(0, true) || high !== view.getBigUint64(8, true))
267
+ throw new ClickHouseCompressionError(40, 'Checksum does not match');
268
+ const body = frame.subarray(9);
269
+ if (method === 0x02) {
270
+ if (body.length !== size)
271
+ throw new ClickHouseCompressionError(246, 'Uncompressed block size differs');
272
+ // Own the returned bytes, as the LZ4 branch does.
273
+ return { data: body.slice(), bytesRead };
274
+ }
275
+ try {
276
+ return { data: decodeLz4Block(body, size), bytesRead };
277
+ }
278
+ catch (error) {
279
+ throw new ClickHouseCompressionError(246, error instanceof Error ? error.message : 'Invalid LZ4 block');
280
+ }
281
+ }
@@ -1,3 +1,4 @@
1
1
  export * from './values.js';
2
2
  export * from './types.js';
3
3
  export * from './sql.js';
4
+ export * from './compression.js';
@@ -4,3 +4,4 @@
4
4
  export * from "./values.js";
5
5
  export * from "./types.js";
6
6
  export * from "./sql.js";
7
+ export * from "./compression.js";