defuss-dbsonl 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCH.md +38 -6
- package/CHANGELOG.md +44 -0
- package/README.md +33 -7
- package/dist/{backend-CU4f3EUz.cjs → backend-Bq8hVmuI.cjs} +9 -5
- package/dist/browser.cjs +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/{common-0JC30Xiv.mjs → common-R-Fl2aza.mjs} +2 -2
- package/dist/index.cjs +461 -74
- package/dist/index.d.cts +53 -17
- package/dist/index.d.mts +53 -17
- package/dist/index.mjs +3 -1305
- package/dist/scan-worker.mjs +18 -0
- package/dist/server-BXybcXSY.mjs +722 -0
- package/dist/server.cjs +361 -12
- package/dist/server.d.cts +16 -1
- package/dist/server.d.mts +16 -1
- package/dist/server.mjs +13 -285
- package/dist/store-Bd1KZ-N7.mjs +1766 -0
- package/dist/{types-B_SuDjVq.d.cts → types-CSHnjgvj.d.cts} +60 -2
- package/dist/{types-B_SuDjVq.d.mts → types-CSHnjgvj.d.mts} +60 -2
- package/docs/API.md +14 -6
- package/docs/FORMAT.md +27 -7
- package/docs/PERFORMANCE.md +137 -54
- package/package.json +15 -4
- package/dist/backend-c-pjfpXZ.mjs +0 -76
- package/dist/{common-2ybGl1zj.cjs → common-YqfTK8sQ.cjs} +1 -1
package/ARCH.md
CHANGED
|
@@ -20,33 +20,65 @@ flowchart TD
|
|
|
20
20
|
|
|
21
21
|
VERIFIED: A persistent B+tree avoids a database-sized RAM map without requiring a second database dependency. Fanout 32 trades modest page sizes for logarithmic tree navigation. Values are separate DSON frames; pages contain only keys, references and revisions. Rewriting a path rather than mutating it gives readers stable roots with no undo log. A batch coalesces edits in private dirty nodes and persists each final dirty page once, avoiding unobservable intermediate roots. An edit whose path is already dirty or cached runs synchronously; only a page read awaits. A bounded cache stores decoded pages, never application values. It evicts by second chance: a hit only marks its page, and eviction moves a marked page to the back once. Exact LRU reordered the Map on every hit, about 5% of a memory commit. Index pages are written by `encodePage`, which produces the same frames as `encodeFrame` in trusted mode about 30% faster because it knows the few property names pages use. A commit edits cached copies of the pages on its paths instead of rereading them, and adds the pages it wrote once their root is published; a page address within a generation never changes meaning, because only an unpublished tail is ever rewritten. Open reads constant-size metadata and generation length, not every value.
|
|
22
22
|
|
|
23
|
-
VERIFIED: A two-slot manifest avoids relying on atomic rename, which Storage and OPFS do not expose uniformly. Each slot is a checksummed DSON frame in a 4096-byte region. The newest valid publication wins. Writers append after the published end, flush, then replace the older slot. A partial slot is ignored. An empty head whose generations are all empty is an interrupted create: only `create: true` initializes it, because no slot was published; invalid fields in a checksummed slot, a missing referenced generation or committed truncation fail closed. A failed publication reports `COMMIT_UNCERTAIN`; reread the revision before retrying. Successful publication increments the logical revision once per nonempty batch.
|
|
23
|
+
VERIFIED: A two-slot manifest avoids relying on atomic rename, which Storage and OPFS do not expose uniformly. Each slot is a checksummed DSON frame in a 4096-byte region. The newest valid publication wins. Writers append after the published end, flush, then replace the older slot. A partial slot is ignored. Format 3, which new databases use, ends every commit with a commit record in the generation; on native files, whose writes every process sees before a flush, the generation flush alone makes a commit durable and the slot is written without one. A lone durable transaction then took 4.6 ms instead of 8.1 ms under Node, where every flush is a full `F_FULLFSYNC` of about 3.9 ms; the alternative, flushing the head too, doubles that. Recovery after a power loss walks the frames after the head's end and adopts each record that repeats the generation's random seal and chains to the commit before it, as long as every frame up to it passes its checksum ([FORMAT.md](docs/FORMAT.md#commit-records-format-3)). The head is flushed every 16 MiB of generation bytes, which bounds that walk. OPFS and directory handles flush the slot on every commit, because their writes are not known to reach other workers before a flush. An empty head whose generations are all empty is an interrupted create: only `create: true` initializes it, because no slot was published; invalid fields in a checksummed slot, a missing referenced generation or committed truncation fail closed. A failed publication reports `COMMIT_UNCERTAIN`; reread the revision before retrying. Successful publication increments the logical revision once per nonempty batch.
|
|
24
24
|
|
|
25
25
|
VERIFIED: These choices spend extra write bandwidth on index paths and two small metadata writes during compaction. They remove full replay and read-held writer exclusion. Benchmark evidence separates batch and per-record flush workloads rather than treating them as equivalent. A universal Pareto-optimality claim would require a defined workload distribution and objective function.
|
|
26
26
|
|
|
27
27
|
## Ownership and lock order
|
|
28
28
|
|
|
29
|
-
VERIFIED: The commit lock serializes head inspection and publication. A snapshot takes a shared generation pin while holding that lock, then releases the commit lock. While a handle's own commit group holds the lock, that handle pins the group's last flushed head instead: nobody else can publish or collect then, and the group releases the lock only after those pins are granted. Readers therefore never see a head before its flush. Portable reads
|
|
29
|
+
VERIFIED: The commit lock serializes head inspection and publication. A snapshot takes a shared generation pin while holding that lock, then releases the commit lock. While a handle's own commit group holds the lock, that handle pins the group's last flushed head instead: nobody else can publish or collect then, and the group releases the lock only after those pins are granted. Readers therefore never see a head before its flush. Portable reads take short I/O locks in shared mode, and writes and removals take them alone. Storage 0.4 shares read-only handles but rejects `BUSY` when a reader meets an owner or a removal, so the lock turns that rejection into waiting. An exclusive lock for every read, which Storage 0.3 needed, would make parallel scans of one generation take turns, across workers too. Native reads use independent read-only descriptors: committed prefixes are immutable, writers truncate only unpublished tails, and the pin prevents removal. A native snapshot therefore reads concurrently with appends. The lifetime of a read session does not reserve the commit lock.
|
|
30
30
|
|
|
31
31
|
VERIFIED: Native locks are separate whole-file locks scoped to open descriptions/handles; they do not expire with a clock or heartbeat. A paused process cannot lose ownership to a second writer. The kernel releases ownership on process death. Web Locks release when their worker/context dies. Memory coordination is instance-local. Raw Storage writes and unrelated processes ignoring the protocol are outside the ownership contract.
|
|
32
32
|
|
|
33
33
|
VERIFIED: Acquisition order is commit lock, generation pin, I/O lock. Snapshot readers use their pin and, for portable adapters, short I/O locks without reacquiring the commit lock. A direct `get()` holds the commit lock until its bounded lookup finishes, which also excludes collection without a separate snapshot pin. Compaction pins both its source and candidate generation before releasing the commit lock. It writes only the candidate and reads the source in short operations. Publication compares the original publication number, so even another compaction causes a conflict. Exclusive compaction keeps the commit lock through the copy for guaranteed progress.
|
|
34
34
|
|
|
35
|
-
VERIFIED: Commits queued on one handle form a group: the next lock holder checks every member in queue order, appends all of their values and pages with one writer, flushes the generation once and publishes one head. Each member keeps its own revision, so the group equals sequential commits that no reader observed in between. A group is capped by one batch's operation and byte budgets; any failure before publication retries its members one at a time, so one member cannot fail another. The alternative, one publication per commit, paid two flushes per commit: with four writers on Node under macOS, about 8 ms per commit. Grouping cuts the flushes per commit; the cost is that a member waits for the slowest check in its group.
|
|
35
|
+
VERIFIED: Commits queued on one handle form a group: the next lock holder checks every member in queue order, appends all of their values and pages with one writer, flushes the generation once and publishes one head. Each member keeps its own revision, so the group equals sequential commits that no reader observed in between. A group is capped by one batch's operation and byte budgets; any failure before publication retries its members one at a time, so one member cannot fail another. The alternative, one publication per commit, paid two flushes per commit in format 2: with four writers on Node under macOS, about 8 ms per commit. Grouping cuts the flushes per commit; the cost is that a member waits for the slowest check in its group.
|
|
36
36
|
|
|
37
37
|
VERIFIED: A forming group first sets the head that new snapshots pin, then waits while transactions on its handle hold a snapshot but have not queued their commit, waking on every arrival, for at most half the previous group's publication time. Without the wait, four transaction writers on one handle alternated between groups of one and three members, because the writer released first committed again while the other three were still in the next group; on Node under macOS that cost 4.4 ms per commit, and the wait brought it to 2.1 ms in full groups of four. A transaction that outlasts one wait is not waited for again, and a writer with no transaction in flight never waits. An earlier variant waited before setting the pinned head, so snapshots that started during its wait queued behind the lock it held; it measured slower and was dropped.
|
|
38
38
|
|
|
39
39
|
VERIFIED: A transaction checks the revisions of the keys it read, not the database revision. The commit lock makes the check and publication atomic, so every read is still current at the commit point and the transactions serialize in commit order. Absence is recorded as revision 0, so a key that appears is a conflict. Scans fall back to the database revision, because a range cannot be rechecked without listing what was absent. The whole-database check it replaced rejected disjoint writers: four writers on separate keys retried 1.5 to 2.1 times per commit.
|
|
40
40
|
|
|
41
|
+
## Parallel scans
|
|
42
|
+
|
|
43
|
+
VERIFIED: `split(parts)` cuts a snapshot by key, not by byte offset. A generation file holds index pages and the superseded values of overwritten and deleted keys between the live values, so a byte range of it is not a set of rows: a worker scanning bytes would return dead records, and telling them apart needs the index anyway. Key ranges from the index cost a few page reads near the root. Every branch entry stores its subtree's row count, so the cut opens only subtrees above an eighth of one share, then cuts the ordered pieces where the running count reaches each share. A boundary is the first key of the next range, not one code unit past the last key of the previous one, which could exceed the 4096-unit key bound that scan options enforce.
|
|
44
|
+
|
|
45
|
+
VERIFIED: A parallel scan needs one root in every worker. `beginRead({at})` pins the head of a snapshot that is still open, on any handle of the same files: another worker, thread or process with its own backend. It takes the commit lock in shared mode, so publication and collection stay excluded, but workers that pin at once do not queue: native lock waiters retry every 5 ms, and in three runs each with 8 Node worker threads, the per-run medians of the full scan were 32 to 43 ms with an exclusive lock and 19 to 32 ms with the shared one, over the four I/O and cache settings. Under the lock it checks that the head is not newer than the published one, or that its older generation still exists and holds its end, then takes a shared pin like any snapshot. Until then the original snapshot's pin keeps the generation from collection.
|
|
46
|
+
|
|
47
|
+
```mermaid
|
|
48
|
+
sequenceDiagram
|
|
49
|
+
participant C as Coordinator
|
|
50
|
+
participant W as Worker
|
|
51
|
+
participant F as Generation file
|
|
52
|
+
C->>C: beginRead() pins the head
|
|
53
|
+
C->>C: split(n) reads pages near the root
|
|
54
|
+
C->>W: head and one key range
|
|
55
|
+
W->>W: beginRead({at}) under a shared commit lock
|
|
56
|
+
W->>F: scanBatches(range) with its own pin and handle
|
|
57
|
+
W-->>C: rows or aggregates
|
|
58
|
+
C->>C: close() once every worker has pinned
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
VERIFIED: On native storage, `scanBatches()` runs in worker threads by default once a snapshot range holds at least 5000 rows. `createFileBackend` starts a pool of up to four workers, one fewer than the CPUs, on the first such scan. Each worker opens its own synchronous backend and handle from `dist/scan-worker.mjs`, which ships beside the server build. A scan counts the rows of its range exactly from the index, cuts it into tasks of about 1 MiB of the generation, at least two per worker, and sends each worker the snapshot's head and one task at a time. The workers pin that head with `beginRead({at})`, scan their task with the caller's `batchSize` and `maxBatchBytes`, and send the batches back. The calling thread hands them out in key order, so the rows, their order and the errors match a scan in one thread, and only batches end early at task edges. On 100,000 documents with the defaults this took 105 ms under Node and 113 ms under Bun, against 401 and 418 ms in one thread ([PERFORMANCE.md](docs/PERFORMANCE.md#parallel-scans-on-macos-arm64)).
|
|
62
|
+
|
|
63
|
+
VERIFIED: Batches are encoded in the calling thread. Encoding them in worker threads was probed on 2026-11-20 and rejected: a value reaches a worker only as a structured clone, and the clone silently turns getters into plain values and class instances into plain objects and drops symbol keys and non-enumerable properties, all of which DSON rejects with an error; it also loses null prototypes and a RegExp's `lastIndex`. Values encoded from the clone would then differ from what `put()` accepts and stores in one thread.
|
|
64
|
+
|
|
65
|
+
VERIFIED: The gain is smaller than with work that stays in the workers, because the calling thread decodes every structured clone. In a probe on 2026-11-20 with synchronous reads and a cached index, 8 workers that filtered and summed their rows took 18 ms under Node and 20 ms under Bun, and 8 workers that sent every row back took 62 and 39 ms, against 113 and 91 ms in one thread. Filters and aggregates belong in the workers where the query layer can put them, through `split()` and `beginRead({at})`.
|
|
66
|
+
|
|
67
|
+
VERIFIED: The pool bounds what it holds and what it leaves behind. A worker stops sending a scan's batches while 8 MiB of their frame bytes are unconsumed, so a paused consumer holds the workers back instead of filling memory; with four workers that is at most about 36 MiB of frames plus one batch each. Under a `limit`, only the rows the limit takes are cut into ranges, and the key after the last of them ends the last range. Among 300,000 native rows, a limit of 5000 took 3.3 ms in workers and 2.9 ms in one thread, where cutting the whole interval as finely had taken 26 ms; a limit of 20,000 took 12.6 ms against 26.9 ms. Closing the iterator or the snapshot cancels the scan and returns after every worker has closed its sessions, so their pins end with the snapshot. Between scans the workers are unreferenced, so they never keep a process alive, and they exit after 30 s without a scan. `sizeOf` callbacks cannot cross threads, so such scans, scans below the threshold, `scan()` row iterators, memory and browser backends, and backends created in worker threads, which would oversubscribe the CPUs with nested pools, scan in the calling thread. If the workers cannot start, for example because a bundler did not copy `scan-worker.mjs`, the pool stays off and every scan runs in the calling thread. `scanWorkers: 0` turns it off; `scanWorkers` and `scanThreshold` set the size and the threshold. Four warm workers beat one thread from about 5000 small documents and lost at 2000.
|
|
68
|
+
|
|
69
|
+
VERIFIED: Each worker has its own page cache. Under the defaults, 1024 pages, one thread scanning 100,000 documents overflows it and decodes the leaf pages again on every scan, while an eighth of the tree fits; the default-cache figures therefore gain more than the worker count. Native backends in worker threads should use `io: 'sync'`. Asynchronous reads go through the libuv thread pool, which every thread of a process shares, while a blocking read stops only the scanning thread. With the defaults, one worker took 227 ms with synchronous and 364 ms with asynchronous reads under Node ([PERFORMANCE.md](docs/PERFORMANCE.md#parallel-scans-on-macos-arm64)).
|
|
70
|
+
|
|
41
71
|
## Native read and write performance
|
|
42
72
|
|
|
43
|
-
VERIFIED: Every database handle owns a connection with at most two idle read descriptors and at most eight idle lock descriptors, one per lock name: normally the commit lock, the I/O locks of the head and the current generation, and its pin. Reopening a lock file cost about 60 µs on macOS, three times per transaction. Only an unlocked descriptor is reused, so simultaneous owners still hold distinct open file descriptions and flock keeps them apart. In-flight reads retain their descriptors until completion. Local FIFO admission avoids polling for same-connection commit-lock contention; separate processes still acquire the same kernel lock. Every lock attempt uses the nonblocking call of the shipped N-API binding of pinned `@lickle/lock` 0.0.1. No blocking lock acquisition or timeout-based ownership is introduced.
|
|
73
|
+
VERIFIED: Every database handle owns a connection with at most two idle read descriptors and at most eight idle lock descriptors, one per lock name: normally the commit lock, the I/O locks of the head and the current generation, and its pin. Reopening a lock file cost about 60 µs on macOS, three times per transaction. Only an unlocked descriptor is reused, so simultaneous owners still hold distinct open file descriptions and flock keeps them apart. Shared holders on one connection are the exception: the second and later share the first one's flock with a count, and the last release unlocks it. Exclusive requests keep their own descriptor, so they still conflict with that flock while any shared holder remains. Four transactions on one handle pin the same generation; with a descriptor each, three of them opened and later closed a descriptor on the thread pool, missed the next commit group, and four writers alternated between groups of one and three once reads no longer yielded to the event loop. In-flight reads retain their descriptors until completion. Local FIFO admission avoids polling for same-connection commit-lock contention; separate processes still acquire the same kernel lock. Every lock attempt uses the nonblocking call of the shipped N-API binding of pinned `@lickle/lock` 0.0.1. No blocking lock acquisition or timeout-based ownership is introduced.
|
|
44
74
|
|
|
45
|
-
VERIFIED: `get()` reads the current head under the commit lock on every call. It can overlap this with a lookup through the previously parsed root. That candidate is accepted only if every head byte is unchanged; otherwise it is discarded and the current root is read. Both branches are drained before releasing the lock, including on errors. Native connections read that 8 KiB manifest with a blocking call even when values use asynchronous I/O: every operation reads it, it stays in the page cache, and a blocking read of it took 0.4 to 0.6 µs against 9 to 18 µs for a thread-pool round trip. A cold manifest blocks the event loop for one 8 KiB read. A per-handle 8 KiB parse cache avoids repeated DSON decoding, not fresh I/O; publication patches in the slot it wrote, so the writer's next read of its own head needs no decode. Aligned comparisons use 32-bit words; measured manual unrolling was not retained because it regressed Node.
|
|
75
|
+
VERIFIED: `get()` reads the current head under the commit lock on every call. It can overlap this with a lookup through the previously parsed root. That candidate is accepted only if every head byte is unchanged; otherwise it is discarded and the current root is read. Both branches are drained before releasing the lock, including on errors. Native connections read that 8 KiB manifest with a blocking call even when values use asynchronous I/O: every operation reads it, it stays in the page cache, and a blocking read of it took 0.4 to 0.6 µs against 9 to 18 µs for a thread-pool round trip. A cold manifest blocks the event loop for one 8 KiB read. Reads of up to `syncReadBytes`, 16 KiB by default, block the same way: point reads of small values and index pages. In an interleaved probe at a load average near 16, 1000 durable point reads took 17 instead of 46 ms under Node and 23 instead of 48 ms under Bun. A scan's 64 KiB windows stay asynchronous, so a long scan still yields to the event loop between windows. A read the OS page cache cannot serve blocks the thread until the device answers; network or slow storage should set `syncReadBytes: 0`. A per-handle 8 KiB parse cache avoids repeated DSON decoding, not fresh I/O; publication patches in the slot it wrote, so the writer's next read of its own head needs no decode. Aligned comparisons use 32-bit words; measured manual unrolling was not retained because it regressed Node.
|
|
46
76
|
|
|
47
77
|
VERIFIED: Known-length record references are checked against both committed end and the record budget before allocation. Native reads then fetch and checksum the complete frame. Values are decoded anew for every point lookup. Each native scan or compaction keeps one read-ahead window of at most 64 KiB within its pinned prefix. Large values bypass that window. The writer buffers at most 64 KiB, drains it before the file flush, and only then publishes the head, so buffering never reorders data ahead of publication.
|
|
48
78
|
|
|
49
|
-
VERIFIED: Native read descriptors do not participate in Storage's exclusive handle registry. This is limited to regular, read-only files and the DBSONL immutability protocol; mutations still use Storage and its I/O lock.
|
|
79
|
+
VERIFIED: Native read descriptors do not participate in Storage's exclusive handle registry. This is limited to regular, read-only files and the DBSONL immutability protocol; mutations still use Storage and its I/O lock.
|
|
80
|
+
|
|
81
|
+
VERIFIED: Mutations keep their Storage handles open between commits. `src/kept-files.ts` wraps the native adapter: a plain open of a head or generation file leases a Storage shared writer that stays open while any handle of that database in the JS realm is open, and the last close releases it. Shared writers read the file size on every call, so other processes' writes stay visible. Each lease is taken inside `withFile`, under the file's I/O lock; a removal, which holds that lock alone, closes the idle files of every adapter in the realm before it unlinks. A new generation closes the idle handles of older ones, and generation names are random and never reused, so a kept descriptor never stands for a newer file of the same name. Opening and closing both files took about 1 ms of a 5.8 ms lone durable transaction in a traced probe at a load average near 15; keeping them open took an interleaved lone transaction from 4.44 to 4.19 ms under Node and from 4.37 to 4.11 ms under Bun ([PERFORMANCE.md](docs/PERFORMANCE.md#compared-with-redis-on-macos-arm64)). A per-handle cache was the simpler alternative, but an idle handle in it would make another handle's removal or open of the same file fail with `BUSY`. Permission changes apply to the next open, as for any open descriptor. Code in the same realm that opens these files through its own Storage adapter, bypassing the backend, gets `BUSY` while a handle of the database is open, not only during a commit. `collect()` unlinks unpinned files and closes its connection's idle reader and idle pin and I/O lock descriptors for each removed generation, so no descriptor of an unlinked lock file is reused. Another idle process may still hold an unlinked descriptor until eviction or database close; OS disk-space release can therefore lag namespace removal. Closing all idle database handles releases those resources. Replacing live head or generation inodes outside this protocol is unsupported.
|
|
50
82
|
|
|
51
83
|
## Reclamation and crashes
|
|
52
84
|
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,49 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.7.0
|
|
4
|
+
|
|
5
|
+
VERIFIED: Durable commits and point reads on native storage took less time in `make bench-redis` than three runs earlier the same day. Point reads took 19 instead of 38 µs under Node and 12 instead of 47 µs under Bun, lone transactions 3.86 instead of 4.35 ms and 3.97 instead of 4.26 ms, and four contending writers 0.98 instead of 1.23 ms and 1.02 instead of 1.17 ms per commit. Three changes did this. Reads of up to 16 KiB are blocking calls under asynchronous I/O; the new `syncReadBytes` option sets the bound, and 0 restores thread-pool reads. The head and generation files stay open between commits as Storage shared writers, shared by every handle in the realm and closed with the last one. Holders of a shared lock on one connection share one flock, which keeps four writers on one handle in commit groups of four. Each batch's encoded bytes are counted once.
|
|
6
|
+
|
|
7
|
+
VERIFIED: defuss-storage is now 0.4.1, whose native adapter flushes with `fcntl(F_FULLFSYNC)` under Bun on macOS as Node.js does. Durable commits under Bun therefore cost a full device flush, about 3.8 ms per commit on the development machine, where the plain `fsync` of 0.4.0 took 0.02 to 0.07 ms and left data in the drive's cache.
|
|
8
|
+
|
|
9
|
+
VERIFIED: `make bench-redis` times atomic batches of 5000 writes for both engines instead of 1000. defuss-dbsonl took less time than Redis in 11 of 16 pairings, one of them a tie within 0.1%; Redis took less time for the four batches and for a lone durable Bun transaction, by 2%. The website shows these runs.
|
|
10
|
+
|
|
11
|
+
VERIFIED: New databases use format 3: every commit ends with a commit record in the generation, so on native files one flush of the generation makes it durable and the head slot is written without a flush. A lone durable transaction took 4.6 ms instead of 8.1 ms under Node on macOS, where each flush is a full `F_FULLFSYNC`. After a power loss, opening, committing, compaction and collection adopt the commits whose records survived with every frame before them intact by checksum; the head is flushed every 16 MiB to bound that walk. Existing format 2 databases keep format 2 and its two flushes, so 0.2 to 0.6 writers can still share them; those versions refuse a format 3 database with `UNSUPPORTED`. A commit whose head publication fails is now adoptable once its generation is flushed, so `COMMIT_UNCERTAIN` can turn out committed, as the code always allowed. `tests/format3.test.ts` covers lost head slots, a torn last record, adoption by another handle, a write rejected before adoption that stays rejected, a value shaped like a record and format 2 databases; the packed package checks that 0.2.0 refuses format 3 and shares a format 2 database with current writers.
|
|
12
|
+
|
|
13
|
+
VERIFIED: defuss-storage 0.4 shares read-only opens of one file, so reads on memory, OPFS and directory-handle storage take the file's I/O lock in shared mode; writes, truncation and removal still take it alone. Storage 0.4 rejects `BUSY` when a reader meets an owner or a removal, and the lock makes both wait instead. Parallel snapshot scans of one generation, in one worker or several, no longer take turns. Native storage already read through its own descriptors and is unchanged. The on-disk format and the lock order are unchanged.
|
|
14
|
+
|
|
15
|
+
VERIFIED: On native storage, `scanBatches()` runs in worker threads by default once its range or limit covers 5000 rows: `createFileBackend` starts a pool of up to four workers that scan key ranges of the pinned snapshot and send the batches back, which the calling thread yields in key order. The rows, their order and the error codes equal a scan in one thread. A full scan of 100,000 documents took 105 ms instead of 401 ms under Node and 113 ms instead of 418 ms under Bun. `scanWorkers` and `scanThreshold` configure the pool, and `scanWorkers: 0` turns it off. Backends in worker threads, memory and browser backends, `scan()` and scans with `sizeOf` stay in the calling thread. The package exports `./scan-worker`, the worker entry, which the server build loads beside itself.
|
|
16
|
+
|
|
17
|
+
VERIFIED: Parallel scans of your own. A snapshot's `split(parts, {gte?, lt?}?)` returns up to `parts` key ranges `{gte?, lt?, count}` with exact row counts that cover every row of the interval once, and `beginRead({at: head})` pins the head of a snapshot that is still open, from any worker, thread or process with its own handle. Ranges are cut by key from the index's subtree counts, not by byte offset, because a generation file also holds index pages and superseded values. The pin takes the commit lock in shared mode, so workers that pin at once do not queue. With 8 Node worker threads on native storage, a full scan of 100,000 documents took 22 ms against 130 ms in one thread with the index cached on every handle, and 26 ms against 401 ms with the defaults ([PERFORMANCE.md](docs/PERFORMANCE.md#parallel-scans-on-macos-arm64)); `make bench-parallel` measures it. Worker threads should open native backends with `{ io: 'sync' }`, because asynchronous reads share the process's libuv thread pool.
|
|
18
|
+
|
|
19
|
+
VERIFIED: `tests/scan-workers.test.ts` runs the pool's real worker threads against one-thread scans: rows, DSON types, order, ranges, limits, batch sizes, `LIMIT_EXCEEDED`, and pins released on close and on an early break. The packed package runs a default pool from the ESM and CommonJS builds under Node and Bun. `tests/parallel-scans.test.ts` checks that the ranges add up to the full scan, also within key intervals, on memory and native storage and that a second handle or backend reads the same snapshot until collection, then gets `CONFLICT`. The packed package runs four Node and Bun worker threads over the ranges of one pinned native snapshot while a writer commits and compacts, and nested OPFS workers in Chromium do the same.
|
|
20
|
+
|
|
21
|
+
VERIFIED: Node 26 runs the test suite too. It removed `--experimental-transform-types`, which the scan worker needed to load its TypeScript source in tests, so the source no longer uses parameter properties and `tsconfig.json` sets `erasableSyntaxOnly`. All 76 tests pass under Node 26.13.1 and the pinned 24.22.1, and the built package runs its scan pool under both. In the `make bench-redis` workloads, Node 26.13.1 took 0.94 to 1.02 of Node 24.22.1's time per workload, within the variation between passes, so the pinned toolchain stays on Node 24.22.1 ([PERFORMANCE.md](docs/PERFORMANCE.md#node-26-against-node-24-on-macos-arm64)).
|
|
22
|
+
|
|
23
|
+
VERIFIED: `tests/shared-reads.test.ts` covers overlapping reads, writers and removals that wait for readers, and parallel scans beside commits, compaction and collection; the overlap cases fail against the exclusive lock of 0.6.0. The browser suite runs three scanning workers beside a writing, compacting worker on OPFS.
|
|
24
|
+
|
|
25
|
+
## 0.6.0
|
|
26
|
+
|
|
27
|
+
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.
|
|
28
|
+
|
|
29
|
+
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.
|
|
30
|
+
|
|
31
|
+
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.
|
|
32
|
+
|
|
33
|
+
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.
|
|
34
|
+
|
|
35
|
+
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.
|
|
36
|
+
|
|
37
|
+
## 0.5.1
|
|
38
|
+
|
|
39
|
+
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.
|
|
40
|
+
|
|
41
|
+
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`.
|
|
42
|
+
|
|
43
|
+
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.
|
|
44
|
+
|
|
45
|
+
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.
|
|
46
|
+
|
|
3
47
|
## 0.5.0
|
|
4
48
|
|
|
5
49
|
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.
|
|
1
|
+
# defuss-dbsonl 0.7.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.
|
|
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
|
|
|
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
|
|
7
|
+
## Install
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
bun add defuss-dbsonl
|
|
11
|
+
# or
|
|
12
|
+
npm install defuss-dbsonl
|
|
12
13
|
```
|
|
13
14
|
|
|
14
|
-
|
|
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,24 @@ 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
|
+
|
|
55
|
+
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.
|
|
56
|
+
|
|
57
|
+
To run your own filters and aggregates in workers, or to scan in browser workers, `split(n)` cuts a snapshot into at most `n` key ranges with exact row counts. Each worker opens its own backend and handle on the same files, pins the same snapshot with `beginRead({ at: head })` and scans one range. The first snapshot must stay open until every worker has pinned. In Node.js and Bun worker threads, open native backends with `{ io: 'sync' }`: a scanning thread can block itself, and asynchronous reads queue on the thread pool that all threads of a process share.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
// Coordinator: pin, split, hand out the head and one range per worker.
|
|
61
|
+
const session = await db.beginRead();
|
|
62
|
+
const ranges = await session.split(4);
|
|
63
|
+
// Worker, on its own createFileBackend(root, { io: 'sync' }) and openDbsonl(backend, 'accounts'):
|
|
64
|
+
const view = await workerDb.beginRead({ at: head });
|
|
65
|
+
for await (const batch of view.scanBatches(range)) { /* decode and filter here */ }
|
|
66
|
+
await view.close();
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
With 8 worker threads that keep their rows, a full scan of 100,000 native documents took 22 ms under Node against 121 ms in one thread, with the index cached on every handle ([PERFORMANCE.md](docs/PERFORMANCE.md#parallel-scans-on-macos-arm64)).
|
|
70
|
+
|
|
46
71
|
Memory storage needs no platform entry:
|
|
47
72
|
|
|
48
73
|
```ts
|
|
@@ -102,7 +127,7 @@ Resource budgets cap retained engine work. The page cache is bounded by encoded
|
|
|
102
127
|
|
|
103
128
|
## Compatibility
|
|
104
129
|
|
|
105
|
-
VERIFIED: Versions 0.2 through 0.
|
|
130
|
+
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
131
|
|
|
107
132
|
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
133
|
|
|
@@ -112,6 +137,7 @@ Version 0.4.0 renamed the native entry from `defuss-dbsonl/node` to `defuss-dbso
|
|
|
112
137
|
make setup # pinned Node/Bun/Redis via mise, dependencies, Chromium, WebKit, VAE runtime
|
|
113
138
|
make verify # lint, tests, coverage, packed-package e2e
|
|
114
139
|
make bench # matched v0.2 versus current benchmarks
|
|
140
|
+
make bench-scan # full scans, row by row and in batches, against the vendored 0.5.0
|
|
115
141
|
make bench-redis # current build versus a throwaway loopback Redis, run as mise exec -- make bench-redis
|
|
116
142
|
make dev # rebuild the website demos and serve docs/ on 127.0.0.1:3000
|
|
117
143
|
make vae # verification, review and documentation gate
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var defussStorage = require('defuss-storage');
|
|
4
|
-
var common = require('./common-
|
|
4
|
+
var common = require('./common-YqfTK8sQ.cjs');
|
|
5
5
|
|
|
6
6
|
function createMemoryCoordinator() {
|
|
7
7
|
const states = /* @__PURE__ */ new Map();
|
|
@@ -52,17 +52,21 @@ function createMemoryBackend(options) {
|
|
|
52
52
|
return { storage: defussStorage.createMemoryStorage(options), coordinator: createMemoryCoordinator(), durability: "memory", writeChunkBytes: Math.min(65536, options?.maxWriteBytes ?? 65536, options?.maxPendingWriteBytes ?? 65536) };
|
|
53
53
|
}
|
|
54
54
|
async function withFile(backend, name, open, work) {
|
|
55
|
-
|
|
55
|
+
const release = await backend.coordinator.acquire(`io-${name}`, open.readOnly === true && open.shared !== false);
|
|
56
|
+
if (!release) throw new Error("Coordinator did not grant a blocking lock.");
|
|
57
|
+
try {
|
|
56
58
|
const file = await backend.storage.open(name, open);
|
|
57
59
|
try {
|
|
58
60
|
return await work(file);
|
|
59
61
|
} finally {
|
|
60
62
|
await file.close();
|
|
61
63
|
}
|
|
62
|
-
}
|
|
64
|
+
} finally {
|
|
65
|
+
await release();
|
|
66
|
+
}
|
|
63
67
|
}
|
|
64
|
-
async function locked(backend, name, work, signal) {
|
|
65
|
-
const release = await backend.coordinator.acquire(name,
|
|
68
|
+
async function locked(backend, name, work, signal, shared = false) {
|
|
69
|
+
const release = await backend.coordinator.acquire(name, shared, signal);
|
|
66
70
|
if (!release) throw new Error("Coordinator did not grant a blocking lock.");
|
|
67
71
|
try {
|
|
68
72
|
common.abort(signal);
|
package/dist/browser.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var common = require('./common-
|
|
3
|
+
var common = require('./common-YqfTK8sQ.cjs');
|
|
4
4
|
|
|
5
5
|
function createBrowserBackend(storage, namespace, locks, writeChunkBytes = 65536) {
|
|
6
6
|
if (!namespace || !locks?.request) throw new TypeError("A namespace and Web Lock manager are required.");
|
package/dist/browser.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as natural,
|
|
1
|
+
import { n as natural, b as abort } from './common-R-Fl2aza.mjs';
|
|
2
2
|
|
|
3
3
|
function createBrowserBackend(storage, namespace, locks, writeChunkBytes = 65536) {
|
|
4
4
|
if (!namespace || !locks?.request) throw new TypeError("A namespace and Web Lock manager are required.");
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
class DbsonlError extends Error {
|
|
2
|
+
code;
|
|
2
3
|
constructor(code, message, options2) {
|
|
3
4
|
super(message, options2);
|
|
4
5
|
this.code = code;
|
|
5
6
|
this.name = "DbsonlError";
|
|
6
7
|
}
|
|
7
|
-
code;
|
|
8
8
|
}
|
|
9
9
|
function abort(signal) {
|
|
10
10
|
if (signal?.aborted) throw new DbsonlError("ABORTED", "Operation cancelled.", { cause: signal.reason });
|
|
@@ -35,4 +35,4 @@ function options(input) {
|
|
|
35
35
|
return out;
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
export {
|
|
38
|
+
export { DEFAULT_OPTIONS as D, DbsonlError as a, abort as b, name as c, corrupt as d, key as k, natural as n, options as o, reference as r };
|