Skip to content

OPFSCoopSyncVFS: hand the access handle over only after the call returns - #347

Merged
rhashimoto merged 3 commits into
rhashimoto:masterfrom
lalexdotcom:fix/coopsync-deferred-handle-release
Sep 26, 2026
Merged

rhashimoto merged 3 commits into
rhashimoto:masterfrom
lalexdotcom:fix/coopsync-deferred-handle-release

Conversation

@lalexdotcom

Copy link
Copy Markdown
Contributor

I'm working on a SQLite library for concurrent access, built on wa-sqlite and tested across several browsers, VFS and builds, largely with Claude's help. That testing sometimes turns up what looks like a VFS bug, and this is one of them.

The analysis and the fix were done with Claude. Low-level VFS code isn't my strength, so I kept the change minimal and backed it with a test that fails without it. I'm happy to run anything else you'd like checked.

Summary

With two connections on the same OPFSCoopSyncVFS database, a statement can
fail with SQLITE_BUSY, database is locked, and reach the caller. It happens
when sqlite3_step() locks, unlocks and locks again within one call — which
SQLite does when it re-prepares a statement whose schema changed — while the
other connection is asking for the access handle. jUnlock gives the handle
away at the inner unlock, and the inner lock that follows returns
SQLITE_BUSY on what is already retry()'s second try.

This PR makes jUnlock hand the handle over from a task, once the call has
returned, and only if no lock was taken again in the meantime. A second,
independent commit makes #initialize tolerate a temporary directory that
another instance deleted first. A third adds tests for both.

The bug

retry() in sqlite-api.js makes two tries per call. That is enough when a
call locks once: the first try returns SQLITE_BUSY and queues the handle
request, the second finds the handle. It is not enough when the second try
itself locks twice. A trace of the failing sqlite3_step(), on the connection
that loses:

jLock(SHARED)  -> SQLITE_BUSY   no handle: request queued in retryOps
               ...              handle acquired; the other connection asks for it
                                -> isHandleRequested = true
jLock(SHARED)  -> SQLITE_OK     second try
jUnlock(NONE)                   schema cookie changed: SQLite re-prepares
                                -> handle released here
jLock(SHARED)  -> SQLITE_BUSY   no try left: sqlite3_step() returns SQLITE_BUSY

Two ordinary situations produce it: two connections opened together on a new
database, and a schema change made by one connection while the other holds
prepared statements.

This is not a lock conflict for the caller to retry. With OPFSCoopSyncVFS a
connection that wants the handle while another holds it waits inside
retry() for the Web Lock; the SQLITE_BUSY here comes from the handle
leaving in the middle of a single call.

It is the same family as #269, where application-defined functions running
statements of their own made one step lock and unlock several times. #269
fixed the flag that was never reset; the first inner unlock still gives the
handle away, and that is what this PR changes.

Why a task and not a microtask

A microtask was the first version, and it is not enough. The JSPI build wraps
every VFS import in WebAssembly.Suspending, the synchronous ones included,
so pending microtasks run at each VFS call — in the middle of the step. The
microtask version fixed the default and Asyncify builds and still failed on
JSPI. OPFSCoopSyncVFS's methods are synchronous, so every suspension resumes
from the microtask queue and a task cannot run before the call returns.

The cost is that the other connection gets the handle when the holder next
returns to its event loop instead of at its first unlock.

The second commit: #initialize

Each instance deletes the .ahp-* directories no lock protects. Two instances
initializing at the same time can list the same orphaned directory; the one
that takes its lock second finds it already gone, and removeEntry() throws
NotFoundError, which rejects create(). The commit ignores NotFoundError
there.

Verification

The third commit adds test/vfs_handover.js to the OPFSCoopSyncVFS suite:

  • re-prepared statement: two connections, each in its own worker. One
    keeps SELECT count(*) FROM sqlite_master prepared (unscoped) and steps
    it 100 times while the other runs 100 CREATE TABLEs; no call may return
    SQLITE_BUSY.
  • temporary directories: 30 orphaned .ahp-* directories, then two
    instances started together, 10 times; no start may fail.

TestContext.create() does not reject when the worker fails to start — it
throws from the message listener and never settles — so the second test starts
its workers through a small helper that does.

yarn web-test-runner test/OPFSCoopSyncVFS.test.js, HeadlessChrome 151:

test with the first two commits reverted with this PR
re-prepared statement, default build SQLITE_BUSY on 47 of 100 steps 0
re-prepared statement, Asyncify build SQLITE_BUSY on 46 of 100 steps 0
temporary directories, both builds NotFoundError on 9 of 10 starts 0
whole OPFSCoopSyncVFS suite 66 passed, 4 failed 70 passed

Warning

