defuss-dbsonl 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ARCH.md CHANGED
@@ -92,12 +92,16 @@ VERIFIED: Data written after the published end is private. A later writer trunca
92
92
 
93
93
  ## Transactions, memory and lifecycle
94
94
 
95
- VERIFIED: Batch values are encoded before admission returns, preventing caller mutation during queued work. Both per-transaction and aggregate pending-byte budgets are enforced. A transaction callback reads from one snapshot plus a bounded staged overlay. The final database revision must still equal its snapshot revision, including read-only transactions and range scans. This conservative validation provides serializability but can reject transactions touching disjoint keys. Automatic retries are omitted because callbacks may have external effects.
95
+ VERIFIED: Batch values are encoded, and caller frames copied, before admission returns, preventing caller mutation during queued work. Both per-transaction and aggregate pending-byte budgets are enforced. A transaction callback reads from one snapshot plus a bounded staged overlay. The final database revision must still equal its snapshot revision, including read-only transactions and range scans. This conservative validation provides serializability but can reject transactions touching disjoint keys. Automatic retries are omitted because callbacks may have external effects.
96
+
97
+ VERIFIED: `batchFrames` and `putFrame` commit a DSON frame the caller already encoded, so a caller that keeps an encoded snapshot of a value does not pay for a second encode. Each frame is copied and the copy decoded once at admission, under the limits every read applies, before it can stage. A public flag that marks frames as trusted was rejected: a damaged or malformed frame would commit and then fail at every later read, as `CORRUPT` or `LIMIT_EXCEEDED`, and compaction, which copies frames after checking only their checksums, would carry one whose checksums match into every new generation. Storing the frame as a byte-array value was rejected too: reads would return bytes instead of the value, and the engine would encode the bytes again. A transfer of the caller's buffer instead of a copy detaches the whole `ArrayBuffer`, and under Node 26 a `Buffer` of 300 bytes sat in a shared pool buffer of 65,600 bytes, so a transfer would take the caller's unrelated bytes with it.
98
+
99
+ VERIFIED: The check has a cost: a caller that encoded its values and committed the frames took 1.12 to 2.06 times as long as `batch` takes to encode and commit the same values ([PERFORMANCE.md](docs/PERFORMANCE.md#caller-encoded-frames-on-macos-arm64)). `db.frame(value)` removes it for a caller that only needs a snapshot to commit later: the engine encodes the value, keeps the bytes in a module-private `WeakMap` under a frozen handle it returns, and commits a handle it finds there without a copy or a decode; that took 0.99 to 1.11 of `batch`'s time. Only the engine can add a handle, so the check is skipped for bytes its own encoder produced and nothing else, which a public trusted flag could not ensure. The bytes are never exposed, so they cannot change after encoding. The cost: a handle does not cross a structured clone or a second copy of the package, such as its CommonJS build beside the ESM one; there it is refused with `TypeError`, and the caller passes a `Uint8Array` frame instead.
96
100
 
97
101
  VERIFIED: Closing a snapshot rejects new reads, drains admitted reads and releases its pin. Paused iterators do not prevent closure. Closing a database stops admission, drains operations, closes its snapshots and discards its cache. Cancellation is cooperative during waiting and copying. After publication starts, completion is success or an uncertain commit error rather than an ordinary cancellation.
98
102
 
99
103
  ## Operations, security and privacy
100
104
 
101
- VERIFIED: The trusted storage root is application-owned. Native byte and lock files reject symlink traversal where supported; database names are lowercase identifiers. Bounds and backward-only child references reject malformed addresses and disk cycles. CRC32C detects damage, not forgery. DSON values may be cyclic and contain binary data. Applications needing encryption or authentication must provide those policies separately.
105
+ VERIFIED: The trusted storage root is application-owned. Native byte and lock files reject symlink traversal where supported; database names are lowercase identifiers. Bounds and backward-only child references reject malformed addresses and disk cycles. CRC32C detects damage, not forgery; a caller's frame is therefore decoded at admission, so a frame with matching checksums but an invalid payload cannot commit. DSON values may be cyclic and contain binary data. Applications needing encryption or authentication must provide those policies separately.
102
106
 
103
107
  VERIFIED: There is no network service or background maintenance. Applications schedule `compact()` and `collect()` and close snapshots promptly. Maintenance needs enough disk space for the live copy. No telemetry or application-value logging occurs. Tests use temporary databases and real processes. Source, tests, examples and tooling each document their own responsibilities in ARCH.md.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.0
4
+
5
+ VERIFIED: `db.batchFrames(mutations, options?)` and `tx.putFrame(key, frame)` commit DSON frames the caller already encoded, with the revisions, conflicts, commit groups, budgets and durability of `batch` and `put`. A `Uint8Array` frame is copied at call time and decoded once to check it; one that is not exactly one valid frame throws `TypeError`, one over a budget `RangeError`. `db.frame(value)` encodes a value into an `OwnedFrame` whose bytes stay in the engine, which those calls commit without a copy or a check. In a benchmark of 10,000 records, a caller that encodes each value, decodes the copy and commits it with `batch` took 1.18 to 2.71 times as long as `batch` alone; with `Uint8Array` frames it took 1.12 to 2.06 times, with `frame()` 0.99 to 1.11 times ([PERFORMANCE.md](docs/PERFORMANCE.md#caller-encoded-frames-on-macos-arm64)). The file format is unchanged. `make bench-frames` reproduces the measurement.
6
+
3
7
  ## 0.9.0
4
8
 
5
9
  VERIFIED: New databases use format 5, which writes index pages only at checkpoints. Between them, a commit appends its values, a compact list of its key changes and its record, and flushes once; the handle that wrote it keeps the changed pages in memory, and every other handle, process or worker replays the records since the last checkpoint. A commit is a checkpoint when the log reaches 16 MiB or the pages held in memory would exceed `maxCachePages`. On a 100,000-document defuss-db load with one ordered index, commits of 256 documents took 2.50 s in all instead of 3.35 to 3.92 s, a 64-document commit 4.39 ms instead of 5.89 to 6.08 ms, and the load wrote 29 to 31 MiB instead of 107 to 166 MiB. Format 2 to 4 databases keep their format; 0.8 refuses format 5 with `UNSUPPORTED`.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # defuss-dbsonl 0.9.0
1
+ # defuss-dbsonl 0.10.0
2
2
 
3
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.4.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
 
@@ -50,6 +50,8 @@ try {
50
50
 
51
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.
52
52
 
53
+ A caller that already holds a value's DSON frame, for example because it keeps an encoded snapshot of the value, commits it with `batchFrames()` or `tx.putFrame()` instead of encoding the value again. DBSONL copies the frame and decodes it once to check it, so a damaged or partial frame is refused before it commits; reads return the value. A caller that encodes only to keep a snapshot until it commits can take it with `db.frame(value)` instead: the engine keeps the bytes, so committing the snapshot needs no copy and no check, and took 0.99 to 1.11 of the time of `batch` with the values, against 1.18 to 2.71 for encoding, decoding and committing the copy ([PERFORMANCE.md](docs/PERFORMANCE.md#caller-encoded-frames-on-macos-arm64)); [API](docs/API.md) lists the checks.
54
+
53
55
  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
56
 
55
57
  On native storage, `scanBatches()` uses worker threads by itself once a snapshot range holds at least 5000 rows: a pool of up to four workers decodes the rows and hands them back in key order. A full scan of 100,000 documents took 105 ms instead of 401 ms under Node. `createFileBackend(root, { scanWorkers: 0 })` turns the pool off; scans with a `sizeOf` callback, `scan()` row iterators and memory and browser backends stay in the calling thread.
@@ -139,6 +141,7 @@ make verify # lint, tests, coverage, packed-package e2e
139
141
  make bench # matched v0.2 versus current benchmarks
140
142
  make bench-scan # full scans, row by row and in batches, against the vendored 0.5.0
141
143
  make bench-redis # current build versus a throwaway loopback Redis, run as mise exec -- make bench-redis
144
+ make bench-frames # values through batch against caller-encoded frames and frame() handles through batchFrames
142
145
  make dev # rebuild the website demos and serve docs/ on 127.0.0.1:3000
143
146
  make vae # verification, review and documentation gate
144
147
  make release # tarball, source ZIP and checksums; never publishes or commits
package/dist/index.cjs CHANGED
@@ -966,6 +966,19 @@ function newGeneration() {
966
966
  function code(error) {
967
967
  return error?.code;
968
968
  }
969
+ const issuedFrames = /* @__PURE__ */ new WeakMap();
970
+ function ownFrame(frame, maxRecordBytes) {
971
+ const issued = issuedFrames.get(frame);
972
+ if (issued) {
973
+ if (issued.length - 16 > maxRecordBytes) throw new RangeError("A frame exceeds maxRecordBytes.");
974
+ return issued;
975
+ }
976
+ if (!(frame instanceof Uint8Array)) throw new TypeError("A frame must be a Uint8Array or a frame from Dbsonl.frame().");
977
+ if (frame.length - 16 > maxRecordBytes) throw new RangeError("A frame exceeds maxRecordBytes.");
978
+ const owned = new Uint8Array(frame);
979
+ if (sequence.decodeFrame(owned, 0, { maxRecordBytes, maxDepth: 512, maxReferences: 1e6 }).byteLength !== owned.length) throw new TypeError("A frame must hold exactly one DSON frame and no other bytes.");
980
+ return owned;
981
+ }
969
982
  const pageId = (head, ref) => `${head.generation}:${ref.offset}:${ref.byteLength}`;
970
983
  const batchBytes = /* @__PURE__ */ new WeakMap();
971
984
  const TASK_BYTES = 1024 * 1024, MAX_TASKS = 1024;
@@ -1394,14 +1407,15 @@ class Dbsonl {
1394
1407
  return this.lookup(head, id);
1395
1408
  }));
1396
1409
  }
1397
- /** Capture values synchronously so subsequent caller mutation cannot change an admitted batch. */
1398
- encode(input) {
1410
+ /** Capture values, or copies of frames, synchronously so subsequent caller mutation cannot change an admitted batch. */
1411
+ encode(input, frames = false) {
1399
1412
  if (!Array.isArray(input) || input.length > this.limits.maxTransactionOperations) throw new common.DbsonlError("LIMIT_EXCEEDED", "Transaction operation capacity exceeded.");
1400
1413
  let bytes = 0;
1414
+ const { maxRecordBytes } = this.limits;
1401
1415
  const encoded = input.map((operation) => {
1402
1416
  common.key(operation.key);
1403
1417
  if (operation.operation !== "put" && operation.operation !== "delete") throw new TypeError("Unknown mutation operation.");
1404
- const encoded2 = operation.operation === "put" ? sequence.encodeFrame(operation.value, { maxRecordBytes: this.limits.maxRecordBytes }) : void 0;
1418
+ const encoded2 = operation.operation !== "put" ? void 0 : frames ? ownFrame(operation.frame, maxRecordBytes) : sequence.encodeFrame(operation.value, { maxRecordBytes });
1405
1419
  bytes += (encoded2?.length ?? 0) + operation.key.length * 2 + 64;
1406
1420
  if (bytes > this.limits.maxTransactionBytes) throw new common.DbsonlError("LIMIT_EXCEEDED", "Transaction encoded-byte capacity exceeded.");
1407
1421
  return { key: operation.key, bytes: encoded2 };
@@ -1663,14 +1677,34 @@ class Dbsonl {
1663
1677
  if (written.has(id) || (entry?.revision ?? 0) !== seen) throw new common.DbsonlError("CONFLICT", "A key the transaction read changed after its snapshot.");
1664
1678
  }
1665
1679
  }
1680
+ /**
1681
+ * Encode value now, as put would, into a frame that batchFrames and putFrame of any handle commit as it is: a snapshot
1682
+ * of the value for a caller that queues it before it commits, encoded once.
1683
+ */
1684
+ frame(value) {
1685
+ const bytes = sequence.encodeFrame(value, { maxRecordBytes: this.limits.maxRecordBytes });
1686
+ const handle = Object.freeze({ byteLength: bytes.length });
1687
+ issuedFrames.set(handle, bytes);
1688
+ return handle;
1689
+ }
1666
1690
  /** Encode at call time, then publish the entire operation list under one new revision. */
1667
1691
  batch(input, options = {}) {
1692
+ return this.admit(input, false, options);
1693
+ }
1694
+ /**
1695
+ * batch for values the caller already encoded, so they are not encoded twice: each frame is checked and copied at call
1696
+ * time and written as it is. Reads decode it like any value.
1697
+ */
1698
+ batchFrames(input, options = {}) {
1699
+ return this.admit(input, true, options);
1700
+ }
1701
+ admit(input, frames, options) {
1668
1702
  if (this.closed) return Promise.reject(new common.DbsonlError("CLOSED", "Database is closed."));
1669
1703
  if (this.pending.size >= this.limits.maxPendingOperations) return Promise.reject(new common.DbsonlError("QUEUE_FULL", "Too many admitted operations."));
1670
1704
  let encoded;
1671
1705
  try {
1672
1706
  common.abort(options.signal);
1673
- encoded = this.encode(input);
1707
+ encoded = this.encode(input, frames);
1674
1708
  } catch (error) {
1675
1709
  return Promise.reject(error);
1676
1710
  }
@@ -1718,9 +1752,9 @@ class Dbsonl {
1718
1752
  if (!active) throw new common.DbsonlError("CLOSED", "Transaction callback has finished.");
1719
1753
  common.abort(options.signal);
1720
1754
  };
1721
- const stage = (operation) => {
1755
+ const stage = (operation, frames = false) => {
1722
1756
  check();
1723
- const encoded = this.encode([operation])[0];
1757
+ const encoded = this.encode([operation], frames)[0];
1724
1758
  const old = staged.get(encoded.key);
1725
1759
  const nextSize = size - (old ? (old.bytes?.length ?? 0) + old.key.length * 2 + 64 : 0) + (encoded.bytes?.length ?? 0) + encoded.key.length * 2 + 64;
1726
1760
  if (nextSize > this.limits.maxTransactionBytes || !old && staged.size >= this.limits.maxTransactionOperations) throw new common.DbsonlError("LIMIT_EXCEEDED", "Transaction capacity exceeded.");
@@ -1741,6 +1775,7 @@ class Dbsonl {
1741
1775
  return lookup;
1742
1776
  },
1743
1777
  put: (id, value) => stage({ operation: "put", key: id, value }),
1778
+ putFrame: (id, frame) => stage({ operation: "put", key: id, frame }, true),
1744
1779
  delete: (id) => stage({ operation: "delete", key: id }),
1745
1780
  async *scan(scan = {}) {
1746
1781
  check();
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CancellationSignal, MemoryStorageOptions } from 'defuss-storage';
2
- import { R as Ref, E as Entry, B as Backend, O as Options, a as Release, b as ReadOptions, H as Head, P as Page, c as ParallelScan, L as Lookup, S as ScanOptions, d as Row, e as BatchScanOptions, f as Partition, M as Mutation, C as CommitOptions, g as Commit, T as Transaction, h as Stats } from './types-CsFsnMNZ.cjs';
3
- export { i as Coordinator } from './types-CsFsnMNZ.cjs';
2
+ import { R as Ref, E as Entry, B as Backend, O as Options, a as Release, b as ReadOptions, H as Head, P as Page, c as ParallelScan, L as Lookup, S as ScanOptions, d as Row, e as BatchScanOptions, f as Partition, g as OwnedFrame, M as Mutation, C as CommitOptions, h as Commit, F as FrameMutation, T as Transaction, i as Stats } from './types-mP6hm3UW.cjs';
3
+ export { j as Coordinator } from './types-mP6hm3UW.cjs';
4
4
 
5
5
  /** VERIFIED: Shared validators reject ambiguous addresses before allocation or mutation. */
6
6
 
@@ -170,7 +170,7 @@ declare class Dbsonl<T = unknown> {
170
170
  /** Internal lookup only: callers must hold a commit lock or generation pin. */
171
171
  private lookup;
172
172
  get(id: string): Promise<Lookup<T>>;
173
- /** Capture values synchronously so subsequent caller mutation cannot change an admitted batch. */
173
+ /** Capture values, or copies of frames, synchronously so subsequent caller mutation cannot change an admitted batch. */
174
174
  private encode;
175
175
  /**
176
176
  * Queue a commit. The next holder of the commit lock publishes every queued commit with one write,
@@ -195,8 +195,19 @@ declare class Dbsonl<T = unknown> {
195
195
  private settledHead;
196
196
  /** Each point read must still see the entry revision it saw, or absence (0); a scan needs the whole database unchanged. */
197
197
  private validate;
198
+ /**
199
+ * Encode value now, as put would, into a frame that batchFrames and putFrame of any handle commit as it is: a snapshot
200
+ * of the value for a caller that queues it before it commits, encoded once.
201
+ */
202
+ frame(value: T): OwnedFrame;
198
203
  /** Encode at call time, then publish the entire operation list under one new revision. */
199
204
  batch(input: readonly Mutation<T>[], options?: CommitOptions): Promise<Commit>;
205
+ /**
206
+ * batch for values the caller already encoded, so they are not encoded twice: each frame is checked and copied at call
207
+ * time and written as it is. Reads decode it like any value.
208
+ */
209
+ batchFrames(input: readonly FrameMutation[], options?: CommitOptions): Promise<Commit>;
210
+ private admit;
200
211
  /** Replace one key through the same commit protocol used for multi-key batches. */
201
212
  put(id: string, value: T, options?: CommitOptions): Promise<Commit>;
202
213
  /** Delete is idempotent in value state, while every nonempty commit receives a revision. */
@@ -246,5 +257,5 @@ declare function openDbsonl<T = unknown>(backend: Backend, name: string, options
246
257
  /** Realm-local implementation for a new, isolated memory namespace. */
247
258
  declare function createMemoryBackend(options?: MemoryStorageOptions): Backend;
248
259
 
249
- export { Backend, BatchScanOptions, Commit, CommitOptions, DEFAULT_OPTIONS, Dbsonl, DbsonlError, Head, Lookup, Mutation, Options, Page, Partition, ReadOptions, ReadSession, Ref, Release, Row, ScanOptions, Stats, Transaction, createMemoryBackend, openDbsonl };
260
+ export { Backend, BatchScanOptions, Commit, CommitOptions, DEFAULT_OPTIONS, Dbsonl, DbsonlError, FrameMutation, Head, Lookup, Mutation, Options, OwnedFrame, Page, Partition, ReadOptions, ReadSession, Ref, Release, Row, ScanOptions, Stats, Transaction, createMemoryBackend, openDbsonl };
250
261
  export type { ErrorCode };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CancellationSignal, MemoryStorageOptions } from 'defuss-storage';
2
- import { R as Ref, E as Entry, B as Backend, O as Options, a as Release, b as ReadOptions, H as Head, P as Page, c as ParallelScan, L as Lookup, S as ScanOptions, d as Row, e as BatchScanOptions, f as Partition, M as Mutation, C as CommitOptions, g as Commit, T as Transaction, h as Stats } from './types-CsFsnMNZ.mjs';
3
- export { i as Coordinator } from './types-CsFsnMNZ.mjs';
2
+ import { R as Ref, E as Entry, B as Backend, O as Options, a as Release, b as ReadOptions, H as Head, P as Page, c as ParallelScan, L as Lookup, S as ScanOptions, d as Row, e as BatchScanOptions, f as Partition, g as OwnedFrame, M as Mutation, C as CommitOptions, h as Commit, F as FrameMutation, T as Transaction, i as Stats } from './types-mP6hm3UW.mjs';
3
+ export { j as Coordinator } from './types-mP6hm3UW.mjs';
4
4
 
5
5
  /** VERIFIED: Shared validators reject ambiguous addresses before allocation or mutation. */
6
6
 
@@ -170,7 +170,7 @@ declare class Dbsonl<T = unknown> {
170
170
  /** Internal lookup only: callers must hold a commit lock or generation pin. */
171
171
  private lookup;
172
172
  get(id: string): Promise<Lookup<T>>;
173
- /** Capture values synchronously so subsequent caller mutation cannot change an admitted batch. */
173
+ /** Capture values, or copies of frames, synchronously so subsequent caller mutation cannot change an admitted batch. */
174
174
  private encode;
175
175
  /**
176
176
  * Queue a commit. The next holder of the commit lock publishes every queued commit with one write,
@@ -195,8 +195,19 @@ declare class Dbsonl<T = unknown> {
195
195
  private settledHead;
196
196
  /** Each point read must still see the entry revision it saw, or absence (0); a scan needs the whole database unchanged. */
197
197
  private validate;
198
+ /**
199
+ * Encode value now, as put would, into a frame that batchFrames and putFrame of any handle commit as it is: a snapshot
200
+ * of the value for a caller that queues it before it commits, encoded once.
201
+ */
202
+ frame(value: T): OwnedFrame;
198
203
  /** Encode at call time, then publish the entire operation list under one new revision. */
199
204
  batch(input: readonly Mutation<T>[], options?: CommitOptions): Promise<Commit>;
205
+ /**
206
+ * batch for values the caller already encoded, so they are not encoded twice: each frame is checked and copied at call
207
+ * time and written as it is. Reads decode it like any value.
208
+ */
209
+ batchFrames(input: readonly FrameMutation[], options?: CommitOptions): Promise<Commit>;
210
+ private admit;
200
211
  /** Replace one key through the same commit protocol used for multi-key batches. */
201
212
  put(id: string, value: T, options?: CommitOptions): Promise<Commit>;
202
213
  /** Delete is idempotent in value state, while every nonempty commit receives a revision. */
@@ -246,5 +257,5 @@ declare function openDbsonl<T = unknown>(backend: Backend, name: string, options
246
257
  /** Realm-local implementation for a new, isolated memory namespace. */
247
258
  declare function createMemoryBackend(options?: MemoryStorageOptions): Backend;
248
259
 
249
- export { Backend, BatchScanOptions, Commit, CommitOptions, DEFAULT_OPTIONS, Dbsonl, DbsonlError, Head, Lookup, Mutation, Options, Page, Partition, ReadOptions, ReadSession, Ref, Release, Row, ScanOptions, Stats, Transaction, createMemoryBackend, openDbsonl };
260
+ export { Backend, BatchScanOptions, Commit, CommitOptions, DEFAULT_OPTIONS, Dbsonl, DbsonlError, FrameMutation, Head, Lookup, Mutation, Options, OwnedFrame, Page, Partition, ReadOptions, ReadSession, Ref, Release, Row, ScanOptions, Stats, Transaction, createMemoryBackend, openDbsonl };
250
261
  export type { ErrorCode };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- export { c as createMemoryBackend, o as openDbsonl } from './store-DsWjd2ZI.mjs';
1
+ export { c as createMemoryBackend, o as openDbsonl } from './store-B9lj_fpx.mjs';
2
2
  export { D as DEFAULT_OPTIONS, a as DbsonlError } from './common-R-Fl2aza.mjs';
3
3
  import 'defuss-dson/sequence';
4
4
  import 'defuss-storage';
@@ -1,6 +1,6 @@
1
1
  import { workerData, parentPort } from 'node:worker_threads';
2
- import { o as openDbsonl } from './store-DsWjd2ZI.mjs';
3
- import { c as createFileBackend, s as serveScans } from './server-Y88y4TNX.mjs';
2
+ import { o as openDbsonl } from './store-B9lj_fpx.mjs';
3
+ import { c as createFileBackend, s as serveScans } from './server-51AzDAJ8.mjs';
4
4
  import 'defuss-dson/sequence';
5
5
  import 'defuss-storage';
6
6
  import './common-R-Fl2aza.mjs';
@@ -7,7 +7,7 @@ import { availableParallelism } from 'node:os';
7
7
  import { isMainThread, Worker } from 'node:worker_threads';
8
8
  import { createFileStorage } from 'defuss-storage/node';
9
9
  import { StorageError } from 'defuss-storage';
10
- import { b as batchBytes, a as createMemoryCoordinator } from './store-DsWjd2ZI.mjs';
10
+ import { b as batchBytes, a as createMemoryCoordinator } from './store-B9lj_fpx.mjs';
11
11
  import { a as DbsonlError, n as natural, c as name, b as abort } from './common-R-Fl2aza.mjs';
12
12
 
13
13
  const CREDIT_BYTES = 8 * 1024 * 1024;
package/dist/server.mjs CHANGED
@@ -7,7 +7,7 @@ import 'node:os';
7
7
  import 'node:worker_threads';
8
8
  import 'defuss-storage/node';
9
9
  import 'defuss-storage';
10
- import './store-DsWjd2ZI.mjs';
10
+ import './store-B9lj_fpx.mjs';
11
11
  import './common-R-Fl2aza.mjs';
12
- export { c as createFileBackend } from './server-Y88y4TNX.mjs';
12
+ export { c as createFileBackend } from './server-51AzDAJ8.mjs';
13
13
  import 'defuss-dson/sequence';
@@ -1039,6 +1039,19 @@ function newGeneration() {
1039
1039
  function code(error) {
1040
1040
  return error?.code;
1041
1041
  }
1042
+ const issuedFrames = /* @__PURE__ */ new WeakMap();
1043
+ function ownFrame(frame, maxRecordBytes) {
1044
+ const issued = issuedFrames.get(frame);
1045
+ if (issued) {
1046
+ if (issued.length - 16 > maxRecordBytes) throw new RangeError("A frame exceeds maxRecordBytes.");
1047
+ return issued;
1048
+ }
1049
+ if (!(frame instanceof Uint8Array)) throw new TypeError("A frame must be a Uint8Array or a frame from Dbsonl.frame().");
1050
+ if (frame.length - 16 > maxRecordBytes) throw new RangeError("A frame exceeds maxRecordBytes.");
1051
+ const owned = new Uint8Array(frame);
1052
+ if (decodeFrame(owned, 0, { maxRecordBytes, maxDepth: 512, maxReferences: 1e6 }).byteLength !== owned.length) throw new TypeError("A frame must hold exactly one DSON frame and no other bytes.");
1053
+ return owned;
1054
+ }
1042
1055
  const pageId = (head, ref) => `${head.generation}:${ref.offset}:${ref.byteLength}`;
1043
1056
  const batchBytes = /* @__PURE__ */ new WeakMap();
1044
1057
  const TASK_BYTES = 1024 * 1024, MAX_TASKS = 1024;
@@ -1467,14 +1480,15 @@ class Dbsonl {
1467
1480
  return this.lookup(head, id);
1468
1481
  }));
1469
1482
  }
1470
- /** Capture values synchronously so subsequent caller mutation cannot change an admitted batch. */
1471
- encode(input) {
1483
+ /** Capture values, or copies of frames, synchronously so subsequent caller mutation cannot change an admitted batch. */
1484
+ encode(input, frames = false) {
1472
1485
  if (!Array.isArray(input) || input.length > this.limits.maxTransactionOperations) throw new DbsonlError("LIMIT_EXCEEDED", "Transaction operation capacity exceeded.");
1473
1486
  let bytes = 0;
1487
+ const { maxRecordBytes } = this.limits;
1474
1488
  const encoded = input.map((operation) => {
1475
1489
  key(operation.key);
1476
1490
  if (operation.operation !== "put" && operation.operation !== "delete") throw new TypeError("Unknown mutation operation.");
1477
- const encoded2 = operation.operation === "put" ? encodeFrame(operation.value, { maxRecordBytes: this.limits.maxRecordBytes }) : void 0;
1491
+ const encoded2 = operation.operation !== "put" ? void 0 : frames ? ownFrame(operation.frame, maxRecordBytes) : encodeFrame(operation.value, { maxRecordBytes });
1478
1492
  bytes += (encoded2?.length ?? 0) + operation.key.length * 2 + 64;
1479
1493
  if (bytes > this.limits.maxTransactionBytes) throw new DbsonlError("LIMIT_EXCEEDED", "Transaction encoded-byte capacity exceeded.");
1480
1494
  return { key: operation.key, bytes: encoded2 };
@@ -1736,14 +1750,34 @@ class Dbsonl {
1736
1750
  if (written.has(id) || (entry?.revision ?? 0) !== seen) throw new DbsonlError("CONFLICT", "A key the transaction read changed after its snapshot.");
1737
1751
  }
1738
1752
  }
1753
+ /**
1754
+ * Encode value now, as put would, into a frame that batchFrames and putFrame of any handle commit as it is: a snapshot
1755
+ * of the value for a caller that queues it before it commits, encoded once.
1756
+ */
1757
+ frame(value) {
1758
+ const bytes = encodeFrame(value, { maxRecordBytes: this.limits.maxRecordBytes });
1759
+ const handle = Object.freeze({ byteLength: bytes.length });
1760
+ issuedFrames.set(handle, bytes);
1761
+ return handle;
1762
+ }
1739
1763
  /** Encode at call time, then publish the entire operation list under one new revision. */
1740
1764
  batch(input, options = {}) {
1765
+ return this.admit(input, false, options);
1766
+ }
1767
+ /**
1768
+ * batch for values the caller already encoded, so they are not encoded twice: each frame is checked and copied at call
1769
+ * time and written as it is. Reads decode it like any value.
1770
+ */
1771
+ batchFrames(input, options = {}) {
1772
+ return this.admit(input, true, options);
1773
+ }
1774
+ admit(input, frames, options) {
1741
1775
  if (this.closed) return Promise.reject(new DbsonlError("CLOSED", "Database is closed."));
1742
1776
  if (this.pending.size >= this.limits.maxPendingOperations) return Promise.reject(new DbsonlError("QUEUE_FULL", "Too many admitted operations."));
1743
1777
  let encoded;
1744
1778
  try {
1745
1779
  abort(options.signal);
1746
- encoded = this.encode(input);
1780
+ encoded = this.encode(input, frames);
1747
1781
  } catch (error) {
1748
1782
  return Promise.reject(error);
1749
1783
  }
@@ -1791,9 +1825,9 @@ class Dbsonl {
1791
1825
  if (!active) throw new DbsonlError("CLOSED", "Transaction callback has finished.");
1792
1826
  abort(options.signal);
1793
1827
  };
1794
- const stage = (operation) => {
1828
+ const stage = (operation, frames = false) => {
1795
1829
  check();
1796
- const encoded = this.encode([operation])[0];
1830
+ const encoded = this.encode([operation], frames)[0];
1797
1831
  const old = staged.get(encoded.key);
1798
1832
  const nextSize = size - (old ? (old.bytes?.length ?? 0) + old.key.length * 2 + 64 : 0) + (encoded.bytes?.length ?? 0) + encoded.key.length * 2 + 64;
1799
1833
  if (nextSize > this.limits.maxTransactionBytes || !old && staged.size >= this.limits.maxTransactionOperations) throw new DbsonlError("LIMIT_EXCEEDED", "Transaction capacity exceeded.");
@@ -1814,6 +1848,7 @@ class Dbsonl {
1814
1848
  return lookup;
1815
1849
  },
1816
1850
  put: (id, value) => stage({ operation: "put", key: id, value }),
1851
+ putFrame: (id, frame) => stage({ operation: "put", key: id, frame }, true),
1817
1852
  delete: (id) => stage({ operation: "delete", key: id }),
1818
1853
  async *scan(scan = {}) {
1819
1854
  check();
@@ -134,6 +134,25 @@ type Mutation<T> = {
134
134
  operation: 'delete';
135
135
  key: string;
136
136
  };
137
+ /** Type-only brand: a plain object with a byteLength is not an OwnedFrame. */
138
+ declare const ownedFrame: unique symbol;
139
+ /** A value Dbsonl.frame() encoded. Its bytes stay inside the engine, so batchFrames and putFrame commit it without copying or checking it again. */
140
+ interface OwnedFrame {
141
+ readonly byteLength: number;
142
+ readonly [ownedFrame]: true;
143
+ }
144
+ /**
145
+ * A put whose value the caller already encoded: exactly one complete DSON frame, as encodeFrame of defuss-dson/sequence
146
+ * returns it, or the OwnedFrame of Dbsonl.frame().
147
+ */
148
+ type FrameMutation = {
149
+ operation: 'put';
150
+ key: string;
151
+ frame: Uint8Array | OwnedFrame;
152
+ } | {
153
+ operation: 'delete';
154
+ key: string;
155
+ };
137
156
  type Lookup<T> = {
138
157
  found: false;
139
158
  value?: never;
@@ -189,8 +208,10 @@ interface Transaction<T> {
189
208
  readonly revision: number;
190
209
  get(key: string): Promise<Lookup<T>>;
191
210
  put(key: string, value: T): void;
211
+ /** put of a value the caller already encoded; the frame is checked and copied like batchFrames checks it. */
212
+ putFrame(key: string, frame: Uint8Array | OwnedFrame): void;
192
213
  delete(key: string): void;
193
214
  scan(options?: ScanOptions): AsyncIterableIterator<Row<T>>;
194
215
  }
195
216
 
196
- 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, Ref as R, ScanOptions as S, Transaction as T, Release as a, ReadOptions as b, ParallelScan as c, Row as d, BatchScanOptions as e, Partition as f, Commit as g, Stats as h, Coordinator as i };
217
+ export type { Backend as B, CommitOptions as C, Entry as E, FrameMutation as F, Head as H, Lookup as L, Mutation as M, Options as O, Page as P, Ref as R, ScanOptions as S, Transaction as T, Release as a, ReadOptions as b, ParallelScan as c, Row as d, BatchScanOptions as e, Partition as f, OwnedFrame as g, Commit as h, Stats as i, Coordinator as j };
@@ -134,6 +134,25 @@ type Mutation<T> = {
134
134
  operation: 'delete';
135
135
  key: string;
136
136
  };
137
+ /** Type-only brand: a plain object with a byteLength is not an OwnedFrame. */
138
+ declare const ownedFrame: unique symbol;
139
+ /** A value Dbsonl.frame() encoded. Its bytes stay inside the engine, so batchFrames and putFrame commit it without copying or checking it again. */
140
+ interface OwnedFrame {
141
+ readonly byteLength: number;
142
+ readonly [ownedFrame]: true;
143
+ }
144
+ /**
145
+ * A put whose value the caller already encoded: exactly one complete DSON frame, as encodeFrame of defuss-dson/sequence
146
+ * returns it, or the OwnedFrame of Dbsonl.frame().
147
+ */
148
+ type FrameMutation = {
149
+ operation: 'put';
150
+ key: string;
151
+ frame: Uint8Array | OwnedFrame;
152
+ } | {
153
+ operation: 'delete';
154
+ key: string;
155
+ };
137
156
  type Lookup<T> = {
138
157
  found: false;
139
158
  value?: never;
@@ -189,8 +208,10 @@ interface Transaction<T> {
189
208
  readonly revision: number;
190
209
  get(key: string): Promise<Lookup<T>>;
191
210
  put(key: string, value: T): void;
211
+ /** put of a value the caller already encoded; the frame is checked and copied like batchFrames checks it. */
212
+ putFrame(key: string, frame: Uint8Array | OwnedFrame): void;
192
213
  delete(key: string): void;
193
214
  scan(options?: ScanOptions): AsyncIterableIterator<Row<T>>;
194
215
  }
195
216
 
196
- 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, Ref as R, ScanOptions as S, Transaction as T, Release as a, ReadOptions as b, ParallelScan as c, Row as d, BatchScanOptions as e, Partition as f, Commit as g, Stats as h, Coordinator as i };
217
+ export type { Backend as B, CommitOptions as C, Entry as E, FrameMutation as F, Head as H, Lookup as L, Mutation as M, Options as O, Page as P, Ref as R, ScanOptions as S, Transaction as T, Release as a, ReadOptions as b, ParallelScan as c, Row as d, BatchScanOptions as e, Partition as f, OwnedFrame as g, Commit as h, Stats as i, Coordinator as j };
package/docs/API.md CHANGED
@@ -21,6 +21,8 @@ Names contain 1 through 64 lowercase letters, digits, hyphens or underscores, be
21
21
  | `put(key, value, options?)` | Single-operation atomic batch |
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
+ | `batchFrames(mutations, {ifRevision?, signal?}?)` | `batch` for values the caller already encoded: `{operation: 'put', key, frame}` or `{operation: 'delete', key}`, where `frame` is what `encodeFrame` of `defuss-dson/sequence` returns, or what `frame()` returns |
25
+ | `frame(value)` (synchronous) | Encode a value as `put` would and return an `OwnedFrame` that `batchFrames` and `putFrame` of any handle of this package commit without a copy or a check |
24
26
  | `transaction(callback, {signal?}?)` | `{result, revision, count}`; callback runs once; a changed read key aborts publication |
25
27
  | `beginRead({at?}?)` | Explicit immutable snapshot with `head`, `revision`, `count`, `get`, `scan`, `scanBatches`, `split`, `close`; `at` pins the head of a snapshot that is still open elsewhere |
26
28
  | `stats()` | Current revision, count, generation, committedBytes, cacheBytes, cachePages, durability |
@@ -33,7 +35,15 @@ VERIFIED: Nonempty batches advance revision even for a delete of an absent key.
33
35
 
34
36
  VERIFIED: Commits queued on one handle publish as a group under one commit lock: one append, one generation flush and one head flush. Each member is checked in queue order against the state the members before it leave, gets its own revision and receipt, and fails alone: a cancelled, conflicting or over-budget member is rejected, and if the shared write fails before publication the members are retried one at a time. Readers never see a state between members, so the outcome equals committing them one by one. A transaction started while its handle's group holds the commit lock pins the last flushed head instead of waiting for the group. A forming group waits for transactions on the same handle that already hold a snapshot, at most half the previous group's publication time, so concurrent transactions share a group instead of alternating between small ones; a commit can therefore wait that long before its group starts. A transaction that outlasts one such wait is not waited for again.
35
37
 
36
- A transaction exposes `revision`, async `get`, synchronous `put`/`delete` and an async `scan`. Staging copies each value through the encoder. Replacing a staged key replaces its budget charge. Reads see staged writes; they report the snapshot revision plus one, while the commit receipt carries the revision the commit actually received. A transaction scan captures the staged overlay at its first pull and merges it with the immutable base in key order; subsequent staging is visible to a new scan. Transaction objects reject use after the callback finishes.
38
+ A transaction exposes `revision`, async `get`, synchronous `put`/`putFrame`/`delete` and an async `scan`. Staging copies each value through the encoder, and each frame as `batchFrames` does. Replacing a staged key replaces its budget charge. Reads see staged writes; they report the snapshot revision plus one, while the commit receipt carries the revision the commit actually received. A transaction scan captures the staged overlay at its first pull and merges it with the immutable base in key order; subsequent staging is visible to a new scan. Transaction objects reject use after the callback finishes.
39
+
40
+ VERIFIED: `batchFrames` and `putFrame` accept a frame only if it is a `Uint8Array` that holds exactly one complete DSON frame and no other bytes. At call time they copy it and decode the copy under the handle's `maxRecordBytes`, depth 512 and 1,000,000 references, the limits every read applies; the decode checks the frame version, declared length, header and payload checksums and DSON structure. `maxRecordBytes` bounds a frame's payload as it bounds the value `put` encodes, so a frame fits exactly when `put` would accept its value. A frame that is not a `Uint8Array`, is truncated, damaged or followed by other bytes throws `TypeError`; one over a budget throws `RangeError`, as `put` does for the value. `putFrame` throws synchronously and `batchFrames` rejects; nothing of that transaction write or batch is staged or committed.
41
+
42
+ VERIFIED: The stored bytes are the copy, written unchanged, so changing or reusing the caller's buffer afterwards changes nothing committed; a Node `Buffer` is copied too, not sliced. Frame bytes count against `maxTransactionBytes` and `maxPendingBytes` like encoded values, and revisions, conflicts, commit groups and durability are those of `batch` and `put`. Reads, transaction reads included, return the decoded value, never the frame.
43
+
44
+ VERIFIED: `frame(value)` encodes under the handle's `maxRecordBytes` and throws as `put` would for the value. It returns a frozen object whose only property is `byteLength`; the bytes stay inside the engine, so a caller can keep the snapshot until it commits but cannot change it. `batchFrames` and `putFrame` take such an object without a copy or a decode, after checking its payload against the receiving handle's `maxRecordBytes` (`RangeError` if larger). A look-alike object, a structured clone or an `OwnedFrame` from another copy of the package, such as its CommonJS build beside the ESM one, throws `TypeError`. One `OwnedFrame` can be committed any number of times.
45
+
46
+ VERIFIED: A `Uint8Array` frame costs a copy and one decode instead of an encode; an `OwnedFrame` costs neither. In a benchmark of 10,000 records, committing `Uint8Array` frames the caller encoded took 1.12 to 2.06 times as long as `batch` with the values, committing `frame()` handles 0.99 to 1.11 times, and a caller that encodes, decodes and then calls `batch` 1.18 to 2.71 times ([PERFORMANCE.md](PERFORMANCE.md#caller-encoded-frames-on-macos-arm64)).
37
47
 
38
48
  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
49
 
@@ -53,7 +63,7 @@ VERIFIED: Optimistic compaction is the default. A concurrent publication yields
53
63
  | --- | --- | --- |
54
64
  | `create` | false | Create only when no manifest exists |
55
65
  | `maxRecordBytes` | 16777216 | DSON payload budget per application value |
56
- | `maxTransactionBytes` | 67108864 | Sum of encoded values, two bytes per key code unit and 64 bytes per staged operation |
66
+ | `maxTransactionBytes` | 67108864 | Sum of encoded values and frames, two bytes per key code unit and 64 bytes per staged operation |
57
67
  | `maxTransactionOperations` | 10000 | Batch operations or distinct staged transaction keys |
58
68
  | `maxPendingOperations` | 256 | Admitted top-level operations per database handle |
59
69
  | `maxPendingBytes` | 134217728 | Aggregate encoded-write budget per database handle |
@@ -235,6 +235,23 @@ VERIFIED: `scripts/microbench.ts` checks equal, unequal, empty, short and unalig
235
235
 
236
236
  VERIFIED: The shared implementation uses the word loop with a byte fallback for unaligned buffers or lengths. Four-way unrolling did not consistently beat it across both engines and runs. The results support this specific choice, not a claim that all JITs or workloads are optimally compiled.
237
237
 
238
+ ## Caller-encoded frames on macOS arm64
239
+
240
+ VERIFIED: One run of `mise exec -- make bench-frames` on 2026-11-24, on the host above, with Node 24.22.1, Bun 1.4.3 and defuss-dson 1.5.1, at a load average of 3.8 to 4.7. Each case commits 10,000 log records in batches of 256 into a new database: small records of a Date, three short strings and two numbers, 254 bytes per frame on average, and large ones whose message has about 1,900 characters, 3870 bytes per frame. Every path starts from the caller's values and ends when its last batch commits. `batch` commits the values. "Round trip" is a caller that keeps an owned snapshot of each value by encoding it and decoding the copy, then commits the copy with `batch`, which encodes it again. `batchFrames` is the same caller committing its `Uint8Array` frames, which DBSONL copies and decodes once to check. `frame()` is the same caller taking its snapshots with `db.frame()` and committing them with `batchFrames`, which neither copies nor decodes them. Two warmup rounds and seven measured rounds alternate the path order, garbage is collected before each run, and the four paths must write generations of the same size. Medians in milliseconds:
241
+
242
+ | Runtime | Storage | Records | `batch` | Round trip + `batch` | `batchFrames` | `frame()` + `batchFrames` | `frame()` vs `batch` |
243
+ | --- | --- | --- | ---: | ---: | ---: | ---: | ---: |
244
+ | Node | memory | small | 26.3 | 53.4 | 43.8 | 27.8 | 1.06 |
245
+ | Node | memory | large | 92.9 | 251.3 | 165.9 | 92.9 | 1.00 |
246
+ | Node | native async | small | 172.1 | 202.4 | 192.8 | 176.4 | 1.02 |
247
+ | Node | native async | large | 276.8 | 449.7 | 349.9 | 287.9 | 1.04 |
248
+ | Bun | memory | small | 17.0 | 36.7 | 27.2 | 18.8 | 1.11 |
249
+ | Bun | memory | large | 57.4 | 154.3 | 118.3 | 59.9 | 1.04 |
250
+ | Bun | native async | small | 169.5 | 206.3 | 194.6 | 167.1 | 0.99 |
251
+ | Bun | native async | large | 225.6 | 333.5 | 299.5 | 225.1 | 1.00 |
252
+
253
+ VERIFIED: `Uint8Array` frames took 0.66 to 0.95 of the round trip's time, because they skip its second encode, but 1.12 to 2.06 of `batch`'s, because the caller's encode plus DBSONL's copy and checking decode cost more than DBSONL's single encode. `frame()` handles skip the copy and the decode, and took 0.99 to 1.11 of `batch`'s time: the snapshot costs the one encode that `batch` would run anyway. Two earlier runs on 2026-11-23, at a load average of 6.4 to 17.4 and before `frame()` existed, gave 0.67 to 0.94 of the round trip and 1.00 to 1.86 of `batch` for `Uint8Array` frames.
254
+
238
255
  ## Reproduction and scope
239
256
 
240
257
  ```sh
@@ -242,6 +259,7 @@ make setup
242
259
  make verify
243
260
  make bench # 1000 records, both runtimes, async/sync/memory, 7 rounds
244
261
  make bench-scale # 10000 records, both runtimes, native async, 3 rounds
262
+ make bench-frames # 10000 records as values, caller-encoded frames or frame() handles, both runtimes, memory and native async
245
263
  ```
246
264
 
247
265
  VERIFIED: The checksum-pinned v0.2.0 and v0.3.0 tarballs are bundled under `vendor/`. Each benchmark child imports one built package, uses a new temporary database, checks every returned value and scan count, verifies the database, and closes it. Version order is reversed between runtimes. Reopen follows close; the OS filesystem cache is warm. The benchmark does not silently select a subset of rounds.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "defuss-dbsonl",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
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",
@@ -83,7 +83,7 @@
83
83
  "devDependencies": {
84
84
  "@types/node": "24.10.0",
85
85
  "@vitest/coverage-v8": "4.1.12",
86
- "esbuild": "0.27.4",
86
+ "esbuild": "0.28.2",
87
87
  "oxlint": "1.89.0",
88
88
  "pkgroll": "2.29.0",
89
89
  "playwright": "1.62.1",