[Bug]: cleanupStaleContentDBs race with parallel Pi MCP servers poisons ContentStore singleton (permanent disk I/O error)
Summary
On Pi with multiple concurrent MCP child processes (server.bundle.mjs, one per Ghostty tab / pi session), ctx_fetch_and_index, ctx_index, ctx_search, and ctx_batch_execute can fail permanently with disk I/O error until the affected server process is killed.
This is not disk full, not FTS5 corruption, and not the busy_timeout class fixed in #642 / reported in #668. Root cause is a race between cleanupStaleContentDBs() and a live ContentStore singleton in another server process that already opened the same shared content DB.
Related (same ecosystem, different mechanism): #854 (Pi servers accumulate), #560 (multi-instance WAL contention), #867 (singleton does not self-heal mid-session). No existing issue covers cleanupStaleContentDBs deleting files under a live ContentStore handle.
Environment
| Field | Value |
|---|---|
| Plugin | context-mode v1.0.166 |
| Host | Pi (@earendil-works/pi-coding-agent) via MCP bridge |
| OS | macOS 26 (darwin 25.x), Apple Silicon |
| Runtime | Bun (server.bundle.mjs) |
| Storage | ~/.pi/context-mode/content/<project-hash>.db |
| Typical setup | 5–7 parallel Ghostty tabs, each running pi on the same project dir |
Repro
- Open two or more Ghostty tabs in the same project directory, each running interactive
pi(MCP bridge spawns oneserver.bundle.mjsper tab — same class as #854). - In tab A, use any write tool once (e.g.
ctx_indexorctx_fetch_and_index) so server A opens the shared content DB and caches_store. - Start server B (new pi tab) — on first
getStore(), server B runs startup cleanup. - Server A continues calling
ctx_fetch_and_index/ctx_search/ctx_index.
Observed: all write/search tools on server A return disk I/O error until that server.bundle.mjs PID is killed. Respawn fixes it; ctx_doctor still reports PASS (tests in-memory FTS5 only).
Minimal programmatic repro (verified locally):
import { ContentStore } from "context-mode/build/store.js";
import { unlinkSync } from "node:fs";
const p = "/tmp/cm-test-diskio.db";
for (const s of ["", "-wal", "-shm"]) try { unlinkSync(p + s); } catch {}
const store = new ContentStore(p); // simulates server A singleton
for (const s of ["", "-wal", "-shm"]) try { unlinkSync(p + s); } catch {} // simulates cleanupStaleContentDBs
store.index({ content: "# x\n\ny", source: "t" });
// → Error: disk I/O errorRoot cause
1. Multiple servers share one content DB
Each Pi tab → one MCP stdio child → one process-local _store singleton, all resolving to the same path:
~/.pi/context-mode/content/<hashProjectDirCanonical(projectDir)>.db
(See getStorePath() / resolveContentStorePath() in build/server.js.)
2. Every new server runs aggressive cleanup on first getStore()
function getStore() {
if (!_store) {
const dbPath = getStorePath();
_store = new ContentStore(dbPath);
// ...
cleanupStaleContentDBs(contentDir, 14); // unlink .db / -wal / -shm
cleanupStaleContentDBs(legacyDir, 0); // legacy ~/.context-mode/content — maxAgeDays=0
}
return _store;
}(build/server.js ~631–660)
3. cleanupStaleContentDBs deletes DB files without checking live handles
// build/store.js ~180–216
// Deletes if mtime > 14 days OR:
// WAL non-empty AND wal mtime not touched in >1 hour
if (shouldClean) {
for (const suffix of ["", "-wal", "-shm"]) {
unlinkSync(filePath + suffix);
}
}Problems:
- No
flock/ no lsof / no SQLite lock probe before unlink. - The >1h stale WAL heuristic can delete a DB another process is actively using (WAL mtime ≠ writer activity).
maxAgeDays=0on legacy dir deletes all legacy content DBs unconditionally on any server startup that hits that path.
4. Poisoned singleton is never reopened
_store is created once per process. If another server (or cleanup) unlinks the files while this process still holds an open SQLite handle, subsequent writes throw SQLITE_IOERR → disk I/O error. There is no invalidation/reopen path (contrast #867 for corruption — same “held handle” class).
ctx_doctor does not catch this because its FTS5 probe uses an in-memory DB, not the persistent content store.
Expected vs actual
| Expected | Actual |
|---|---|
| Parallel Pi sessions on one project either share one content server safely, or tolerate N writers via WAL + busy_timeout | N servers compete; cleanup in server B can unlink server A's DB files |
| Transient lock → retry / clear error | Permanent disk I/O error until manual pkill -f server.bundle.mjs |
| Doctor detects broken persistent store | Doctor PASS while MCP tools are broken |
Workaround (today)
- One interactive
pitab per project — use splits inside Ghostty, not separate tabs. - Background work via
pi -p(no MCP bridge) or Cursor SDK bridge separately. - When broken: kill poisoned servers —
pkill -f 'context-mode/server.bundle.mjs'— bridge respawns on next tool call. - Do not manually
rm ~/.pi/context-mode/content/*.dbwhile pi tabs are open.
Proposed fixes
A. Safe cleanup (minimal)
Before unlinkSync, skip/delete only if:
- no process has the
.dbopen (fuser/lsof/ platform lockfile), or - DB passes a brief exclusive open test, or
- cleanup runs from a single designated process, not every
getStore().
B. Disable cross-process cleanup in multi-server hosts
Env flag e.g. CONTEXT_MODE_NO_CONTENT_CLEANUP=1, or auto-detect when sibling server.bundle.mjs processes exist for the same content dir (#854 class).
C. Self-heal poisoned singleton
On SQLITE_IOERR / disk I/O error from ContentStore writes: close _store, verify file exists, reopen or recreate once (extends #867 pattern to IOERR-from-unlink).
D. Architectural (Pi)
Single shared content-mode server per user/project (socket/launchd) instead of N stdio children — fixes #854 accumulation and this race together.
Pre-submission checklist
- Searched existing issues — closest: #854, #668, #560, #867; none for
cleanupStaleContentDBsrace - On latest version (v1.0.166)
- Repro steps + minimal code repro provided
- Root cause traced in shipped
build/server.js+build/store.js - Workaround documented
Happy to open a PR for (A)+(C) if the approach is welcome.
Source: mksglu/context-mode