Skip to content
This repository was archived by the owner on Oct 23, 2026. It is now read-only.

fix(db): recover WASM SQLite locks via PID sentinel, not a 60s age window - #1261

Merged
BYK merged 3 commits into
mainfrom
fix/db-wasm-lock-signal-cleanup
Jul 17, 2026
Merged

BYK merged 3 commits into
mainfrom
fix/db-wasm-lock-signal-cleanup

Conversation

@BYK

@BYK BYK commented Jul 17, 2026

Copy link
Copy Markdown
Member

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-wasm locks the DB with a <db>.lock directory (mkdir mutex) and releases it via rmdir on close. A CLI process killed by SIGINT (Ctrl+C) / SIGTERM mid-write bypasses the process.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 with database is locked for up to a minute.

Fix

PID-owner sentinel for precise liveness detection instead of a time guess:

  • On open (WASM), write <db>.lock.owner = our PID.
  • On the next open, clearStaleWasmLock reads it:
    • owner dead → lock is provably orphaned → cleared immediately (no wait),
    • owner alive → genuine live lock → left to busy_timeout (no stealing),
    • no sentinel → fall back to the age window (older CLI / races).
  • On clean close, remove the sentinel.

The sentinel lives outside the lock dir — a file inside it would make the driver's rmdir unlock 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

  • New tests: dead-owner lock cleared immediately despite fresh mtime; live-owner (current PID) lock preserved despite old mtime. 28 sqlite-adapter tests, 296 db tests pass.
  • E2E reproduction: a fresh lock dir with a dead-owner sentinel is cleared on the next run in ~startup time (no 60s stall); previously this exact case blocked for 60s.
  • SEA binary still excludes the WASM driver (0 driver symbols); native path unchanged.
  • npm real-install (no node_modules) smoke passes.

Also corrected the now-inaccurate JSDoc that described the (previously wrong) 'live lock is recently re-touched' premise.

…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`).
@github-actions

github-actions Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-07-17 11:29 UTC

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 4 potential issues.

Fix All in Cursor

❌ 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.

Comment thread src/lib/db/sqlite.ts Resolved
Comment thread src/lib/db/sqlite.ts Resolved
Comment thread src/lib/db/sqlite.ts Resolved
Comment thread src/lib/db/sqlite.ts Outdated
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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 0f30ef2. Configure here.

@github-actions

github-actions Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Codecov Results 📊

✅ Patch coverage is 91.89%. Project has 5480 uncovered lines.
✅ Project coverage is 81.67%. Comparing base (base) to head (head).

Files with missing lines (1)
File Patch % Lines
src/lib/db/sqlite.ts 90.32% ⚠️ 3 Missing and 2 partials
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        +2

Generated 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.
@BYK

BYK commented Jul 17, 2026

Copy link
Copy Markdown
Member Author

Thanks — addressed all four Cursor Bugbot findings in a62280a:

  • Sentinel races under concurrent opens (High) and Dead sentinel steals live locks (Medium): These share a root cause — a stale/overwritten single sentinel could justify deleting a lock another process just acquired (the corruption path). Fixed by adding LOCK_SAFETY_FLOOR_MS (3s): no lock is ever removed while younger than the floor, regardless of the sentinel. So a freshly-acquired live lock can never be stolen by a leftover dead-PID sentinel; past the floor a dead owner clears the orphan immediately, a live owner keeps it, and concurrent races degrade to the age floor rather than corruption. Added a test proving a fresh lock + dead sentinel is preserved.
  • Duplicate liveness helper (Low): Extracted isProcessRunning into a new dependency-free src/lib/process-utils.ts; binary.ts re-exports it (existing importers unaffected) and db/sqlite.ts imports from there — one implementation, and no dragging binary.ts's heavy graph onto the DB hot path.
  • PID reuse blocks recovery (Low): Bounded — with no sentinel the age fallback still fires; a reused-PID false positive at worst defers cleanup by one run, never corrupts. Acceptable given the alternative (stealing a possibly-live lock) is strictly worse.

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.

Comment thread src/lib/db/sqlite.ts Resolved
Comment thread src/lib/db/sqlite.ts
} catch (error) {
log.debug("Could not write WASM lock owner sentinel", error);
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@BYK
BYK merged commit abde588 into main Jul 17, 2026
34 checks passed
@BYK
BYK deleted the fix/db-wasm-lock-signal-cleanup branch July 17, 2026 11:29
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant