Skip to content

bridge: add a Node storage backend, and stop silently downgrading the journal mode - #9

Merged
Roasbeef merged 7 commits into
mainfrom
node-fs-storage-backend
Aug 11, 2026
Merged

Roasbeef merged 7 commits into
mainfrom
node-fs-storage-backend

Conversation

@Roasbeef

Copy link
Copy Markdown
Member

In this PR, we teach the driver to persist under Node, and fix a silent journal
mode downgrade that turns out to have been hitting the browser all along.

Until now the driver could only run in a browser, because everything below the
database/sql layer assumed browser APIs: the bridge spawned a Web Worker, the
worker pulled sqlite3.js in with importScripts and let Emscripten fetch the
wasm binary over the network, and the only durable storage on offer was OPFS. A
Go program compiled for js/wasm and hosted by Node hit all three of those at
once and had nowhere to put its data.

None of that is a deep problem, because Node has something a browser does not:
real synchronous file I/O. OPFS is asynchronous underneath, which is why
persisting to it needs either the async proxy worker or the SAH pool's
preallocated access handles, and why that machinery is as involved as it is.
The node:fs sync API is exactly the shape SQLite's VFS layer wants, so the
new nodefs VFS is close to a direct translation rather than a pooling scheme.

See each commit message for a detailed description w.r.t the incremental
changes.

Reconstructing exclusive access

The one guarantee OPFS provides for free that a plain filesystem does not is
exclusive access, since a SyncAccessHandle cannot be held by two tabs at
once. Two processes writing one database corrupt it silently, so the VFS
reconstructs that guarantee with a pid-stamped lock file, taken when a main
database is opened for writing. A second process now fails to open rather than
interleaving writes, and a lock whose owning process is provably gone is
reclaimed, so a crash does not strand the database.

Durability is a promise, not a preference

Asking for vfs=opfs and getting a working in-memory database instead used to
be the documented behavior. That is the wrong default for anything whose
database is the only copy of its state: it looks completely healthy for the
whole run and then takes the state with it when the process exits.

Naming a durable VFS is now taken as a statement about durability. If opfs,
opfs-wl, opfs-sahpool, or nodefs is asked for and cannot be opened, the
open fails. Only vfs=auto still falls back, since "auto" means whatever this
host can do, and even then not when require_persistent is set. Callers whose
durable open succeeds today see no change at all; only the failure path is
different, and it now says so.

WAL was never actually on

This is the part worth a careful look, because it is a behavior change for
existing browser callers.

No VFS reachable from here implements xShmMap, so the only route to WAL is
the one SQLite documents for hosts without shared
memory
: put the connection in
locking_mode=EXCLUSIVE first, and the WAL index lives on the heap instead.
The worker was setting journal_mode first and applying the caller's own
pragmas afterwards, so a caller that passed both, as every caller does in
practice, had its locking mode applied one step too late. SQLite answered the
WAL request by quietly leaving the database on the rollback journal:

[WAL then EXCLUSIVE]   effective=delete
[EXCLUSIVE then WAL]   effective=wal

Measured the same way in Chromium for opfs, opfs-wl and opfs-sahpool.
This was never a Node-specific problem; Node is just what made us look.

Ordering the journal mode last is only half the repair. Once a database is
actually in WAL, a non-exclusive connection cannot so much as read it here, and
a pragma as ordinary as auto_vacuum reads page 1. Listing locking_mode
after it, which is where it reads most naturally, turns the second open of a
WAL database into SQLITE_CANTOPEN. Rather than ask every caller to know that,
the worker hoists any locking_mode pragma to the front, since the driver is
the part that knows its VFSes have no shared memory.

Getting the order right still leaves the original complaint unanswered, because
the failure was silent and would go on being silent for the next mode SQLite
cannot give us. PRAGMA journal_mode reports the mode in force rather than the
mode requested, so the two can differ with nobody the wiser. The difference is
not academic: synchronous=NORMAL under WAL costs you the recently committed
tail on power loss, while the same setting under a rollback journal risks the
database itself. So we read the mode back and refuse to continue when it is not
what was asked for. An in-memory database is exempt, since it is always in
"memory" mode and has no durability to lose.

[no-exclusive WAL] rejected: journal_mode=WAL was requested but SQLite is in
                   "delete" mode on VFS nodefs; refusing to run with weaker
                   guarantees than the caller asked for

