sqlite3.dart icon indicating copy to clipboard operation
sqlite3.dart copied to clipboard

async OPFS VFS: xCheckReservedLock blocks hot-journal rollback, and a stale Atomics.notify wakes requestAndWaitForResponse early

Open negocialatlat opened this issue 3 weeks ago • 1 comments

Hi! While load-testing Drift on the web (WebDatabase in opfsLocks mode, sqlite3 3.9.0, Chrome and Firefox), we hit two issues in the async OPFS VFS (lib/src/wasm/vfs/async_opfs/). Both are still present in 3.9.1 and on main. Patching them locally fixed both of our failures.

1. xCheckReservedLock reports our own SHARED lock as RESERVED, so a hot journal is never rolled back

client.dart:

return lockStatus != SqlFileLockingLevels.SQLITE_LOCK_NONE ? 1 : 0;

When SQLite opens a database that has a hot journal, hasHotJournal() first takes a SHARED lock and then calls xCheckReservedLock. Because the VFS returns 1 for any lock we hold, SQLite assumes another connection is writing, so it does not roll the journal back. It then reads a half-written database.

Repro: start a large transaction on an OPFS database (we inserted ~300k rows in one transaction, enough to spill pages to disk), then kill the tab or browser mid-transaction. Reopen, and PRAGMA integrity_check fails.

  • Chrome, killed at 6 s: corrupted 3 out of 3 times.
  • Firefox, killed at 6 s: corrupted 2 out of 2 times.

We copied the same OPFS files out of the browser profile and opened them with native SQLite. Native SQLite rolled the journal back and reported ok. The native VFS on Android also recovers (3/3).

Fix: compare against RESERVED, as simple_opfs.dart already does:

return lockStatus >= SqlFileLockingLevels.SQLITE_LOCK_RESERVED ? 1 : 0;

With this change: 3/3 clean (Chrome, killed at 1.5 s), 5/5 (Chrome, killed at 6 s) and 3/3 (Firefox, killed at 6 s).

2. A stale Atomics.notify can wake requestAndWaitForResponse before the response is written

sync_channel.dart:

Atomics.wait(int32View, _responseIndex, -1);
return Atomics.load(int32View, _responseIndex);

The code waits once and does not check why it woke up. If a late notify from the previous request arrives, the wait returns while the response slot is still -1. The client then treats -1 as the response code. On the worker side, the same race makes takeOpcode() return -1, and WorkerOperation.values[-1] throws.

Repro: bulk-load 300k rows in batches through opfsLocks. It failed in 3 of 16 loads. With a log line on the spurious wake, we saw it 21 times across 4 longer runs.

Fix we used: loop until the slot is filled. In the worker, skip an empty opcode.

// sync_channel.dart, requestAndWaitForResponse
Atomics.wait(int32View, _responseIndex, -1);
var rc = Atomics.load(int32View, _responseIndex);
while (rc == -1) {
  Atomics.wait(int32View, _responseIndex, -1);
  rc = Atomics.load(int32View, _responseIndex);
}
return rc;

// worker.dart, the request loop
final taken = synchronizer.takeOpcode();
if (taken == -1) continue;
opcode = WorkerOperation.values[taken];

We can send a PR if that helps. Thanks for the package!

negocialatlat avatar Nov 09 '26 17:11 negocialatlat

Independent confirmation of (1), plus two more lock defects in the same VFS that (1) alone does not cure.

Versions

  • Reproduced (run): sqlite3 3.8.0 with the sqlite3.wasm of the drift 2.35.3 release (SQLite 3.54.1), Chrome 157 on macOS, a cross-origin-isolated page. First seen through drift's opfsLocks storage, then with package:sqlite3/wasm.dart alone (WasmVfs + VfsWorker).
  • Same code (compared, not run): main at efc8c76bb6277bc3fdc44c30e76dda4cfa30e7d1 — lib/src/wasm/vfs/async_opfs/client.dart and worker.dart are byte-identical to 3.8.0.
  • Not checked: other browsers.

