macOS: stale PID lock misjudged as alive after reboot due to PID reuse — server crash-loops and never self-heals
Summary
On macOS, after an unclean shutdown (reboot/power loss), the data-directory PID lock (.openviking.pid) is left behind. If the stale PID is reused by an unrelated process after reboot, _is_pid_alive() returns True for it, acquire_data_dir_lock() raises DataDirectoryLocked on every startup, and the server never recovers — under a service manager (launchd KeepAlive) this becomes an infinite crash loop.
The PID-reuse guard in _is_pid_alive() (verifying the process identity via /proc/<pid>/cmdline, see #1088) is Linux-only. macOS has no /proc, so on Darwin the check degrades to a bare os.kill(pid, 0) liveness probe — any live process holding the recycled PID (e.g. Spotlight's mdwrite) is misjudged as a running OpenViking instance.
Windows received the same class of fixes in #790 / #854 / #1201. macOS is the remaining uncovered platform.
Environment
- macOS (Apple Silicon, arm64)
- openviking 0.4.9.dev17 (editable install), still present on current
main(6e944cc3, 2026-08-22) - Service managed by launchd LaunchAgent (
RunAtLoad=true,KeepAlive.SuccessfulExit=false,ThrottleInterval=10)
Real-world incident (what happened to me)
- Server (PID 857) wrote
.openviking.pidcontaining857. - Machine rebooted; the process was killed before
atexit/SIGTERM cleanup ran → stale lock file survived. - After reboot, macOS assigned PID 857 to
mdwrite(Spotlight metadata writer, a long-lived system process). - Every subsequent launchd start: FastAPI lifespan →
OpenVikingService()→acquire_data_dir_lock()→DataDirectoryLocked("Another OpenViking process (PID 857) ...")→ uvicornApplication startup failed. Exiting.→ exit code 3. - launchd retried every 10 s for ~7 days ≈ 50,000 crashes, producing ~330 MB of logs, with zero chance of self-healing (the lock holder
mdwritenever exits).
Diagnosis was harder than necessary because the server prints OpenViking HTTP Server is running on 127.0.0.1:1933 to stdout before uvicorn.run(), while the actual traceback only lands in the file logger — the launchd-managed stdout log contained nothing but 50,000 copies of the banner.
Root cause
openviking/utils/process_lock.py:
def _is_pid_alive(pid: int) -> bool:
...
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
...
# PID exists, but on Linux PIDs are recycled. Verify this is actually
# an OpenViking process by checking /proc/{pid}/cmdline ...
if sys.platform.startswith("linux"): # ← Darwin never enters here
...
return True
Suggested fixes (either)
Option A — Darwin process-identity check, mirroring the Linux branch:
if sys.platform == "darwin":
try:
out = subprocess.run(
["sysctl", "-n", f"kern.proc.pid.{pid}"],
capture_output=True, text=True, timeout=2,
)
name = (out.stdout or "").lower()
if "openviking" not in name and "python" not in name:
return False # recycled PID held by an unrelated process
except (OSError, subprocess.SubprocessError):
pass
Option B — start-time nonce (stronger, cross-platform): record the holder process's start time (e.g. kern.proc.pid p_starttime on Darwin, /proc/<pid>/stat field 22 on Linux) in the lock file alongside the PID, and treat the lock as stale when the live process's start time differs. This closes the PID-reuse window entirely instead of relying on name matching.
Reproduction
- Start
openviking-server; note the PID written to<workspace>/.openviking.pid. - Kill it with
kill -9(or reboot) so cleanup never runs. sudo-less trick to simulate reuse: keep starting/killing short-lived processes until one lands on the recorded PID — or simply reboot and wait for the OS to recycle it (on macOS, low PIDs are quickly reused by system daemons).- Start the server again →
DataDirectoryLockedevery time, until the innocent PID holder exits.
Happy to open a PR for Option A if the approach sounds right.
Adding a Windows data point: this is not macOS-only. Windows has no process-identity check either, so a recycled PID produces the very same permanent DataDirectoryLocked (and the same non-self-healing failure mode). The line "Windows received the same class of fixes in #790 / #854 / #1201 — macOS is the remaining uncovered platform" does not cover PID reuse.
Real incident (Windows 11, openviking 0.4.19, 2026-09-14)
- 00:05 — a daily restart task killed and restarted the server; the new instance wrote
D:\openVikingData\.openviking.pid=10340. - 12:46–12:49 — Windows Update rebooted the host. The server was killed by the shutdown, so the
atexitcleanup never removed the lock file. - After boot the OS reused PID 10340 for
postgres.exe(a long-lived service process in session 0). - Every start attempt afterwards died in the lifespan:
2026-09-14 12:51:36,838 - uvicorn.error - INFO - Started server process [29616]
openviking.utils.process_lock.DataDirectoryLocked: Another OpenViking process (PID 10340) is already using the data directory 'D:\openVikingData'. Running multiple OpenViking instances on the same data directory causes silent storage contention and data corruption.
2026-09-14 12:51:36,845 - uvicorn.error - ERROR - Application startup failed. Exiting.
Same failure mode as the macOS report: the recycled PID is held by a daemon that never exits, and the launcher here is a one-shot logon autostart, so nothing ever retries — the server stays down until a human notices.
Why the Windows fixes so far do not cover it
- 0.4.19:
_is_pid_alive()probes withos.kill(pid, 0). For a process owned by another account (the postgres service) that raisesPermissionError, which the code treats as "process exists", then falls through to the Linux-only/proc/<pid>/cmdlineidentity check — skipped on Windows — and returnsTrue. - current
main/ v0.4.20 (after #4791): the Windows branch probes via_winapi.OpenProcess(SYNCHRONIZE)+WaitForSingleObject(handle, 0). That fixed the signalling problem, but it is still liveness only — any live process sitting on the recycled PID is accepted as the lock holder, so the false positive is unchanged:
if sys.platform == "win32":
...
# identity of the PID holder is never checked, unlike the Linux branch
return _winapi.WaitForSingleObject(handle, 0) != _winapi.WAIT_OBJECT_0
Suggested fix
Option B from the report (record the holder's process start time, or a boot-scoped nonce, in the lock file and treat a mismatch as stale) is the one that actually closes this on all three platforms — liveness probes alone cannot. If a Windows-only guard is preferred, the equivalent of the Linux check is OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION) + QueryFullProcessImageNameW, treating an image that is neither openviking-server.exe nor the venv interpreter (whose command line names openviking-server.exe) as a stale lock. For reference, that image-name/command-line check is what our local launcher does as a stopgap, and it clears this repro on every run.
Deterministic Windows repro (no reboot needed)
- Start
openviking-serverand read the PID written to<workspace>\.openviking.pid. taskkill /f /im openviking-server.exe— terminated without cleanup, the lock file survives.- Write a PID held by any unrelated long-lived process into
.openviking.pid(e.g.postgres.exe; confirm withtasklist /fi "PID eq <pid>"). - Start the server again →
DataDirectoryLockedon every attempt, until that innocent process exits.
Thanks for the detailed report and the additional Windows evidence. We acknowledge that a recycled PID can keep OpenViking from starting after an unclean shutdown.
We have decided to keep recovery from this case as an operator responsibility. Existing cleanup handles normal shutdown and stale locks it can identify; automatic recovery when the recorded PID is still live is not guaranteed. Remaining blocked until an operator intervenes is an accepted limitation of the current lock policy. Before removing the leftover .openviking.pid and restarting, the operator must verify that no OpenViking instance is using that data directory.
Closing this as not planned. We are not expanding automatic recovery with additional platform-specific process-identity checks for this case.