Reviewers should know: callers that ask for WAL and set
locking_mode=EXCLUSIVE will now genuinely get WAL where they previously got
the rollback journal, in the browser as well as under Node. That is the mode
their synchronous setting was almost certainly chosen for, but it is a real
change and worth a look on your side before this lands.

A deadlock only a Node host could hit

The promise rejection handler in the bridge adapter printed the JavaScript
error to stdout from inside a syscall/js callback. A browser answers that
write synchronously, but Node's fs.write is genuinely asynchronous, so the Go
scheduler parked waiting for a callback that could not run until the handler it
was already inside returned, and the whole runtime deadlocked. The message
reaches the caller through the returned error regardless, so the print is
simply gone.

Testing

Two suites come with the backend. One drives the bridge from Node directly. The
other runs the Go driver itself under Node through a go test -exec wrapper,
so the claim that database/sql code persists to a real file is checked
against the real driver rather than against a description of it.

# tests 19  # pass 19  # fail 0

ok  9 - a stale lock from a dead process is reclaimed
ok 15 - WAL is delivered under nodefs when locking_mode is EXCLUSIVE
ok 16 - a journal mode SQLite cannot honor is an error, not a downgrade
ok 17 - a WAL database reopens with locking_mode listed after other pragmas
ok 19 - a WAL database survives an unclean process exit

--- PASS: TestNodeDriverPersistsToHostFilesystem
--- PASS: TestNodeDriverRefusesMemoryFallback
--- PASS: TestNodeDriverUnavailableVFSIsTyped

Test 17 was confirmed to fail without the locking_mode hoist, and test 19
uses a real child process and SIGKILL, since the lock file is pid-stamped.
The memory-fallback refusals were checked against a reintroduced silent
fallback, which fails them, so they are not passing vacuously.

Not covered here

  • The browser WAL result above was measured with a standalone Chromium probe
    against the pinned 3.53.1 assets. The repo's own playwright suite routes
    through fetch-assets, which replaces those assets, so it was not the thing
    that produced these numbers.
  • WAL under nodefs is single-connection by construction, which is what the
    exclusive locking mode buys. Nothing here makes concurrent readers work.

Roasbeef added 3 commits July 29, 2026 00:22
In this commit, we teach the driver to persist under Node. Until now it
could only run in a browser, because everything below the database/sql
layer assumed browser APIs: the bridge spawned a Web Worker, the worker
pulled sqlite3.js in with importScripts and let Emscripten fetch the
wasm binary over the network, and the only durable storage on offer was
OPFS. A Go program compiled for js/wasm and hosted by Node hit all three
of those at once and had nowhere to put its data.

None of that is a deep problem, because Node has something a browser
does not: real synchronous file I/O. OPFS is asynchronous underneath,
which is why persisting to it needs either the async proxy worker or the
SAH pool's preallocated access handles, and why that machinery is as
involved as it is. The node:fs sync API is exactly the shape SQLite's
VFS layer wants, so the new VFS in sqlite-node-vfs.js is close to a
direct translation rather than a pooling scheme. It is modeled on
opfs-sahpool for structure only.

The one guarantee OPFS provides for free that a plain filesystem does
not is exclusive access, since a SyncAccessHandle cannot be held by two
tabs at once. Two processes writing one database corrupt it silently, so
the VFS reconstructs that guarantee with a pid-stamped lock file taken
when a main database is opened for writing. A second process now fails
to open rather than interleaving writes, and a lock whose owning process
is gone is reclaimed, so a crash does not strand the database.

The bridge and the worker each grew one seam rather than a fork. The
bridge wraps a node:worker_threads worker in an adapter presenting the
browser Worker interface, and hands it the worker source rather than a
path, because a path is resolved through the nearest package.json and a
".js" file inside a "type": "module" package would be loaded as ESM with
its require calls broken. The worker abstracts script loading, wasm
instantiation, and message transport, leaving the request handlers
host-independent. The browser path through both files is unchanged.

Also fixed here is a deadlock only a Node host could hit. The promise
rejection handler in the bridge adapter printed the JavaScript error to
stdout from inside a syscall/js callback. A browser answers that write
synchronously, but Node's fs.write is genuinely asynchronous, so the Go
scheduler parked waiting for a callback that could not run until the
handler it was already inside returned, and the whole runtime
deadlocked. The message reaches the caller through the returned error
regardless, so the print is simply gone.

