Repository navigation
Open
Labels
response requestedFurther information is requested
Description
Summary
With OPFSCoopSyncVFS, multiple connections writing to the same fresh OPFS file can hang forever, and the hang leaves the lock file poisoned: afterwards, even a brand-new connection cannot open the database. Reproduced deterministically (4/4 runs) in Chromium against both 1.7.2 and 2.0.2.
Repro (self-contained, ~40 lines)
mkdir repro && cd repro
npm i @journeyapps/[email protected] playwright
# save the script below as repro.mjs, then:
node repro.mjs// Four module workers open the same fresh OPFS file and migrate it
// concurrently. Expected: all four settle (success or SQLITE_BUSY).
// Observed: nothing settles within 20s (RESULT: HANG:0); the lock
// file is left poisoned -- a fresh connection can no longer open it.
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { chromium } from 'playwright';
const PORT = 8765;
const WA = join(process.cwd(), 'node_modules', '@journeyapps', 'wa-sqlite');
const WORKER_SRC = `
import SQLiteESMFactory from '/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs';
import * as SQLite from '/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js';
import { OPFSCoopSyncVFS } from '/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js';
import { SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE } from '/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js';
const module = await SQLiteESMFactory({ locateFile: (f) => '/node_modules/@journeyapps/wa-sqlite/dist/' + f });
const sqlite3 = SQLite.Factory(module);
const vfs = await OPFSCoopSyncVFS.create('opfs', module);
sqlite3.vfs_register(vfs, true);
self.onmessage = async (ev) => {
const { id, filename } = ev.data;
try {
const db = await sqlite3.open_v2(filename, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
await sqlite3.exec(db, 'CREATE TABLE t (i INTEGER)');
await sqlite3.exec(db, 'BEGIN');
for (let i = 0; i < 200; i++) await sqlite3.exec(db, 'INSERT INTO t (i) VALUES (' + i + ')');
await sqlite3.exec(db, 'COMMIT');
self.postMessage({ id, status: 'ok' });
} catch (e) {
self.postMessage({ id, status: 'error', message: String(e && e.message || e) });
}
};
`;
const PAGE = `<!DOCTYPE html>
<html><body><script type="module">
const filename = 'repro-' + Date.now() + '.db';
const workers = [0, 1, 2, 3].map((id) => {
const w = new Worker('/worker.mjs', { type: 'module' });
w.postMessage({ id, filename });
return w;
});
const results = new Array(4).fill(null);
const deadline = setTimeout(() => {
const done = results.filter((r) => r !== null).length;
document.body.dataset.result = 'HANG:' + done;
}, 20000);
workers.forEach((w) => {
w.onmessage = (ev) => {
if (ev.data.status === 'error') {
document.body.dataset.result = 'WORKER_ERROR:' + ev.data.message;
return;
}
results[ev.data.id] = ev.data.status;
if (results.every((r) => r !== null)) {
clearTimeout(deadline);
document.body.dataset.result = 'DONE:' + results.join(',');
}
};
});
</script></body></html>`;
const server = createServer(async (req, res) => {
const url = new URL(req.url, 'http://127.0.0.1:' + PORT);
res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp');
if (url.pathname === '/') { res.end(PAGE); return; }
if (url.pathname === '/worker.mjs') { res.setHeader('Content-Type', 'text/javascript'); res.end(WORKER_SRC); return; }
if (url.pathname.startsWith('/node_modules/')) {
try {
const buf = await readFile(join(WA, url.pathname.slice('/node_modules/@journeyapps/wa-sqlite/'.length)));
const ext = url.pathname.split('.').pop();
res.setHeader('Content-Type', ext === 'wasm' ? 'application/wasm' : ext === 'mjs' || ext === 'js' ? 'text/javascript' : 'application/octet-stream');
res.end(buf); return;
} catch { res.statusCode = 404; res.end('nf'); return; }
}
res.statusCode = 404; res.end('nf');
});
await new Promise((r) => server.listen(PORT, '127.0.0.1', r));
const browser = await chromium.launch();
try {
const page = await browser.newPage();
await page.goto('http://127.0.0.1:' + PORT + '/', { waitUntil: 'domcontentloaded' });
await page.waitForFunction(() => document.body.dataset.result, undefined, { timeout: 45000 });
const result = await page.evaluate(() => document.body.dataset.result);
console.log('RESULT:', result);
if (result.startsWith('HANG')) { console.error('REPRODUCED: hang + poisoned lock file.'); process.exit(1); }
} finally { await browser.close(); server.close(); }Observed behavior
- Hang (deterministic): all four connections complete their WASM init, then nothing settles within 20s — the losers and the winner alike. In the repo's deeper tracing (1.7.2), the losers got instant
SQLITE_BUSY("database is locked") on their first write and the winner hung at its first write inside its own transaction; the same shape reproduces on 2.0.2. - Poisoned lock file (persistent): after the hang, a fresh connection cannot even complete
open_v2on the same file. The state is file-level, not connection-level — it survives the hung connections being closed, and persists until browser storage is cleared. busy_timeoutdoes not help: withPRAGMA busy_timeout = 5000, the losers wait the FULL window before aborting (the busy retry granularity is the whole timeout — a loser waited 5s while the winner had finished in 18ms) and the winner still hangs: its lock acquisition BLOCKS inside the VFS, invisible to SQLite's busy handler.journal_mode = WALreduced but did not eliminate the hang.- Established files are fine: the same concurrent-write shape against an established file (created + migrated once, then two connections bursting overlapping transactions) settled cleanly in 1280/1280 transactions across 17 runs. The defect is specific to the fresh-file multi-writer phase (concurrent first-creation/migration).
Expected behavior
SQLite's documented concurrency contract: overlapping writers either serialize through the lock queue or fail with an honest SQLITE_BUSY — never a permanent hang, and never a state where the file cannot be opened again.
Environment
- @journeyapps/wa-sqlite 1.7.2 and 2.0.2 (both tested; repro above pins 2.0.2)
- Chromium headless shell 151 (Playwright), also reproduced on Chromium 149
- Cross-origin isolated page (COOP/COEP) with OPFS, Chromium on Linux and Windows
Metadata
Metadata
Assignees
Labels
response requestedFurther information is requested
Activity
rhashimoto commentedon Aug 12, 2026
It's great to get a test case! I'd like to ask you to modify it to use this project (which is not on npm) instead of the @journeyapps/wa-sqlite fork and verify that the hang still occurs. That will make it easier for me to investigate.
lalexdotcom commentedon Sep 16, 2026
Reading through the open issues after opening #347, this one looked like the
same root cause seen from the other end — and it is. Here is the reproduction
against this repository that you asked for, what a trace says is actually
deadlocking, and one thing about the script above that is worth knowing before
anyone spends time on it.
The script in the issue cannot report anything but a hang
Its workers use top-level await (
await SQLiteESMFactory(...)), and the pageposts their task immediately, at construction. A message posted before a module
worker has finished evaluating is dropped, not queued — measured on both
Chromium 151 and Firefox 153: the worker installs
self.onmessageafterwards,and nothing is ever delivered to it.
Instrumented, with the worker announcing each stage:
So every run reports
HANG:0— all four workers finish their WASM init andnothing settles — whatever the VFS does. That is the same shape @markalanhayton
describes, so I suspect the posted script never exercised the bug, even though
the bug is real: it reproduces reliably once the workers are handed their work
after they are ready.
Reproduction against this repo
No fork and no build —
dist/is committed, so this needs only a checkout andPlaywright. Save it as
repro-341.mjsat the root of a wa-sqlite checkout:repro-341.mjsTwo deviations from the original script, both marked in the source: the workers
announce themselves before being given work (above), and
CREATE TABLEisIF NOT EXISTS, without which the losers reporttable t already exists—settled, but noise.
Results
Chromium 151.0.7922.34 (Playwright 1.62.1) on Linux, four module workers on
one fresh OPFS file per run,
git archiveof each tree so that onlysrc/examples/OPFSCoopSyncVFS.jsdiffers:database is lockedmaster(07ad48c)master+ #347With my own harness I also ran two more cells: Firefox 153 hangs as well (1 run
in 10 on master, 0 in 10 with the patch), and a third tree carrying only the
jUnlockcommit of #347 — 0 hangs in 30, so that commit accounts for the wholefix and the
#initializecommit in the PR is unrelated to this issue.A single connection on the same harness settles in ~110 ms, always.
Beyond the hang: on master, only 5 of the 30 runs had all four
connections succeed. In the others, connections got
database is lockedon afresh file, where serialising would have been the correct outcome. With the
patch every connection in every run succeeded, and no
SQLITE_BUSYreached theapplication at all.
The poisoned lock file did not reproduce
After a hang the script closes the page — terminating the hung workers and
releasing their access handles — and then runs the same full workload
(
open_v2+CREATE TABLE+ a 200-row transaction) with one fresh connection,on the same file, in the same browser context. It succeeded after every hang,
19 for 19.
So I can confirm the hang but not the persistent poisoning. One caveat: each run
uses an ephemeral browser context, so a state that survives a browser restart in
a persistent profile would not show up here. My guess is that what looked like a
poisoned lock file was the deadlock itself seen from a new connection, with the
hung workers still alive and still holding the handle — but it is a guess, and
the persistent-profile case is untested.
What deadlocks, from a
vfs.logtraceEndgame of a run where workers 2 and 3 hang (
tin ms since worker start):Three things compound:
jLock()setsisFileLocked = truebefore theSQLITE_BUSYreturn, andjUnlock()deliberately changes no state whenisLockBusy— so a connectionwhose call ends on a BUSY keeps
isFileLocked === trueindefinitely.handleRequestChannel.onmessagehandler sets itself tonullafter onenotification. With
isFileLockedstale-true it only recordsisHandleRequested = trueand defers the release to ajUnlock()that, for aconnection whose statement has already failed, never comes — and it is now
deaf to every later notification.
#requestAccessHandle()queued by that failedjLock()still runs tocompletion: it acquires the Web Lock and creates access handles for a
connection that has nothing left to do. Everyone else waits on that Web Lock
forever.
Why #347 removes it
The hand-over is what puts a connection on that path. Today the handle is
released at the inner
jUnlock(NONE)of a call that is not over; the relockinside the same call then returns
SQLITE_BUSY,retry()has already spent itstwo attempts, and the application gets
database is locked— which leavesexactly the idle connection with a queued handle request of step 3. Deferring
the hand-over until the call has returned means the call completes: no spurious
BUSY, and no orphaned handle request.
That removes the trigger, not the underlying fragility. Points 1-3 are still
true with the patch applied: any other route that leaves a connection idle after
a
SQLITE_BUSYcan strand the access handle the same way, and a holder stilllistens for exactly one notification. A connection whose call ends on a BUSY
arguably ought to clear
isFileLocked, and the channel handler ought to stayinstalled for as long as the handle is held. I have not written that — it is a
wider change than the one in #347, and I would rather you decide whether it
belongs there.
rhashimoto commentedon Sep 26, 2026
@lalexdotcom Wow, thanks for all the effort you put into this! AFAICT your analysis looks correct. Maybe the retry logic should be redesigned while keeping these scenarios and your last paragraph in mind.
lalexdotcom commentedon Sep 29, 2026
I found a deterministic trigger on master (
5be9cd14), and it is not inOPFSCoopSyncVFSbut inretry()insrc/sqlite-api.js.One worker, two databases, no contention. On the default (synchronous) build, a worker opens two fresh databases with
OPFSCoopSyncVFSand runs the same small workload on both at once (Promise.all). That is the case you said in #104 should work in a non-Asyncify build. The second one fails withdatabase is lockedevery time: 10 of 10 runs on Chromium 151 and on Firefox 153, and 20 of 20 in a longer battery. There is no other worker, so nothing holds the handle. With four workers doing the same on two shared databases, the connection that got the BUSY is left with its handle request in flight, the request takes the Web Lock for a connection that has given up, and the other workers wait forever: 17-20 runs of 20 hung, depending on the engine. That is exactly the stranded-handle state from my earlier comment, reached without any hand-over.Why.
Module.retryOpsis one list for the whole module, andretry()resets it to[]in itsfinally. With two calls in flight:f()for real, andjLock()pushes B's own request.finallyrunsModule.retryOps = [], which drops B's request from the list.Module.retryOps.length === 0, soretry()returnsSQLITE_BUSYto the application while B's request is still running.Two more consequences of the list being shared showed up when I fixed only the reset (removing just the operations the call had awaited):
createSyncAccessHandlefailure made both databases of that worker fail, and the others hung.OPFSWriteAheadVFSis the only other VFS that pushes toretryOps, and the same two-database shape gives it a spuriousdatabase is lockedtoo, 20 of 20 on both engines.What fixes it. Give each call its own list: a call waits only for the operations its own
f()started, so it neither waits for, clears, nor fails on another call's. In the synchronous build those operations are started beforef()returns. In the async builds they can be started after a suspension (JSPI suspends at every VFS call), so there the list has to be read once the call has settled. My first attempt read it atf()'s return, lost the operations under JSPI, and failedvfs_read_freshnessonjspi.async function retry(f) { let rc; + let ops = []; for (let retryCount = 0; retryCount < 2; ++retryCount) { - // Wait for all pending retry operations to complete. This is - // normally empty on the first loop iteration. - if (Module.retryOps.length) { - try { - await Promise.all(Module.retryOps); - } finally { - Module.retryOps = []; - } + // Wait only for the retry operations this call started. + if (ops.length) { + await Promise.all(ops); + } + + // Give the call its own list, so that it neither waits for, clears, + // nor fails on another call's operations. A synchronous build starts + // them before f() returns; an asynchronous one may start them after + // a suspension, so there the list is read once the call has settled. + const own = []; + Module.retryOps = own; + const result = f(); + ops = own.slice(); + rc = await result; + if (result instanceof Promise) { + ops = own.slice(); } - - rc = await f(); - if (rc === SQLite.SQLITE_OK || Module.retryOps.length === 0) { + if (rc === SQLite.SQLITE_OK || ops.length === 0) {With it, every shape above runs clean on the default build on both engines: 0 BUSY and 0 hangs, the injected failure fails only its own database, and the row counts match. The whole test suite passes (5830 tests). It removes the routes to a BUSY; the three points about the VFS in my earlier comment are unchanged.
Would you like this as a PR, with a test for the two-database case that fails on master? Or would you rather fold it into the redesign you mentioned?
Reproduction: repro-341-retryops.mjs. Run it from the root of a checkout, after
npm i playwright:node repro-341-retryops.mjs [workers] [runs] [chromium|firefox]. On master with one worker, every run printsdone ok + database is locked; with the change,done ok + ok.rhashimoto commentedon Sep 29, 2026
@lalexdotcom I did say that on the linked issue, but that was before any retry VFS existed. I also said:
While it isn't the case that there are concurrent WASM calls here, I might argue that a retry is part of the same call.
It's good to know this problem exists for multiple databases, but I don't see it as a high priority. I'm not aware of a lot of applications that want to use more than one database, and I suspect most of the ones that do can launch multiple Workers. I'm inclined to leave this alone.
I think that the retry hack could use a good redesign and refactoring, but its usefulness could be declining. As of this month, JSPI is supported in all the major browsers. Maybe the next VFS generation won't need to bother with retry.
lalexdotcom commentedon Sep 29, 2026
Fair enough — you did add the caveat on #104, and I agree that a call that awaits between retries is still in flight, so two databases with
Promise.allis two calls in one module. Every trigger I found needs that shape, so it is outside the supported case.The diff and the repro stay in the comment above in case they are useful for the redesign.
lalexdotcom commentedon Sep 29, 2026
One more thing, if you think it's worth it: a line in the docs of the VFS that use
retryOps(OPFSCoopSyncVFS,OPFSWriteAheadVFS) saying that only one call may be in flight per module at a time, including across databases, and that a call stays in flight until its retries are done. That is the constraint these VFS actually need, and it isn't written anywhere a user would find it.rhashimoto commentedon Sep 29, 2026
That's a good idea. I added a sentence to the appropriate sections of the examples README.