Skip to content

Personal AI, On Personal Devices

Python

fix(cli): reject reused Linux daemon PIDs

Huanyi Xie52cc3ff23d13
diff --git a/src/openjarvis/cli/daemon_cmd.py b/src/openjarvis/cli/daemon_cmd.py
index 4a6a8e18..0d1bd05e 100644
--- a/src/openjarvis/cli/daemon_cmd.py
+++ b/src/openjarvis/cli/daemon_cmd.py
@@ -9,6 +9,7 @@ import subprocess
import sys
import time
from contextlib import contextmanager
+from pathlib import Path
from typing import Iterator
import click
@@ -32,6 +33,29 @@ def _pid_alive(pid: int) -> bool:
return process_alive(pid)
+def _registered_pid_alive(pid: int) -> bool:
+ """Reject a reused Linux PID whose process started after registration."""
+ if not _pid_alive(pid):
+ return False
+ if sys.platform != "linux":
+ return True
+ try:
+ # The comm field may contain spaces and parentheses; fields after its
+ # final ')' begin with field 3. Field 22 is start time in clock ticks.
+ stat = Path(f"/proc/{pid}/stat").read_text()
+ start_ticks = int(stat.rsplit(")", 1)[1].split()[19])
+ boot_line = next(
+ line
+ for line in Path("/proc/stat").read_text().splitlines()
+ if line.startswith("btime ")
+ )
+ started_at = int(boot_line.split()[1]) + start_ticks / os.sysconf("SC_CLK_TCK")
+ return started_at <= _PID_FILE.stat().st_mtime
+ except (OSError, ValueError, IndexError, StopIteration):
+ # Preserve liveness-only behavior where process metadata is unavailable.
+ return True
+
+
@contextmanager
def _state_lock() -> Iterator[None]:
"""Serialize daemon bookkeeping across launching and supervised processes."""
@@ -82,7 +106,7 @@ def _read_pid_unlocked() -> int | None:
if pid is None:
_PID_FILE.unlink(missing_ok=True)
return None
- if not _pid_alive(pid):
+ if not _registered_pid_alive(pid):
_clear_state_unlocked(pid)
return None
return pid
@@ -131,7 +155,7 @@ def _write_pid_unlocked(
# The server may have bound before its launcher recorded pending state.
# Keep the actual PID and bound address in either ordering.
return
- if existing is not None and existing != pid and _pid_alive(existing):
+ if existing is not None and existing != pid and _registered_pid_alive(existing):
if not (ready and same_launch and current.get("ready") is False):
raise RuntimeError(f"Another server is already registered (PID {existing})")
secure_write_text(_PID_FILE, str(pid))
diff --git a/tests/cli/test_daemon_cmd.py b/tests/cli/test_daemon_cmd.py
index 79a672ee..9d8ee322 100644
--- a/tests/cli/test_daemon_cmd.py
+++ b/tests/cli/test_daemon_cmd.py
@@ -11,6 +11,7 @@ from contextlib import nullcontext
from pathlib import Path
from unittest.mock import MagicMock, patch
+import pytest
from click.testing import CliRunner
from openjarvis.cli import cli
@@ -138,6 +139,34 @@ class TestPidLiveness:
proc.terminate()
proc.wait()
+ @pytest.mark.skipif(sys.platform != "linux", reason="Linux procfs start times")
+ def test_pid_reused_after_registration_does_not_block_or_get_signaled(
+ self, tmp_path
+ ):
+ from openjarvis.cli import daemon_cmd
+
+ proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])
+ pid_file = tmp_path / "server.pid"
+ state_file = tmp_path / "server.json"
+ try:
+ pid_file.write_text(str(proc.pid))
+ os.utime(pid_file, (time.time() - 120, time.time() - 120))
+ with (
+ patch.object(daemon_cmd, "_PID_FILE", pid_file),
+ patch.object(daemon_cmd, "_STATE_FILE", state_file),
+ ):
+ assert daemon_cmd._read_pid() is None
+ assert not pid_file.exists()
+ assert proc.poll() is None
+ pid_file.write_text(str(proc.pid))
+ os.utime(pid_file, (time.time() - 120, time.time() - 120))
+ daemon_cmd._write_pid(os.getpid(), "127.0.0.1", 8000)
+ assert daemon_cmd._read_pid() == os.getpid()
+ assert proc.poll() is None
+ finally:
+ proc.terminate()
+ proc.wait()
+
class TestDaemonDetachment:
"""The spawned server must outlive the console that started it.