The suite does not run the JSPI build on current Chrome:
TestContext.supportsJSPI() builds a WebAssembly.Function, which Chrome 151
no longer has (WebAssembly.Suspending and WebAssembly.promising are there).
I checked the JSPI build, and Firefox, separately: the failure reproduces on
both, the microtask version still fails on JSPI, and this PR clears both.

Checklist

  • I grant to recipients of this Project distribution a perpetual,
    non-exclusive, royalty-free, irrevocable copyright license to reproduce, prepare
    derivative works of, publicly display, sublicense, and distribute this
    Contribution and such derivative works.
  • I certify that I am legally entitled to grant this license, and that this
    Contribution contains no content requiring a license from any third party.

lalexdotcom and others added 3 commits September 15, 2026 11:03
…all.

SQLite can lock, unlock and lock again within a single call, e.g. when
sqlite3_step re-prepares a statement whose schema changed, or when a
function runs statements of its own. jUnlock released the handle at the
inner unlock whenever another connection had asked for it, so the inner
lock found the handle gone and returned SQLITE_BUSY. retry() makes two
tries only, and when that inner lock falls on the second one the
SQLITE_BUSY reaches the caller.

jUnlock now releases the handle from a task, after the call has
returned, and only if no lock was taken again in the meantime. A
microtask is not enough: the JSPI build suspends at every VFS call,
which runs pending microtasks in the middle of the call.

Co-Authored-By: Claude Opus 5 <[email protected]>
…tance.

Two instances initializing at the same time can both list the same
orphaned .ahp- directory. The one that takes its lock second then finds
it already deleted, and removeEntry() throws NotFoundError, which failed
the whole VFS creation.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ctories.

vfs_handover runs two connections, each in its own worker. One keeps a
statement prepared while the other changes the schema, so every step of
it re-prepares while the other connection asks for the access handle;
no step may return SQLITE_BUSY. A second test starts two instances
together over orphaned .ahp- directories; neither may fail.

Co-Authored-By: Claude Opus 5 <[email protected]>
@lalexdotcom

Copy link
Copy Markdown
Contributor Author

This also fixes #341

Reading through the open issues after opening this PR, #341 — four connections
migrating the same fresh OPFS file, hanging forever — turns out to be this bug
seen from the other end. @markalanhayton was asked for a reproduction against
this repository rather than the @journeyapps fork; I have run one, and the
jUnlock commit alone clears it.

Chromium via Playwright, four module workers on one fresh OPFS file per run,
each open_v2 + CREATE TABLE + a 200-row transaction:

tree runs hung all four succeeded settled with database is locked
master (07ad48c) 30 19 5 10
master + this PR 30 0 30 0

The jUnlock commit alone accounts for it: 0 hangs in 30 with that commit only.
Firefox 153 reproduces too, less often (1 in 10, 0 in 10 patched).

The reproduction script, the full numbers and a vfs.log trace of what
deadlocks are in my comment on #341.

One qualification on the closing keyword below: #341 describes two symptoms, the
hang and a lock file left poisoned so that no later connection can open the
database. The hang is fixed, and measured. The poisoning never reproduced here,
on any of the hangs — so if you would rather keep #341 open for that half,
drop the keyword.

Fixes #341

lalexdotcom added a commit to lalexdotcom/browser-sqlite that referenced this pull request Sep 18, 2026
OPFSCoopSyncVFS gave its access handle to another connection at the
first jUnlock(NONE), and SQLite locks, unlocks and locks again inside
one sqlite3_step when it re-prepares a statement whose schema changed.
The inner lock then found the handle gone, and wa-sqlite's retry(),
which tries a call twice, returned SQLITE_BUSY to the caller: two
clients opened together failed an early write, and a write following
another client's CREATE TABLE failed 17-18 times in 20 on Firefox. The
patch defers the hand-over to a task after the call; a microtask is not
enough on the JSPI build, which runs microtasks at every VFS call. The
same patch lets #initialize ignore a temporary directory another
instance deleted first, which failed a CoopSync client starting
alongside another with WORKER_CRASHED.

