Repository navigation
fix(db): recover WASM SQLite locks via PID sentinel, not a 60s age window - #1261
Conversation
…ndow Follow-up to #1260. On the WASM fallback (Node < 22.15), a CLI killed by SIGINT/SIGTERM mid-write bypasses the `exit` handler and leaks the `<db>.lock` mutex directory. The previous recovery only cleared a leftover lock once it was older than a 60s age window, so a quick re-run after Ctrl+C failed with "database is locked" for up to a minute. (Flagged by Cursor Bugbot and sentry-warden.) Add a PID-owner sentinel written next to the lock (`<db>.lock.owner`) on open and removed on clean close. On the next open, `clearStaleWasmLock` reads it: if the owning process is dead the lock is provably orphaned and cleared immediately (no wait); if alive it's a genuine live lock and left to busy_timeout. The age window remains only as a fallback for locks with no sentinel (e.g. left by an older CLI). The sentinel lives *outside* the lock dir because a file inside it would break the driver's own rmdir-based unlock. Chose this over adding a SIGINT/SIGTERM handler in the DB layer, which would risk interfering with commands that own SIGINT for graceful streaming shutdown (`log list --follow`, `dashboard view`).
|
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 4 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 0f30ef2. Configure here.
| const stat = statSync(lockDir); // throws ENOENT when no lock — common case | ||
| const owner = readLockOwner(dbPath); | ||
| if (owner !== null && isProcessAlive(owner)) { | ||
| // Owner still running: a genuine live lock. Leave it to busy_timeout. |
There was a problem hiding this comment.
PID reuse blocks lock recovery
Low Severity
If the sentinel PID has been reused by an unrelated alive process, clearStaleWasmLock always keeps the lock and never consults the age heuristic. An orphaned .lock can then persist until that unrelated PID exits, recreating long database is locked stalls.
Reviewed by Cursor Bugbot for commit 0f30ef2. Configure here.
Codecov Results 📊✅ Patch coverage is 91.89%. Project has 5480 uncovered lines. Files with missing lines (1)
Coverage diff@@ Coverage Diff @@
## main #PR +/-##
==========================================
+ Coverage 81.67% 81.67% —%
==========================================
Files 425 426 +1
Lines 29868 29896 +28
Branches 19398 19420 +22
==========================================
+ Hits 24393 24416 +23
- Misses 5475 5480 +5
- Partials 2033 2035 +2Generated by Codecov Action |
…e floor Addresses Cursor Bugbot findings on the PID-sentinel approach: - (High/Medium) A stale dead-PID sentinel could instantly delete a lock that a different, still-live process (e.g. an older CLI that doesn't write sentinels) had just acquired — a corruption path. Introduce LOCK_SAFETY_FLOOR_MS (3s): no lock is ever removed while younger than the floor, regardless of what the sentinel says. Past the floor, a dead-owner sentinel clears the orphan immediately (near-instant Ctrl+C recovery); a live-owner sentinel keeps it; no sentinel falls back to the 60s age window. This is now strictly safer than the previous age-only recovery while still fixing the SIGINT-leak stall. - (Low) Dedupe the process-liveness helper. Extract isProcessRunning into a new dependency-free leaf module src/lib/process-utils.ts; binary.ts re-exports it (existing importers unaffected) and db/sqlite.ts imports it from there rather than duplicating process.kill(pid, 0) logic or pulling in binary.ts's heavy graph on the DB hot path. - (Low) PID-reuse keeping an orphan lock is now bounded: the age fallback still applies when there's no sentinel, and the safety floor plus dead-owner check cover the sentinel case; a reused-PID false-positive at worst defers cleanup, never corrupts.
|
Thanks — addressed all four Cursor Bugbot findings in a62280a:
Verified: fresh lock + dead sentinel is kept (no steal); dead-owner lock past the 3s floor recovers in ~1s instead of 60s; SEA binary still excludes the WASM driver; 29 sqlite + 419 db/upgrade tests pass. |
| } catch (error) { | ||
| log.debug("Could not write WASM lock owner sentinel", error); | ||
| } | ||
| } |
There was a problem hiding this comment.
Bug: PID reuse can cause isProcessRunning to return a false positive, permanently preventing an orphaned lock from being cleared because there is no timeout fallback in this code path.
Severity: HIGH
Suggested Fix
To prevent false positives from PID reuse, isProcessRunning should be made more robust. Instead of only checking if a process with the given PID exists, it should also verify that the process command or start time matches what is expected for the lock owner. This ensures the running PID belongs to the original process, not an unrelated one.
Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.
Location: src/lib/db/sqlite.ts#L388
Potential issue: The lock clearing logic can be defeated by PID reuse. If a process with
a lock dies and its PID is reassigned to an unrelated process, `clearStaleWasmLock` will
incorrectly determine the lock owner is still alive by calling `isProcessRunning`.
Because the code path for a non-null owner with a running PID has no fallback timeout,
the orphaned lock is never cleared. This causes subsequent database initializations to
fail permanently with a "database is locked" error until the unrelated process with the
reused PID exits.
Did we get this right? 👍 / 👎 to inform future reviews.
…rrel re-export The previous commit re-exported isProcessRunning from binary.ts, which trips Biome's noExportedImports / noBarrelFile rules (caught by the repo-wide lint, not the scoped one). Remove the re-export: the sole external consumer (upgrade.test.ts) now imports isProcessRunning from src/lib/process-utils.js directly, and binary.ts keeps a plain internal import.


Summary
Follow-up to #1260 addressing a post-merge finding from Cursor Bugbot and sentry-warden.
On the WASM SQLite fallback (npm package on Node < 22.15),
node-sqlite3-wasmlocks the DB with a<db>.lockdirectory (mkdir mutex) and releases it viarmdiron close. A CLI process killed by SIGINT (Ctrl+C) / SIGTERM mid-write bypasses theprocess.on('exit')handler, so the lock dir leaks. The previous recovery only cleared a leftover lock once it aged past a 60-second window — so a quick re-run after Ctrl+C failed withdatabase is lockedfor up to a minute.Fix
PID-owner sentinel for precise liveness detection instead of a time guess:
<db>.lock.owner= our PID.clearStaleWasmLockreads it:busy_timeout(no stealing),The sentinel lives outside the lock dir — a file inside it would make the driver's
rmdirunlock fail (verified), defeating the driver's own cleanup.Why not a SIGINT/SIGTERM handler?
A DB-layer signal handler would risk interfering with commands that legitimately own SIGINT for graceful streaming shutdown (
log list --follow,dashboard view), which keep the process alive after the signal. The recovery-side fix has zero interference risk.Verification
node_modules) smoke passes.Also corrected the now-inaccurate JSDoc that described the (previously wrong) 'live lock is recently re-touched' premise.