Alongside the backend come two test suites. One drives the bridge from
Node directly, and the other runs the Go driver itself under Node
through a go test -exec wrapper, so the claim that database/sql code
persists to a real file is checked against the real driver rather than
against a description of it.
In this commit, we make a request for durable storage a promise the
worker either keeps or breaks loudly. Asking for vfs=opfs and getting a
working in-memory database instead used to be the documented behavior,
and it is the wrong default for anything whose database is the only copy
of its state.

A wallet is the clear case. Its VTXO, swap, and round state exists
nowhere else, so a database that quietly turns out to be in memory looks
completely healthy for the whole run and then takes the state with it
when the process exits, which can lose funds. The failure is invisible
at exactly the moment it could still be corrected, and irreversible
afterwards. A startup error is a far better outcome than a wallet that
silently forgets.

Naming a durable VFS is now taken as a statement about durability, not a
preference among equally acceptable options: if opfs, opfs-wl,
opfs-sahpool, or nodefs is asked for and cannot be opened, the open
fails. Only vfs=auto still falls back, since "auto" means whatever this
host can do, and even then not when require_persistent is set. Callers
whose durable open succeeds today see no change at all; only the failure
path is different, and it now says so.
In this commit, we make the driver keep the journal mode its caller asked
for, or say so. Until now the worker set journal_mode first and applied the
caller's own pragmas afterwards, which looks harmless and is not. None of the
VFSes reachable from here implements xShmMap, so the only route to WAL is the
one SQLite documents for hosts without shared memory: put the connection in
locking_mode=EXCLUSIVE first and the WAL index lives on the heap instead. A
caller that passed both, as every caller of this driver in practice does, had
its locking mode applied one step too late, and SQLite answered the WAL
request by leaving the database on the rollback journal.

Ordering the journal mode last is only half the repair, because the locking
mode has to come before the caller's other pragmas too, not merely before the
journal mode. Once a database is actually in WAL, a non-exclusive connection
cannot so much as read it here, and a pragma as ordinary as auto_vacuum reads
page 1. Listing locking_mode after it, which is where it reads most naturally
and where both of our callers had put it, turns the second open of a WAL
database into SQLITE_CANTOPEN. Rather than ask every caller to know that, the
worker hoists any locking_mode pragma to the front, since the driver is the
part that knows its VFSes have no shared memory. With both halves in place
WAL works on nodefs, opfs, opfs-wl and opfs-sahpool alike.

Getting the order right still leaves the original complaint unanswered,
because the failure was silent and would go on being silent for the next mode
SQLite cannot give us. PRAGMA journal_mode reports the mode in force rather
than the mode requested, so the two can differ with nobody the wiser, and the
difference is not academic: synchronous=NORMAL under WAL costs you the
recently committed tail on power loss, while the same setting under a
rollback journal risks the database itself. So we read the mode back and
refuse to continue when it is not what was asked for. An in-memory database
is exempt, since it is always in "memory" mode and has no durability to lose.

Two smaller things follow from having a pragma that can now fail. A refused
open closes the database it had already opened, because the VFS claims a file
exclusively for as long as a handle is alive, through an OPFS access handle
or a nodefs lock file, and leaving one behind would meet a corrected retry
with "already open" and bury the real fault underneath it. And a failing
pragma now names itself, since SQLite reports only what went wrong and a DSN
carries several.

@litbot-9000 litbot-9000 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FINAL — Reviewed all three commits at the PR head f5add42 against base f72f300, with the wavelength#1064 tree side by side to check the integration concretely.

What I ran. node --test tests/node-backend.test.cjs → 19/19 pass. GOOS=js GOARCH=wasm go test -exec "node scripts/node-wasm-test-exec.cjs" -run TestNodeDriver -v ./ → 5/5 pass. GOOS=js GOARCH=wasm go vet ./... clean. I also wrote four throwaway probes: an instrumented copy of the VFS that logs every xOpen/xSync/xDelete SQLite makes; a two-real-process contention harness; an injected-ENOSPC harness; and a direct check of the wasm API surface.