wa-sqlite is now pinned to upstream 07ad48c by SHA (user, 2026-09-15):
it is vendored, so a commit serves as well as a release, and that
commit carries the OPFSAnyContextVFS fix (#344) the old patch held. The
patch is now patches/[email protected] and holds the CoopSync change
only; the same change is proposed upstream as rhashimoto/wa-sqlite#347.

coopsync-handover.test.ts pins both on the sync and jspi builds; the
retry test's header records that its falsifier died with the fix.

Co-Authored-By: Claude Opus 5 <[email protected]>
lalexdotcom added a commit to lalexdotcom/browser-sqlite that referenced this pull request Sep 18, 2026
A write on OPFSCoopSyncVFS could fail with BUSY whenever another client or
tab used the same database. SQLite locks, unlocks and locks again inside
one sqlite3_step when it re-prepares a cached statement whose schema
changed, and the VFS gave its single access handle away at that inner
unlock whenever the other connection had asked for it; wa-sqlite's retry()
tries a call twice, and the second try's inner lock returned SQLITE_BUSY.
Measured before the fix: two clients opened together failed a write 4-6
times in 20 on Chromium and 15 on Firefox; a write after another client's
CREATE TABLE, 17-18 in 20 on Firefox. Every other VFS: none.

The fix is a wa-sqlite patch: jUnlock hands the handle over from a task
once the call has returned (a microtask still failed on the JSPI build),
and #initialize ignores a temporary directory another instance deleted
first, which made two CoopSync clients starting together fail with
WORKER_CRASHED. 720 probe attempts across sync, async and jspi on both
engines saw no BUSY afterwards, reads included. Proposed upstream as
rhashimoto/wa-sqlite#347, with tests that fail without it.

wa-sqlite is pinned to upstream 07ad48c by SHA (user), which carries the
OPFSAnyContextVFS fix the previous patch held; the patch now holds the
CoopSync change only.

Co-Authored-By: Claude Opus 5 <[email protected]>
lalexdotcom added a commit to lalexdotcom/browser-sqlite that referenced this pull request Sep 18, 2026
…d, state, vfs, lessons

- measurements: COOPSYNC-HANDOVER — the re-prepare inside one step, every
  VFS and scenario before the patch, the microtask and task versions on
  three builds and two engines, wa-sqlite's own suite, the falsifiers.
- lessons: what can run inside a WASM call depends on the build; a test
  can pin a defect as the contract; a trace changes the rate it measures.
- state: the merge, what the code will not tell, the next session (the
  multi-client and cross-tab tests on every VFS), rhashimoto/wa-sqlite#347
  pending; baseline re-measured on 256ce09.
- follow-ups: the CoopSync write entry closed; OPFSWriteAheadVFS refuses a
  second client off Chromium, and the multi-client suites run on one VFS.
- vfs, architecture, stack-and-build, conventions, history: the pin by
  SHA, the patch traps, the fork and its suite, the upstream rule.

Co-Authored-By: Claude Opus 5 <[email protected]>
@rhashimoto

Copy link
Copy Markdown
Owner

Thanks for the PR! And for alerting me to obsolete JSPI feature detection. And for all your insight on #341.

It took me a while to remember how all this worked (which is kind of a red flag), but in the end LGTM.

@rhashimoto
rhashimoto merged commit d685fef into rhashimoto:master Sep 26, 2026
1 check passed
@lalexdotcom
lalexdotcom deleted the fix/coopsync-deferred-handle-release branch September 28, 2026 14:02
simolus3 pushed a commit to powersync-ja/wa-sqlite that referenced this pull request Oct 5, 2026
…rns (rhashimoto#347)

* Defer the OPFSCoopSyncVFS access handle hand-over to the end of the call.

SQLite can lock, unlock and lock again within a single call, e.g. when
sqlite3_step re-prepares a statement whose schema changed, or when a
function runs statements of its own. jUnlock released the handle at the
inner unlock whenever another connection had asked for it, so the inner
lock found the handle gone and returned SQLITE_BUSY. retry() makes two
tries only, and when that inner lock falls on the second one the
SQLITE_BUSY reaches the caller.

jUnlock now releases the handle from a task, after the call has
returned, and only if no lock was taken again in the meantime. A
microtask is not enough: the JSPI build suspends at every VFS call,
which runs pending microtasks in the middle of the call.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Tolerate a temporary directory deleted by another OPFSCoopSyncVFS instance.

Two instances initializing at the same time can both list the same
orphaned .ahp- directory. The one that takes its lock second then finds
it already deleted, and removeEntry() throws NotFoundError, which failed
the whole VFS creation.

Co-Authored-By: Claude Opus 5 <[email protected]>

* Add OPFSCoopSyncVFS tests for the handle hand-over and temporary directories.

vfs_handover runs two connections, each in its own worker. One keeps a
statement prepared while the other changes the schema, so every step of
it re-prepares while the other connection asks for the access handle;
no step may return SQLITE_BUSY. A second test starts two instances
together over orphaned .ahp- directories; neither may fail.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
lalexdotcom added a commit to lalexdotcom/wa-sqlite that referenced this pull request Oct 23, 2026
… open

A worker that goes away without closing its access handles, such as one
whose page the back/forward cache evicts, can have its directory's lock
released before its handles are closed. The next instance's sweep then
gets the lock, removeEntry throws NoModificationAllowedError, and
create() fails. The directory is left for a later instance to delete,
as it already is when another instance deleted it first (rhashimoto#347).

Fixes rhashimoto#362.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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