Created
September 29, 2026 17:56
-
-
Save steida/b1827f147d624705bcb66cf74f5e63dd to your computer and use it in GitHub Desktop.
SQLite WASM opfs-sahpool: a leftover rollback journal is never rolled back (crash repro + tester1 tests)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Step 1 leaves a write transaction open whose pages have spilled into the | |
| // db file; the page then terminates this worker, as closing a tab would. | |
| // Step 2 runs in a new worker and reads the db, like the reloaded page. | |
| const q = new URLSearchParams(location.search); | |
| const { default: sqlite3InitModule } = await import(q.get("module")); | |
| const sqlite3 = await sqlite3InitModule(); | |
| const name = q.get("name"); | |
| const lockingMode = q.get("lockingMode") ?? "normal"; | |
| const ROWS = "select count(*) || ' rows, ' || sum(v = zeroblob(3000)) || ' unchanged' from t"; | |
| if (q.get("step") === "1") { | |
| const pool = await sqlite3.installOpfsSAHPoolVfs({ name, clearOnInit: true }); | |
| const db = new pool.OpfsSAHPoolDb("/crash.db"); | |
| const wal = lockingMode === "wal"; | |
| db.exec(wal ? "pragma locking_mode = exclusive; pragma journal_mode = wal" : "pragma journal_mode = delete"); | |
| db.exec(` | |
| create table t(id integer primary key, v blob); | |
| with recursive c(i) as (select 1 union all select i + 1 from c where i < 300) | |
| insert into t(v) select zeroblob(3000) from c; | |
| pragma locking_mode = ${wal ? "exclusive" : lockingMode}; | |
| pragma cache_size = 10; | |
| begin; | |
| update t set v = randomblob(3000); | |
| `); | |
| postMessage({ step: 1, files: pool.getFileNames().sort(), version: sqlite3.version.libVersion }); | |
| } else { | |
| // Wait until the terminated worker's access handles are released, so that | |
| // installOpfsSAHPoolVfs() does not fail (3.53.4 deletes the pool if it does). | |
| const root = await navigator.storage.getDirectory(); | |
| const opaque = await (await root.getDirectoryHandle("." + name)).getDirectoryHandle(".opaque"); | |
| let waits = 0; | |
| for (;;) { | |
| try { | |
| for await (const h of opaque.values()) (await h.createSyncAccessHandle()).close(); | |
| break; | |
| } catch (e) { | |
| if (++waits > 100) throw e; | |
| await new Promise((r) => setTimeout(r, 100)); | |
| } | |
| } | |
| const pool = await sqlite3.installOpfsSAHPoolVfs({ name }); | |
| const filesBefore = pool.getFileNames().sort(); | |
| const db = new pool.OpfsSAHPoolDb("/crash.db", q.get("readonly") ? "r" : "c"); | |
| let rows, integrity; | |
| try { | |
| if (lockingMode === "wal") db.exec("pragma locking_mode = exclusive"); | |
| rows = db.selectValue(ROWS); | |
| integrity = db.selectValues("pragma integrity_check").join("; "); | |
| } catch (e) { | |
| rows = integrity = String(e.message); | |
| } | |
| const filesAfter = pool.getFileNames().sort(); | |
| db.close(); | |
| await pool.removeVfs(); | |
| postMessage({ step: 2, waits, filesBefore, rows, integrity, filesAfter }); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!doctype html> | |
| <meta charset="utf-8"> | |
| <title>sahpool worker killed mid-transaction</title> | |
| <pre id="out"></pre> | |
| <script type="module"> | |
| // ?module=<URL of sqlite3.mjs or index.mjs>&lockingMode=normal|exclusive | |
| const q = new URLSearchParams(location.search); | |
| const module = new URL(q.get("module") ?? "jswasm/sqlite3.mjs", location.href).href; | |
| const lockingMode = q.get("lockingMode") ?? "normal"; | |
| const name = "crash-" + Date.now().toString(36); | |
| const log = (s) => (document.getElementById("out").textContent += s + "\n"); | |
| const step = (n) => | |
| new Promise((resolve, reject) => { | |
| const params = new URLSearchParams({ module, name, step: n, lockingMode, readonly: q.get("readonly") ?? "" }); | |
| const w = new Worker("crash-worker.js?" + params, { type: "module" }); | |
| w.onmessage = ({ data }) => resolve([w, data]); | |
| w.onerror = (e) => reject(new Error(e.message)); | |
| }); | |
| try { | |
| const [w1, r1] = await step(1); | |
| w1.terminate(); | |
| log(`SQLite ${r1.version}, locking_mode=${lockingMode}`); | |
| log(`step 1: transaction open with spilled pages, files ${r1.files.join(", ")}; worker terminated`); | |
| const [w2, r2] = await step(2); | |
| w2.terminate(); | |
| log(`step 2: files on open ${r2.filesBefore.join(", ")}`); | |
| log(` rows ${r2.rows}`); | |
| log(` integrity ${r2.integrity}`); | |
| log(` files after ${r2.filesAfter.join(", ")}`); | |
| const pass = r2.rows === "300 rows, 300 unchanged" && !r2.filesAfter.includes("/crash.db-journal"); | |
| log(pass ? "PASS: the journal was rolled back" : "FAIL: expected 300 rows, 300 unchanged, and no journal"); | |
| window.result = { lockingMode, r1, r2, pass, userAgent: navigator.userAgent }; | |
| } catch (e) { | |
| log("ERROR " + e.message); | |
| window.result = { error: String(e.message) }; | |
| } | |
| window.done = true; | |
| </script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //////////////////////////////////////////////////////////////////////// | |
| /** | |
| Storage-failure tests for the "opfs-sahpool" VFS, meant to sit | |
| after the 'OPFS SyncAccessHandle Pool VFS' group in tester1.c-pp.js | |
| (they use tester1's T, capi, isWorker(), and sahPoolConfig). | |
| The failures are simulated by wrapping | |
| FileSystemSyncAccessHandle.prototype.write() and truncate() in | |
| this worker, so the tests are deterministic and need neither a | |
| full disk nor a quota override. While sahFaults is installed: | |
| - A write() which would grow a file is allowed while | |
| growthBudget (bytes, shared by all files) lasts. After that it | |
| either throws a DOMException named errorName (writeMode 'throw'; | |
| Chromium throws QuotaExceededError for both an exhausted quota | |
| and a full disk, WebKit for an exhausted quota and | |
| InvalidStateError for a full disk) or returns shortResult | |
| without writing (writeMode 'short': Firefox returns a short | |
| count on a full disk, Chromium's off-the-record storage has | |
| returned 0xFFFFFFF8). Writes which do not grow a file always | |
| pass. | |
| - With truncateMode 'throw', truncate() throws the same | |
| DOMException, as Chromium and WebKit do on a full APFS disk | |
| even when shrinking a file (Firefox throws NS_ERROR_FAILURE). | |
| */ | |
| const sahFaults = (function(){ | |
| const proto = globalThis.FileSystemSyncAccessHandle?.prototype; | |
| const orig = proto ? {write: proto.write, truncate: proto.truncate} : undefined; | |
| const f = Object.create(null); | |
| const oops = (op)=>new DOMException( | |
| "Simulated "+op+"() failure: no space available for this operation", | |
| f.errorName | |
| ); | |
| f.install = function(opt){ | |
| Object.assign(f, { | |
| writeMode: 'throw', errorName: 'QuotaExceededError', | |
| shortResult: 0, growthBudget: 0, truncateMode: 'pass', | |
| nWriteFail: 0, nTruncateFail: 0 | |
| }, opt); | |
| proto.write = function(buf, wopt){ | |
| const at = wopt?.at; | |
| const growth = (undefined===at) | |
| ? 0 : Math.max(0, at + buf.byteLength - this.getSize()); | |
| if( growth > f.growthBudget ){ | |
| ++f.nWriteFail; | |
| if( 'short'===f.writeMode ) return f.shortResult; | |
| throw oops('write'); | |
| } | |
| f.growthBudget -= growth; | |
| return orig.write.call(this, buf, wopt); | |
| }; | |
| proto.truncate = function(n){ | |
| if( 'throw'===f.truncateMode ){ | |
| ++f.nTruncateFail; | |
| throw oops('truncate'); | |
| } | |
| return orig.truncate.call(this, n); | |
| }; | |
| return f; | |
| }; | |
| f.uninstall = function(){ | |
| proto.write = orig.write; | |
| proto.truncate = orig.truncate; | |
| }; | |
| return f; | |
| })(); | |
| const sahFaultsSnapshot = | |
| "select count(*)||':'||sum(length(v))||':'||group_concat(substr(v,1,1),'')" | |
| +" from (select v from t order by id)"; | |
| /** Creates table t with 10 rows and returns sahFaultsSnapshot of it. */ | |
| const sahFaultsSetup = function(db){ | |
| db.exec("create table t(id integer primary key, v text)"); | |
| for(let i = 0; i < 10; ++i){ | |
| db.exec({sql: "insert into t(v) values(?)", | |
| bind: [String.fromCharCode(65+i).repeat(1000)]}); | |
| } | |
| return db.selectValue(sahFaultsSnapshot); | |
| }; | |
| /** Opens a transaction whose COMMIT must both overwrite the existing | |
| pages of the db and append new ones. */ | |
| const sahFaultsBegin = function(db){ | |
| db.exec(["begin;", "update t set v=lower(v);"]); | |
| for(let i = 0; i < 8; ++i){ | |
| db.exec({sql: "insert into t(v) values(?)", bind: ['x'.repeat(3000)]}); | |
| } | |
| }; | |
| T.g('OPFS SyncAccessHandle Pool VFS: storage failures', | |
| (sqlite3)=>((isWorker() && !!sqlite3.installOpfsSAHPoolVfs | |
| && !!globalThis.FileSystemSyncAccessHandle) | |
| || "requires OPFS SAH Pool APIs")) | |
| .t({ | |
| name: 'SAH: a journal left by a failed rollback is hot', | |
| test: async function(sqlite3){ | |
| const u = await sqlite3.installOpfsSAHPoolVfs({ | |
| name: sahPoolConfig.name+'-hotjournal', clearOnInit: true | |
| }); | |
| try{ | |
| for(const opt of [ | |
| /* Chromium, full APFS disk */ | |
| {errorName: 'QuotaExceededError'}, | |
| /* WebKit, full APFS disk */ | |
| {errorName: 'InvalidStateError'}, | |
| /* Firefox, full APFS disk */ | |
| {writeMode: 'short', errorName: 'NS_ERROR_FAILURE'} | |
| ]){ | |
| const dbName = '/hotjournal.db', jName = dbName+'-journal'; | |
| let db = new u.OpfsSAHPoolDb(dbName); | |
| try{ | |
| const before = sahFaultsSetup(db); | |
| T.assert('10:10000:ABCDEFGHIJ' === before); | |
| sahFaultsBegin(db); | |
| /* The "disk" fills up during COMMIT: one more page may be | |
| appended to the db, then writes which grow a file fail, | |
| and so does the rollback's truncation of the db back to | |
| its original size. The db is left half-written, its | |
| original pages are in the journal. */ | |
| sahFaults.install(Object.assign({ | |
| growthBudget: db.selectValue('pragma page_size'), | |
| truncateMode: 'throw' | |
| }, opt)); | |
| try{ | |
| T.mustThrowMatching(()=>db.exec("commit"), | |
| (e)=>e instanceof sqlite3.SQLite3Error); | |
| }finally{ | |
| sahFaults.uninstall(); | |
| } | |
| T.assert(sahFaults.nWriteFail > 0 && sahFaults.nTruncateFail > 0, | |
| "The fault injector was not triggered.") | |
| .assert(u.getFileNames().indexOf(jName) >= 0, | |
| "The failed rollback leaves the journal behind."); | |
| db.close(); | |
| /* No connection holds a RESERVED lock, so the journal is hot | |
| and the next connection must roll it back. If | |
| xCheckReservedLock() claims a lock is held, it reads the | |
| half-written db and gets SQLITE_CORRUPT instead, on every | |
| statement and every reopen. */ | |
| db = new u.OpfsSAHPoolDb(dbName); | |
| T.assert(before === db.selectValue(sahFaultsSnapshot), | |
| "The hot journal was not rolled back for " | |
| +JSON.stringify(opt)+".") | |
| .assert('ok' === db.selectValue('pragma integrity_check')) | |
| .assert(u.getFileNames().indexOf(jName) < 0); | |
| }finally{ | |
| db.close(); | |
| } | |
| u.unlink(dbName); | |
| } | |
| }finally{ | |
| await u.removeVfs(); | |
| } | |
| } | |
| }) | |
| .t({ | |
| name: 'SAH: a second connection leaves a live journal alone', | |
| test: async function(sqlite3){ | |
| /* Nothing prevents two connections to one file in one pool, and | |
| xLock() does not keep them apart, so xCheckReservedLock() is | |
| the only thing which stops B from taking A's journal for a hot | |
| one. Rolling it back would restore the old pages under A, and | |
| A's COMMIT would then succeed but lose part of its update. */ | |
| const u = await sqlite3.installOpfsSAHPoolVfs({ | |
| name: sahPoolConfig.name+'-twoconn', clearOnInit: true | |
| }); | |
| const dbName = '/twoconn.db', jName = dbName+'-journal'; | |
| const q = "select count(*)||':'||sum(v=zeroblob(3000)) from t"; | |
| const a = new u.OpfsSAHPoolDb(dbName), b = new u.OpfsSAHPoolDb(dbName); | |
| try{ | |
| a.exec(["create table t(id integer primary key, v blob);", | |
| "with recursive c(i) as (select 1 union all select i+1", | |
| " from c where i<300) insert into t(v)", | |
| " select zeroblob(3000) from c;"]); | |
| T.assert('300:300' === b.selectValue(q)); | |
| /* The small cache makes the UPDATE spill: A syncs its journal, | |
| overwrites db pages, and holds an EXCLUSIVE lock. */ | |
| a.exec(["pragma cache_size=10;", "begin;", | |
| "update t set v=randomblob(3000);"]); | |
| T.assert(u.getFileNames().indexOf(jName) >= 0); | |
| b.selectValue(q); | |
| T.assert(u.getFileNames().indexOf(jName) >= 0, | |
| "B rolled back the journal of A's live transaction."); | |
| const c = new u.OpfsSAHPoolDb(dbName); | |
| try{ c.selectValue(q); }finally{ c.close(); } | |
| T.assert(u.getFileNames().indexOf(jName) >= 0, | |
| "A connection opened later rolled back A's journal."); | |
| a.exec("commit"); | |
| T.assert('300:0' === a.selectValue(q), | |
| "A's committed update was partly lost.") | |
| .assert('ok' === a.selectValue('pragma integrity_check')); | |
| }finally{ | |
| a.close(); | |
| b.close(); | |
| await u.removeVfs(); | |
| } | |
| } | |
| }) | |
| .t({ | |
| name: 'SAH: writes which fail for lack of space report SQLITE_FULL', | |
| test: async function(sqlite3){ | |
| const u = await sqlite3.installOpfsSAHPoolVfs({ | |
| name: sahPoolConfig.name+'-full', clearOnInit: true | |
| }); | |
| const db = new u.OpfsSAHPoolDb('/full.db'); | |
| try{ | |
| const before = sahFaultsSetup(db); | |
| for(const [opt, rc] of [ | |
| /* Chromium (quota and full disk), WebKit (quota) */ | |
| [{writeMode: 'throw'}, capi.SQLITE_FULL], | |
| /* Firefox (full disk) */ | |
| [{writeMode: 'short'}, capi.SQLITE_FULL], | |
| /* Chromium off-the-record storage (FILE_ERROR_NO_SPACE as uint32) */ | |
| [{writeMode: 'short', shortResult: 0xFFFFFFF8}, capi.SQLITE_FULL], | |
| /* WebKit reports a full disk as InvalidStateError, which it also | |
| uses for unrelated failures, so that has to stay SQLITE_IOERR. */ | |
| [{writeMode: 'throw', errorName: 'InvalidStateError'}, capi.SQLITE_IOERR] | |
| ]){ | |
| sahFaultsBegin(db); | |
| sahFaults.install(Object.assign({ | |
| growthBudget: db.selectValue('pragma page_size') | |
| }, opt)); | |
| try{ | |
| T.mustThrowMatching(()=>db.exec("commit"), rc, | |
| "Expecting "+capi.sqlite3_js_rc_str(rc) | |
| +" for "+JSON.stringify(opt)); | |
| }finally{ | |
| sahFaults.uninstall(); | |
| } | |
| T.assert(sahFaults.nWriteFail > 0, | |
| "The fault injector was not triggered."); | |
| if( !capi.sqlite3_get_autocommit(db) ) db.exec("rollback"); | |
| T.assert(before === db.selectValue(sahFaultsSnapshot)) | |
| .assert('ok' === db.selectValue('pragma integrity_check')); | |
| } | |
| }finally{ | |
| db.close(); | |
| await u.removeVfs(); | |
| } | |
| } | |
| }) | |
| ;/* end opfs-sahpool storage-failure tests */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment