memorix icon indicating copy to clipboard operation
memorix copied to clipboard

background start / ensure: TOCTOU race can spawn duplicate serve-http control planes

Open abhishekgarg18 opened this issue 3 months ago • 1 comments

Summary

doStart(port) in src/cli/commands/background.ts checks isPortInUse(port) and, only if nothing answers, spawns a detached serve-http --port <port> child. There is no lock around this check-then-spawn sequence, so two callers racing through it at roughly the same time can both observe "not in use yet" and each spawn their own server on the same port. Only one gets written to background.json (whichever call reaches saveState last) — the other becomes an untracked orphan that keeps running indefinitely.

Real-world repro

Hit this on an actual machine (macOS, Apple Silicon) after a reboot. Two independent integrations were both calling into the shared memorix CLI around the same time on login:

  • A Claude Code plugin (.mcp.json → memorix serve --mode lite, per-session)
  • An omp extension (shells out to memorix hook ... per agent event)

Neither of these directly spawns serve-http, but something in that startup window (a background start/ensure call — most likely the LaunchAgent RunAtLoad firing concurrently with an agent session's own startup check) raced through doStart's check-then-spawn window twice. Result:

abhigarg   897   node .../dist/cli/index.js serve-http --port 3211   (tracked, in background.json)
abhigarg  7054   node .../dist/cli/index.js serve-http --port 3211   (untracked orphan)

Both bound successfully because the health-check probe (isPortInUse, 1500ms timeout via /health) returned false for both before either process had actually started listening.

Minimal repro (synthetic, on a throwaway port)

Without the fix, firing two background start calls at the same instant on an unused port produces two serve-http processes bound to that port — confirmed with:

( memorix background start --port 4321 & )
( memorix background start --port 4321 & )
sleep 4
ps aux | grep "serve-http --port 4321"   # shows 2 processes without the fix, 1 with it

Fix

PR incoming: wraps doStart's existing logic (renamed internally to doStartUnlocked, unchanged) in an exported doStart that serializes callers with a simple exclusive-create lock file (~/.memorix/background.lock). Stale locks (crashed holder) are reclaimed after 15s; if the lock can't be acquired at all within 5s, falls back to running unlocked rather than deadlocking — worst case reverts to today's behavior, never worse.

Verified with the repro above: before the fix, 2 processes bound to the port; after, exactly 1 (the second caller correctly logs "already running" and backs off).

abhishekgarg18 avatar Aug 27 '26 05:08 abhishekgarg18

The fix is included in 1.8.5; the issue was already closed automatically by the release merge, so this comment records the public resolution and verification.

AVIDS2 avatar Aug 30 '26 03:08 AVIDS2