What holds up. The core design is sound and the reasoning in the comments is largely correct. xRead genuinely zero-fills and returns SQLITE_IOERR_SHORT_READ (Node's readSync returns a short count past EOF rather than throwing, so that branch is both reachable and right). xSync really does fsyncSync and deliberately declines to weaken to fdatasync on the DATAONLY hint — I confirmed SQLite only ever passes SQLITE_SYNC_FULL here anyway. xDeviceCharacteristics returning 0 is the conservative direction. Declaring iVersion = 1 on the io_methods is the correct way to tell SQLite there is no shm, and it is what makes sqlite3PagerWalSupported() require exclusiveMode — so the WAL story really is enforced by SQLite, not merely assumed. The require_persistent trace is clean: both paths into openMemoryDB are guarded (sqlite-worker.js:544 and :592), an explicitly named VFS rethrows before the fallback is ever reached (:581), and RequirePersistent || DisallowMemory is threaded through bridge_adapter.go:53. The orderPragmas hoist is load-bearing and correctly implemented. Cross-repo, the DSN vocabulary matches exactly — wavelength sends vfs=nodefs, require_persistent=true (the parser wants literally "true", and that is what it gets), journal_mode as its own key, and locking_mode=EXCLUSIVE in the pragma list — and sqlite-node-vfs.js ships at the path wavelength's Makefile copies from and is covered by embed.go and embed_test.go. No mismatch there.

Headline finding. Two of the three commits are about refusing to silently substitute a weaker guarantee, and the VFS underneath them does exactly that in two places. xDelete accepts doSyncDir and ignores it — I instrumented it and confirmed SQLite passes doSyncDir=1 at synchronous=EXTRA and 0 at the default, so setting synchronous=EXTRA on a wallet database silently gets you no more than FULL. And the whole journal-mode readback is bypassed if journal_mode is passed in the generic pragma list instead of the DSN key: I opened with pragma: ["journal_mode=WAL", "synchronous=NORMAL"] and got a happy persistent: true handle sitting on journal_mode=delete with synchronous=NORMAL — the exact combination applyJournalMode's own comment says risks a corrupt database.

Also. No CI job executes any of the new code: compile runs go test ./... on the host (the Node driver test is js && wasm-tagged), and the new testMatch: "**/*.spec.js" in playwright.config.js excludes node-backend.test.cjs from the Playwright job. 600 lines of storage layer under a wallet key store, green board, never run.

Nothing here is fund-losing on the path wavelength actually takes today, so this is not a blocker set — but the durability holes are in exactly the area the PR is claiming to have closed, and I would not want them merged unremarked. One smaller item I could not anchor to a diff line: open.go:206 accepts require_persistent only when it is literally "true", so require_persistent=1 or a bare require_persistent is silently ignored. wavelength sends "true" so the integration is fine, but silently ignoring an unrecognised value on the flag whose entire job is refusing to run without durable storage is the wrong default; an unparseable value should be an error.

Comment thread bridge/sqlite-worker.js Outdated
// it first, as this once did, meant a caller asking for WAL got the
// rollback journal and no indication that it had.
try {
for (const pragma of orderPragmas(args.pragma || [])) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Commit 3's guarantee has a hole: journal_mode in the generic pragma list bypasses the readback entirely.

applyJournalMode only runs against args.journalMode. A caller that puts the journal mode in args.pragma — which Options.Pragma accepts, and which is the natural place to put it, since that is where every other pragma goes — gets the pre-PR behaviour back with no warning. Verified against this branch:

const o = await b.open({file: db, vfs: "nodefs", mode: "rwc",
                        pragma: ["journal_mode=WAL", "synchronous=NORMAL"]});
// OPEN SUCCEEDED. persistent= true vfs= nodefs
// effective journal_mode = [["delete"]]
// effective synchronous  = [[1]]     // NORMAL

That is precisely the state applyJournalMode's own doc comment (lines 505-516) says must not happen: synchronous=NORMAL chosen on the assumption of WAL, actually running on the rollback journal, where the comment correctly notes it "risks a corrupt database". The open reports persistent: true and hands back a working handle.

wavelength#1064 happens to route journal_mode to the DSN key (db/sqlite_open_wasm.go:52), so the integration is safe today — but nothing enforces that, and Options.Pragma is public API with no doc saying journal_mode is forbidden there.

Fix it in the same place you already special-case locking_mode: have orderPragmas/open detect a journal_mode= entry in args.pragma and either reject it with a message pointing at the journal_mode DSN key, or fold it into args.journalMode so it goes through applyJournalMode. Worth a test asserting the pragma-list route cannot silently downgrade.

Comment thread bridge/sqlite-node-vfs.js
return 0;
},

xDelete: function (pVfs, zName, doSyncDir) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — doSyncDir is accepted and ignored, which silently turns synchronous=EXTRA into synchronous=FULL.

In rollback-journal mode the entire difference between FULL and EXTRA is that EXTRA additionally fsyncs the containing directory after the journal is unlinked, so the unlink — which is the commit point — is itself durable. Without it, a power loss after a committed transaction can resurrect the journal on recovery and roll that transaction back.

SQLite really does ask for it. I instrumented this method and ran a commit at each level against nodefs:

synchronous=FULL (default):  PROBE xDelete .../wallet.db-journal doSyncDir= 0
synchronous=EXTRA:           PROBE xDelete .../wallet.db-journal doSyncDir= 1

So the parameter is live, the VFS drops it, and an operator who sets synchronous=EXTRA on a wallet database gets FULL while believing otherwise. Same class of defect as the other two commits in this PR — a silently weaker durability guarantee than the caller asked for — and it is a few lines to fix on Linux/macOS, guarded by doSyncDir & 1:

const dfd = nodeFS.openSync(nodePath.dirname(target), "r");
try { nodeFS.fsyncSync(dfd); } finally { nodeFS.closeSync(dfd); }

Related, and worth deciding explicitly rather than by omission: os_unix.c also fsyncs the parent directory at the first xSync of a newly created journal/WAL file (UNIXFILE_DIRSYNC), so the journal's existence is durable before the main database is modified. That one is invisible through the VFS interface — SQLite does not signal it — so a custom VFS has to know to do it, and this one does not. On ext4 an fsync of the new file usually drags the dirent along, but that is a filesystem accident rather than a guarantee, and the failure mode is an unrecoverable database, not a lost transaction. At minimum the header comment should state that the directory is never synced, so the next reader does not assume parity with the unix VFS.

Comment thread bridge/sqlite-node-vfs.js Outdated

if (owner && pidIsAlive(owner.pid)) {
throw new Error(
`database is locked by another process ` +

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — This message — the one thing that makes a two-process collision diagnosable — never reaches the operator.

xOpen catches this error, stashes it in lastError, and returns a bare SQLITE_CANTOPEN. The message is only retrievable through xGetLastError, which SQLite documents as not currently used by the core. Verified with two real processes, A holding wallet.db and B opening the same path:

holder pid 50129 lock: {"pid":50129,"at":1786415712142}
RW SECOND PROCESS: refused -> SQLite3Error: SQLITE_CANTOPEN: sqlite3 result code 14: unable to open database file

The refusal itself works, and that part of the design is sound — but pid 50129 is dropped on the floor and the operator gets the most generic error SQLite has.

It gets worse in the actual consumer. wavelength#1064's openWASMSQLiteWithRetry retries specifically on this string (db/sqlite_open_wasm.go:129-132 matches SQLITE_CANTOPEN / unable to open database file, 25 attempts × 200ms). So a second waved accidentally pointed at the same data directory spins for five seconds and then dies with "unable to open database file" — indistinguishable from a permissions problem, a missing directory, or the OPFS reload race that retry loop was actually written for. At 3am that is the difference between a 30-second diagnosis and an hour.

Since the core will not carry the message, surface it from a layer that can: have the worker turn a SQLITE_CANTOPEN on a nodefs main-db open into an error naming the lock file and the holding pid (it can simply read ${dbPath}-nodefs-lock after the failed open). A typed error would also let wavelength stop retrying a collision it can never win.

Comment thread bridge/sqlite-node-vfs.js

// pidIsAlive reports whether a process id still exists. Signal 0 performs the
// permission and existence checks without delivering anything.
function pidIsAlive(pid) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — pid liveness is not a sound basis for the exclusivity claim in two deployments that matter.

The header comment says this lock file "reconstructs" OPFS's exclusive-access property. It does not, in two directions:

  1. pid reuse. A crashed process leaves a lock naming pid N. If N is later recycled by an unrelated process, pidIsAlive returns true forever and the wallet is stranded — with LOCK_STALE_GRACE_MS = 0 there is no timeout to fall back on, and the only recovery is manually deleting an undocumented -nodefs-lock file. Fixable: also record the owner's start time (/proc/<pid>/stat field 22 on Linux) and treat a pid whose start time does not match as dead.

  2. pid namespaces — the dangerous direction. Two containers sharing a bind-mounted data volume have unrelated pid numbering. Process A in namespace 1 holds the lock as pid 7; process B in namespace 2 evaluates process.kill(7, 0) against its own namespace, quite likely finds nothing, declares the lock stale, unlinks it and opens the database. Now there are two writers on one wallet file with xLock/xUnlock/xCheckReservedLock all no-ops (lines 287-295, 348-356, 229-235), so there is nothing else in the stack to catch it. Silent corruption of the only copy of the wallet state.

The real unix VFS survives this case, because POSIX fcntl advisory locks are enforced by the kernel on the inode and work across pid namespaces. Node core exposes no flock/fcntl, so I accept the pid-file scheme as a pragmatic choice — but then the limits need to be stated rather than implied away. Please narrow the header comment to what is actually guaranteed (same-pid-namespace, no pid reuse), say the same in the README next to the nodefs section, and document the -nodefs-lock file and how to clear it. Adding the start-time check would close (1) cheaply.

Comment thread Makefile
# driver itself under Node. This deliberately does not depend on fetch-assets,
# because the committed assets pin a SQLite version that re-fetching would
# silently move.
node-test:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — No CI job runs any of this. node-test is wired into make test, but .github/workflows/ci.yml never invokes make test — the compile job runs go test -v ./... directly (a host build, so driver_node_js_wasm_test.go is excluded by its js && wasm tag), browser-test runs make browser-test, and playwright-test runs npm test. This PR also adds testMatch: "**/*.spec.js" to playwright.config.js, which explicitly excludes tests/node-backend.test.cjs from the Playwright job.

Net: the 606-line sqlite-node-vfs.js, the 553-line tests/node-backend.test.cjs, and the 293-line driver_node_js_wasm_test.go are covered by a green board that never executes them. For the storage layer under a wallet key store, a green CI that does not run it is worse than no CI, because it reads as coverage.

Both suites do pass locally — node --test tests/node-backend.test.cjs (19/19) and GOOS=js GOARCH=wasm go test -exec "node scripts/node-wasm-test-exec.cjs" -run TestNodeDriver ./ (5/5) — so this is a wiring gap, not a broken harness. Please add a node-test job to ci.yml in this PR (setup-node + make node-test) so the next change to the VFS is caught by the board rather than by a wallet.

Comment thread tests/node-backend.test.cjs Outdated
});
});

