defuss-dbsonl 0.7.0 → 0.9.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
@@ -149,6 +149,102 @@ function encodePage(page, maxRecordBytes) {
149
149
  values.fill(void 0, 0, used);
150
150
  }
151
151
  }
152
+ const LEAF = 1, BRANCH = 2, CHANGES = 3;
153
+ const MAX_ITEMS = 32, MAX_KEY_UNITS = 4096;
154
+ let scratch = new Uint8Array(8192);
155
+ function encodeCompactPage(page) {
156
+ return encodeItems(page.kind === "leaf" ? LEAF : BRANCH, page.kind === "leaf" ? page.entries : page.children);
157
+ }
158
+ function encodeChanges(entries) {
159
+ return encodeItems(CHANGES, entries);
160
+ }
161
+ function encodeItems(kind, items) {
162
+ const leaf = kind !== BRANCH;
163
+ let need = 16;
164
+ for (const item of items) need += (leaf ? item.key : item.max).length * 2 + 40;
165
+ if (scratch.length < need) scratch = new Uint8Array(need * 2);
166
+ const out = scratch;
167
+ let p = 0, previous = "";
168
+ const varint = (value) => {
169
+ while (value >= 128) {
170
+ out[p++] = value % 128 | 128;
171
+ value = Math.floor(value / 128);
172
+ }
173
+ out[p++] = value;
174
+ };
175
+ out[p++] = kind;
176
+ varint(items.length);
177
+ for (const item of items) {
178
+ const text = leaf ? item.key : item.max, limit = Math.min(previous.length, text.length);
179
+ let shared = 0;
180
+ while (shared < limit && previous.charCodeAt(shared) === text.charCodeAt(shared)) shared++;
181
+ let wide = 0;
182
+ for (let i = shared; i < text.length; i++) if (text.charCodeAt(i) > 255) {
183
+ wide = 1;
184
+ break;
185
+ }
186
+ varint(shared);
187
+ varint((text.length - shared) * 2 + wide);
188
+ if (wide) for (let i = shared; i < text.length; i++) {
189
+ const code = text.charCodeAt(i);
190
+ out[p++] = code & 255;
191
+ out[p++] = code >>> 8;
192
+ }
193
+ else for (let i = shared; i < text.length; i++) out[p++] = text.charCodeAt(i);
194
+ previous = text;
195
+ varint(item.ref.offset);
196
+ varint(item.ref.byteLength);
197
+ varint(leaf ? item.revision : item.count);
198
+ }
199
+ return out.slice(0, p);
200
+ }
201
+ function decodeCompactPage(bytes) {
202
+ const { kind, items } = decodeItems(bytes, MAX_ITEMS);
203
+ if (kind === CHANGES) common.corrupt("Invalid compact index page kind.");
204
+ return kind === LEAF ? { kind: "leaf", entries: items } : { kind: "branch", children: items };
205
+ }
206
+ function decodeChanges(bytes, maxItems) {
207
+ const { kind, items } = decodeItems(bytes, maxItems);
208
+ if (kind !== CHANGES) common.corrupt("Invalid commit change list.");
209
+ for (let i = 1; i < items.length; i++) if (items[i - 1].key >= items[i].key) common.corrupt("Commit change keys are not strictly ordered.");
210
+ return items;
211
+ }
212
+ function decodeItems(bytes, maxItems) {
213
+ let p = 0;
214
+ const varint = () => {
215
+ let value = 0, scale = 1;
216
+ for (let i = 0; i < 8; i++) {
217
+ if (p >= bytes.length) common.corrupt("Truncated compact index page.");
218
+ const byte = bytes[p++];
219
+ value += (byte & 127) * scale;
220
+ if (byte < 128) return Number.isSafeInteger(value) ? value : common.corrupt("Compact index page number out of range.");
221
+ scale *= 128;
222
+ }
223
+ return common.corrupt("Compact index page number out of range.");
224
+ };
225
+ const kind = bytes[p++];
226
+ if (kind !== LEAF && kind !== BRANCH && kind !== CHANGES) common.corrupt("Invalid compact index page kind.");
227
+ const count = varint();
228
+ if (count < 1 || count > maxItems) common.corrupt("Invalid index fanout.");
229
+ const items = [];
230
+ let previous = "";
231
+ for (let i = 0; i < count; i++) {
232
+ const shared = varint(), header = varint(), units = Math.floor(header / 2), wide = header % 2;
233
+ if (shared > previous.length || shared + units > MAX_KEY_UNITS) common.corrupt("Invalid compact index key.");
234
+ const end = p + units * (wide + 1);
235
+ if (end > bytes.length) common.corrupt("Truncated compact index page.");
236
+ let suffix = "";
237
+ if (wide) for (let j = p; j < end; j += 2) suffix += String.fromCharCode(bytes[j] | bytes[j + 1] << 8);
238
+ else suffix = String.fromCharCode.apply(null, bytes.subarray(p, end));
239
+ p = end;
240
+ const text = shared ? previous.slice(0, shared) + suffix : suffix;
241
+ previous = text;
242
+ const ref = { offset: varint(), byteLength: varint() }, last = varint();
243
+ items.push(kind === BRANCH ? { max: text, ref, count: last } : { key: text, ref, revision: last });
244
+ }
245
+ if (p !== bytes.length) common.corrupt("Trailing bytes after a compact index page.");
246
+ return { kind, items };
247
+ }
152
248
 
153
249
  const SLOT_BYTES = 4096;
154
250
  const generationFile = (name, generation) => `${name}.g-${generation}.dsq`;
@@ -175,13 +271,23 @@ function equalBytes(a, b) {
175
271
  }
176
272
  function checkHead(value) {
177
273
  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.");
274
+ if (!h || h.dbsonl !== 2 && h.dbsonl !== 3 && h.dbsonl !== 4 && h.dbsonl !== 5) throw new common.DbsonlError("UNSUPPORTED", "Unsupported database manifest version.");
275
+ 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
276
  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
277
  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.");
278
+ if (h.dbsonl === 5) {
279
+ if (!Number.isSafeInteger(h.log) || h.log < 0 || h.log > h.end || h.last === void 0) common.corrupt("Invalid manifest log.");
280
+ if (h.last !== null) {
281
+ common.reference(h.last, h.end);
282
+ if (h.last.offset < h.log) common.corrupt("Invalid manifest log.");
283
+ }
284
+ } else if (h.log !== void 0 || h.last !== void 0) common.corrupt("Invalid manifest fields.");
285
+ if ((h.dbsonl !== 5 || h.last === null) && h.root === null !== (h.count === 0)) common.corrupt("Empty root and count disagree.");
183
286
  return h;
184
287
  }