(1) confirmed — and it can corrupt silently

Same cause and same fix as described above (xCheckReservedLock answers «yes» for our own SHARED lock). Two additions:

A reproduction without killing a browser. A crash state made by the system SQLite — a transaction larger than the page cache makes SQLite sync its journal and spill pages into the database file before the commit; copy both files at that moment:

import shutil, sqlite3
db = sqlite3.connect("db", isolation_level=None)
db.execute("PRAGMA journal_mode=DELETE"); db.execute("PRAGMA synchronous=FULL")
db.execute("CREATE TABLE t (v INTEGER, pad BLOB)")
db.execute("BEGIN")
for i in range(200): db.execute("INSERT INTO t VALUES (?, zeroblob(900))", (i,))
db.execute("COMMIT")                      # 200 rows, SUM(v) = 19900
db.execute("PRAGMA cache_size=10")
db.execute("BEGIN")
db.execute("UPDATE t SET v = v + 1000, pad = randomblob(900)")
for i in range(400): db.execute("INSERT INTO t VALUES (?, randomblob(900))", (5000 + i,))
shutil.copy("db", "database"); shutil.copy("db-journal", "database-journal")   # the crash
db.execute("ROLLBACK")

Write the two files into an OPFS directory, open /database through WasmVfs + VfsWorker (rooted at that directory) and run SELECT COUNT(*), SUM(v) FROM t:

rows SUM(v) integrity_check journal afterwards
system SQLite 200 19900 ok removed
WasmVfs 3.8.0 200 215900 ok still there
with fix (1) 200 19900 ok removed

So the damage is not always a failing integrity_check: the database can read fine and hold part of an uncommitted transaction.

Small transactions are enough. With a three-statement transaction (one 256 KiB blob) and the browser killed a few milliseconds after the commit is sent, most series of 24 kills on a fresh database ended in database disk image is malformed. In every case where the journal file was kept, the system SQLite recovered the database from the same two files.

Two more lock defects (same directory)

Symptom: a second connection can write while another connection is inside an open read transaction, once the first connection has completed any earlier lock cycle.

(a) client.dart, WasmFile.xUnlock — the worker is told to unlock, but lockStatus keeps its old value. The next xLock sees lockStatus != NONE and skips the explicit lock request. Fix: lockStatus = mode; at the end of xUnlock.

(b) worker.dart, _xLock — explicitlyLocked = true is set after _openForSynchronousAccess(file), which adds the file to _implicitlyHeldLocks because it is not yet marked explicit (and in the else branch the file is already in that set). The idle sweep (_releaseImplicitLocks) then closes the handle of an explicitly locked file. Fix: _implicitlyHeldLocks.remove(file); after marking the file explicitly locked, in both branches.

(a) alone does not cure the symptom; (a)+(b) do.

Reproduction (one WasmVfs, two connections on /database):

c1.execute('CREATE TABLE IF NOT EXISTS t (v INTEGER)');
c1.execute('INSERT INTO t (v) VALUES (1)');          // one whole lock cycle
c1.execute('BEGIN'); c1.select('SELECT COUNT(*) FROM t');   // read transaction open
await Future.delayed(const Duration(milliseconds: 1500));   // > the worker's idle time
final c2 = sqlite3.open('/database');
c2.execute('INSERT INTO t (v) VALUES (2)');          // 3.8.0: succeeds
c1.execute('COMMIT');                                 // the reader ends
c2.execute('INSERT INTO t (v) VALUES (3)');          // must succeed with any correct lock
second connection writes while the read transaction is open …and again after the reader's COMMIT
3.8.0 succeeds succeeds
fix (a) only succeeds succeeds
fixes (a)+(b) refused (disk I/O error, code 10, already at open) succeeds

(The last column shows the corrected lock is also let go again.)

Note that with (1) fixed, these two matter more, not less: hot-journal rollback relies on the locks to tell a crashed writer from a live one.

togovarte avatar Nov 10 '26 18:11 togovarte