test("a second process cannot open the same database", async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 minor — This test does not do what its name says, and the path it is named for has no coverage at all.

It never starts a second process. It opens the database once, asserts a lock file exists naming this pid, and asserts the lock is gone after close. Those are worth asserting, but the contention branch in acquireLock — owner && pidIsAlive(owner.pid) → throw (sqlite-node-vfs.js:185-190) — is never executed by this suite. The sibling test at line 191 does not reach it either: openPersistentFiles in the worker rejects the duplicate with "already open" before acquireLock is ever called.

So the single mechanism protecting a wallet database from two concurrent writers is untested. I did exercise it by hand with two real node processes and it does refuse correctly, so the code is right — it just has no regression guard, which for this particular property is the one you most want.

The suite already spawns a child process for the unclean-exit test, so the machinery exists: start a holder child, wait for it to signal that it has the database open, then assert the parent's open is rejected, then kill the holder. Consider renaming this one to something like "the lock file is taken on open and released on close" so the name matches what it checks.

Comment thread bridge/sqlite-node-vfs.js Outdated
openMode = "r+";
}

if (isMainDB && !readOnly) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 minor — The exclusivity the header comment promises is writer-only: a read-only open takes no lock and is not blocked by one. Verified — with process A holding wallet.db read-write, process B opened the same file with mode: "ro" and read committed rows out of it:

