Repository navigation
Description
OPFSCoopSyncVFS.create() rejects on the first page load after a same-origin navigation away from a page that has a database open:
NoModificationAllowedError: Failed to execute 'removeEntry' on 'FileSystemDirectoryHandle': An attempt was made to modify an object where modifications are not allowed.
It comes from the stale-directory sweep in #initialize:
wa-sqlite/src/examples/OPFSCoopSyncVFS.js
Lines 73 to 86 in e98c65d
| for await (const entry of root.values()) { | |
| if (entry.kind === 'directory' && entry.name.startsWith('.ahp-')) { | |
| // A lock with the same name as the directory protects it from | |
| // being deleted. | |
| await navigator.locks.request(entry.name, { ifAvailable: true }, async lock => { | |
| if (lock) { | |
| this.log?.(`Deleting temporary directory ${entry.name}`); | |
| await root.removeEntry(entry.name, { recursive: true }); | |
| } else { | |
| this.log?.(`Temporary directory ${entry.name} is in use`); | |
| } | |
| }); | |
| } | |
| } |
What seems to happen
Chrome keeps the outgoing page in the back/forward cache. Its pagehide event reports persisted: true, and its worker still holds the .ahp-* lock plus the access handles on that directory's temporary files. Loading the next page makes Chrome evict the cached page. The new page's sweep gets the .ahp-* lock with ifAvailable: true while the evicted page's access handles are still open, so removeEntry throws. Nothing catches it, and create() rejects.
That ordering is my reading of the symptoms, since I can't see inside Chrome. What the repro does show: the lock was available, the delete failed, and an immediate retry succeeds.
Reproduction
Serve these two files from http://localhost with any static server, such as python3 -m http.server, and open index.html?runs=10 in Chrome. Each run opens repro.db in a worker, keeps it open, and navigates to the next run. The imports point at master through jsDelivr; local copies work the same.
index.html
<!doctype html>
<meta charset="utf-8" />
<title>OPFSCoopSyncVFS bfcache repro</title>
<pre id="log">Running…</pre>
<script type="module">
// Each run opens repro.db in a worker, keeps it open, then navigates to the
// next run. Start with ?runs=10. Add &mode=reload to leave each page with
// location.reload() instead, which never uses the back/forward cache.
const params = new URLSearchParams(location.search);
const state = params.has("n")
? JSON.parse(localStorage.repro)
: { runs: Number(params.get("runs") ?? 10), mode: params.get("mode") ?? "navigate", results: [] };
if (!params.has("n") && state.mode === "reload") history.replaceState(null, "", "?n=reload");
const result = { run: state.results.length + 1 };
state.results.push(result);
const save = () => (localStorage.repro = JSON.stringify(state));
addEventListener("pagehide", (event) => {
result.bfcache = event.persisted;
save();
});
const open = () =>
new Promise((resolve) => {
const worker = new Worker("./worker.js", { type: "module" });
worker.onmessage = ({ data }) => {
if (!data.ok) worker.terminate();
resolve(data);
};
});
result.first = await open();
if (!result.first.ok) result.retry = await open();
save();
if (result.run < state.runs) {
setTimeout(() => (state.mode === "reload" ? location.reload() : (location.href = `?n=${result.run + 1}`)), 300);
} else {
document.querySelector("#log").textContent = state.results
.map((r) => {
const retry = r.retry ? ` | retry: ${r.retry.ok ? "ok" : r.retry.error}` : "";
const left = r.bfcache === undefined ? "" : ` | left via bfcache: ${r.bfcache}`;
return `run ${r.run}: ${r.first.ok ? "ok" : r.first.error}${retry}${left}`;
})
.join("\n");
}
</script>worker.js
// Opens repro.db through OPFSCoopSyncVFS, writes a row, and keeps the
// connection open, the way an app page would.
import SQLiteESMFactory from "https://cdn.jsdelivr.net/gh/rhashimoto/wa-sqlite@e98c65de87c51edd15aea3cf6da53b5950410a12/dist/wa-sqlite.mjs";
import * as SQLite from "https://cdn.jsdelivr.net/gh/rhashimoto/wa-sqlite@e98c65de87c51edd15aea3cf6da53b5950410a12/src/sqlite-api.js";
import { OPFSCoopSyncVFS } from "https://cdn.jsdelivr.net/gh/rhashimoto/wa-sqlite@e98c65de87c51edd15aea3cf6da53b5950410a12/src/examples/OPFSCoopSyncVFS.js";
try {
const module = await SQLiteESMFactory();
const sqlite3 = SQLite.Factory(module);
const vfs = await OPFSCoopSyncVFS.create("opfs", module);
sqlite3.vfs_register(vfs, true);
const db = await sqlite3.open_v2("repro.db");
await sqlite3.exec(db, "CREATE TABLE IF NOT EXISTS t(x); INSERT INTO t VALUES (1);");
postMessage({ ok: true });
} catch (e) {
postMessage({ ok: false, error: `${e.name}: ${e.message}` });
}Chrome 152 on Linux x86_64, wa-sqlite master at e98c65d:
| Case | First open failed | Immediate retry |
|---|---|---|
| Navigation, headless Chrome | 9 of 9 | succeeded 9 of 9 |
| Navigation, regular Chrome | 9 of 9 | succeeded 9 of 9 |
| Navigation, headless Chrome at 4× CPU throttle | 10 of 10 | succeeded 10 of 10 |
?mode=reload, which skips the back/forward cache |
0 of 9 | |
| Navigation with the sweep patched as below | 0 of 48 |
Counts are for runs 2 onward, and every navigation run entered the back/forward cache. Run 1 fails too when the tab's previous page held a database.
One more data point fits the eviction explanation. Calling navigator.locks.query() in the new page before opening made the first open succeed 9 of 9, as if the query evicts the cached page early enough for its handles to close first.
Suggested fix
The sweep is cleanup, so a directory it can't delete yet can wait for a later open:
if (lock) {
this.log?.(`Deleting temporary directory ${entry.name}`);
- await root.removeEntry(entry.name, { recursive: true });
+ try {
+ await root.removeEntry(entry.name, { recursive: true });
+ } catch (e) {
+ // Best-effort cleanup: the previous owner's access handles
+ // may not be closed yet. A later open will sweep it.
+ this.log?.(`Could not delete temporary directory ${entry.name}`, e);
+ }
} else {That patch produced the 0-of-48 row, which includes 9 runs in regular Chrome and 10 at 4× throttle.
#347 changes the same call to ignore NotFoundError, which still lets this NoModificationAllowedError through. Ignoring NoModificationAllowedError there as well would cover this case. #296 reached the same line after site data was cleared on Windows.
Downstream
@tanstack/browser-db-sqlite-persistence bundles this VFS through @journeyapps/wa-sqlite, whose 2.0.6 has the same sweep, and there this failure fails the whole database open. TanStack/db#1844, merged but not yet released, terminates its worker on pagehide, which avoids this for TanStack users. Other apps that keep a database open across page navigations will still hit it.
Activity
lalexdotcom commentedon Oct 16, 2026
I can reproduce this, and the suggested direction fixes it. Same navigation repro as above, wa-sqlite master
6238f532, Chrome for Testing 153 (headless, linux-arm64), two passes of 10 runs. Counts are for runs 2 to 10 of each pass, and every page left withpagehide.persisted === true.#initialize()NoModificationAllowedError(immediate retry: 18 of 18 ok)NoModificationAllowedErrornext to #347'sNotFoundErrorIn every arm, each run read back all the rows earlier runs wrote. The temporary directory the sweep leaves behind doesn't accumulate: each run sees at most two
.ahp-*directories, its own and the previous page's, and the next open sweeps the leftover.A pitfall if anyone reruns this:
Cache-Control: no-storeon the page keeps Chrome from using the back/forward cache, and master then passes for the wrong reason.Same root as #381: a departed worker's Web Lock is released before its access handles close.
@rhashimoto, would you take a PR for this? It would add
NoModificationAllowedErrorto the errors the sweep tolerates (one line, next to #347's), with a test.rhashimoto commentedon Oct 17, 2026
Sure, that would be great!
OPFSCoopSyncVFS: tolerate a temporary directory whose files are still…