defuss-dbsonl 0.5.0 → 0.6.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/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ VERIFIED: Snapshots have `scanBatches({gte?, lt?, limit?, signal?, batchSize?, maxBatchBytes?, sizeOf?})`, which yields the rows of `scan` as arrays of at most 256 rows and 4 MiB by default, with one tracked pull per batch and one tree step per leaf. It is ported from the 0.4-based fork that defuss-dataview's DBSONL adapter used, with the option names and guarantees that adapter checks: a nonempty array per batch, at most `batchSize` rows and `sizeOf` applied once per row.
6
+
7
+ VERIFIED: Scans now read ahead 64 KiB on every backend, not only on backends with a positional `read`, so a memory or OPFS scan no longer opens, reads and closes the file once per row.
8
+
9
+ VERIFIED: defuss-dson is now 1.5.1, which writes the same frames as 1.3.0, reads each frame through one reader and converts frame offsets to int32 values, which Bun needs to decode at full speed when the offsets come from decoded index pages. `scanBatches` decodes the frames of a leaf that the read window already holds in one `decodeFrames` call; when a frame fails, it rereads that run frame by frame, so errors arrive at the same row as before.
10
+
11
+ VERIFIED: In three runs of the new `make bench-scan` over 100,000 documents, the row scan on memory storage took 0.61 of 0.5.0's time under Node and 0.63 under Bun; `scanBatches` took 0.46 and 0.52 on memory storage and 0.73 and 0.84 on native storage. Against the same source on defuss-dson 1.4.0, the version bump alone took 12% off `scanBatches` on Node memory storage and 8% on native storage, and `decodeFrames` another 6% on both; under Bun, 4% and 0%, then 5% on both. `vendor/defuss-dbsonl-0.5.0.tgz` is the published 0.5.0 package these runs compare against.
12
+
13
+ VERIFIED: `tests/batches.test.ts` covers batch scans on memory and native storage, and the packed-package and browser suites call `scanBatches` too. The on-disk format and lock protocol are unchanged.
14
+
15
+ ## 0.5.1
16
+
17
+ VERIFIED: `package.json` names the project website, https://dbsonl.defuss.org, as its homepage, and links the GitHub repository and issue tracker. The README explains installing from npm: on 2026-11-16, `bun add defuss-dbsonl@0.5.0` and `npm install defuss-dbsonl@0.5.0` each installed five packages in an empty project with no install script, and the `/server` entry stored and read a value under Node.js and Bun on macOS arm64.
18
+
19
+ VERIFIED: The website describes 0.5.0: per-key transaction conflicts, commit groups, the second-chance page cache and the `make bench` figures of three runs on the 0.5.0 source. Against v0.3.0 in those runs no figure was slower in all three, and atomic batches took 1.6 times less time under Node.js and 2.4 times less under Bun. `docs/PERFORMANCE.md` has the tables; the 0.4.0 runs moved to `validation/bench-macos-arm64-0.4.0.json`.
20
+
21
+ VERIFIED: Below the hero, the website compares defuss-dbsonl with Redis 8.10.3 in the 16 pairings of `make bench-redis`. It shows the headline figures, four gauges that follow a runtime and storage switch, opening on Bun flushed to disk, and two dumbbell charts drawn with ECharts 6.1.0. The tables moved into that section. Under the DSON line, the hero has a second rotating line listing what defuss-dbsonl adds. `make e2e` checks that both charts draw, that the switches move the gauges, and that the page still does not scroll sideways at iPhone size.
22
+
23
+ VERIFIED: `tests/contracts.test.ts` adds eight tests for documented contracts no other test reached. Coverage rose from 91.33% to 93.86% of statements, 86.17% to 90.15% of branches, 96.39% to 97.29% of functions and 97.67% to 98.41% of lines. No production code changed.
24
+
3
25
  ## 0.5.0
4
26
 
5
27
  VERIFIED: The website fits phones: code and tables scroll sideways instead of wrapping, tables tint every other row, cards put their icon beside the heading, and the install tabs stack. `make e2e` now also drives the website in WebKit at iPhone size, including the OPFS counter and the menu sheet, and fails if the page scrolls sideways.
package/README.md CHANGED
@@ -1,17 +1,24 @@
1
- # defuss-dbsonl 0.5.0
1
+ # defuss-dbsonl 0.6.0
2
2
 
3
- Transactional key-value storage for Node.js, Bun and browser workers. Values are DSON, so dates, binary views, bigint, `undefined` and cyclic references survive storage. It is built on [defuss-dson](https://dson.defuss.org) 1.4.0 and [defuss-storage](https://storage.defuss.org) 0.3.1 and ships TypeScript declarations with ESM and CommonJS builds. It is designed as the backing store and API of [defuss-dataview](https://dataview.defuss.org), which adds filters, sorting and paging for table and tree grids. Project website: [docs/index.html](docs/index.html).
3
+ Transactional key-value storage for Node.js, Bun and browser workers. Values are DSON, so dates, binary views, bigint, `undefined` and cyclic references survive storage. It is built on [defuss-dson](https://dson.defuss.org) 1.5.1 and [defuss-storage](https://storage.defuss.org) 0.3.1 and ships TypeScript declarations with ESM and CommonJS builds. It is designed as the backing store and API of [defuss-dataview](https://dataview.defuss.org), which adds filters, sorting and paging for table and tree grids. Project website: [dbsonl.defuss.org](https://dbsonl.defuss.org).
4
4
 
5
5
  VERIFIED: A database is a persistent copy-on-write B+tree with immutable snapshots, atomic batches, optimistic serializable transactions, compaction and process-safe coordination. Opening reads two small manifest slots instead of replaying a log, and readers never block writers.
6
6
 
7
- ## Install and use
7
+ ## Install
8
8
 
9
9
  ```sh
10
- make release
11
- bun add ./validation/defuss-dbsonl-0.5.0.tgz
10
+ bun add defuss-dbsonl
11
+ # or
12
+ npm install defuss-dbsonl
12
13
  ```
13
14
 
14
- `make release` builds the tarball locally; registry publication is a separate step.
15
+ The package is on the npm registry. It needs Node.js 20.19 or newer, Bun, or a dedicated browser worker with OPFS and Web Locks. `defuss-dson` and `defuss-storage` install with it.
16
+
17
+ VERIFIED: The native lock addon, `@lickle/lock`, ships prebuilt binaries as optional dependencies for Linux x64 glibc, macOS x64 and arm64, and Windows x64, so nothing compiles during installation. On 2026-11-16, `bun add defuss-dbsonl@0.5.0` and `npm install defuss-dbsonl@0.5.0` in empty projects each installed five packages, none of which declares an install script, and the `/server` entry stored and read a value under both Node.js and Bun on macOS arm64.
18
+
19
+ To install a local build instead, `make release` writes the tarball to `validation/`; add it with `bun add ./validation/defuss-dbsonl-<version>.tgz`.
20
+
21
+ ## Use
15
22
 
16
23
  ```ts
17
24
  import { openDbsonl } from 'defuss-dbsonl';
@@ -43,6 +50,8 @@ try {
43
50
 
44
51
  The transaction callback runs once. A concurrent commit that changed a key the callback read makes it fail with `CONFLICT` instead of retrying, because a retry would repeat any side effects in your callback; after a scan, any concurrent commit does. Retry explicitly where that is safe. Concurrent batches and transactions on one handle publish together: one write and one pair of flushes for the queued group, while each keeps its own revision and receipt. `ifRevision` gives compare-and-swap for changes prepared outside a transaction.
45
52
 
53
+ For bulk reads, a snapshot's `scanBatches()` yields the same rows as `scan()` in arrays of up to 256. It tracks one pull per batch instead of one per row, so a full scan takes less time; [API](docs/API.md) has its byte budget and options.
54
+
46
55
  Memory storage needs no platform entry:
47
56
 
48
57
  ```ts
@@ -102,7 +111,7 @@ Resource budgets cap retained engine work. The page cache is bounded by encoded
102
111
 
103
112
  ## Compatibility
104
113
 
105
- VERIFIED: Versions 0.2 through 0.4 share the on-disk format and the lock protocol. The packed-package suite runs 0.2.0 and the current build concurrently on Node and Bun against one database, so upgrading needs no migration.
114
+ VERIFIED: Versions 0.2 through 0.6 share the on-disk format and the lock protocol. The packed-package suite runs 0.2.0 and the current build concurrently on Node and Bun against one database, so upgrading needs no migration.
106
115
 
107
116
  Version 0.4.0 renamed the native entry from `defuss-dbsonl/node` to `defuss-dbsonl/server` and removed the `/legacy` and `/records` subpaths. Data in the v0.1 log format must be migrated with defuss-dbsonl 0.3.x first; that release ships `defuss-dbsonl/legacy` and `examples/migrate.ts`. See [CHANGELOG.md](CHANGELOG.md).
108
117
 
@@ -112,6 +121,7 @@ Version 0.4.0 renamed the native entry from `defuss-dbsonl/node` to `defuss-dbso
112
121
  make setup # pinned Node/Bun/Redis via mise, dependencies, Chromium, WebKit, VAE runtime
113
122
  make verify # lint, tests, coverage, packed-package e2e
114
123
  make bench # matched v0.2 versus current benchmarks
124
+ make bench-scan # full scans, row by row and in batches, against the vendored 0.5.0
115
125
  make bench-redis # current build versus a throwaway loopback Redis, run as mise exec -- make bench-redis
116
126
  make dev # rebuild the website demos and serve docs/ on 127.0.0.1:3000
117
127
  make vae # verification, review and documentation gate
package/dist/index.cjs CHANGED
@@ -233,17 +233,16 @@ async function readValue(backend$1, name, head, ref, maxRecordBytes, window) {
233
233
  common.reference(ref, head.end);
234
234
  if (ref.byteLength - 16 > maxRecordBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "Referenced record exceeds the decoder budget.");
235
235
  let bytes;
236
- if (window?.bytes && window.offset !== void 0 && ref.offset >= window.offset && ref.offset + ref.byteLength <= window.offset + window.bytes.length) {
236
+ if (window && windowContains(window, ref)) {
237
237
  bytes = window.bytes.subarray(ref.offset - window.offset, ref.offset - window.offset + ref.byteLength);
238
238
  } else {
239
- const length = backend$1.read && window && ref.byteLength <= 65536 ? Math.min(65536, head.end - ref.offset) : ref.byteLength;
239
+ const length = window && ref.byteLength <= 65536 ? Math.min(65536, head.end - ref.offset) : ref.byteLength;
240
240
  const filename = generationFile(name, head.generation);
241
241
  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.
242
+ // Portable handles read the same bounded window, so a scan opens the file once per window, not per row.
244
243
  await backend.withFile(backend$1, filename, { readOnly: true }, (file) => readExact(file, ref.offset, length))
245
244
  );
246
- if (window && backend$1.read) {
245
+ if (window) {
247
246
  window.offset = ref.offset;
248
247
  window.bytes = length <= 65536 ? data : new Uint8Array(0);
249
248
  }
@@ -251,6 +250,28 @@ async function readValue(backend$1, name, head, ref, maxRecordBytes, window) {
251
250
  }
252
251
  return decodeRef(bytes, ref, maxRecordBytes);
253
252
  }
253
+ function windowContains(window, ref) {
254
+ return !!window.bytes && window.offset !== void 0 && ref.offset >= window.offset && ref.offset + ref.byteLength <= window.offset + window.bytes.length;
255
+ }
256
+ function readCachedValue(head, ref, maxRecordBytes, window) {
257
+ common.reference(ref, head.end);
258
+ if (ref.byteLength - 16 > maxRecordBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "Referenced record exceeds the decoder budget.");
259
+ return decodeRef(window.bytes.subarray(ref.offset - window.offset, ref.offset - window.offset + ref.byteLength), ref, maxRecordBytes);
260
+ }
261
+ function readCachedValues(entries, start, end, maxRecordBytes, window) {
262
+ try {
263
+ const offsets = [];
264
+ for (let i = start; i < end; i++) offsets.push(entries[i].ref.offset - window.offset);
265
+ const frames = sequence.decodeFrames(window.bytes, offsets, { maxRecordBytes, maxDepth: 512, maxReferences: 1e6 }), values = [];
266
+ for (let i = 0; i < frames.length; i++) {
267
+ if (frames[i].byteLength !== entries[start + i].ref.byteLength) return [];
268
+ values.push(frames[i].value);
269
+ }
270
+ return values;
271
+ } catch {
272
+ return [];
273
+ }
274
+ }
254
275
  function decodeRef(bytes, ref, maxRecordBytes) {
255
276
  if (bytes.length !== ref.byteLength) common.corrupt("Committed record is truncated.");
256
277
  try {
@@ -392,6 +413,23 @@ async function* entries(load, root, gte, lt, depth = 0) {
392
413
  }
393
414
  }
394
415
  }
416
+ async function* entryPages(load, root, gte, lt, depth = 0) {
417
+ if (!root) return;
418
+ if (depth > 64) common.corrupt("Index depth exceeds the format safety bound.");
419
+ const loaded = load(root), page = "kind" in loaded ? loaded : await loaded;
420
+ if (page.kind === "leaf") {
421
+ const start = gte === void 0 ? 0 : lower(page.entries, gte, (item) => item.key);
422
+ const end = lt === void 0 ? page.entries.length : lower(page.entries, lt, (item) => item.key);
423
+ if (end > start) yield start === 0 && end === page.entries.length ? page.entries : page.entries.slice(start, end);
424
+ } else {
425
+ let prior;
426
+ for (const child of page.children) {
427
+ if (lt !== void 0 && prior !== void 0 && prior >= lt) break;
428
+ if (gte === void 0 || child.max >= gte) yield* entryPages(load, child.ref, gte, lt, depth + 1);
429
+ prior = child.max;
430
+ }
431
+ }
432
+ }
395
433
  class BatchTree {
396
434
  /** cached returns an already validated committed page, or undefined to read it through the writer. */
397
435
  constructor(writer, root, count, byteBudget, cached = () => void 0) {
@@ -585,9 +623,9 @@ class ReadSession {
585
623
  pending = /* @__PURE__ */ new Set();
586
624
  revision;
587
625
  count;
588
- work(fn) {
626
+ work(fn, invokesUserCode = false) {
589
627
  if (this.closed) return Promise.reject(new common.DbsonlError("CLOSED", "Snapshot is closed."));
590
- const promise = fn();
628
+ const promise = invokesUserCode ? Promise.resolve().then(fn) : fn();
591
629
  this.pending.add(promise);
592
630
  void promise.then(() => this.pending.delete(promise), () => this.pending.delete(promise));
593
631
  return promise;
@@ -626,6 +664,71 @@ class ReadSession {
626
664
  throw: (error) => iterator.throw(error)
627
665
  };
628
666
  }
667
+ /** Native bounded batches: one tracked pull per batch and one async traversal per leaf. */
668
+ scanBatches(options = {}) {
669
+ const { gte, lt, signal, sizeOf } = options;
670
+ if (gte !== void 0) common.key(gte);
671
+ if (lt !== void 0) common.key(lt);
672
+ const limit = common.natural(options.limit ?? Number.MAX_SAFE_INTEGER, "scan limit");
673
+ const batchSize = common.natural(options.batchSize ?? 256, "batchSize", 1);
674
+ const maxBytes = common.natural(options.maxBatchBytes ?? 4 * 1024 * 1024, "maxBatchBytes", 1);
675
+ if (sizeOf !== void 0 && typeof sizeOf !== "function") throw new TypeError("sizeOf must be a function.");
676
+ const { db, head } = this;
677
+ async function* batches() {
678
+ let count = 0, bytes = 0, batch = [];
679
+ const window = {};
680
+ common.abort(signal);
681
+ if (!limit) return;
682
+ for await (const page of entryPages((ref) => db.load(head, ref), head.root, gte, lt)) {
683
+ let first = 0, last = 0, run = [];
684
+ for (let i = 0; i < page.length; i++) {
685
+ const entry = page[i];
686
+ common.abort(signal);
687
+ if (i >= last && windowContains(window, entry.ref)) {
688
+ const stop = Math.min(page.length, i + limit - count, i + batchSize - batch.length);
689
+ first = i;
690
+ last = i + 1;
691
+ while (last < stop && windowContains(window, page[last].ref)) last++;
692
+ run = last - first > 1 ? db.cachedValues(page, first, last, window) : [];
693
+ }
694
+ 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);
695
+ common.abort(signal);
696
+ const row = { key: entry.key, revision: entry.revision, value };
697
+ const size = common.natural(sizeOf ? sizeOf(row) : entry.ref.byteLength, "batch row bytes");
698
+ if (size > maxBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "One row exceeds the batch byte budget.");
699
+ if (batch.length && bytes + size > maxBytes) {
700
+ yield batch;
701
+ batch = [];
702
+ bytes = 0;
703
+ common.abort(signal);
704
+ }
705
+ batch.push(row);
706
+ bytes += size;
707
+ count++;
708
+ if (batch.length === batchSize) {
709
+ yield batch;
710
+ batch = [];
711
+ bytes = 0;
712
+ common.abort(signal);
713
+ }
714
+ if (count === limit) {
715
+ if (batch.length) yield batch;
716
+ return;
717
+ }
718
+ }
719
+ }
720
+ if (batch.length) yield batch;
721
+ }
722
+ const iterator = batches();
723
+ return {
724
+ [Symbol.asyncIterator]() {
725
+ return this;
726
+ },
727
+ next: () => this.work(() => iterator.next(), true),
728
+ return: () => iterator.return(void 0),
729
+ throw: (error) => iterator.throw(error)
730
+ };
731
+ }
629
732
  /** Drain admitted reads before releasing the generation pin used by garbage collection. */
630
733
  close() {
631
734
  if (this.closing) return this.closing;
@@ -739,7 +842,7 @@ class Dbsonl {
739
842
  return release;
740
843
  }
741
844
  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) => {
845
+ 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
846
  this.sessions.delete(session2);
744
847
  } }, Object.freeze(head), release);
745
848
  this.sessions.add(session);
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CancellationSignal, MemoryStorageOptions } from 'defuss-storage';
2
- import { B as Backend, O as Options, R as Release, H as Head, a as Ref, P as Page, L as Lookup, S as ScanOptions, b as Row, M as Mutation, C as CommitOptions, c as Commit, T as Transaction, d as Stats } from './types-B_SuDjVq.cjs';
3
- export { e as Coordinator } from './types-B_SuDjVq.cjs';
2
+ import { B as Backend, O as Options, R as Release, H as Head, a as Ref, P as Page, E as Entry, L as Lookup, S as ScanOptions, b as Row, c as BatchScanOptions, M as Mutation, C as CommitOptions, d as Commit, T as Transaction, e as Stats } from './types-7kcIxgpp.cjs';
3
+ export { f as Coordinator } from './types-7kcIxgpp.cjs';
4
4
 
5
5
  /** VERIFIED: Shared validators reject ambiguous addresses before allocation or mutation. */
6
6
 
@@ -41,6 +41,8 @@ declare class ReadSession<T = unknown> {
41
41
  constructor(db: {
42
42
  load(head: Readonly<Head>, ref: Ref): Page | Promise<Page>;
43
43
  value(head: Readonly<Head>, ref: Ref, window?: ReadWindow): Promise<T>;
44
+ cachedValue(head: Readonly<Head>, ref: Ref, window: ReadWindow): T;
45
+ cachedValues(entries: readonly Entry[], start: number, end: number, window: ReadWindow): T[];
44
46
  forget(session: ReadSession<T>): void;
45
47
  }, head: Readonly<Head>, release: Release);
46
48
  private work;
@@ -48,6 +50,8 @@ declare class ReadSession<T = unknown> {
48
50
  get(id: string): Promise<Lookup<T>>;
49
51
  /** Yield one owned decoded value per pull, in UTF-16 code-unit key order. */
50
52
  scan(options?: ScanOptions): AsyncIterableIterator<Row<T>>;
53
+ /** Native bounded batches: one tracked pull per batch and one async traversal per leaf. */
54
+ scanBatches(options?: BatchScanOptions<T>): AsyncIterableIterator<readonly Row<T>[], void>;
51
55
  /** Drain admitted reads before releasing the generation pin used by garbage collection. */
52
56
  close(): Promise<void>;
53
57
  }
@@ -178,5 +182,5 @@ declare function openDbsonl<T = unknown>(backend: Backend, name: string, options
178
182
  /** Realm-local implementation for a new, isolated memory namespace. */
179
183
  declare function createMemoryBackend(options?: MemoryStorageOptions): Backend;
180
184
 
181
- export { Backend, Commit, CommitOptions, DEFAULT_OPTIONS, Dbsonl, DbsonlError, Head, Lookup, Mutation, Options, Page, ReadSession, Ref, Release, Row, ScanOptions, Stats, Transaction, createMemoryBackend, openDbsonl };
185
+ export { Backend, BatchScanOptions, Commit, CommitOptions, DEFAULT_OPTIONS, Dbsonl, DbsonlError, Head, Lookup, Mutation, Options, Page, ReadSession, Ref, Release, Row, ScanOptions, Stats, Transaction, createMemoryBackend, openDbsonl };
182
186
  export type { ErrorCode };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CancellationSignal, MemoryStorageOptions } from 'defuss-storage';
2
- import { B as Backend, O as Options, R as Release, H as Head, a as Ref, P as Page, L as Lookup, S as ScanOptions, b as Row, M as Mutation, C as CommitOptions, c as Commit, T as Transaction, d as Stats } from './types-B_SuDjVq.mjs';
3
- export { e as Coordinator } from './types-B_SuDjVq.mjs';
2
+ import { B as Backend, O as Options, R as Release, H as Head, a as Ref, P as Page, E as Entry, L as Lookup, S as ScanOptions, b as Row, c as BatchScanOptions, M as Mutation, C as CommitOptions, d as Commit, T as Transaction, e as Stats } from './types-7kcIxgpp.mjs';
3
+ export { f as Coordinator } from './types-7kcIxgpp.mjs';
4
4
 
5
5
  /** VERIFIED: Shared validators reject ambiguous addresses before allocation or mutation. */
6
6
 
@@ -41,6 +41,8 @@ declare class ReadSession<T = unknown> {
41
41
  constructor(db: {
42
42
  load(head: Readonly<Head>, ref: Ref): Page | Promise<Page>;
43
43
  value(head: Readonly<Head>, ref: Ref, window?: ReadWindow): Promise<T>;
44
+ cachedValue(head: Readonly<Head>, ref: Ref, window: ReadWindow): T;
45
+ cachedValues(entries: readonly Entry[], start: number, end: number, window: ReadWindow): T[];
44
46
  forget(session: ReadSession<T>): void;
45
47
  }, head: Readonly<Head>, release: Release);
46
48
  private work;
@@ -48,6 +50,8 @@ declare class ReadSession<T = unknown> {
48
50
  get(id: string): Promise<Lookup<T>>;
49
51
  /** Yield one owned decoded value per pull, in UTF-16 code-unit key order. */
50
52
  scan(options?: ScanOptions): AsyncIterableIterator<Row<T>>;
53
+ /** Native bounded batches: one tracked pull per batch and one async traversal per leaf. */
54
+ scanBatches(options?: BatchScanOptions<T>): AsyncIterableIterator<readonly Row<T>[], void>;
51
55
  /** Drain admitted reads before releasing the generation pin used by garbage collection. */
52
56
  close(): Promise<void>;
53
57
  }
@@ -178,5 +182,5 @@ declare function openDbsonl<T = unknown>(backend: Backend, name: string, options
178
182
  /** Realm-local implementation for a new, isolated memory namespace. */
179
183
  declare function createMemoryBackend(options?: MemoryStorageOptions): Backend;
180
184
 
181
- export { Backend, Commit, CommitOptions, DEFAULT_OPTIONS, Dbsonl, DbsonlError, Head, Lookup, Mutation, Options, Page, ReadSession, Ref, Release, Row, ScanOptions, Stats, Transaction, createMemoryBackend, openDbsonl };
185
+ export { Backend, BatchScanOptions, Commit, CommitOptions, DEFAULT_OPTIONS, Dbsonl, DbsonlError, Head, Lookup, Mutation, Options, Page, ReadSession, Ref, Release, Row, ScanOptions, Stats, Transaction, createMemoryBackend, openDbsonl };
182
186
  export type { ErrorCode };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { encodeFrame, decodeFrame } from 'defuss-dson/sequence';
1
+ import { encodeFrame, decodeFrame, decodeFrames } from 'defuss-dson/sequence';
2
2
  import { w as withFile, a as writeBytes, l as locked } from './backend-c-pjfpXZ.mjs';
3
3
  export { c as createMemoryBackend } from './backend-c-pjfpXZ.mjs';
4
4
  import { c as corrupt, D as DbsonlError, r as reference, n as natural, k as key, b as name, o as options, a as abort } from './common-0JC30Xiv.mjs';
@@ -233,17 +233,16 @@ async function readValue(backend, name, head, ref, maxRecordBytes, window) {
233
233
  reference(ref, head.end);
234
234
  if (ref.byteLength - 16 > maxRecordBytes) throw new DbsonlError("LIMIT_EXCEEDED", "Referenced record exceeds the decoder budget.");
235
235
  let bytes;
236
- if (window?.bytes && window.offset !== void 0 && ref.offset >= window.offset && ref.offset + ref.byteLength <= window.offset + window.bytes.length) {
236
+ if (window && windowContains(window, ref)) {
237
237
  bytes = window.bytes.subarray(ref.offset - window.offset, ref.offset - window.offset + ref.byteLength);
238
238
  } else {
239
- const length = backend.read && window && ref.byteLength <= 65536 ? Math.min(65536, head.end - ref.offset) : ref.byteLength;
239
+ const length = window && ref.byteLength <= 65536 ? Math.min(65536, head.end - ref.offset) : ref.byteLength;
240
240
  const filename = generationFile(name, head.generation);
241
241
  const data = backend.read ? await backend.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.
242
+ // Portable handles read the same bounded window, so a scan opens the file once per window, not per row.
244
243
  await withFile(backend, filename, { readOnly: true }, (file) => readExact(file, ref.offset, length))
245
244
  );
246
- if (window && backend.read) {
245
+ if (window) {
247
246
  window.offset = ref.offset;
248
247
  window.bytes = length <= 65536 ? data : new Uint8Array(0);
249
248
  }
@@ -251,6 +250,28 @@ async function readValue(backend, name, head, ref, maxRecordBytes, window) {
251
250
  }
252
251
  return decodeRef(bytes, ref, maxRecordBytes);
253
252
  }
253
+ function windowContains(window, ref) {
254
+ return !!window.bytes && window.offset !== void 0 && ref.offset >= window.offset && ref.offset + ref.byteLength <= window.offset + window.bytes.length;
255
+ }
256
+ function readCachedValue(head, ref, maxRecordBytes, window) {
257
+ reference(ref, head.end);
258
+ if (ref.byteLength - 16 > maxRecordBytes) throw new DbsonlError("LIMIT_EXCEEDED", "Referenced record exceeds the decoder budget.");
259
+ return decodeRef(window.bytes.subarray(ref.offset - window.offset, ref.offset - window.offset + ref.byteLength), ref, maxRecordBytes);
260
+ }
261
+ function readCachedValues(entries, start, end, maxRecordBytes, window) {
262
+ try {
263
+ const offsets = [];
264
+ for (let i = start; i < end; i++) offsets.push(entries[i].ref.offset - window.offset);
265
+ const frames = decodeFrames(window.bytes, offsets, { maxRecordBytes, maxDepth: 512, maxReferences: 1e6 }), values = [];
266
+ for (let i = 0; i < frames.length; i++) {
267
+ if (frames[i].byteLength !== entries[start + i].ref.byteLength) return [];
268
+ values.push(frames[i].value);
269
+ }
270
+ return values;
271
+ } catch {
272
+ return [];
273
+ }
274
+ }
254
275
  function decodeRef(bytes, ref, maxRecordBytes) {
255
276
  if (bytes.length !== ref.byteLength) corrupt("Committed record is truncated.");
256
277
  try {
@@ -392,6 +413,23 @@ async function* entries(load, root, gte, lt, depth = 0) {
392
413
  }
393
414
  }
394
415
  }
416
+ async function* entryPages(load, root, gte, lt, depth = 0) {
417
+ if (!root) return;
418
+ if (depth > 64) corrupt("Index depth exceeds the format safety bound.");
419
+ const loaded = load(root), page = "kind" in loaded ? loaded : await loaded;
420
+ if (page.kind === "leaf") {
421
+ const start = gte === void 0 ? 0 : lower(page.entries, gte, (item) => item.key);
422
+ const end = lt === void 0 ? page.entries.length : lower(page.entries, lt, (item) => item.key);
423
+ if (end > start) yield start === 0 && end === page.entries.length ? page.entries : page.entries.slice(start, end);
424
+ } else {
425
+ let prior;
426
+ for (const child of page.children) {
427
+ if (lt !== void 0 && prior !== void 0 && prior >= lt) break;
428
+ if (gte === void 0 || child.max >= gte) yield* entryPages(load, child.ref, gte, lt, depth + 1);
429
+ prior = child.max;
430
+ }
431
+ }
432
+ }
395
433
  class BatchTree {
396
434
  /** cached returns an already validated committed page, or undefined to read it through the writer. */
397
435
  constructor(writer, root, count, byteBudget, cached = () => void 0) {
@@ -585,9 +623,9 @@ class ReadSession {
585
623
  pending = /* @__PURE__ */ new Set();
586
624
  revision;
587
625
  count;
588
- work(fn) {
626
+ work(fn, invokesUserCode = false) {
589
627
  if (this.closed) return Promise.reject(new DbsonlError("CLOSED", "Snapshot is closed."));
590
- const promise = fn();
628
+ const promise = invokesUserCode ? Promise.resolve().then(fn) : fn();
591
629
  this.pending.add(promise);
592
630
  void promise.then(() => this.pending.delete(promise), () => this.pending.delete(promise));
593
631
  return promise;
@@ -626,6 +664,71 @@ class ReadSession {
626
664
  throw: (error) => iterator.throw(error)
627
665
  };
628
666
  }
667
+ /** Native bounded batches: one tracked pull per batch and one async traversal per leaf. */
668
+ scanBatches(options = {}) {
669
+ const { gte, lt, signal, sizeOf } = options;
670
+ if (gte !== void 0) key(gte);
671
+ if (lt !== void 0) key(lt);
672
+ const limit = natural(options.limit ?? Number.MAX_SAFE_INTEGER, "scan limit");
673
+ const batchSize = natural(options.batchSize ?? 256, "batchSize", 1);
674
+ const maxBytes = natural(options.maxBatchBytes ?? 4 * 1024 * 1024, "maxBatchBytes", 1);
675
+ if (sizeOf !== void 0 && typeof sizeOf !== "function") throw new TypeError("sizeOf must be a function.");
676
+ const { db, head } = this;
677
+ async function* batches() {
678
+ let count = 0, bytes = 0, batch = [];
679
+ const window = {};
680
+ abort(signal);
681
+ if (!limit) return;
682
+ for await (const page of entryPages((ref) => db.load(head, ref), head.root, gte, lt)) {
683
+ let first = 0, last = 0, run = [];
684
+ for (let i = 0; i < page.length; i++) {
685
+ const entry = page[i];
686
+ abort(signal);
687
+ if (i >= last && windowContains(window, entry.ref)) {
688
+ const stop = Math.min(page.length, i + limit - count, i + batchSize - batch.length);
689
+ first = i;
690
+ last = i + 1;
691
+ while (last < stop && windowContains(window, page[last].ref)) last++;
692
+ run = last - first > 1 ? db.cachedValues(page, first, last, window) : [];
693
+ }
694
+ 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);
695
+ abort(signal);
696
+ const row = { key: entry.key, revision: entry.revision, value };
697
+ const size = natural(sizeOf ? sizeOf(row) : entry.ref.byteLength, "batch row bytes");
698
+ if (size > maxBytes) throw new DbsonlError("LIMIT_EXCEEDED", "One row exceeds the batch byte budget.");
699
+ if (batch.length && bytes + size > maxBytes) {
700
+ yield batch;
701
+ batch = [];
702
+ bytes = 0;
703
+ abort(signal);
704
+ }
705
+ batch.push(row);
706
+ bytes += size;
707
+ count++;
708
+ if (batch.length === batchSize) {
709
+ yield batch;
710
+ batch = [];
711
+ bytes = 0;
712
+ abort(signal);
713
+ }
714
+ if (count === limit) {
715
+ if (batch.length) yield batch;
716
+ return;
717
+ }
718
+ }
719
+ }
720
+ if (batch.length) yield batch;
721
+ }
722
+ const iterator = batches();
723
+ return {
724
+ [Symbol.asyncIterator]() {
725
+ return this;
726
+ },
727
+ next: () => this.work(() => iterator.next(), true),
728
+ return: () => iterator.return(void 0),
729
+ throw: (error) => iterator.throw(error)
730
+ };
731
+ }
629
732
  /** Drain admitted reads before releasing the generation pin used by garbage collection. */
630
733
  close() {
631
734
  if (this.closing) return this.closing;
@@ -739,7 +842,7 @@ class Dbsonl {
739
842
  return release;
740
843
  }
741
844
  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) => {
845
+ 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
846
  this.sessions.delete(session2);
744
847
  } }, Object.freeze(head), release);
745
848
  this.sessions.add(session);
@@ -102,6 +102,12 @@ interface ScanOptions {
102
102
  limit?: number;
103
103
  signal?: CancellationSignal;
104
104
  }
105
+ /** Batch bytes use encoded frame lengths unless a pure retained-size estimator is supplied. */
106
+ interface BatchScanOptions<T> extends ScanOptions {
107
+ batchSize?: number;
108
+ maxBatchBytes?: number;
109
+ sizeOf?: (row: Row<T>) => number;
110
+ }
105
111
  interface CommitOptions {
106
112
  ifRevision?: number;
107
113
  signal?: CancellationSignal;
@@ -125,4 +131,4 @@ interface Transaction<T> {
125
131
  scan(options?: ScanOptions): AsyncIterableIterator<Row<T>>;
126
132
  }
127
133
 
128
- export type { Backend as B, CommitOptions as C, Head as H, Lookup as L, Mutation as M, Options as O, Page as P, Release as R, ScanOptions as S, Transaction as T, Ref as a, Row as b, Commit as c, Stats as d, Coordinator as e };
134
+ export type { Backend as B, CommitOptions as C, Entry as E, Head as H, Lookup as L, Mutation as M, Options as O, Page as P, Release as R, ScanOptions as S, Transaction as T, Ref as a, Row as b, BatchScanOptions as c, Commit as d, Stats as e, Coordinator as f };
@@ -102,6 +102,12 @@ interface ScanOptions {
102
102
  limit?: number;
103
103
  signal?: CancellationSignal;
104
104
  }
105
+ /** Batch bytes use encoded frame lengths unless a pure retained-size estimator is supplied. */
106
+ interface BatchScanOptions<T> extends ScanOptions {
107
+ batchSize?: number;
108
+ maxBatchBytes?: number;
109
+ sizeOf?: (row: Row<T>) => number;
110
+ }
105
111
  interface CommitOptions {
106
112
  ifRevision?: number;
107
113
  signal?: CancellationSignal;
@@ -125,4 +131,4 @@ interface Transaction<T> {
125
131
  scan(options?: ScanOptions): AsyncIterableIterator<Row<T>>;
126
132
  }
127
133
 
128
- export type { Backend as B, CommitOptions as C, Head as H, Lookup as L, Mutation as M, Options as O, Page as P, Release as R, ScanOptions as S, Transaction as T, Ref as a, Row as b, Commit as c, Stats as d, Coordinator as e };
134
+ export type { Backend as B, CommitOptions as C, Entry as E, Head as H, Lookup as L, Mutation as M, Options as O, Page as P, Release as R, ScanOptions as S, Transaction as T, Ref as a, Row as b, BatchScanOptions as c, Commit as d, Stats as e, Coordinator as f };
package/docs/API.md CHANGED
@@ -22,7 +22,7 @@ Names contain 1 through 64 lowercase letters, digits, hyphens or underscores, be
22
22
  | `delete(key, options?)` | Atomic delete; deleting an absent key is valid |
23
23
  | `batch(mutations, {ifRevision?, signal?}?)` | One revision for all operations; duplicate keys apply in input order |
24
24
  | `transaction(callback, {signal?}?)` | `{result, revision, count}`; callback runs once; a changed read key aborts publication |
25
- | `beginRead()` | Explicit immutable snapshot with `revision`, `count`, `get`, `scan`, `close` |
25
+ | `beginRead()` | Explicit immutable snapshot with `revision`, `count`, `get`, `scan`, `scanBatches`, `close` |
26
26
  | `stats()` | Current revision, count, generation, committedBytes, cacheBytes, cachePages, durability |
27
27
  | `verify()` | Full persisted logical integrity traversal; returns revision and count |
28
28
  | `compact({mode?, signal?}?)` | Copy live data and rebuild index; returns revision, beforeBytes, afterBytes |
@@ -37,6 +37,8 @@ A transaction exposes `revision`, async `get`, synchronous `put`/`delete` and an
37
37
 
38
38
  Snapshot and transaction scans accept `{gte?, lt?, limit?, signal?}` and yield one `{key, value, revision}` per pull. `gte` is inclusive, `lt` exclusive. Returned values are owned decoded objects. A paused iterator becomes unusable when its snapshot closes. Use `try/finally` to close snapshots even after errors or early breaks.
39
39
 
40
+ VERIFIED: A snapshot's `scanBatches({gte?, lt?, limit?, signal?, batchSize?, maxBatchBytes?, sizeOf?})` yields the rows `scan` yields for the same range and limit, as fresh nonempty arrays of owned decoded `{key, value, revision}` records. A batch holds at most `batchSize` rows (default 256) and `maxBatchBytes` bytes (default 4 MiB). A row counts its encoded frame length, or the safe non-negative integer that `sizeOf(row)` returns; `sizeOf` runs once per row. When the next row would exceed the byte budget, the batch ends and that row starts the next one. A row larger than the whole budget fails the pull with `LIMIT_EXCEEDED`; batches yielded before it stay valid. Each pull is admitted before `sizeOf` runs, so `close()`, even when called from inside `sizeOf`, waits for the pull before it releases the snapshot. With one tracked pull per batch instead of per row, a full scan took 0.46 to 0.84 of the 0.5.0 row scan's time ([PERFORMANCE.md](PERFORMANCE.md#batch-scans-on-macos-arm64)). Transaction scans stay row iterators.
41
+
40
42
  VERIFIED: Optimistic compaction is the default. A concurrent publication yields `CONFLICT` and leaves an unpublished candidate for `collect()`. Exclusive compaction holds the commit lock through copying; readers retain their roots and writers queue. Compaction does not change logical revision or record revisions. Collection refreshes the fallback head before deleting files and never removes an active generation pin.
41
43
 
42
44
  ## Options and memory accounting
@@ -80,6 +82,6 @@ VERIFIED: `Backend` contains a Storage adapter, a positive `writeChunkBytes`, a
80
82
 
81
83
  VERIFIED: `createFileBackend(root, {io: 'async'})` is the default. The `{io: 'sync'}` option uses blocking reads, writes, size queries and flushes; use it in a worker or CLI when throughput matters more than scheduling other tasks on that thread. Lock attempts are always nonblocking and contended OS locks wait asynchronously. A single `get()` holds the commit lock through its read; explicit snapshots retain their independent lifetime and permit writers to proceed.
82
84
 
83
- VERIFIED: Each open database retains at most two idle native read descriptors plus at most eight idle lock descriptors (normally four), an 8 KiB manifest parse cache, and its configured page cache. Each active scan/compaction can retain a 64 KiB read-ahead window; each active writer has a buffer of at most 64 KiB. Point reads never retain decoded or encoded values between calls. If the head changes, a native get may temporarily decode both its prior-root candidate and the current-root value; this work is bounded by two record budgets, excluding decoded-object overhead. These fixed buffers and descriptor resources are separate from `stats().cacheBytes`. Close database handles when idle generations should release OS resources immediately; unlinking a file held open by another process does not immediately free its disk blocks.
85
+ VERIFIED: Each open database retains at most two idle native read descriptors plus at most eight idle lock descriptors (normally four), an 8 KiB manifest parse cache, and its configured page cache. Each active scan or compaction can retain a 64 KiB read-ahead window, on every backend; each active writer has a buffer of at most 64 KiB. Point reads never retain decoded or encoded values between calls. If the head changes, a native get may temporarily decode both its prior-root candidate and the current-root value; this work is bounded by two record budgets, excluding decoded-object overhead. These fixed buffers and descriptor resources are separate from `stats().cacheBytes`. Close database handles when idle generations should release OS resources immediately; unlinking a file held open by another process does not immediately free its disk blocks.
84
86
 
85
87
  VERIFIED: Custom backends may optionally expose `connect(name)`, returning `{backend, close}` for a per-database scope. The engine closes that scope on failed open and after draining successful handles. An optional `read(name, offset, length)` performs fresh positional reads of immutable committed prefixes, or the manifest under the commit lock. It must honor read chunk limits, reject invalid names/symlinks/nonregular files and return owned bytes. It fills the requested range unless EOF is encountered; partial OS reads must be retried. It must allow concurrent readers and writers of disjoint, unpublished bytes. Omitting both capabilities retains the portable Storage path. The supplied native implementation provides them; OPFS deliberately keeps its exclusive-handle protocol.
package/docs/FORMAT.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # DBSONL format 2
2
2
 
3
- VERIFIED: The disk format uses DSON 1.3.0 sequence frames. defuss-dson 1.4.0 writes the same bytes as 1.3.0, so builds on either version read each other's files. Each frame has a 16-byte DSQ header with length, header CRC32C and payload CRC32C. Payloads encode values and references locally to that frame. DBSONL adds no JSON/base64 layer.
3
+ VERIFIED: The disk format uses DSON 1.3.0 sequence frames. defuss-dson 1.4.0, 1.5.0 and 1.5.1 write the same bytes as 1.3.0, so builds on any of these versions read each other's files. Each frame has a 16-byte DSQ header with length, header CRC32C and payload CRC32C. Payloads encode values and references locally to that frame. DBSONL adds no JSON/base64 layer.
4
4
 
5
5
  ## Files
6
6
 
@@ -1,38 +1,40 @@
1
1
  # Performance evidence
2
2
 
3
- VERIFIED: Every table compares builds under the same format, transactional API, durability barriers, values and assertions. The macOS arm64 tables measure v0.2.0, v0.3.0 and v0.4.0 in the same runs. The Linux x64 tables come from an earlier run that measured v0.2.0 and a 0.3.0 build only; no Linux host was available for 0.4.0. The vendored 0.3.0 tarball is the build those Linux tables measured: its `dist` hashes match the recorded artifacts. The Redis section compares the current source with another store instead, under the pairings it states.
4
-
5
- ## macOS arm64: v0.2, v0.3 and v0.4
6
-
7
- VERIFIED: Three consecutive runs of `make bench` under the pinned toolchain (`mise exec`) on an Apple M5 Max (18 logical CPUs), macOS 25.6.0, APFS, Node 24.22.1 (V8) and Bun 1.4.3 (JavaScriptCore), on 2026-11-15. The machine was busy, with a load average between 4.6 and 8.3. Each run takes the median of seven rounds after two warmups; the tables show the median of the three runs. Times are milliseconds per 1000 operations or rows; batch, compaction and reopen are per workload. All three raw reports are in `validation/bench-macos-arm64.json`.
8
-
9
- | Runtime | Workload | v0.2 ms | v0.3 ms | v0.4 ms | v0.4 vs v0.2 |
10
- | --- | --- | ---: | ---: | ---: | ---: |
11
- | Node | Fresh-root get | 445.39 | 30.07 | 31.14 | 14.31x |
12
- | Node | Pinned snapshot get | 132.79 | 13.53 | 12.98 | 10.23x |
13
- | Node | Snapshot scan | 129.26 | 4.99 | 5.55 | 23.29x |
14
- | Node | Atomic batch | 31.60 | 19.53 | 18.68 | 1.69x |
15
- | Node | Compaction | 177.95 | 24.76 | 24.65 | 7.22x |
16
- | Node | Indexed reopen | 0.48 | 0.47 | 0.52 | 0.93x |
17
- | Bun | Fresh-root get | 514.84 | 39.91 | 41.10 | 12.53x |
18
- | Bun | Pinned snapshot get | 155.19 | 15.89 | 17.35 | 8.94x |
19
- | Bun | Snapshot scan | 155.67 | 7.58 | 9.37 | 16.62x |
20
- | Bun | Atomic batch | 26.97 | 14.05 | 12.84 | 2.10x |
21
- | Bun | Compaction | 180.52 | 18.97 | 19.37 | 9.32x |
22
- | Bun | Indexed reopen | 0.38 | 0.34 | 0.31 | 1.24x |
23
-
24
- | Runtime | Mode | v0.2 get ms | v0.3 get ms | v0.4 get ms |
3
+ VERIFIED: Every table compares builds under the same format, transactional API, durability barriers, values and assertions. The first macOS arm64 tables measure v0.2.0, v0.3.0 and v0.5.0 in the same runs; the 10000-record check measured v0.4.0 in an earlier session. The Linux x64 tables come from an earlier run that measured v0.2.0 and a 0.3.0 build only; no Linux host was available later. The vendored 0.3.0 tarball is the build those Linux tables measured: its `dist` hashes match the recorded artifacts. The Redis section compares the current source with another store instead, under the pairings it states.
4
+
5
+ ## macOS arm64: v0.2, v0.3 and v0.5
6
+
7
+ VERIFIED: Three consecutive runs of `make bench` under the pinned toolchain (`mise exec`) on an Apple M5 Max (18 logical CPUs), macOS 25.6.0, APFS, Node 24.22.1 (V8) and Bun 1.4.3 (JavaScriptCore), on 2026-11-16. The machine was busy: the 1-minute load average was 8.25 before the first run and 10.96 after the last. Each run takes the median of seven rounds after two warmups; the tables show the median of the three runs. Times are milliseconds per 1000 operations or rows; batch, compaction and reopen are per workload. All three raw reports are in `validation/bench-macos-arm64.json`.
8
+
9
+ | Runtime | Workload | v0.2 ms | v0.3 ms | v0.5 ms | v0.5 vs v0.3 | v0.5 vs v0.2 |
10
+ | --- | --- | ---: | ---: | ---: | ---: | ---: |
11
+ | Node | Fresh-root get | 600.01 | 34.92 | 21.28 | 1.64x | 28.19x |
12
+ | Node | Pinned snapshot get | 189.58 | 14.40 | 11.72 | 1.23x | 16.18x |
13
+ | Node | Snapshot scan | 188.60 | 5.68 | 4.35 | 1.30x | 43.33x |
14
+ | Node | Atomic batch | 36.49 | 20.60 | 12.72 | 1.62x | 2.87x |
15
+ | Node | Compaction | 237.56 | 29.09 | 19.67 | 1.48x | 12.08x |
16
+ | Node | Indexed reopen | 0.75 | 0.55 | 0.62 | 0.88x | 1.21x |
17
+ | Bun | Fresh-root get | 515.68 | 44.51 | 44.38 | 1.00x | 11.62x |
18
+ | Bun | Pinned snapshot get | 159.85 | 25.10 | 18.51 | 1.36x | 8.63x |
19
+ | Bun | Snapshot scan | 168.86 | 10.02 | 6.70 | 1.50x | 25.22x |
20
+ | Bun | Atomic batch | 32.24 | 16.22 | 6.67 | 2.43x | 4.83x |
21
+ | Bun | Compaction | 183.75 | 20.18 | 10.71 | 1.88x | 17.16x |
22
+ | Bun | Indexed reopen | 0.37 | 0.48 | 0.44 | 1.09x | 0.84x |
23
+
24
+ | Runtime | Mode | v0.2 get ms | v0.3 get ms | v0.5 get ms |
25
25
  | --- | --- | ---: | ---: | ---: |
26
- | Node | sync | 398.20 | 13.08 | 13.85 |
27
- | Node | memory | 21.66 | 12.09 | 11.21 |
28
- | Bun | sync | 436.05 | 24.07 | 28.45 |
29
- | Bun | memory | 27.86 | 21.15 | 23.50 |
26
+ | Node | sync | 488.60 | 16.08 | 10.72 |
27
+ | Node | memory | 24.00 | 13.63 | 9.77 |
28
+ | Bun | sync | 485.93 | 24.24 | 19.14 |
29
+ | Bun | memory | 38.07 | 23.14 | 21.06 |
30
30
 
31
- VERIFIED: On Node, v0.3 and v0.4 trade places from run to run with no consistent direction. On Bun, v0.4 was slower than v0.3 in all three runs for snapshot reads and scans on memory storage (20% to 26%), scans on native synchronous I/O (14% to 34%) and scans on native asynchronous I/O (12% to 28%). Both builds issue the same Storage reads.
31
+ VERIFIED: No v0.5 figure was slower than v0.3 in all three runs. Reopen, a fraction of a millisecond, traded places from run to run, and so did Bun's fresh-root get on native asynchronous I/O and Node's on synchronous I/O. The largest gains are in batches and compaction.
32
32
 
33
- UNKNOWN: Why Bun runs these 0.4.0 read paths slower. Decoding moved into a shared `decodeRef` helper and the bundle layout changed when the legacy entries were removed; a Bun CPU profile of the memory snapshot-scan workload on both builds would locate the difference.
33
+ VERIFIED: The 0.4.0 Bun slowdown on reads is gone in these runs. In the 2026-11-15 session, 0.4.0 ran Bun snapshot reads and scans on memory storage 20% to 26% slower than 0.3.0, and scans on native storage 12% to 34% slower. Here v0.5 is faster than v0.3 on each of those workloads: memory snapshot get 4.53 against 7.33 ms, memory scan 3.14 against 6.65 ms, native asynchronous scan 6.70 against 10.02 ms. The three 0.4.0 runs are kept in `validation/bench-macos-arm64-0.4.0.json`. Both sessions ran under different loads, so their milliseconds do not compare directly, and 0.4.0 has no column here.
34
34
 
35
- VERIFIED: The 10000-record check is one run of `make bench-scale` in the same session, native asynchronous I/O, two warmups and three measured rounds, in milliseconds per 10000 lookups. Raw measurements are in `validation/bench-scale-macos-arm64.json`.
35
+ UNKNOWN: Why Bun ran those 0.4.0 read paths slower; the 0.5.0 runs no longer show it.
36
+
37
+ VERIFIED: The 10000-record check is one run of `make bench-scale` in the 2026-11-15 session, which measured v0.4.0, native asynchronous I/O, two warmups and three measured rounds, in milliseconds per 10000 lookups. Raw measurements are in `validation/bench-scale-macos-arm64.json`.
36
38
 
37
39
  | Runtime | v0.2 get ms | v0.3 get ms | v0.4 get ms | v0.4 vs v0.2 |
38
40
  | --- | ---: | ---: | ---: | ---: |
@@ -78,6 +80,32 @@ VERIFIED: The memory batches lose to encoding. In a CPU profile of a Node memory
78
80
 
79
81
  VERIFIED: Rejected in these probes: splitting pages at 16 or 8 entries instead of 32 left contended memory commits within noise and made memory batches 10% to 30% slower; deduplicating objects by identity in the page writer cost a leaf 1.5 to 2 µs of its gain; inserting cached pages unmarked was slightly slower than marking them. An earlier commit delay that waited before setting the head new snapshots pin measured 3.90 to 3.92 ms per contended Node commit against 3.62 to 3.81 ms without it. Cutting small frames from shared slabs left batch times within run-to-run noise.
80
82
 
83
+ ## Batch scans on macOS arm64
84
+
85
+ VERIFIED: Three consecutive runs of `mise exec -- make bench-scan` on 2026-11-17, on the host above, with Node 24.22.1, Bun 1.4.3 and defuss-dson 1.5.1, at a load average of 2.2 to 4.7. Each run writes 100,000 documents of four fields (a short string, a number, a two-string array and a Date) in batches of 5000, then scans every one of them per case: the row scan of the vendored 0.5.0 package, the current row scan and the current `scanBatches` with its defaults. One untimed warmup checks that all three return the same count and checksum, then seven rounds alternate their order, each after a full garbage collection. The table shows the median of the three per-run medians in milliseconds per full scan. The raw reports are in `validation/bench-scan-macos-arm64.json`.
86
+
87
+ | Runtime | Storage | 0.5.0 `scan` | `scan` | `scanBatches` | `scanBatches` vs 0.5.0 |
88
+ | --- | --- | ---: | ---: | ---: | ---: |
89
+ | Node | memory | 391.4 | 237.2 | 178.8 | 0.46 |
90
+ | Node | native async | 341.1 | 316.8 | 247.5 | 0.73 |
91
+ | Bun | memory | 345.9 | 219.2 | 179.0 | 0.52 |
92
+ | Bun | native async | 322.3 | 306.8 | 269.4 | 0.84 |
93
+
94
+ VERIFIED: On memory storage the row scan alone took 0.61 of 0.5.0's time under Node and 0.63 under Bun, mostly because scans now read ahead on every backend: 0.5.0 opened, read and closed the memory file once per row. On native storage, which already read ahead, the row scan took 0.93 under Node and 0.95 under Bun, the per-frame saving of defuss-dson 1.5. Batches gain more: one tracked pull per batch, one tree step per leaf, and one `decodeFrames` call per run of frames that the read window holds.
95
+
96
+ VERIFIED: The same session also measured `scanBatches` on defuss-dson 1.4.0 and on 1.5.0 with the runs switched off, three runs each, medians in milliseconds per full scan:
97
+
98
+ | Runtime | Storage | defuss-dson 1.4.0 | 1.5.0, no runs | 1.5.1 with `decodeFrames` |
99
+ | --- | --- | ---: | ---: | ---: |
100
+ | Node | memory | 216.2 | 189.7 | 178.8 |
101
+ | Node | native async | 284.1 | 262.4 | 247.5 |
102
+ | Bun | memory | 196.2 | 188.6 | 179.0 |
103
+ | Bun | native async | 284.1 | 283.7 | 269.4 |
104
+
105
+ VERIFIED: defuss-dson 1.5.1 converts each frame offset to an int32 before reading. With 1.5.0, run offsets derived from decoded index pages, which are doubles in JavaScriptCore, took Bun off the decoder's int32 code: 503 type-speculation exits in its 32-bit reads, and `scanBatches` took 0.70 of 0.5.0's time on memory storage instead of 0.52, slower than without runs. Node was unaffected. Converting the offsets in defuss-dbsonl gave the same times as 1.5.1 does now, within 2%; the conversion lives in defuss-dson so that every caller gets it.
106
+
107
+ VERIFIED: Most of what remains is decoding. In a CPU profile under Node on defuss-dson 1.4.0, of one process that loads the 100,000 documents into memory storage and then scans them ten times with `scanBatches`, defuss-dson took 74% of the time: decoding values, checking each frame's checksum, and setting up a reader and limits for every frame. defuss-dbsonl's own code took 14%. defuss-dson 1.5.0 removes most of the per-frame setup; the checksums and building each value remain.
108
+
81
109
  ## Linux x64: v0.2 and v0.3
82
110
 
83
111
  VERIFIED: Times below are medians of seven measured rounds after two complete warmup rounds, in milliseconds per 1000 operations or rows. Batch means one atomic commit of 1000 mutations, including flushes. Reopen is one indexed open, not 1000 opens. Raw samples, measured build SHA-256 hashes, exact runtime versions and host metadata are in `validation/bench.json` in the source ZIP.
package/package.json CHANGED
@@ -1,9 +1,17 @@
1
1
  {
2
2
  "name": "defuss-dbsonl",
3
- "version": "0.5.0",
4
- "description": "Transactional DSON storage with a persistent copy-on-write index, MVCC snapshots, compaction and process-safe coordination.",
3
+ "version": "0.6.0",
4
+ "description": "High performance transactional DSON storage with a persistent copy-on-write index, MVCC snapshots, compaction and process-safe coordination.",
5
5
  "license": "MIT",
6
6
  "author": "Aron Homberg",
7
+ "homepage": "https://dbsonl.defuss.org",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/kyr0/defuss-dbjsonl.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/kyr0/defuss-dbjsonl/issues"
14
+ },
7
15
  "type": "module",
8
16
  "packageManager": "bun@1.4.3",
9
17
  "sideEffects": false,
@@ -56,7 +64,7 @@
56
64
  },
57
65
  "dependencies": {
58
66
  "@lickle/lock": "0.0.1",
59
- "defuss-dson": "1.4.0",
67
+ "defuss-dson": "1.5.1",
60
68
  "defuss-storage": "0.3.1"
61
69
  },
62
70
  "scripts": {