RW SECOND PROCESS: refused -> SQLITE_CANTOPEN ...
RO SECOND PROCESS: OPENED, rows = [[1]]

I do not think this corrupts anything, and I checked why: with xCheckReservedLock hardcoded to 0, a reader that encounters the writer's live journal concludes it is hot and tries to roll it back, which a read-only pager refuses with SQLITE_READONLY_ROLLBACK; and a WAL database is unreadable by a non-exclusive connection here anyway. So the outcomes are confusing errors and possibly stale reads, not silent damage.

Still, the header comment reads as an unqualified "two Node processes fail loudly", and a reader is a second Node process that does not. Worth either taking the lock in shared form for read-only main-db opens, or narrowing the comment to say the guarantee covers writers only and describing what a concurrent reader can expect.

Comment thread bridge/sqlite-node-vfs.js Outdated
}
return 0;
} catch (error) {
return storeErr(error, capi.SQLITE_IOERR_WRITE);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 minor — A full disk is reported as a generic I/O error. os_unix.c's unixWrite special-cases ENOSPC and returns SQLITE_FULL ("database or disk is full"); this maps every write failure to SQLITE_IOERR_WRITE without looking at error.code. Verified by injecting an ENOSPC into writeSync inside the worker:

sqlite3_step() rc= 778 SQLITE_IOERR_WRITE SQL = INSERT INTO t VALUES(2)
write failure surfaced as: SQLITE_IOERR_WRITE: sqlite3 result code 778: disk I/O error

For a daemon this is the difference between an operator running df and an operator suspecting failing hardware or a corrupt file. Cheap to fix: return storeErr(error, error.code === "ENOSPC" ? capi.SQLITE_FULL : capi.SQLITE_IOERR_WRITE), and the same for xTruncate. While you are in here, EACCES on xOpen currently arrives as the same SQLITE_CANTOPEN as "file does not exist"; SQLITE_CANTOPEN is right for both, but the accompanying message would be worth keeping (see the lock-message comment).

Comment thread bridge/sqlite-node-vfs.js

fd = nodeFS.openSync(target, openMode);

openFiles.set(Number(pFile), {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ nit — If anything after this line throws — new capi.sqlite3_file(pFile), poke32 — the catch block closes the fd and releases the lock but leaves the openFiles entry in place, keyed on a pFile pointer whose file is now closed. SQLite will not call xClose for a failed xOpen (it leaves pMethods null), so the entry lives until the worker exits, and a later allocation landing on the same address would find a stale record with a closed fd. Very unlikely to fire in practice, but it costs one line: openFiles.delete(Number(pFile)) in the catch, alongside the existing cleanup.

Comment thread bridge/sqlite-node-vfs.js Outdated
// still honored. A crashed process leaves its lock behind; refusing forever
// would strand the database, so a lock is reclaimable once its owner is
// provably dead.
const LOCK_STALE_GRACE_MS = 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ nit — LOCK_STALE_GRACE_MS = 0 makes the LOCK_STALE_GRACE_MS > 0 guard at line 193 dead, so the doc comment describes a grace period the code never applies. Not wrong — 0 does mean "reclaimable as soon as the owner is provably dead", which is the intended behaviour — but a constant that exists only to disable a branch reads as an unfinished knob. Either drop the constant and the branch, or say in the comment that 0 is the deliberate setting and what a non-zero value would buy.

The pid-stamped lock file is the whole of what replaces the exclusive
access OPFS gives away for free, and two paths through it let two
processes hold one database at once. Both need a race between two
processes, and both end in a silently corrupted wallet.

The first is in the reclaim. Two processes recovering from the same
crashed owner both see a stale lock, and reclaiming by unlinking lets
the second delete the fresh lock the first just took and then take one
of its own. Unlinking is replaced by a rename, which can succeed only
once for a given file and so elects a single reclaimer; the loser comes
back around the loop and finds the winner's live lock. Because a rename
is atomic but not conditional, the reclaimer reads what it actually
moved and puts it back if it belongs to someone running. releaseLock
gets the matching check, and no longer deletes a lock that has stopped
naming this process.

The second is in xOpen, which created the database with O_TRUNC and took
the lock afterwards. Two processes racing the same first-time open would
have the second truncate a database the first had already begun writing,
learning it had lost the lock only after the damage. The claim now comes
first and the create is O_EXCL, so an existing database is never
truncated on the way in.

A recycled pid was a third way to get this wrong, in the other
direction: a crashed owner whose number is later reused reads as alive
forever and strands the database. The lock now records the owner's
kernel start time where the platform exposes it, which makes (pid, start
time) an identity rather than a guess.

Two durability gaps went with them, both the same silent substitution
the rest of this branch refuses. xDelete accepted doSyncDir and ignored
it, and that flag is the entire difference between synchronous=EXTRA and
FULL in rollback-journal mode, where the unlink of the journal is the
commit point; without it a power loss can resurrect a journal and roll a
committed transaction back. The unix VFS also syncs a created file's
parent at its first sync, which SQLite cannot signal through the VFS
interface, so files this VFS creates are tracked and synced there. A
full disk was reported as a generic I/O error rather than SQLITE_FULL,
which is the difference between running df and suspecting the hardware.

Last, a failed xOpen left its bookkeeping behind: SQLite leaves pMethods
null and never calls xClose for it, so a later allocation on the same
pointer would find a stale record naming a closed fd.

What the lock does not cover is now stated rather than implied. The
header comment and the README say that it holds for writers only, within
one pid namespace on a local filesystem, and name the lock file and how
to clear it by hand.

Each fix has a test that fails without it, including a real two-process
refusal and a three-process race over one stale lock. The existing "a
second process cannot open the same database" never started a second
process, so it is renamed to what it actually checks.
The readback added alongside it only ever ran against the journalMode
option, so a caller who wrote the journal mode into the pragma list got
the old behavior back with nothing said. That is not an exotic way to
hold it: the pragma list is where every other pragma goes, and
Options.Pragma is public API with no documentation forbidding this one.

Opening with pragma ["journal_mode=WAL", "synchronous=NORMAL"] returned
a healthy handle sitting on the rollback journal with synchronous set
for WAL, the combination that risks the database rather than the
recently committed tail. It is exactly the state the readback exists to
refuse.

The journal mode is now lifted out of the pragma list and routed to the
checked path, in the same place locking_mode is already hoisted, rather
than rejected: the caller meant the thing that now happens, and telling
them to move it to another key would only be a way of saying so. Asking
for two different modes in the two places is an error, since there is no
reading of that which is not a mistake.
require_persistent was honored only when it was literally "true", so
require_persistent=1, or the bare flag, was silently ignored. This is
the option whose entire job is refusing to start without durable
storage, and reading an unrecognized value as "no" disarms it at exactly
the moment a caller was reaching for it. Both it and disallow_memory now
parse as booleans and refuse what they cannot read.
Nothing in CI executed any of this. The compile job runs go test on the
host, so the driver's Node tests are excluded by their js && wasm tag,
and the Playwright job matches only *.spec.js, which leaves out the
bridge suite. That is the VFS, its suite, and the Go driver tests under
Node all sitting behind a green board that never runs them, which for a
storage layer under a wallet key store reads as coverage while providing
none.

@litbot-9000 litbot-9000 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-checked at 9e5b7d51. Every finding from my earlier review is addressed, and I verified the fixes rather than reading the commit subjects.

Ran on the new head: node --test tests/node-backend.test.cjs → 26/26 (was 19), GOOS=js GOARCH=wasm go test -exec "node scripts/node-wasm-test-exec.cjs" -run TestNodeDriver → pass, GOOS=js GOARCH=wasm go vet ./... clean, host go test ./... pass.

  • doSyncDir (was: synchronous=EXTRA silently no better than FULL) — xDelete now resolves the target first and calls syncDir(dirname) when the flag is set. The ENOENT branch is also inverted so a real unlink failure returns SQLITE_IOERR_DELETE instead of being read as success.
  • Journal mode via the pragma list — extractJournalMode pulls it out of the caller's pragmas and routes it to applyJournalMode, so the readback covers both spellings; a mode given both ways and disagreeing is now a hard error. The two new tests named for exactly those paths pass.
  • require_persistent parsing — now strconv.ParseBool with an error on anything unparseable, and disallow_memory got the same treatment. That is the stronger fix: I only flagged the silent-ignore, and refusing rather than defaulting is the right direction for a flag whose job is refusing to run without durable storage.
  • Lock soundness — the identity is now (pid, start ticks) read from /proc, so a recycled pid no longer reads as the original owner, with a bounded reclaim marker. What I like more is that the limits are now written down instead of implied: writer-only locking, single pid namespace, and no flock in Node core. A reader hitting the cross-container case will find the answer in the file rather than in a corrupted database.
  • CI coverage — the new node-test job runs make node-test, and its comment states plainly why the other three jobs never touched this code. That was the finding I cared most about: the rest of this is only as good as something running it.

Dismissing my CHANGES_REQUESTED so it does not sit stale on the merge train. Not re-reviewing the four new commits line by line — this is a verification pass on the specific findings, not a fresh review of the fixes.

@Roasbeef
Roasbeef merged commit d14cd0d into main Aug 11, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants