opfs-sahpool never rolls back a hot journal, so an interrupted transaction stays half-applied
(1.1) By Daniel Steigerwald (steida) on 2026-09-29 18:25:28 edited from 1.0 [source]
The opfs-sahpool VFS's xCheckReservedLock() always sets *pOut = 1. SQLite only calls it from hasHotJournal(), and a leftover journal only counts as hot if no RESERVED lock is held, so opfs-sahpool never rolls a leftover journal back.
If the worker dies during a write transaction after some of its pages have reached the database file, the next connection reads a half-applied transaction, and integrity_check still says "ok". That happens when a tab is closed or reloaded, the browser kills it, or the page calls worker.terminate(), either during COMMIT or during a transaction large enough to spill its cache. If the rollback itself failed first (I saw that on a full APFS disk), the database is SQLITE_CORRUPT from then on, although replaying the exported db and journal with native SQLite recovers it.
The legacy "opfs" VFS had the same problem, reported by Roy Hashimoto in forum thread a2f573b00cda1372 and fixed in June 2024 (check-in c298b8ba). opfs-sahpool still hard-codes 1 on trunk.
Repro (no fault injection, just the public API and worker.terminate(); runs from ext/wasm/ with crash.html?module=../jswasm/sqlite3.mjs):
https://gist.github.com/steida/b1827f147d624705bcb66cf74f5e63dd
- Worker 1 creates 300 rows of
zeroblob(3000), setscache_size=10, and runsbegin; update t set v=randomblob(3000), so the cache spills. - The page terminates worker 1.
Worker 2 opens the database and counts the rows still equal to
zeroblob(3000).Unpatched: "300 rows, 16 unchanged", the journal is left behind, integrity_check ok.
With the change below: "300 rows, 300 unchanged", the journal is gone.
Same result on 3.53.4 (npm) and trunk 1f7010d4, in Chromium 153, Firefox 155, WebKit 26.6 (Playwright) and Safari 26.6.2 on macOS, with locking_mode normal and exclusive. WAL mode is not affected.
Suggested change (for illustration only):
--- a/ext/wasm/api/sqlite3-vfs-opfs-sahpool.c-pp.js
+++ b/ext/wasm/api/sqlite3-vfs-opfs-sahpool.c-pp.js
@@ -189,7 +189,15 @@
const pool = getPoolForPFile(pFile);
pool.log('xCheckReservedLock');
pool.storeErr();
- wasm.poke32(pOut, 1);
+ /* SQLite calls this while holding at most a SHARED lock to
+ decide whether a leftover rollback journal is hot. Always
+ reporting a lock means that a hot journal is never rolled
+ back, and never reporting one would let a second connection
+ to the same file roll back the journal of a live transaction.
+ This pool holds its SAHs exclusively, so only files opened
+ via this pool can hold such a lock. */
+ const file = pool.getOFileForS3File(pFile);
+ wasm.poke32(pOut, pool.hasReservedLock(file.path) ? 1 : 0);
return 0;
},
xClose: function(pFile){
@@ -879,6 +887,20 @@
this.#mapS3FileToOFile_.delete(pFile);
setPoolForPFile(pFile, false);
}
}
+
+ /**
+ Returns true if any (sqlite3_file*) currently opened via this
+ pool for the given client-defined file name holds a RESERVED
+ or greater lock, else false.
+ */
+ hasReservedLock(path){
+ for(const f of this.#mapS3FileToOFile_.values()){
+ if(f.path===path && f.lockType>=capi.SQLITE_LOCK_RESERVED){
+ return true;
+ }
+ }
+ return false;
+ }
Why not always 0, like the 2024 fix: opfs-sahpool lets two connections in one worker open the same file (xOpen reuses the SAH and xLock never fails). With a constant 0, a second connection's read rolls back the first connection's live journal, and in my test 284 of 300 rows from the first connection's committed update were lost, with integrity_check ok. hasReservedLock() works like unixCheckReservedLock(). If you'd rather enforce a single connection per file, 0 is fine.
One behaviour change: a read-only open of a database with a hot journal now fails with SQLITE_READONLY_ROLLBACK, as native SQLite does, instead of reading the half-written data.
The gist also has three tester1 tests (tester1-sahpool-failures.js, meant to go after the "OPFS SyncAccessHandle Pool VFS" group). They use a small FileSystemSyncAccessHandle fault injector because tester1 can't terminate its worker. With the change, the full tester1 worker pages pass in Chromium, Firefox and Safari; unpatched they fail at 13.1.
I ran into this while building Evolu, a local-first library, where the local database is often the only copy of the user's data.
(2) By Arthur (ArthurClune) on 2026-09-29 21:27:00 in reply to 1.1 [link] [source]
I hit the same issue today
(3.1) By Stephan Beal (stephan) on 2026-09-30 09:16:02 edited from 3.0 in reply to 1.1 [link] [source]
Suggested change (for illustration only):
Thank you for this lovely find. Please post future reports of this type in the bugs, as we're trying to keep our bug reports centralized over there.
One behaviour change...
It's no secret that this project is allergic API behavior changes, but this one is an exception.
Please double-check me here, but can the patch not be simplified to:
--- ext/wasm/api/sqlite3-vfs-opfs-sahpool.c-pp.js
+++ ext/wasm/api/sqlite3-vfs-opfs-sahpool.c-pp.js
@@ -187,11 +187,17 @@
const ioMethods = {
xCheckReservedLock: function(pFile,pOut){
const pool = getPoolForPFile(pFile);
pool.log('xCheckReservedLock');
pool.storeErr();
- wasm.poke32(pOut, 1);
+ const file = pool.getOFileForS3File(pFile);
+ wasm.poke32(
+ pOut,
+ (file.lockType>=capi.SQLITE_LOCK_RESERVED) ? 1 : 0
+ /* forum:b2fbb61642 */
+ );
+;
return 0;
},
:-?
(4) By Daniel Steigerwald (steida) on 2026-09-30 09:15:01 in reply to 3.0 [link] [source]
Thank you, and noted about sqlite.org/bugs.
I double-checked: the simplification fixes the crash recovery (all my hot-journal cases pass in Chromium, Firefox and WebKit), but it is equivalent to always returning 0. SQLite calls xCheckReservedLock() only from hasHotJournal(), and only while the connection holds at most a SHARED lock (sqlite3PagerSharedLock() checks eLock<=SHARED_LOCK, and unixCheckReservedLock() asserts it), so the file's own lockType is never RESERVED there.
That's fine as long as only one connection has the file open, which persistence.md says opfs-sahpool doesn't support anyway. The difference only shows if someone opens the same file twice in one worker, which nothing prevents (xOpen reuses the SAH and xLock never fails). With 0, the second connection's read rolls back the first connection's live journal; the first connection's COMMIT then succeeds, but in my test 284 of its 300 updated rows reverted, with integrity_check "ok". With the hasReservedLock() version the journal is left alone and the commit survives, though a connection opened meanwhile still sees the uncommitted pages, so two connections aren't safe either way.
So it's your call: the simpler version relying on the documented single-connection rule, hasReservedLock() as cheap insurance against silently losing committed data, or making xOpen refuse a second open of the same file.
(Small thing: the snippet declares file but reads f.lockType, and there is a stray ; line.)
(5) By Stephan Beal (stephan) on 2026-09-30 09:37:41 in reply to 4 [link] [source]
The difference only shows if someone opens the same file twice in one worker, which nothing prevents...
Aha.
So it's your call: the simpler version relying on the documented single-connection rule, hasReservedLock() as cheap insurance against silently losing committed data, or making xOpen refuse a second open of the same file.
An xOpen change has the potential to break currently-working clients and the simpler check leaves them open to corruption, so we'll go with the deeper change you suggest. Thank you for clarifying that.
(6) By Daniel Steigerwald (steida) on 2026-09-30 09:49:44 in reply to 5 [link] [source]
Thank you. When the check-in lands, I'll run the crash repro and the tester1 tests from the gist against trunk in Chromium, Firefox, WebKit and Safari on macOS, and report back.
(7.1) By Stephan Beal (stephan) on 2026-09-30 10:38:24 edited from 7.0 in reply to 4 [link] [source]
So it's your call: the simpler version relying on the documented single-connection rule
Going back to that for a moment: my reading of the docs, but they are admittedly not crystal clear here, is that they're trying to tell us that you can't have two copies of that VFS accessing the same files. Same-thread access via different handles in the VFS should work, which is only to say that it was never my intent to specifically prohibit that. The docs will be clarified momentarily.
This fix now in trunk and branch-3.53, noting that we're not currently expecting to release another 3.53.x. (Edit: corrected links)
Thank you again!
(8) By Daniel Steigerwald (steida) on 2026-09-30 10:49:15 in reply to 7.1 [link] [source]
Thank you, and good to know same-thread handles are meant to work. In that case there's one more gap worth knowing about. Because xLock never fails, overlapping handles in one thread can still lose committed rows (two writers: both COMMITs return OK, yet some rows revert, and integrity_check says "ok"), read each other's uncommitted pages, and with two exclusive-mode WAL handles corrupt the file (integrity_check reports "Rowid out of order"). hasReservedLock() closes only the rollback case.
An in-process lock table per filename, as unixLock() does for connections sharing an inode, makes overlapping handles behave like native SQLite within one process: SQLITE_BUSY instead of silent damage, and the data stays correct. The "opfs" VFS already returns SQLITE_BUSY for two handles in one worker. In my tests (Chromium, Firefox, WebKit and Safari) all the cases above return SQLITE_BUSY and end with correct data, while crash recovery and one-after-another use of two handles keep working.
The cost: a handle left with an un-reset statement or an open read transaction would block the other handle's writes with SQLITE_BUSY where they succeed today. And since no busy handler can resolve a conflict within one thread, xSleep should be a no-op for this VFS, so busy_timeout doesn't just freeze the worker.
Suggested change on top of 9168a6f1 (for illustration only):
--- a/ext/wasm/api/sqlite3-vfs-opfs-sahpool.c-pp.js
+++ b/ext/wasm/api/sqlite3-vfs-opfs-sahpool.c-pp.js
@@ -209,6 +209,7 @@
if(file) {
try{
pool.log(`xClose ${file.path}`);
+ pool.unlockFile(file, capi.SQLITE_LOCK_NONE);
pool.mapS3FileToOFile(pFile, false);
file.sah.flush();
if(file.flags & capi.SQLITE_OPEN_DELETEONCLOSE){
@@ -240,8 +241,7 @@
pool.log(`xLock ${lockType}`);
pool.storeErr();
const file = pool.getOFileForS3File(pFile);
- file.lockType = lockType;
- return 0;
+ return pool.lockFile(file, lockType);
},
xRead: function(pFile,pDest,n,offset64){
const pool = getPoolForPFile(pFile);
@@ -295,7 +295,7 @@
const pool = getPoolForPFile(pFile);
pool.log('xUnlock');
const file = pool.getOFileForS3File(pFile);
- file.lockType = lockType;
+ pool.unlockFile(file, lockType);
return 0;
},
xWrite: function(pFile,pSrc,n,offset64){
@@ -511,6 +511,10 @@
#availableSAH = new Set();
/* Maps (sqlite3_file*) to xOpen's file objects. */
#mapS3FileToOFile_ = new Map();
+ /* Maps client-side file names to the lock state of the files
+ opened via this pool: {nShared, lockType}, like os_unix.c's
+ unixInodeInfo. */
+ #mapPathToLock = new Map();
/* Maps SAH to an abstract File Object which contains
various metadata about that handle. */
@@ -893,6 +897,56 @@
}
}
+ /**
+ Implements xLock() for the given xOpen file object. This pool
+ holds its SAHs exclusively, so the files opened via it are the
+ only connections to a given file. They are kept apart the way
+ unixLock() keeps apart the connections of one process which
+ share an inode: a lock which conflicts with another
+ connection's lock fails with SQLITE_BUSY, and a failed attempt
+ to get from RESERVED to EXCLUSIVE leaves a PENDING lock, which
+ admits no new SHARED locks.
+ */
+ lockFile(file, lockType){
+ if(file.lockType>=lockType) return 0;
+ let lk = this.#mapPathToLock.get(file.path);
+ if(!lk){
+ lk = {nShared: 0, lockType: capi.SQLITE_LOCK_NONE};
+ this.#mapPathToLock.set(file.path, lk);
+ }
+ if(file.lockType!==lk.lockType
+ && (lk.lockType>=capi.SQLITE_LOCK_PENDING
+ || lockType>capi.SQLITE_LOCK_SHARED)){
+ return capi.SQLITE_BUSY;
+ }
+ if(lockType===capi.SQLITE_LOCK_SHARED){
+ ++lk.nShared;
+ if(lk.lockType===capi.SQLITE_LOCK_NONE) lk.lockType = lockType;
+ }else if(lockType===capi.SQLITE_LOCK_EXCLUSIVE && lk.nShared>1){
+ if(file.lockType===capi.SQLITE_LOCK_RESERVED){
+ file.lockType = lk.lockType = capi.SQLITE_LOCK_PENDING;
+ }
+ return capi.SQLITE_BUSY;
+ }else{
+ lk.lockType = lockType;
+ }
+ file.lockType = lockType;
+ return 0;
+ }
+
+ /** Implements xUnlock() for the given xOpen file object. */
+ unlockFile(file, lockType){
+ if(file.lockType<=lockType) return;
+ const lk = this.#mapPathToLock.get(file.path);
+ if(file.lockType>capi.SQLITE_LOCK_SHARED){
+ lk.lockType = capi.SQLITE_LOCK_SHARED;
+ }
+ if(lockType===capi.SQLITE_LOCK_NONE && 0===--lk.nShared){
+ this.#mapPathToLock.delete(file.path);
+ }
+ file.lockType = lockType;
+ }
+
/**
Returns true if the given client-defined file name is in this
object's name-to-SAH map.
@@ -1087,13 +1141,8 @@
its opaque name) holds a RESERVED or greater lock, else false.
*/
hasReservedLock(filename){
- const lr = capi.SQLITE_LOCK_RESERVED;
- for(const f of this.#mapS3FileToOFile_.values()){
- if(f.lockType>=lr && filename===f.path){
- return true;
- }
- }
- return false;
+ const lk = this.#mapPathToLock.get(filename);
+ return !!lk && lk.lockType>capi.SQLITE_LOCK_SHARED;
}
}/*class OpfsSAHPool*/;
(9) By Stephan Beal (stephan) on 2026-09-30 12:14:03 in reply to 8 [link] [source]
Suggested change ...
That is now in both trunk and branch-3.53.
Thank you!
Trivia: this very lovely patch put me in an uncomfortable position license-wise. In this project we're not permitted to accept "drive-by patches" to deliverable files because doing so can endanger the project's Public Domain status. However, we frequently use them as a blueprint and rewrite them to get an equivalent effect. In this patch there was no structure which could be sensibly rewritten, most of the symbol names are well-established (so can't simply be renamed), and the new function and argument names are 100% conventional with regards to the surrounding code. It finally, after some digging, became clear that it's essentially a 1-to-1 translation of a subset of os_unix.c. So, after discussion with drh, the code from your patch was taken almost 100% verbatim and the docs were only very slightly edited.
(10) By Daniel Steigerwald (steida) on 2026-09-30 12:52:54 in reply to 9 [link] [source]
One small follow-up to the lock table: busy_timeout can now freeze the worker. Only other handles in the same thread can hold a conflicting lock (the SAHs are exclusive), and they can't release it while SQLite's busy handler sleeps in xSleep. So with busy_timeout set, a conflict blocks the worker for the whole timeout and then returns SQLITE_BUSY anyway; in my tests busy_timeout=3000 blocked it for about 3 seconds per statement. The pool already has a no-op xSleep for when the default VFS has none, and using it always returns SQLITE_BUSY right away. Since opfs-sahpool isn't registered as the default VFS, sqlite3_sleep() is unaffected; only busy waits on its own handles change.
--- a/ext/wasm/api/sqlite3-vfs-opfs-sahpool.c-pp.js
+++ b/ext/wasm/api/sqlite3-vfs-opfs-sahpool.c-pp.js
@@ -462,7 +462,6 @@
/* Inherit certain VFS members from the default VFS,
if available. */
opfsVfs.$xRandomness = dVfs.$xRandomness;
- opfsVfs.$xSleep = dVfs.$xSleep;
dVfs.dispose();
}
if(!opfsVfs.$xRandomness && !vfsMethods.xRandomness){
@@ -474,10 +473,11 @@
for(; i < nOut; ++i) heap[npOut + i] = (Math.random()*255000) & 0xFF;
return i;
};
- }
- if(!opfsVfs.$xSleep && !vfsMethods.xSleep){
- vfsMethods.xSleep = (pVfs,ms)=>0;
}
+ /* Only other handles in this same thread can hold a conflicting
+ lock, and they cannot release it while we sleep, so a busy
+ handler's waiting can never help. */
+ vfsMethods.xSleep = (pVfs,ms)=>0;
sqlite3.vfs.installVfs({
vfs: {struct: opfsVfs, methods: vfsMethods}
});
(11) By Stephan Beal (stephan) on 2026-09-30 13:40:07 in reply to 10 [link] [source]
busy_timeout can now freeze the worker.
That's not good.
Trunk and branch-3.53 now include this change as well as fix for a potential small VFS-internal resource leak via removeVfs() or on initialization failure. Also, my understanding of xSleep's place in the VFS API was improved.
Thank you again for these fixes!
PS: the typo in the new internals doc is mine, not yours. It'll be patched eventually but isn't worth making a standalone commit for.
(12) By Daniel Steigerwald (steida) on 2026-09-30 14:59:13 in reply to 11 [link] [source]
Thank you! I built trunk cdbfe6a938: busy_timeout conflicts now return SQLITE_BUSY in 1-2 ms instead of 3 s, and the crash repro still recovers, in Chromium, Firefox and WebKit.
One thing about the jaccwabyt change (f4786666d9). Moving rmInstanceHandle() after the ondispose handlers makes .pointer readable there, so the leak fix works, but it also removes the old protection against re-entry. Previously, a handler that disposed the same struct again (directly, or through two structs disposing each other) found no handle and returned. Now it re-enters __freeStruct(): a handler in the ondispose array, or a cycle, throws TypeError on obj.ondispose.pop() after the inner call deleted it, and an ondispose function calling this.dispose() frees the same memory repeatedly until wasm aborts. A flag on the instance handle keeps both behaviors:
const __freeStruct = function(ctor, obj, m){
const ii = getInstanceHandle(obj, false);
- if( !ii ) return;
+ if( !ii || ii.disposing ) return;
+ ii.disposing = true /* ondispose handlers may re-enter */;
With it, .pointer stays readable in the handlers and all three re-entry cases are no-ops again (same three browsers). SQLite's own handlers don't re-enter as far as I can see, so this only affects client code.
(13) By Stephan Beal (stephan) on 2026-09-30 15:48:07 in reply to 12 [link] [source]
Moving rmInstanceHandle() after the ondispose handlers makes .pointer readable there, so the leak fix works, but it also removes the old protection against re-entry
Excellent spot. That is now patched in the conventional places, thank you!
To the best of my fallible knowledge we've never made any use of circular cleanups in the library/VFSes, but i'm thankful that this was spotted quickly.