defuss-dbsonl 0.5.0 → 0.7.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.
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  var sequence = require('defuss-dson/sequence');
4
- var backend = require('./backend-CU4f3EUz.cjs');
5
- var common = require('./common-2ybGl1zj.cjs');
4
+ var backend = require('./backend-Bq8hVmuI.cjs');
5
+ var common = require('./common-YqfTK8sQ.cjs');
6
6
  require('defuss-storage');
7
7
 
8
8
  const STRING = 14, FLOAT64 = 15, ARRAY = 17, OBJECT = 18;
@@ -173,6 +173,15 @@ function equalBytes(a, b) {
173
173
  for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
174
174
  return true;
175
175
  }
176
+ function checkHead(value) {
177
+ const h = value;
178
+ if (!h || h.dbsonl !== 2 && h.dbsonl !== 3) throw new common.DbsonlError("UNSUPPORTED", "Unsupported database manifest version.");
179
+ if (h.dbsonl === 3 ? typeof h.seal !== "string" || !/^[0-9a-f]{32}$/.test(h.seal) : h.seal !== void 0) common.corrupt("Invalid manifest seal.");
180
+ if (!Number.isSafeInteger(h.publication) || h.publication < 1 || !Number.isSafeInteger(h.revision) || h.revision < 0 || !Number.isSafeInteger(h.count) || h.count < 0 || !Number.isSafeInteger(h.end) || h.end < 0 || typeof h.generation !== "string" || !/^[0-9a-f]{32}$/.test(h.generation)) common.corrupt("Invalid manifest fields.");
181
+ if (h.root !== null) common.reference(h.root, h.end);
182
+ if (h.root === null !== (h.count === 0)) common.corrupt("Empty root and count disagree.");
183
+ return h;
184
+ }
176
185
  async function readHead(backend$1, name, cache) {
177
186
  const data = backend$1.read ? await backend$1.read(headFile(name), 0, SLOT_BYTES * 2 + 1) : await backend.withFile(backend$1, headFile(name), { readOnly: true }, async (file) => {
178
187
  const size2 = await file.size();
@@ -195,12 +204,7 @@ async function readHead(backend$1, name, cache) {
195
204
  } catch {
196
205
  continue;
197
206
  }
198
- const h = value;
199
- if (!h || h.dbsonl !== 2) throw new common.DbsonlError("UNSUPPORTED", "Unsupported database manifest version.");
200
- if (!Number.isSafeInteger(h.publication) || h.publication < 1 || !Number.isSafeInteger(h.revision) || h.revision < 0 || !Number.isSafeInteger(h.count) || h.count < 0 || !Number.isSafeInteger(h.end) || h.end < 0 || !/^[0-9a-f]{32}$/.test(h.generation)) common.corrupt("Invalid manifest fields.");
201
- if (h.root !== null) common.reference(h.root, h.end);
202
- if (h.root === null !== (h.count === 0)) common.corrupt("Empty root and count disagree.");
203
- heads.push(h);
207
+ heads.push(checkHead(value));
204
208
  }
205
209
  if (!heads.length) common.corrupt("No valid commit slot. Refuse automatic data loss recovery.");
206
210
  heads.sort((a, b) => b.publication - a.publication);
@@ -211,7 +215,7 @@ async function readHead(backend$1, name, cache) {
211
215
  }
212
216
  return head;
213
217
  }
214
- async function publish(backend$1, name, head, cache) {
218
+ async function publish(backend$1, name, head, cache, flush = true) {
215
219
  common.natural(head.publication, "publication", 1);
216
220
  const bytes = sequence.encodeFrame(head, { maxRecordBytes: SLOT_BYTES - 16, trusted: true });
217
221
  const slot = new Uint8Array(SLOT_BYTES);
@@ -219,7 +223,7 @@ async function publish(backend$1, name, head, cache) {
219
223
  const offset = head.publication % 2 * SLOT_BYTES;
220
224
  await backend.withFile(backend$1, headFile(name), {}, async (file) => {
221
225
  await backend.writeBytes(file, offset, slot, backend$1.writeChunkBytes);
222
- await file.flush();
226
+ if (flush) await file.flush();
223
227
  });
224
228
  if (cache?.bytes?.length === SLOT_BYTES * 2) {
225
229
  const next = cache.bytes.slice();
@@ -228,22 +232,79 @@ async function publish(backend$1, name, head, cache) {
228
232
  cache.head = head;
229
233
  }
230
234
  }
235
+ const CRC_TABLE = (() => {
236
+ const table = new Uint32Array(256);
237
+ for (let n = 0; n < 256; n++) {
238
+ let c = n;
239
+ for (let k = 0; k < 8; k++) c = c & 1 ? c >>> 1 ^ 2197175160 : c >>> 1;
240
+ table[n] = c >>> 0;
241
+ }
242
+ return table;
243
+ })();
244
+ function crc32c(bytes) {
245
+ let c = 4294967295;
246
+ for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 255] ^ c >>> 8;
247
+ return (c ^ 4294967295) >>> 0;
248
+ }
249
+ const RECORD_BYTES = 1024;
250
+ function commitRecord(head, offset, prev) {
251
+ return sequence.encodeFrame({ dbsonl: 3, seal: head.seal, publication: head.publication, revision: head.revision, root: head.root, count: head.count, offset, prev }, { maxRecordBytes: RECORD_BYTES - 16, trusted: true });
252
+ }
253
+ async function recoverTail(file, head, size) {
254
+ if (head.dbsonl !== 3) return void 0;
255
+ let position = head.end, prev = head.end, found;
256
+ while (position + sequence.FRAME_HEADER_BYTES <= size) {
257
+ let frame;
258
+ try {
259
+ frame = sequence.inspectFrame(await readExact(file, position, sequence.FRAME_HEADER_BYTES), 0, { maxRecordBytes: size });
260
+ } catch {
261
+ break;
262
+ }
263
+ const length = frame.byteLength;
264
+ if (position + length > size) break;
265
+ const bytes = await readExact(file, position, length);
266
+ if (length > RECORD_BYTES) {
267
+ if (crc32c(bytes.subarray(frame.payloadOffset, frame.payloadOffset + frame.payloadLength)) !== frame.checksum) break;
268
+ position += length;
269
+ continue;
270
+ }
271
+ let value;
272
+ try {
273
+ value = sequence.decodeFrame(bytes, 0, { maxRecordBytes: RECORD_BYTES, maxDepth: 512, maxReferences: 1e6 }).value;
274
+ } catch {
275
+ break;
276
+ }
277
+ const record = value;
278
+ if (record && typeof record === "object" && record.dbsonl === 3 && record.seal === head.seal && record.offset === position && record.prev === prev) {
279
+ let next;
280
+ try {
281
+ next = checkHead({ dbsonl: 3, seal: head.seal, publication: record.publication, revision: record.revision, generation: head.generation, root: record.root, count: record.count, end: position + length });
282
+ } catch {
283
+ break;
284
+ }
285
+ if (next.publication <= (found ?? head).publication) break;
286
+ found = next;
287
+ prev = next.end;
288
+ }
289
+ position += length;
290
+ }
291
+ return found;
292
+ }
231
293
  const PAGE_BYTES = 512 * 1024;
232
294
  async function readValue(backend$1, name, head, ref, maxRecordBytes, window) {
233
295
  common.reference(ref, head.end);
234
296
  if (ref.byteLength - 16 > maxRecordBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "Referenced record exceeds the decoder budget.");
235
297
  let bytes;
236
- if (window?.bytes && window.offset !== void 0 && ref.offset >= window.offset && ref.offset + ref.byteLength <= window.offset + window.bytes.length) {
298
+ if (window && windowContains(window, ref)) {
237
299
  bytes = window.bytes.subarray(ref.offset - window.offset, ref.offset - window.offset + ref.byteLength);
238
300
  } else {
239
- const length = backend$1.read && window && ref.byteLength <= 65536 ? Math.min(65536, head.end - ref.offset) : ref.byteLength;
301
+ const length = window && ref.byteLength <= 65536 ? Math.min(65536, head.end - ref.offset) : ref.byteLength;
240
302
  const filename = generationFile(name, head.generation);
241
303
  const data = backend$1.read ? await backend$1.read(filename, ref.offset, length) : (
242
- // Portable handles also benefit from known, bounded reference lengths:
243
- // fetch header and payload together rather than allocate and copy twice.
304
+ // Portable handles read the same bounded window, so a scan opens the file once per window, not per row.
244
305
  await backend.withFile(backend$1, filename, { readOnly: true }, (file) => readExact(file, ref.offset, length))
245
306
  );
246
- if (window && backend$1.read) {
307
+ if (window) {
247
308
  window.offset = ref.offset;
248
309
  window.bytes = length <= 65536 ? data : new Uint8Array(0);
249
310
  }
@@ -251,6 +312,28 @@ async function readValue(backend$1, name, head, ref, maxRecordBytes, window) {
251
312
  }
252
313
  return decodeRef(bytes, ref, maxRecordBytes);
253
314
  }
315
+ function windowContains(window, ref) {
316
+ return !!window.bytes && window.offset !== void 0 && ref.offset >= window.offset && ref.offset + ref.byteLength <= window.offset + window.bytes.length;
317
+ }
318
+ function readCachedValue(head, ref, maxRecordBytes, window) {
319
+ common.reference(ref, head.end);
320
+ if (ref.byteLength - 16 > maxRecordBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "Referenced record exceeds the decoder budget.");
321
+ return decodeRef(window.bytes.subarray(ref.offset - window.offset, ref.offset - window.offset + ref.byteLength), ref, maxRecordBytes);
322
+ }
323
+ function readCachedValues(entries, start, end, maxRecordBytes, window) {
324
+ try {
325
+ const offsets = [];
326
+ for (let i = start; i < end; i++) offsets.push(entries[i].ref.offset - window.offset);
327
+ const frames = sequence.decodeFrames(window.bytes, offsets, { maxRecordBytes, maxDepth: 512, maxReferences: 1e6 }), values = [];
328
+ for (let i = 0; i < frames.length; i++) {
329
+ if (frames[i].byteLength !== entries[start + i].ref.byteLength) return [];
330
+ values.push(frames[i].value);
331
+ }
332
+ return values;
333
+ } catch {
334
+ return [];
335
+ }
336
+ }
254
337
  function decodeRef(bytes, ref, maxRecordBytes) {
255
338
  if (bytes.length !== ref.byteLength) common.corrupt("Committed record is truncated.");
256
339
  try {
@@ -263,6 +346,13 @@ function decodeRef(bytes, ref, maxRecordBytes) {
263
346
  }
264
347
  }
265
348
  class Appender {
349
+ end;
350
+ buffer;
351
+ used = 0;
352
+ flushedEnd;
353
+ file;
354
+ limits;
355
+ chunkSize;
266
356
  constructor(file, end, limits, chunkSize) {
267
357
  this.file = file;
268
358
  this.limits = limits;
@@ -271,13 +361,6 @@ class Appender {
271
361
  this.flushedEnd = end;
272
362
  this.buffer = new Uint8Array(Math.min(chunkSize, 65536));
273
363
  }
274
- file;
275
- limits;
276
- chunkSize;
277
- end;
278
- buffer;
279
- used = 0;
280
- flushedEnd;
281
364
  /** Coalesce small frames, but preserve the data-before-manifest durability barrier. */
282
365
  async flush() {
283
366
  if (!this.used) return;
@@ -392,18 +475,24 @@ async function* entries(load, root, gte, lt, depth = 0) {
392
475
  }
393
476
  }
394
477
  }
395
- class BatchTree {
396
- /** cached returns an already validated committed page, or undefined to read it through the writer. */
397
- constructor(writer, root, count, byteBudget, cached = () => void 0) {
398
- this.writer = writer;
399
- this.byteBudget = byteBudget;
400
- this.cached = cached;
401
- this.root = root;
402
- this.count = count;
478
+ async function* entryPages(load, root, gte, lt, depth = 0) {
479
+ if (!root) return;
480
+ if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
481
+ const loaded = load(root), page = "kind" in loaded ? loaded : await loaded;
482
+ if (page.kind === "leaf") {
483
+ const start = gte === void 0 ? 0 : lower(page.entries, gte, (item) => item.key);
484
+ const end = lt === void 0 ? page.entries.length : lower(page.entries, lt, (item) => item.key);
485
+ if (end > start) yield start === 0 && end === page.entries.length ? page.entries : page.entries.slice(start, end);
486
+ } else {
487
+ let prior;
488
+ for (const child of page.children) {
489
+ if (lt !== void 0 && prior !== void 0 && prior >= lt) break;
490
+ if (gte === void 0 || child.max >= gte) yield* entryPages(load, child.ref, gte, lt, depth + 1);
491
+ prior = child.max;
492
+ }
403
493
  }
404
- writer;
405
- byteBudget;
406
- cached;
494
+ }
495
+ class BatchTree {
407
496
  root;
408
497
  count;
409
498
  loadedBytes = 0;
@@ -413,6 +502,17 @@ class BatchTree {
413
502
  }
414
503
  /** Pages this batch appended, for the caller to cache once the root is published. */
415
504
  written = [];
505
+ /** cached returns an already validated committed page, or undefined to read it through the writer. */
506
+ writer;
507
+ byteBudget;
508
+ cached;
509
+ constructor(writer, root, count, byteBudget, cached = () => void 0) {
510
+ this.writer = writer;
511
+ this.byteBudget = byteBudget;
512
+ this.cached = cached;
513
+ this.root = root;
514
+ this.count = count;
515
+ }
416
516
  /** Committed pages on the next edit's path, found by missing(); each becomes a dirty copy in editable(). */
417
517
  fetched = /* @__PURE__ */ new Map();
418
518
  editable(link) {
@@ -516,13 +616,94 @@ class BatchTree {
516
616
  return { root: this.root ? await persist(this.root) : null, count: this.count };
517
617
  }
518
618
  }
619
+ async function firstKey(load, piece) {
620
+ if (piece.key !== void 0) return piece.key;
621
+ let ref = piece.ref;
622
+ for (let depth = 0; ; depth++) {
623
+ if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
624
+ const loaded = load(ref), page = "kind" in loaded ? loaded : await loaded;
625
+ if (page.kind === "leaf") return page.entries[0].key;
626
+ ref = page.children[0].ref;
627
+ }
628
+ }
629
+ async function open(load, piece, next) {
630
+ const loaded = load(piece.ref), page = "kind" in loaded ? loaded : await loaded;
631
+ if (page.kind === "leaf") {
632
+ for (const entry of page.entries) next.push({ count: 1, key: entry.key });
633
+ return;
634
+ }
635
+ let low = piece.low;
636
+ for (const child of page.children) {
637
+ next.push({ count: child.count, ref: child.ref, ...low !== void 0 && { low }, high: child.max });
638
+ low = child.max;
639
+ }
640
+ }
641
+ async function split(load, root, total, parts, gte, lt) {
642
+ const whole = (count2) => [{ ...gte !== void 0 && { gte }, ...lt !== void 0 && { lt }, count: count2 }];
643
+ if (!root || gte !== void 0 && lt !== void 0 && gte >= lt) return whole(0);
644
+ if (gte === void 0 && lt === void 0 && parts === 1) return whole(total);
645
+ let pieces = await within(load, root, total, gte, lt);
646
+ const rows = pieces.reduce((sum, piece) => sum + piece.count, 0);
647
+ if (!rows || parts === 1) return whole(rows);
648
+ const limit = Math.max(1, Math.floor(rows / parts / 8));
649
+ for (let depth = 0; pieces.some((piece) => piece.ref && piece.count > limit); depth++) {
650
+ if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
651
+ const next = [];
652
+ for (const piece of pieces) if (!piece.ref || piece.count <= limit) next.push(piece);
653
+ else await open(load, piece, next);
654
+ pieces = next;
655
+ }
656
+ const out = [];
657
+ let used = 0, count = 0, low = gte;
658
+ for (let i = 0; i < pieces.length; i++) {
659
+ count += pieces[i].count;
660
+ used += pieces[i].count;
661
+ if (i + 1 < pieces.length && out.length + 1 < parts && used * parts >= rows * (out.length + 1)) {
662
+ const high = await firstKey(load, pieces[i + 1]);
663
+ out.push(low === void 0 ? { lt: high, count } : { gte: low, lt: high, count });
664
+ low = high;
665
+ count = 0;
666
+ }
667
+ }
668
+ out.push({ ...low !== void 0 && { gte: low }, ...lt !== void 0 && { lt }, count });
669
+ return out;
670
+ }
671
+ async function keyAt(load, root, total, index, gte, lt) {
672
+ if (!root || gte !== void 0 && lt !== void 0 && gte >= lt) return void 0;
673
+ let pieces = await within(load, root, total, gte, lt);
674
+ for (let depth = 0; ; depth++) {
675
+ if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
676
+ let i = 0;
677
+ for (; i < pieces.length && index >= pieces[i].count; i++) index -= pieces[i].count;
678
+ const piece = pieces[i];
679
+ if (!piece) return void 0;
680
+ if (piece.key !== void 0) return piece.key;
681
+ const next = [];
682
+ await open(load, piece, next);
683
+ pieces = next;
684
+ }
685
+ }
686
+ async function within(load, root, total, gte, lt) {
687
+ const inside = (piece) => piece.key !== void 0 ? (gte === void 0 || piece.key >= gte) && (lt === void 0 || piece.key < lt) : (gte === void 0 || piece.low !== void 0 && piece.low >= gte) && (lt === void 0 || piece.high < lt);
688
+ const outside = (piece) => piece.key !== void 0 ? !inside(piece) : gte !== void 0 && piece.high < gte || lt !== void 0 && piece.low !== void 0 && piece.low >= lt;
689
+ let pieces = [{ count: total, ref: root }];
690
+ for (let depth = 0; pieces.some((piece) => !inside(piece) && !outside(piece)); depth++) {
691
+ if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
692
+ const next = [];
693
+ for (const piece of pieces) if (outside(piece)) continue;
694
+ else if (inside(piece)) next.push(piece);
695
+ else await open(load, piece, next);
696
+ pieces = next.filter((piece) => !outside(piece));
697
+ }
698
+ return pieces;
699
+ }
519
700
  class BulkTree {
701
+ leaf = [];
702
+ levels = [];
703
+ writer;
520
704
  constructor(writer) {
521
705
  this.writer = writer;
522
706
  }
523
- writer;
524
- leaf = [];
525
- levels = [];
526
707
  async push(child, level) {
527
708
  const items = this.levels[level] ?? (this.levels[level] = []);
528
709
  items.push(child);
@@ -556,8 +737,16 @@ class BulkTree {
556
737
  }
557
738
 
558
739
  const GROUP_MEMBERS = 64;
740
+ const HEAD_FLUSH_BYTES = 16 * 1024 * 1024;
741
+ class Recovered {
742
+ head;
743
+ constructor(head) {
744
+ this.head = head;
745
+ }
746
+ }
559
747
  const clock = globalThis;
560
- const encodedBytes = (input) => input.reduce((sum, item) => sum + (item.bytes?.length ?? 0) + item.key.length * 2 + 64, 0);
748
+ const batchSizes = /* @__PURE__ */ new WeakMap();
749
+ const encodedBytes = (input) => batchSizes.get(input) ?? input.reduce((sum, item) => sum + (item.bytes?.length ?? 0) + item.key.length * 2 + 64, 0);
561
750
  function newGeneration() {
562
751
  const crypto = globalThis.crypto;
563
752
  if (!crypto?.randomUUID) throw new common.DbsonlError("UNSUPPORTED", "A secure randomUUID implementation is required.");
@@ -567,7 +756,19 @@ function code(error) {
567
756
  return error?.code;
568
757
  }
569
758
  const pageId = (head, ref) => `${head.generation}:${ref.offset}:${ref.byteLength}`;
759
+ const batchBytes = /* @__PURE__ */ new WeakMap();
760
+ const TASK_BYTES = 1024 * 1024, MAX_TASKS = 1024;
570
761
  class ReadSession {
762
+ closed = false;
763
+ closing;
764
+ pending = /* @__PURE__ */ new Set();
765
+ /** Scans running in workers; close() stops them, so their worker pins end with this snapshot. */
766
+ scans = /* @__PURE__ */ new Set();
767
+ revision;
768
+ count;
769
+ head;
770
+ db;
771
+ release;
571
772
  /** @internal Sessions are created only by the database factory. */
572
773
  constructor(db, head, release) {
573
774
  this.db = db;
@@ -577,17 +778,9 @@ class ReadSession {
577
778
  this.revision = head.revision;
578
779
  this.count = head.count;
579
780
  }
580
- db;
581
- head;
582
- release;
583
- closed = false;
584
- closing;
585
- pending = /* @__PURE__ */ new Set();
586
- revision;
587
- count;
588
- work(fn) {
781
+ work(fn, invokesUserCode = false) {
589
782
  if (this.closed) return Promise.reject(new common.DbsonlError("CLOSED", "Snapshot is closed."));
590
- const promise = fn();
783
+ const promise = invokesUserCode ? Promise.resolve().then(fn) : fn();
591
784
  this.pending.add(promise);
592
785
  void promise.then(() => this.pending.delete(promise), () => this.pending.delete(promise));
593
786
  return promise;
@@ -626,12 +819,128 @@ class ReadSession {
626
819
  throw: (error) => iterator.throw(error)
627
820
  };
628
821
  }
822
+ /** Native bounded batches: one tracked pull per batch and one async traversal per leaf. */
823
+ scanBatches(options = {}) {
824
+ const { gte, lt, signal, sizeOf } = options;
825
+ if (gte !== void 0) common.key(gte);
826
+ if (lt !== void 0) common.key(lt);
827
+ const limit = common.natural(options.limit ?? Number.MAX_SAFE_INTEGER, "scan limit");
828
+ const batchSize = common.natural(options.batchSize ?? 256, "batchSize", 1);
829
+ const maxBytes = common.natural(options.maxBatchBytes ?? 4 * 1024 * 1024, "maxBatchBytes", 1);
830
+ if (sizeOf !== void 0 && typeof sizeOf !== "function") throw new TypeError("sizeOf must be a function.");
831
+ const { db, head, scans } = this, plan = (gte2, lt2, limit2, batchSize2, maxBatchBytes) => this.parallel(gte2, lt2, limit2, batchSize2, maxBatchBytes);
832
+ async function* batches() {
833
+ let count = 0, bytes = 0, batch = [];
834
+ const window = {};
835
+ common.abort(signal);
836
+ if (!limit) return;
837
+ const parallel = sizeOf === void 0 ? await plan(gte, lt, limit, batchSize, maxBytes) : void 0;
838
+ if (parallel) {
839
+ scans.add(parallel);
840
+ try {
841
+ for (let rows = await parallel.next(); rows; rows = await parallel.next()) {
842
+ common.abort(signal);
843
+ if (count + rows.length > limit) rows = rows.slice(0, limit - count);
844
+ count += rows.length;
845
+ yield rows;
846
+ if (count === limit) return;
847
+ common.abort(signal);
848
+ }
849
+ } finally {
850
+ scans.delete(parallel);
851
+ await parallel.close();
852
+ }
853
+ return;
854
+ }
855
+ for await (const page of entryPages((ref) => db.load(head, ref), head.root, gte, lt)) {
856
+ let first = 0, last = 0, run = [];
857
+ for (let i = 0; i < page.length; i++) {
858
+ const entry = page[i];
859
+ common.abort(signal);
860
+ if (i >= last && windowContains(window, entry.ref)) {
861
+ const stop = Math.min(page.length, i + limit - count, i + batchSize - batch.length);
862
+ first = i;
863
+ last = i + 1;
864
+ while (last < stop && windowContains(window, page[last].ref)) last++;
865
+ run = last - first > 1 ? db.cachedValues(page, first, last, window) : [];
866
+ }
867
+ const value = i < last && run.length ? run[i - first] : windowContains(window, entry.ref) ? db.cachedValue(head, entry.ref, window) : await db.value(head, entry.ref, window);
868
+ common.abort(signal);
869
+ const row = { key: entry.key, revision: entry.revision, value };
870
+ const size = common.natural(sizeOf ? sizeOf(row) : entry.ref.byteLength, "batch row bytes");
871
+ if (size > maxBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "One row exceeds the batch byte budget.");
872
+ if (batch.length && bytes + size > maxBytes) {
873
+ batchBytes.set(batch, bytes);
874
+ yield batch;
875
+ batch = [];
876
+ bytes = 0;
877
+ common.abort(signal);
878
+ }
879
+ batch.push(row);
880
+ bytes += size;
881
+ count++;
882
+ if (batch.length === batchSize) {
883
+ batchBytes.set(batch, bytes);
884
+ yield batch;
885
+ batch = [];
886
+ bytes = 0;
887
+ common.abort(signal);
888
+ }
889
+ if (count === limit) {
890
+ if (batch.length) {
891
+ batchBytes.set(batch, bytes);
892
+ yield batch;
893
+ }
894
+ return;
895
+ }
896
+ }
897
+ }
898
+ if (batch.length) {
899
+ batchBytes.set(batch, bytes);
900
+ yield batch;
901
+ }
902
+ }
903
+ const iterator = batches();
904
+ return {
905
+ [Symbol.asyncIterator]() {
906
+ return this;
907
+ },
908
+ next: () => this.work(() => iterator.next(), true),
909
+ return: () => iterator.return(void 0),
910
+ throw: (error) => iterator.throw(error)
911
+ };
912
+ }
913
+ /** Ranges and a running worker scan for a large scanBatches call, or undefined to scan in this thread. */
914
+ async parallel(gte, lt, limit, batchSize, maxBatchBytes) {
915
+ const parallel = this.db.parallel, { head } = this;
916
+ if (!parallel?.workers || head.count < parallel.threshold || limit < parallel.threshold || gte !== void 0 && lt !== void 0 && gte >= lt) return void 0;
917
+ const load = (ref) => this.db.load(head, ref);
918
+ const [counted] = await split(load, head.root, head.count, 1, gte, lt);
919
+ const rows = Math.min(counted.count, limit);
920
+ if (rows < parallel.threshold) return void 0;
921
+ const end = rows < counted.count ? await keyAt(load, head.root, head.count, rows, gte, lt) : lt;
922
+ const parts = Math.min(MAX_TASKS, Math.max(parallel.workers * 2, Math.ceil(rows * (head.end / head.count) / TASK_BYTES)));
923
+ const ranges = (await split(load, head.root, head.count, parts, gte, end)).map((range) => ({ ...range.gte !== void 0 && { gte: range.gte }, ...range.lt !== void 0 && { lt: range.lt } }));
924
+ return ranges.length < 2 ? void 0 : parallel.scan(head, ranges, batchSize, maxBatchBytes);
925
+ }
926
+ /**
927
+ * Cut this snapshot into at most parts contiguous key ranges of near-equal size, for scans in parallel. The ranges
928
+ * cover every key in order without overlap, and each count is exact. Other workers scan them through
929
+ * beginRead({ at: session.head }) on handles of their own.
930
+ */
931
+ split(parts, range = {}) {
932
+ common.natural(parts, "parts", 1);
933
+ if (range.gte !== void 0) common.key(range.gte);
934
+ if (range.lt !== void 0) common.key(range.lt);
935
+ return this.work(() => split((ref) => this.db.load(this.head, ref), this.head.root, this.head.count, parts, range.gte, range.lt));
936
+ }
629
937
  /** Drain admitted reads before releasing the generation pin used by garbage collection. */
630
938
  close() {
631
939
  if (this.closing) return this.closing;
632
940
  this.closed = true;
633
941
  this.closing = (async () => {
634
942
  await Promise.allSettled(this.pending);
943
+ await Promise.allSettled([...this.scans].map((scan) => scan.close()));
635
944
  await this.release();
636
945
  this.db.forget(this);
637
946
  })();
@@ -639,15 +948,6 @@ class ReadSession {
639
948
  }
640
949
  }
641
950
  class Dbsonl {
642
- constructor(backend, name, options, closeBackend) {
643
- this.backend = backend;
644
- this.name = name;
645
- this.closeBackend = closeBackend;
646
- this.limits = common.options(options);
647
- }
648
- backend;
649
- name;
650
- closeBackend;
651
951
  closed = false;
652
952
  closing;
653
953
  pending = /* @__PURE__ */ new Set();
@@ -671,6 +971,21 @@ class Dbsonl {
671
971
  arrival;
672
972
  /** Wall time of the last group publication in ms, which bounds gather(). */
673
973
  groupCost = 0;
974
+ /** Format 3: the generation end of this handle's last flushed head slot; see HEAD_FLUSH_BYTES. */
975
+ headFlushed = 0;
976
+ /** The backend's scan workers, bound to this database's name and decoder budgets. */
977
+ scanner;
978
+ backend;
979
+ name;
980
+ closeBackend;
981
+ constructor(backend, name, options, closeBackend) {
982
+ this.backend = backend;
983
+ this.name = name;
984
+ this.closeBackend = closeBackend;
985
+ this.limits = common.options(options);
986
+ const parallel = backend.parallel, { maxRecordBytes, maxCacheBytes, maxCachePages } = this.limits;
987
+ this.scanner = parallel && { workers: parallel.workers, threshold: parallel.threshold, scan: (head, ranges, batchSize, maxBatchBytes) => parallel.scan({ name, head, ranges, batchSize, maxBatchBytes, limits: { maxRecordBytes, maxCacheBytes, maxCachePages } }) };
988
+ }
674
989
  run(fn) {
675
990
  if (this.closed) return Promise.reject(new common.DbsonlError("CLOSED", "Database is closed."));
676
991
  if (this.pending.size >= this.limits.maxPendingOperations) return Promise.reject(new common.DbsonlError("QUEUE_FULL", "Too many admitted operations."));
@@ -739,15 +1054,41 @@ class Dbsonl {
739
1054
  return release;
740
1055
  }
741
1056
  session(head, release) {
742
- const session = new ReadSession({ load: (head2, ref) => this.load(head2, ref), value: (head2, ref, window) => this.value(head2, ref, window), forget: (session2) => {
1057
+ const session = new ReadSession({ load: (head2, ref) => this.load(head2, ref), value: (head2, ref, window) => this.value(head2, ref, window), cachedValue: (head2, ref, window) => readCachedValue(head2, ref, this.limits.maxRecordBytes, window), cachedValues: (entries2, start, end, window) => readCachedValues(entries2, start, end, this.limits.maxRecordBytes, window), forget: (session2) => {
743
1058
  this.sessions.delete(session2);
744
- } }, Object.freeze(head), release);
1059
+ }, parallel: this.scanner }, Object.freeze(head), release);
745
1060
  this.sessions.add(session);
746
1061
  return session;
747
1062
  }
748
- /** Pin the currently published root; subsequent writers do not wait for its lifetime. */
749
- beginRead() {
750
- return this.run(() => this.snapshot());
1063
+ /**
1064
+ * Pin the currently published root; subsequent writers do not wait for its lifetime. With at, pin the head of a
1065
+ * snapshot that is still open on any handle, worker or process of this database, so parallel scans read one root.
1066
+ */
1067
+ beginRead(options = {}) {
1068
+ if (options.at === void 0) return this.run(() => this.snapshot());
1069
+ let head;
1070
+ try {
1071
+ const at = options.at, root = at.root && { offset: at.root.offset, byteLength: at.root.byteLength };
1072
+ head = checkHead({ dbsonl: at.dbsonl, publication: at.publication, revision: at.revision, generation: at.generation, root, count: at.count, end: at.end, ...at.seal !== void 0 && { seal: at.seal } });
1073
+ } catch (cause) {
1074
+ throw new TypeError("options.at must be the head of a snapshot of this database.", { cause });
1075
+ }
1076
+ return this.run(() => backend.locked(this.backend, `commit-${this.name}`, async () => {
1077
+ const current = await readHead(this.backend, this.name, this.headCache);
1078
+ if (head.generation === current.generation) {
1079
+ if (head.end > current.end || head.publication > current.publication) throw new TypeError("options.at is newer than the published head.");
1080
+ } else {
1081
+ let size;
1082
+ try {
1083
+ size = await backend.withFile(this.backend, generationFile(this.name, head.generation), { readOnly: true }, (file) => file.size());
1084
+ } catch (cause) {
1085
+ if (code(cause) === "NOT_FOUND") throw new common.DbsonlError("CONFLICT", "The snapshot was collected; begin a new read.", { cause });
1086
+ throw cause;
1087
+ }
1088
+ if (size < head.end) common.corrupt("Committed generation is truncated.");
1089
+ }
1090
+ return this.session(head, await this.pin(head));
1091
+ }, void 0, true));
751
1092
  }
752
1093
  /** Internal lookup only: callers must hold a commit lock or generation pin. */
753
1094
  async lookup(head, id) {
@@ -781,14 +1122,16 @@ class Dbsonl {
781
1122
  encode(input) {
782
1123
  if (!Array.isArray(input) || input.length > this.limits.maxTransactionOperations) throw new common.DbsonlError("LIMIT_EXCEEDED", "Transaction operation capacity exceeded.");
783
1124
  let bytes = 0;
784
- return input.map((operation) => {
1125
+ const encoded = input.map((operation) => {
785
1126
  common.key(operation.key);
786
1127
  if (operation.operation !== "put" && operation.operation !== "delete") throw new TypeError("Unknown mutation operation.");
787
- const encoded = operation.operation === "put" ? sequence.encodeFrame(operation.value, { maxRecordBytes: this.limits.maxRecordBytes }) : void 0;
788
- bytes += (encoded?.length ?? 0) + operation.key.length * 2 + 64;
1128
+ const encoded2 = operation.operation === "put" ? sequence.encodeFrame(operation.value, { maxRecordBytes: this.limits.maxRecordBytes }) : void 0;
1129
+ bytes += (encoded2?.length ?? 0) + operation.key.length * 2 + 64;
789
1130
  if (bytes > this.limits.maxTransactionBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "Transaction encoded-byte capacity exceeded.");
790
- return { key: operation.key, bytes: encoded };
1131
+ return { key: operation.key, bytes: encoded2 };
791
1132
  });
1133
+ batchSizes.set(encoded, bytes);
1134
+ return encoded;
792
1135
  }
793
1136
  /**
794
1137
  * Queue a commit. The next holder of the commit lock publishes every queued commit with one write,
@@ -934,7 +1277,11 @@ class Dbsonl {
934
1277
  const next = await backend.withFile(this.backend, generationFile(this.name, head.generation), {}, async (file) => {
935
1278
  const size = await file.size();
936
1279
  if (size < head.end) common.corrupt("Committed generation is truncated.");
937
- if (size > head.end) await file.truncate(head.end);
1280
+ if (size > head.end) {
1281
+ const found = await recoverTail(file, head, size);
1282
+ if (found) throw new Recovered(found);
1283
+ await file.truncate(head.end);
1284
+ }
938
1285
  const writer = new Appender(file, head.end, this.limits, this.backend.writeChunkBytes);
939
1286
  const tree = new BatchTree(writer, head.root, head.count, this.limits.maxTransactionBytes, (ref) => this.cached(pageId(head, ref)));
940
1287
  const counts = [];
@@ -952,13 +1299,21 @@ class Dbsonl {
952
1299
  counts.push(tree.size);
953
1300
  }
954
1301
  const { root, count } = await tree.finish();
1302
+ const published = { ...head, publication: common.natural(head.publication + 1, "publication"), revision, root, count, end: writer.end };
1303
+ if (head.dbsonl === 3) {
1304
+ const ref = writer.bytes(commitRecord(published, writer.end, head.end));
1305
+ if (ref instanceof Promise) await ref;
1306
+ published.end = writer.end;
1307
+ }
955
1308
  await writer.flush();
956
1309
  await file.flush();
957
- return { head: { ...head, publication: common.natural(head.publication + 1, "publication"), revision, root, count, end: writer.end }, written: tree.written, counts };
1310
+ return { head: published, written: tree.written, counts };
958
1311
  });
959
1312
  publishing = true;
1313
+ const flush = !(next.head.dbsonl === 3 && this.backend.coherent) || next.head.end - this.headFlushed >= HEAD_FLUSH_BYTES;
960
1314
  try {
961
- await publish(this.backend, this.name, next.head, this.headCache);
1315
+ await publish(this.backend, this.name, next.head, this.headCache, flush);
1316
+ if (flush) this.headFlushed = next.head.end;
962
1317
  } catch (cause) {
963
1318
  this.lockedHead = void 0;
964
1319
  throw new common.DbsonlError("COMMIT_UNCERTAIN", "Head publication failed; read the current revision before retrying.", { cause });
@@ -967,6 +1322,17 @@ class Dbsonl {
967
1322
  for (const { ref, page } of next.written) this.remember(pageId(next.head, ref), page, ref.byteLength);
968
1323
  accepted.forEach(({ member, revision: revision2 }, index) => member.resolve({ revision: revision2, count: next.counts[index] }));
969
1324
  } catch (error) {
1325
+ if (error instanceof Recovered) {
1326
+ try {
1327
+ await publish(this.backend, this.name, error.head, this.headCache);
1328
+ this.headFlushed = error.head.end;
1329
+ } catch (cause) {
1330
+ const error2 = new common.DbsonlError("COMMIT_UNCERTAIN", "Publishing recovered commits failed; read the current revision before retrying.", { cause });
1331
+ for (const member of group) if (!member.done) member.reject(error2);
1332
+ return;
1333
+ }
1334
+ return this.publishGroup(group.filter((member) => !member.done));
1335
+ }
970
1336
  if (!publishing && group.length > 1) {
971
1337
  for (const member of group) if (!member.done) await this.publishGroup([member]);
972
1338
  return;
@@ -974,6 +1340,23 @@ class Dbsonl {
974
1340
  for (const member of group) if (!member.done) member.reject(error);
975
1341
  }
976
1342
  }
1343
+ /** Under the commit lock: the published head, after adopting format 3 commits whose head slot did not reach the disk. */
1344
+ async settledHead() {
1345
+ const head = await readHead(this.backend, this.name, this.headCache);
1346
+ if (head.dbsonl !== 3) return head;
1347
+ const found = await backend.withFile(this.backend, generationFile(this.name, head.generation), { readOnly: true }, async (file) => {
1348
+ const size = await file.size();
1349
+ return size > head.end ? recoverTail(file, head, size) : void 0;
1350
+ });
1351
+ if (!found) return head;
1352
+ try {
1353
+ await publish(this.backend, this.name, found, this.headCache);
1354
+ this.headFlushed = found.end;
1355
+ } catch (cause) {
1356
+ throw new common.DbsonlError("COMMIT_UNCERTAIN", "Publishing recovered commits failed; read the current revision before retrying.", { cause });
1357
+ }
1358
+ return found;
1359
+ }
977
1360
  /** Each point read must still see the entry revision it saw, or absence (0); a scan needs the whole database unchanged. */
978
1361
  async validate(head, reads, written) {
979
1362
  if (reads.whole) throw new common.DbsonlError("CONFLICT", "Database changed since the transaction snapshot.");
@@ -1169,7 +1552,7 @@ class Dbsonl {
1169
1552
  const generation = newGeneration();
1170
1553
  const filename = generationFile(this.name, generation);
1171
1554
  const prepare = async () => {
1172
- head = await readHead(this.backend, this.name, this.headCache);
1555
+ head = await this.settledHead();
1173
1556
  sourcePin = await this.backend.coordinator.acquire(`pin-${generationFile(this.name, head.generation)}`, true);
1174
1557
  pin = await this.backend.coordinator.acquire(`pin-${filename}`, true);
1175
1558
  };
@@ -1191,7 +1574,7 @@ class Dbsonl {
1191
1574
  if (packed.count !== head.count) common.corrupt("Compaction key count disagrees with manifest.");
1192
1575
  await writer.flush();
1193
1576
  await file.flush();
1194
- return { ...head, ...packed, generation, end: writer.end, publication: common.natural(head.publication + 1, "publication") };
1577
+ return { ...head, ...packed, generation, end: writer.end, publication: common.natural(head.publication + 1, "publication"), ...head.dbsonl === 3 && { seal: newGeneration() } };
1195
1578
  });
1196
1579
  await this.backend.coordinator.syncDirectory();
1197
1580
  const install = async () => {
@@ -1218,7 +1601,7 @@ class Dbsonl {
1218
1601
  /** Reclaim unreferenced generations only after every process has released its pin. */
1219
1602
  collect() {
1220
1603
  return this.run(() => backend.locked(this.backend, `commit-${this.name}`, async () => {
1221
- const head = await readHead(this.backend, this.name, this.headCache);
1604
+ const head = await this.settledHead();
1222
1605
  await publish(this.backend, this.name, { ...head, publication: common.natural(head.publication + 1, "publication") }, this.headCache);
1223
1606
  const current = generationFile(this.name, head.generation);
1224
1607
  const removed = [], retained = [];
@@ -1288,13 +1671,17 @@ async function openDbsonl(backend$1, name, options = {}) {
1288
1671
  await backend.withFile(backend$1, generationFile(name, generation), { create: true, exclusive: true }, (file) => file.flush());
1289
1672
  if (missing) await backend.withFile(backend$1, headFile(name), { create: true, exclusive: true }, (file) => file.flush());
1290
1673
  await backend$1.coordinator.syncDirectory();
1291
- head = { dbsonl: 2, publication: 1, revision: 0, generation, root: null, count: 0, end: 0 };
1674
+ head = { dbsonl: 3, publication: 1, revision: 0, generation, root: null, count: 0, end: 0, seal: newGeneration() };
1292
1675
  await publish(backend$1, name, head);
1293
1676
  await publish(backend$1, name, { ...head, publication: 2 });
1294
1677
  }
1295
- await backend.withFile(backend$1, generationFile(name, head.generation), { readOnly: true }, async (file) => {
1296
- if (await file.size() < head.end) common.corrupt("Committed generation is truncated.");
1678
+ const opened = head;
1679
+ const found = await backend.withFile(backend$1, generationFile(name, opened.generation), { readOnly: true }, async (file) => {
1680
+ const size = await file.size();
1681
+ if (size < opened.end) common.corrupt("Committed generation is truncated.");
1682
+ return size > opened.end ? recoverTail(file, opened, size) : void 0;
1297
1683
  });
1684
+ if (found) await publish(backend$1, name, found);
1298
1685
  }, options.signal);
1299
1686
  return new Dbsonl(backend$1, name, options, connection?.close);
1300
1687
  } catch (error) {