288
+ function sameRef(a, b) {
289
+ return a === b || !!a && !!b && a.offset === b.offset && a.byteLength === b.byteLength;
290
+ }
185
291
  async function readHead(backend$1, name, cache) {
186
292
  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) => {
187
293
  const size2 = await file.size();
@@ -232,26 +338,16 @@ async function publish(backend$1, name, head, cache, flush = true) {
232
338
  cache.head = head;
233
339
  }
234
340
  }
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
341
  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;
342
+ return checksum(bytes, 0, bytes.length);
248
343
  }
249
344
  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 });
345
+ function commitRecord(head, offset, prev, changes = null) {
346
+ const record = { dbsonl: head.dbsonl, seal: head.seal, publication: head.publication, revision: head.revision, root: head.root, count: head.count, offset, prev, ...head.dbsonl === 5 && { log: changes ? head.log : null, changes, previous: changes ? head.last : null } };
347
+ return sequence.encodeFrame(record, { maxRecordBytes: RECORD_BYTES - 16, trusted: true });
252
348
  }
253
349
  async function recoverTail(file, head, size) {
254
- if (head.dbsonl !== 3) return void 0;
350
+ if (head.dbsonl < 3) return void 0;
255
351
  let position = head.end, prev = head.end, found;
256
352
  while (position + sequence.FRAME_HEADER_BYTES <= size) {
257
353
  let frame;
@@ -275,10 +371,12 @@ async function recoverTail(file, head, size) {
275
371
  break;
276
372
  }
277
373
  const record = value;
278
- if (record && typeof record === "object" && record.dbsonl === 3 && record.seal === head.seal && record.offset === position && record.prev === prev) {
374
+ if (record && typeof record === "object" && record.dbsonl === head.dbsonl && record.seal === head.seal && record.offset === position && record.prev === prev) {
279
375
  let next;
376
+ const before = found ?? head, self = { offset: position, byteLength: length };
377
+ if (head.dbsonl === 5 && record.changes && (!sameRef(record.root, before.root) || record.log !== before.log || !sameRef(record.previous, before.last))) break;
280
378
  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 });
379
+ next = checkHead({ dbsonl: head.dbsonl, seal: head.seal, publication: record.publication, revision: record.revision, generation: head.generation, root: record.root, count: record.count, end: position + length, ...head.dbsonl === 5 && (record.changes ? { log: before.log, last: self } : { log: position + length, last: null }) });
282
380
  } catch {
283
381
  break;
284
382
  }
@@ -291,7 +389,65 @@ async function recoverTail(file, head, size) {
291
389
  return found;
292
390
  }
293
391
  const PAGE_BYTES = 512 * 1024;
294
- async function readValue(backend$1, name, head, ref, maxRecordBytes, window) {
392
+ async function readRecord(backend, name, head, ref) {
393
+ common.reference(ref, head.end);
394
+ if (ref.byteLength > RECORD_BYTES) common.corrupt("Commit record exceeds its budget.");
395
+ const record = decodeRef(await readGeneration(backend, name, head, ref.offset, ref.byteLength), ref, RECORD_BYTES);
396
+ if (!record || typeof record !== "object" || record.dbsonl !== 5 || record.seal !== head.seal || record.offset !== ref.offset || record.log !== head.log || !sameRef(record.root, head.root) || !record.changes) common.corrupt("Invalid commit record in the log.");
397
+ const { changes, previous = null } = record;
398
+ common.reference(changes, ref.offset);
399
+ if (changes.offset < head.log || previous && (common.reference(previous, ref.offset), previous.offset < head.log)) common.corrupt("Commit record points outside its log.");
400
+ if (!Number.isSafeInteger(record.revision) || !Number.isSafeInteger(record.count) || record.count < 0) common.corrupt("Invalid commit record fields.");
401
+ return { offset: ref.offset, revision: record.revision, count: record.count, changes, previous };
402
+ }
403
+ async function readChanges(backend, name, head, ref, maxRecordBytes) {
404
+ const bytes = await readValue(backend, name, head, ref, maxRecordBytes);
405
+ if (!(bytes instanceof Uint8Array)) common.corrupt("Invalid commit change list.");
406
+ return decodeChanges(bytes, bytes.length);
407
+ }
408
+ function readGeneration(backend$1, name, head, offset, length) {
409
+ const filename = generationFile(name, head.generation);
410
+ return backend$1.read ? backend$1.read(filename, offset, length) : (
411
+ // Portable handles read the same bounded window, so a scan opens the file once per window, not per row.
412
+ backend.withFile(backend$1, filename, { readOnly: true }, (file) => readExact(file, offset, length))
413
+ );
414
+ }
415
+ const COPY_GAP_BYTES = 16 * 1024;
416
+ const COPY_RUN_BYTES = 1024 * 1024;
417
+ async function readFrames(backend, name, head, refs, maxRecordBytes) {
418
+ for (const ref of refs) {
419
+ common.reference(ref, head.end);
420
+ if (ref.byteLength - 16 > maxRecordBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "Referenced record exceeds the decoder budget.");
421
+ }
422
+ const order = refs.map((_, i) => i).sort((a, b) => refs[a].offset - refs[b].offset);
423
+ const runs = [];
424
+ for (const i of order) {
425
+ const { offset, byteLength } = refs[i], run = runs[runs.length - 1];
426
+ if (run && offset - run.end <= COPY_GAP_BYTES && offset + byteLength - run.offset <= COPY_RUN_BYTES) {
427
+ run.end = Math.max(run.end, offset + byteLength);
428
+ run.members.push(i);
429
+ } else runs.push({ offset, end: offset + byteLength, members: [i] });
430
+ }
431
+ const frames = Array.from({ length: refs.length });
432
+ for (const run of runs) {
433
+ const data = await readGeneration(backend, name, head, run.offset, run.end - run.offset);
434
+ for (const i of run.members) frames[i] = checkedFrame(data.subarray(refs[i].offset - run.offset, refs[i].offset - run.offset + refs[i].byteLength), refs[i], maxRecordBytes);
435
+ }
436
+ return frames;
437
+ }
438
+ function checkedFrame(bytes, ref, maxRecordBytes) {
439
+ if (bytes.length !== ref.byteLength) common.corrupt("Committed record is truncated.");
440
+ let frame;
441
+ try {
442
+ frame = sequence.inspectFrame(bytes, 0, { maxRecordBytes });
443
+ } catch (cause) {
444
+ throw new common.DbsonlError(cause instanceof RangeError ? "LIMIT_EXCEEDED" : "CORRUPT", "DSON record header is invalid.", { cause });
445
+ }
446
+ if (frame.byteLength !== ref.byteLength) common.corrupt("Record reference length does not match its frame.");
447
+ if (checksum(bytes, frame.payloadOffset, frame.payloadOffset + frame.payloadLength) !== frame.checksum) common.corrupt("DSON record payload checksum mismatch.");
448
+ return bytes;
449
+ }
450
+ async function readValue(backend, name, head, ref, maxRecordBytes, window) {
295
451
  common.reference(ref, head.end);
296
452
  if (ref.byteLength - 16 > maxRecordBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "Referenced record exceeds the decoder budget.");
297
453
  let bytes;
@@ -299,11 +455,7 @@ async function readValue(backend$1, name, head, ref, maxRecordBytes, window) {
299
455
  bytes = window.bytes.subarray(ref.offset - window.offset, ref.offset - window.offset + ref.byteLength);
300
456
  } else {
301
457
  const length = window && ref.byteLength <= 65536 ? Math.min(65536, head.end - ref.offset) : ref.byteLength;
302
- const filename = generationFile(name, head.generation);
303
- const data = backend$1.read ? await backend$1.read(filename, ref.offset, length) : (
304
- // Portable handles read the same bounded window, so a scan opens the file once per window, not per row.
305
- await backend.withFile(backend$1, filename, { readOnly: true }, (file) => readExact(file, ref.offset, length))
306
- );
458
+ const data = await readGeneration(backend, name, head, ref.offset, length);
307
459
  if (window) {
308
460
  window.offset = ref.offset;
309
461
  window.bytes = length <= 65536 ? data : new Uint8Array(0);
@@ -353,10 +505,13 @@ class Appender {
353
505
  file;
354
506
  limits;
355
507
  chunkSize;
356
- constructor(file, end, limits, chunkSize) {
508
+ /** Format 4: index pages use the compact encoding. */
509
+ compact;
510
+ constructor(file, end, limits, chunkSize, compact = false) {
357
511
  this.file = file;
358
512
  this.limits = limits;
359
513
  this.chunkSize = chunkSize;
514
+ this.compact = compact;
360
515
  this.end = end;
361
516
  this.flushedEnd = end;
362
517
  this.buffer = new Uint8Array(Math.min(chunkSize, 65536));
@@ -393,7 +548,8 @@ class Appender {
393
548
  return ref;
394
549
  }
395
550
  async value(value, page = false) {
396
- return this.bytes(page ? encodePage(value, PAGE_BYTES) : sequence.encodeFrame(value, { maxRecordBytes: this.limits.maxRecordBytes }));
551
+ if (!page) return this.bytes(sequence.encodeFrame(value, { maxRecordBytes: this.limits.maxRecordBytes }));
552
+ return this.bytes(this.compact ? sequence.encodeFrame(encodeCompactPage(value), { maxRecordBytes: PAGE_BYTES, trusted: true }) : encodePage(value, PAGE_BYTES));
397
553
  }
398
554
  /** Committed pages only: the writer's own handle is exclusive, so it cannot reopen the file. */
399
555
  async read(ref) {
@@ -426,6 +582,10 @@ function validatePage(value, ref) {
426
582
  }
427
583
  return page;
428
584
  }
585
+ function toPage(value, ref, compact) {
586
+ if (compact !== value instanceof Uint8Array) common.corrupt("Index page encoding does not match the database format.");
587
+ return validatePage(compact ? decodeCompactPage(value) : value, ref);
588
+ }
429
589
  async function save(writer, page) {
430
590
  const ref = await writer.value(page, true);
431
591
  const max = page.kind === "leaf" ? page.entries.at(-1).key : page.children.at(-1).max;
@@ -492,6 +652,9 @@ async function* entryPages(load, root, gte, lt, depth = 0) {
492
652
  }
493
653
  }
494
654
  }
655
+ function isMemoryPage(link) {
656
+ return !!link && typeof link === "object" && "kind" in link;
657
+ }
495
658
  class BatchTree {
496
659
  root;
497
660
  count;
@@ -502,27 +665,57 @@ class BatchTree {
502
665
  }
503
666
  /** Pages this batch appended, for the caller to cache once the root is published. */
504
667
  written = [];
505
- /** cached returns an already validated committed page, or undefined to read it through the writer. */
668
+ /** cached returns an already validated committed page, or undefined to read it through the writer or load. */
506
669
  writer;
507
670
  byteBudget;
508
671
  cached;
509
- constructor(writer, root, count, byteBudget, cached = () => void 0) {
672
+ /** Format 5 replay has no writer: it reads committed pages through the store. */
673
+ load;
674
+ constructor(writer, root, count, byteBudget, cached = () => void 0, load) {
510
675
  this.writer = writer;
511
676
  this.byteBudget = byteBudget;
512
677
  this.cached = cached;
513
678
  this.root = root;
514
679
  this.count = count;
680
+ this.load = load;
681
+ }
682
+ /**
683
+ * Pages this batch created or copied. A page held in memory since an earlier commit may be read by a snapshot of
684
+ * that commit, so this batch copies it before editing, as it copies committed pages.
685
+ */
686
+ mine = /* @__PURE__ */ new WeakSet();
687
+ /**
688
+ * Format 5: how many more pages the tree holds in memory than before this batch: copies of written pages and pages
689
+ * new from splits, less pages that emptied or collapsed. A copy of an in-memory page replaces it and counts nothing.
690
+ */
691
+ memoryPages = 0;
692
+ /** Format 5: the new root without writing its pages; a later checkpoint's finish() writes them. */
693
+ open() {
694
+ return { root: this.root, count: this.count };
515
695
  }
516
696
  /** Committed pages on the next edit's path, found by missing(); each becomes a dirty copy in editable(). */
517
697
  fetched = /* @__PURE__ */ new Map();
518
698
  editable(link) {
519
- if (!link) return { kind: "leaf", entries: [] };
520
- if ("kind" in link) return link;
699
+ if (!link) {
700
+ const page2 = { kind: "leaf", entries: [] };
701
+ this.mine.add(page2);
702
+ this.memoryPages++;
703
+ return page2;
704
+ }
705
+ if ("kind" in link) {
706
+ if (this.mine.has(link)) return link;
707
+ const copy2 = link.kind === "leaf" ? { kind: "leaf", entries: link.entries.slice() } : { kind: "branch", children: link.children.slice() };
708
+ this.mine.add(copy2);
709
+ return copy2;
710
+ }
521
711
  if (this.loadedBytes + link.byteLength > this.byteBudget) throw new common.DbsonlError("LIMIT_EXCEEDED", "Dirty index paths exceed the transaction byte budget.");
522
712
  this.loadedBytes += link.byteLength;
523
713
  const page = this.fetched.get(link);
524
714
  this.fetched.delete(link);
525
- return page.kind === "leaf" ? { kind: "leaf", entries: page.entries.slice() } : { kind: "branch", children: page.children.slice() };
715
+ const copy = page.kind === "leaf" ? { kind: "leaf", entries: page.entries.slice() } : { kind: "branch", children: page.children.slice() };
716
+ this.mine.add(copy);
717
+ this.memoryPages++;
718
+ return copy;
526
719
  }
527
720
  /** Collect the committed pages on key's path; return the first one that needs a read, if any. */
528
721
  missing(key2) {
@@ -543,6 +736,7 @@ class BatchTree {
543
736
  return void 0;
544
737
  }
545
738
  route(page) {
739
+ this.mine.add(page);
546
740
  const max = page.kind === "leaf" ? page.entries.at(-1).key : page.children.at(-1).max;
547
741
  const count = page.kind === "leaf" ? page.entries.length : page.children.reduce((sum, item) => sum + item.count, 0);
548
742
  common.natural(count, "key count");
@@ -558,8 +752,10 @@ class BatchTree {
558
752
  this.edit(key2, entry);
559
753
  return;
560
754
  }
561
- return this.writer.read(ref).then((value) => {
562
- this.fetched.set(ref, validatePage(value, ref));
755
+ const writer = this.writer;
756
+ const page = this.load ? Promise.resolve(this.load(ref)) : writer.read(ref).then((value) => toPage(value, ref, writer.compact));
757
+ return page.then((page2) => {
758
+ this.fetched.set(ref, page2);
563
759
  return this.apply(key2, entry);
564
760
  });
565
761
  }
@@ -571,17 +767,25 @@ class BatchTree {
571
767
  const at = lower(page.entries, key2, (item) => item.key), exists = page.entries[at]?.key === key2;
572
768
  if (entry) page.entries.splice(at, exists ? 1 : 0, entry);
573
769
  else if (exists) page.entries.splice(at, 1);
574
- if (!page.entries.length) return [];
770
+ if (!page.entries.length) {
771
+ this.memoryPages--;
772
+ return [];
773
+ }
575
774
  if (page.entries.length > FANOUT) {
576
775
  const right = page.entries.splice(Math.ceil(page.entries.length / 2));
776
+ this.memoryPages++;
577
777
  return [this.route(page), this.route({ kind: "leaf", entries: right })];
578
778
  }
579
779
  } else {
580
780
  const at = Math.min(page.children.length - 1, lower(page.children, key2, (item) => item.max));
581
781
  page.children.splice(at, 1, ...edit(page.children[at].ref, depth + 1));
582
- if (!page.children.length) return [];
782
+ if (!page.children.length) {
783
+ this.memoryPages--;
784
+ return [];
785
+ }
583
786
  if (page.children.length > FANOUT) {
584
787
  const right = page.children.splice(Math.ceil(page.children.length / 2));
788
+ this.memoryPages++;
585
789
  return [this.route(page), this.route({ kind: "branch", children: right })];
586
790
  }
587
791
  }
@@ -593,10 +797,14 @@ class BatchTree {
593
797
  this.count = 0;
594
798
  return;
595
799
  }
800
+ if (changed.length > 1) this.memoryPages++;
596
801
  const result = changed.length === 1 ? changed[0] : this.route({ kind: "branch", children: changed });
597
802
  this.root = result.ref;
598
803
  this.count = result.count;
599
- while (this.root && "kind" in this.root && this.root.kind === "branch" && this.root.children.length === 1) this.root = this.root.children[0].ref;
804
+ while (this.root && "kind" in this.root && this.root.kind === "branch" && this.root.children.length === 1) {
805
+ this.root = this.root.children[0].ref;
806
+ this.memoryPages--;
807
+ }
600
808
  }
601
809
  /** Children flush first, preserving backward-only references without an in-place page write. */
602
810
  async finish() {
@@ -738,6 +946,9 @@ class BulkTree {
738
946
 
739
947
  const GROUP_MEMBERS = 64;
740
948
  const HEAD_FLUSH_BYTES = 16 * 1024 * 1024;
949
+ const LOW_WATER = 0.9;
950
+ const CHECKPOINT_BYTES = 16 * 1024 * 1024;
951
+ const COPY_BYTES = 4 * 1024 * 1024;
741
952
  class Recovered {
742
953
  head;
743
954
  constructor(head) {
@@ -769,11 +980,14 @@ class ReadSession {
769
980
  head;
770
981
  db;
771
982
  release;
983
+ /** The root of the whole state: head.root, or in format 5 the root with the logged changes applied in memory. */
984
+ root;
772
985
  /** @internal Sessions are created only by the database factory. */
773
- constructor(db, head, release) {
986
+ constructor(db, head, release, root = head.root) {
774
987
  this.db = db;
775
988
  this.head = head;
776
989
  this.release = release;
990
+ this.root = root;
777
991
  if (head.root) Object.freeze(head.root);
778
992
  this.revision = head.revision;
779
993
  this.count = head.count;
@@ -789,7 +1003,7 @@ class ReadSession {
789
1003
  get(id) {
790
1004
  common.key(id);
791
1005
  return this.work(async () => {
792
- const entry = await find((ref) => this.db.load(this.head, ref), this.head.root, id);
1006
+ const entry = await find((ref) => this.db.load(this.head, ref), this.root, id);
793
1007
  return entry ? { found: true, value: await this.db.value(this.head, entry.ref), revision: entry.revision } : { found: false };
794
1008
  });
795
1009
  }
@@ -798,12 +1012,12 @@ class ReadSession {
798
1012
  if (options.gte !== void 0) common.key(options.gte);
799
1013
  if (options.lt !== void 0) common.key(options.lt);
800
1014
  const limit = common.natural(options.limit ?? Number.MAX_SAFE_INTEGER, "scan limit");
801
- const { db, head } = this;
1015
+ const { db, head, root } = this;
802
1016
  async function* rows() {
803
1017
  let count = 0;
804
1018
  const window = {};
805
1019
  if (!limit) return;
806
- for await (const entry of entries((ref) => db.load(head, ref), head.root, options.gte, options.lt)) {
1020
+ for await (const entry of entries((ref) => db.load(head, ref), root, options.gte, options.lt)) {
807
1021
  common.abort(options.signal);
808
1022
  yield { key: entry.key, revision: entry.revision, value: await db.value(head, entry.ref, window) };
809
1023
  if (++count >= limit) break;
@@ -828,7 +1042,7 @@ class ReadSession {
828
1042
  const batchSize = common.natural(options.batchSize ?? 256, "batchSize", 1);
829
1043
  const maxBytes = common.natural(options.maxBatchBytes ?? 4 * 1024 * 1024, "maxBatchBytes", 1);
830
1044
  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);
1045
+ const { db, head, root, scans } = this, plan = (gte2, lt2, limit2, batchSize2, maxBatchBytes) => this.parallel(gte2, lt2, limit2, batchSize2, maxBatchBytes);
832
1046
  async function* batches() {
833
1047
  let count = 0, bytes = 0, batch = [];
834
1048
  const window = {};
@@ -852,7 +1066,7 @@ class ReadSession {
852
1066
  }
853
1067
  return;
854
1068
  }
855
- for await (const page of entryPages((ref) => db.load(head, ref), head.root, gte, lt)) {
1069
+ for await (const page of entryPages((ref) => db.load(head, ref), root, gte, lt)) {
856
1070
  let first = 0, last = 0, run = [];
857
1071
  for (let i = 0; i < page.length; i++) {
858
1072
  const entry = page[i];
@@ -912,15 +1126,15 @@ class ReadSession {
912
1126
  }
913
1127
  /** Ranges and a running worker scan for a large scanBatches call, or undefined to scan in this thread. */
914
1128
  async parallel(gte, lt, limit, batchSize, maxBatchBytes) {
915
- const parallel = this.db.parallel, { head } = this;
1129
+ const parallel = this.db.parallel, { head, root } = this;
916
1130
  if (!parallel?.workers || head.count < parallel.threshold || limit < parallel.threshold || gte !== void 0 && lt !== void 0 && gte >= lt) return void 0;
917
1131
  const load = (ref) => this.db.load(head, ref);
918
- const [counted] = await split(load, head.root, head.count, 1, gte, lt);
1132
+ const [counted] = await split(load, root, head.count, 1, gte, lt);
919
1133
  const rows = Math.min(counted.count, limit);
920
1134
  if (rows < parallel.threshold) return void 0;
921
- const end = rows < counted.count ? await keyAt(load, head.root, head.count, rows, gte, lt) : lt;
1135
+ const end = rows < counted.count ? await keyAt(load, root, head.count, rows, gte, lt) : lt;
922
1136
  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 } }));
1137
+ const ranges = (await split(load, root, head.count, parts, gte, end)).map((range) => ({ ...range.gte !== void 0 && { gte: range.gte }, ...range.lt !== void 0 && { lt: range.lt } }));
924
1138
  return ranges.length < 2 ? void 0 : parallel.scan(head, ranges, batchSize, maxBatchBytes);
925
1139
  }
926
1140
  /**
@@ -932,7 +1146,7 @@ class ReadSession {
932
1146
  common.natural(parts, "parts", 1);
933
1147
  if (range.gte !== void 0) common.key(range.gte);
934
1148
  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));
1149
+ return this.work(() => split((ref) => this.db.load(this.head, ref), this.root, this.head.count, parts, range.gte, range.lt));
936
1150
  }
937
1151
  /** Drain admitted reads before releasing the generation pin used by garbage collection. */
938
1152
  close() {
@@ -971,13 +1185,18 @@ class Dbsonl {
971
1185
  arrival;
972
1186
  /** Wall time of the last group publication in ms, which bounds gather(). */
973
1187
  groupCost = 0;
974
- /** Format 3: the generation end of this handle's last flushed head slot; see HEAD_FLUSH_BYTES. */
1188
+ /** Formats 3 and 4: the generation end of this handle's last flushed head slot; see HEAD_FLUSH_BYTES. */
975
1189
  headFlushed = 0;
976
1190
  /** The backend's scan workers, bound to this database's name and decoder budgets. */
977
1191
  scanner;
978
1192
  backend;
979
1193
  name;
980
1194
  closeBackend;
1195
+ /**
1196
+ * Format 5: the last head this handle resolved, its root with the logged changes applied, and how many pages of that
1197
+ * tree are held in memory; see effective().
1198
+ */
1199
+ view;
981
1200
  constructor(backend, name, options, closeBackend) {
982
1201
  this.backend = backend;
983
1202
  this.name = name;
@@ -994,8 +1213,53 @@ class Dbsonl {
994
1213
  void promise.then(() => this.pending.delete(promise), () => this.pending.delete(promise));
995
1214
  return promise;
996
1215
  }
1216
+ /**
1217
+ * Format 5: the root of head's whole state: the written root with the changes of the records after head.log applied
1218
+ * in memory. Callers hold the commit lock or a pin of head's generation. The last result is kept, so a newer head of
1219
+ * the same log replays only the records after it, and the writer's own commits replay nothing.
1220
+ */
1221
+ async effective(head) {
1222
+ if (head.dbsonl !== 5 || !head.last) return head.root;
1223
+ const known = this.view;
1224
+ if (known && known.head.generation === head.generation && known.head.publication === head.publication) return known.root;
1225
+ const base = known && known.head.generation === head.generation && known.head.log === head.log && sameRef(known.head.root, head.root) && known.head.end <= head.end ? known : void 0;
1226
+ const stop = base?.head.last?.offset, records = [];
1227
+ let reached = false;
1228
+ for (let ref = head.last; ref; ) {
1229
+ if (ref.offset === stop) {
1230
+ reached = true;
1231
+ break;
1232
+ }
1233
+ const record = await readRecord(this.backend, this.name, head, ref);
1234
+ records.push(record);
1235
+ ref = record.previous;
1236
+ }
1237
+ const incremental = !!base && (stop === void 0 || reached);
1238
+ const tree = new BatchTree(null, incremental ? base.root : head.root, head.count, Number.MAX_SAFE_INTEGER, (ref) => this.cached(pageId(head, ref)), (ref) => this.load(head, ref));
1239
+ let revision = incremental ? base.head.revision : 0;
1240
+ for (let i = records.length - 1; i >= 0; i--) {
1241
+ const record = records[i];
1242
+ if (record.revision <= revision) common.corrupt("Logged commit revisions are not increasing.");
1243
+ for (const change of await readChanges(this.backend, this.name, head, record.changes, Math.max(PAGE_BYTES, this.limits.maxTransactionBytes))) {
1244
+ if (change.revision > record.revision) common.corrupt("Logged change revision exceeds its commit.");
1245
+ const applying = tree.apply(change.key, change.ref.byteLength ? change : void 0);
1246
+ if (applying) await applying;
1247
+ }
1248
+ revision = record.revision;
1249
+ }
1250
+ const { root, count } = tree.open();
1251
+ if (revision !== head.revision || count !== head.count) common.corrupt("Logged commits disagree with the manifest.");
1252
+ this.view = { head, root, pages: (incremental ? base.pages : 0) + tree.memoryPages };
1253
+ return root;
1254
+ }
1255
+ /** Format 5: the pages head's tree holds in memory, once effective() resolved it. */
1256
+ memoryPages(head) {
1257
+ const view = this.view;
1258
+ return view && view.head.generation === head.generation && view.head.publication === head.publication ? view.pages : 0;
1259
+ }
997
1260
  /** Internal cache returns immutable implementation-owned pages, never application values. */
998
1261
  load(head, ref) {
1262
+ if (isMemoryPage(ref)) return ref;
999
1263
  const id = pageId(head, ref);
1000
1264
  return this.cached(id) ?? this.loadUncached(head, ref, id);
1001
1265
  }
@@ -1010,7 +1274,7 @@ class Dbsonl {
1010
1274
  }
1011
1275
  /** The cold path alone allocates an asynchronous load operation. */
1012
1276
  async loadUncached(head, ref, id) {
1013
- return this.remember(id, validatePage(await readValue(this.backend, this.name, head, ref, PAGE_BYTES), ref), ref.byteLength);
1277
+ return this.remember(id, toPage(await readValue(this.backend, this.name, head, ref, PAGE_BYTES), ref, head.dbsonl >= 4), ref.byteLength);
1014
1278
  }
1015
1279
  remember(id, page, bytes) {
1016
1280
  if (bytes > this.limits.maxCacheBytes || !this.limits.maxCachePages) return page;
@@ -1018,12 +1282,15 @@ class Dbsonl {
1018
1282
  if (existing) return existing.page;
1019
1283
  this.cache.set(id, { page, bytes, used: true });
1020
1284
  this.cacheBytes += bytes;
1021
- while (this.cacheBytes > this.limits.maxCacheBytes || this.cache.size > this.limits.maxCachePages) {
1022
- const [oldest, entry] = this.cache.entries().next().value;
1023
- this.cache.delete(oldest);
1285
+ if (this.cacheBytes <= this.limits.maxCacheBytes && this.cache.size <= this.limits.maxCachePages) return page;
1286
+ const bytesMark = this.limits.maxCacheBytes * LOW_WATER, pagesMark = this.limits.maxCachePages * LOW_WATER;
1287
+ for (const [key2, entry] of this.cache) {
1288
+ if (this.cacheBytes <= bytesMark && this.cache.size <= pagesMark) break;
1289
+ if (key2 === id) continue;
1290
+ this.cache.delete(key2);
1024
1291
  if (entry.used) {
1025
1292
  entry.used = false;
1026
- this.cache.set(oldest, entry);
1293
+ this.cache.set(key2, entry);
1027
1294
  } else this.cacheBytes -= entry.bytes;
1028
1295
  }
1029
1296
  return page;
@@ -1038,7 +1305,7 @@ class Dbsonl {
1038
1305
  const pinning = this.pin(head);
1039
1306
  this.pinning.add(pinning);
1040
1307
  try {
1041
- return this.session(head, await pinning);
1308
+ return await this.session(head, await pinning);
1042
1309
  } finally {
1043
1310
  this.pinning.delete(pinning);
1044
1311
  }
@@ -1053,10 +1320,18 @@ class Dbsonl {
1053
1320
  if (!release) throw new Error("Coordinator did not grant generation pin.");
1054
1321
  return release;
1055
1322
  }
1056
- session(head, release) {
1323
+ /** The pin protects the replay of a format 5 log as well as the session's reads. */
1324
+ async session(head, release) {
1325
+ let root;
1326
+ try {
1327
+ root = await this.effective(head);
1328
+ } catch (error) {
1329
+ await release();
1330
+ throw error;
1331
+ }
1057
1332
  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) => {
1058
1333
  this.sessions.delete(session2);
1059
- }, parallel: this.scanner }, Object.freeze(head), release);
1334
+ }, parallel: this.scanner }, Object.freeze(head), release, root);
1060
1335
  this.sessions.add(session);
1061
1336
  return session;
1062
1337
  }
@@ -1069,7 +1344,8 @@ class Dbsonl {
1069
1344
  let head;
1070
1345
  try {
1071
1346
  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 } });
1347
+ const last = at.last && { offset: at.last.offset, byteLength: at.last.byteLength };
1348
+ 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 }, ...at.log !== void 0 && { log: at.log }, ...at.last !== void 0 && { last } });
1073
1349
  } catch (cause) {
1074
1350
  throw new TypeError("options.at must be the head of a snapshot of this database.", { cause });
1075
1351
  }
@@ -1092,7 +1368,7 @@ class Dbsonl {
1092
1368
  }
1093
1369
  /** Internal lookup only: callers must hold a commit lock or generation pin. */
1094
1370
  async lookup(head, id) {
1095
- const entry = await find((ref) => this.load(head, ref), head.root, id);
1371
+ const entry = await find((ref) => this.load(head, ref), await this.effective(head), id);
1096
1372
  return entry ? { found: true, value: await this.value(head, entry.ref), revision: entry.revision } : { found: false };
1097
1373
  }
1098
1374
  get(id) {
@@ -1274,6 +1550,7 @@ class Dbsonl {
1274
1550
  for (const { member } of accepted) member.resolve({ revision, count: head.count });
1275
1551
  return;
1276
1552
  }
1553
+ const base = await this.effective(head);
1277
1554
  const next = await backend.withFile(this.backend, generationFile(this.name, head.generation), {}, async (file) => {
1278
1555
  const size = await file.size();
1279
1556
  if (size < head.end) common.corrupt("Committed generation is truncated.");
@@ -1282,9 +1559,9 @@ class Dbsonl {
1282
1559
  if (found) throw new Recovered(found);
1283
1560
  await file.truncate(head.end);
1284
1561
  }
1285
- const writer = new Appender(file, head.end, this.limits, this.backend.writeChunkBytes);
1286
- const tree = new BatchTree(writer, head.root, head.count, this.limits.maxTransactionBytes, (ref) => this.cached(pageId(head, ref)));
1287
- const counts = [];
1562
+ const writer = new Appender(file, head.end, this.limits, this.backend.writeChunkBytes, head.dbsonl >= 4);
1563
+ const tree = new BatchTree(writer, base, head.count, this.limits.maxTransactionBytes, (ref) => this.cached(pageId(head, ref)));
1564
+ const counts = [], changes = /* @__PURE__ */ new Map();
1288
1565
  for (const { member, revision: revision2 } of accepted) {
1289
1566
  for (const operation of member.input) {
1290
1567
  common.abort(member.signal);
@@ -1295,22 +1572,42 @@ class Dbsonl {
1295
1572
  }
1296
1573
  const applying = tree.apply(operation.key, entry);
1297
1574
  if (applying) await applying;
1575
+ if (head.dbsonl === 5) changes.set(operation.key, entry ?? { key: operation.key, ref: { offset: 0, byteLength: 0 }, revision: revision2 });
1298
1576
  }
1299
1577
  counts.push(tree.size);
1300
1578
  }
1579
+ const publication = common.natural(head.publication + 1, "publication");
1580
+ const pages = this.memoryPages(head) + tree.memoryPages;
1581
+ if (head.dbsonl === 5 && writer.end - head.log < CHECKPOINT_BYTES && pages <= this.limits.maxCachePages) {
1582
+ const { root: root2, count: count2 } = tree.open();
1583
+ const sorted = [...changes.values()].sort((a, b) => a.key < b.key ? -1 : 1);
1584
+ const list = await writer.bytes(sequence.encodeFrame(encodeChanges(sorted), { maxRecordBytes: Math.max(PAGE_BYTES, this.limits.maxTransactionBytes), trusted: true }));
1585
+ const published2 = { ...head, publication, revision, count: count2, end: writer.end }, offset = writer.end;
1586
+ const record = writer.bytes(commitRecord(published2, offset, head.end, list));
1587
+ if (record instanceof Promise) await record;
1588
+ published2.end = writer.end;
1589
+ published2.last = { offset, byteLength: writer.end - offset };
1590
+ await writer.flush();
1591
+ await file.flush();
1592
+ return { head: published2, written: tree.written, counts, root: root2, pages };
1593
+ }
1301
1594
  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) {
1595
+ const published = { ...head, publication, revision, root, count, end: writer.end };
1596
+ if (head.dbsonl >= 3) {
1304
1597
  const ref = writer.bytes(commitRecord(published, writer.end, head.end));
1305
1598
  if (ref instanceof Promise) await ref;
1306
1599
  published.end = writer.end;
1600
+ if (head.dbsonl === 5) {
1601
+ published.log = writer.end;
1602
+ published.last = null;
1603
+ }
1307
1604
  }
1308
1605
  await writer.flush();
1309
1606
  await file.flush();
1310
- return { head: published, written: tree.written, counts };
1607
+ return { head: published, written: tree.written, counts, root: published.root, pages: 0 };
1311
1608
  });
1312
1609
  publishing = true;
1313
- const flush = !(next.head.dbsonl === 3 && this.backend.coherent) || next.head.end - this.headFlushed >= HEAD_FLUSH_BYTES;
1610
+ const flush = !(next.head.dbsonl >= 3 && this.backend.coherent) || next.head.end - this.headFlushed >= HEAD_FLUSH_BYTES;
1314
1611
  try {
1315
1612
  await publish(this.backend, this.name, next.head, this.headCache, flush);
1316
1613
  if (flush) this.headFlushed = next.head.end;
@@ -1319,6 +1616,7 @@ class Dbsonl {
1319
1616
  throw new common.DbsonlError("COMMIT_UNCERTAIN", "Head publication failed; read the current revision before retrying.", { cause });
1320
1617
  }
1321
1618
  this.lockedHead = next.head;
1619
+ if (next.head.dbsonl === 5) this.view = { head: next.head, root: next.root, pages: next.pages };
1322
1620
  for (const { ref, page } of next.written) this.remember(pageId(next.head, ref), page, ref.byteLength);
1323
1621
  accepted.forEach(({ member, revision: revision2 }, index) => member.resolve({ revision: revision2, count: next.counts[index] }));
1324
1622
  } catch (error) {
@@ -1340,10 +1638,10 @@ class Dbsonl {
1340
1638
  for (const member of group) if (!member.done) member.reject(error);
1341
1639
  }
1342
1640
  }
1343
- /** Under the commit lock: the published head, after adopting format 3 commits whose head slot did not reach the disk. */
1641
+ /** Under the commit lock: the published head, after adopting format 3 or 4 commits whose head slot did not reach the disk. */
1344
1642
  async settledHead() {
1345
1643
  const head = await readHead(this.backend, this.name, this.headCache);
1346
- if (head.dbsonl !== 3) return head;
1644
+ if (head.dbsonl < 3) return head;
1347
1645
  const found = await backend.withFile(this.backend, generationFile(this.name, head.generation), { readOnly: true }, async (file) => {
1348
1646
  const size = await file.size();
1349
1647
  return size > head.end ? recoverTail(file, head, size) : void 0;
@@ -1361,7 +1659,7 @@ class Dbsonl {
1361
1659
  async validate(head, reads, written) {
1362
1660
  if (reads.whole) throw new common.DbsonlError("CONFLICT", "Database changed since the transaction snapshot.");
1363
1661
  for (const [id, seen] of reads.keys) {
1364
- const entry = written.has(id) ? void 0 : await find((ref) => this.load(head, ref), head.root, id);
1662
+ const entry = written.has(id) ? void 0 : await find((ref) => this.load(head, ref), await this.effective(head), id);
1365
1663
  if (written.has(id) || (entry?.revision ?? 0) !== seen) throw new common.DbsonlError("CONFLICT", "A key the transaction read changed after its snapshot.");
1366
1664
  }
1367
1665
  }
@@ -1504,6 +1802,9 @@ class Dbsonl {
1504
1802
  /** Full logical integrity walk, separate from the O(1) open path. */
1505
1803
  verify() {
1506
1804
  return this.run(async () => {
1805
+ this.cache.clear();
1806
+ this.cacheBytes = 0;
1807
+ this.view = void 0;
1507
1808
  const session = await this.snapshot();
1508
1809
  let count = 0;
1509
1810
  try {
@@ -1527,9 +1828,8 @@ class Dbsonl {
1527
1828
  }
1528
1829
  return { min: minimum, max: page.children.at(-1).max, count: total };
1529
1830
  }
1530
- this.cache.clear();
1531
- this.cacheBytes = 0;
1532
- if (session.head.root) count = (await audit(this, session.head.root, 0)).count;
1831
+ const root = await this.effective(session.head);
1832
+ if (root) count = (await audit(this, root, 0)).count;
1533
1833
  if (count !== session.count) common.corrupt("Root key count disagrees with manifest.");
1534
1834
  return { revision: session.revision, count };
1535
1835
  } finally {
@@ -1561,20 +1861,34 @@ class Dbsonl {
1561
1861
  outerRelease = await this.backend.coordinator.acquire(`commit-${this.name}`, false, options.signal);
1562
1862
  await prepare();
1563
1863
  } else await backend.locked(this.backend, `commit-${this.name}`, prepare, options.signal);
1864
+ const root = await this.effective(head);
1564
1865
  const next = await backend.withFile(this.backend, filename, { create: true, exclusive: true }, async (file) => {
1565
- const writer = new Appender(file, 0, this.limits, this.backend.writeChunkBytes);
1866
+ const writer = new Appender(file, 0, this.limits, this.backend.writeChunkBytes, head.dbsonl >= 4);
1566
1867
  const tree = new BulkTree(writer);
1567
- const window = {};
1568
- for await (const entry of entries((ref) => this.load(head, ref), head.root)) {
1868
+ let batch = [], bytes = 0;
1869
+ const copy = async () => {
1870
+ const frames = await readFrames(this.backend, this.name, head, batch.map((entry) => entry.ref), this.limits.maxRecordBytes);
1871
+ for (let i = 0; i < batch.length; i++) {
1872
+ const ref = writer.bytes(frames[i]);
1873
+ await tree.add({ ...batch[i], ref: ref instanceof Promise ? await ref : ref });
1874
+ }
1875
+ batch = [];
1876
+ bytes = 0;
1877
+ };
1878
+ for await (const page of entryPages((ref) => this.load(head, ref), root)) {
1569
1879
  common.abort(options.signal);
1570
- const value = await this.value(head, entry.ref, window);
1571
- await tree.add({ ...entry, ref: await writer.value(value) });
1880
+ for (const entry of page) {
1881
+ batch.push(entry);
1882
+ bytes += entry.ref.byteLength;
1883
+ }
1884
+ if (bytes >= COPY_BYTES) await copy();
1572
1885
  }
1886
+ if (batch.length) await copy();
1573
1887
  const packed = await tree.finish();
1574
1888
  if (packed.count !== head.count) common.corrupt("Compaction key count disagrees with manifest.");
1575
1889
  await writer.flush();
1576
1890
  await file.flush();
1577
- return { ...head, ...packed, generation, end: writer.end, publication: common.natural(head.publication + 1, "publication"), ...head.dbsonl === 3 && { seal: newGeneration() } };
1891
+ return { ...head, ...packed, generation, end: writer.end, publication: common.natural(head.publication + 1, "publication"), ...head.dbsonl >= 3 && { seal: newGeneration() }, ...head.dbsonl === 5 && { log: writer.end, last: null } };
1578
1892
  });
1579
1893
  await this.backend.coordinator.syncDirectory();
1580
1894
  const install = async () => {
@@ -1671,7 +1985,7 @@ async function openDbsonl(backend$1, name, options = {}) {
1671
1985
  await backend.withFile(backend$1, generationFile(name, generation), { create: true, exclusive: true }, (file) => file.flush());
1672
1986
  if (missing) await backend.withFile(backend$1, headFile(name), { create: true, exclusive: true }, (file) => file.flush());
1673
1987
  await backend$1.coordinator.syncDirectory();
1674
- head = { dbsonl: 3, publication: 1, revision: 0, generation, root: null, count: 0, end: 0, seal: newGeneration() };
1988
+ head = { dbsonl: 5, publication: 1, revision: 0, generation, root: null, count: 0, end: 0, seal: newGeneration(), log: 0, last: null };
1675
1989
  await publish(backend$1, name, head);
1676
1990
  await publish(backend$1, name, { ...head, publication: 2 });
1677
1991
  }