Personal AI, On Personal Devices
Python
fix(cli): persist stable Linux daemon process identities
Elliot Slusky7620b2506be9
diff --git a/src/openjarvis/cli/daemon_cmd.py b/src/openjarvis/cli/daemon_cmd.pyindex 0d1bd05e..12d633f4 100644--- a/src/openjarvis/cli/daemon_cmd.py+++ b/src/openjarvis/cli/daemon_cmd.py@@ -33,27 +33,100 @@ 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+def _linux_process_identity(pid: int) -> dict | None:+ """Read a process identity unaffected by wall-clock adjustments.++ Linux's boot epoch changes when the clock is set; boot_id and start ticks+ do not. Both are needed because PIDs and start ticks can repeat after boot.+ """if sys.platform != "linux":- return True+ return Nonetry:# 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.+ boot_id = Path("/proc/sys/kernel/random/boot_id").read_text().strip()+ if start_ticks < 0 or not boot_id:+ return None+ return {"pid": pid, "boot_id": boot_id, "start_ticks": start_ticks}+ except (OSError, ValueError, IndexError):+ return None+++def _read_pid_identity() -> dict:+ """Read the optional Linux identity sidecar, preserving legacy PID files."""+ try:+ identity = json.loads(_PID_FILE.with_suffix(".identity.json").read_text())+ except (OSError, ValueError):+ return {}+ if (+ not isinstance(identity, dict)+ or type(identity.get("pid")) is not int+ or identity["pid"] <= 0+ or type(identity.get("start_ticks")) is not int+ or identity["start_ticks"] < 0+ or not isinstance(identity.get("boot_id"), str)+ or not identity["boot_id"]+ ):+ return {}+ return identity+++def _legacy_linux_daemon(pid: int) -> bool | None:+ """Recognize an old registration before it has a saved process identity."""+ try:+ argv = [+ os.fsdecode(arg)+ for arg in Path(f"/proc/{pid}/cmdline").read_bytes().split(b"\0")+ if arg+ ]+ except OSError:+ return None+ # Console entry points are either argv[0] or the script passed to Python.+ for index in (0, 1):+ if len(argv) > index and Path(argv[index]).name in {"jarvis", "jarvis.exe"}:+ command = argv[index + 1 :]+ break+ else:+ # `start` uses this form; supervised servers may add interpreter flags.+ try:+ index = argv.index("-m")+ except ValueError:+ return False+ if "-c" in argv[:index] or argv[index + 1 : index + 2] != ["openjarvis.cli"]:+ return False+ command = argv[index + 2 :]+ return next((arg for arg in command if not arg.startswith("-")), None) == "serve"+++def _registered_pid_alive(pid: int) -> bool:+ """Reject reused Linux PIDs without comparing mutable wall-clock times."""+ if not _pid_alive(pid):+ return False+ if sys.platform != "linux":+ return True+ current = _linux_process_identity(pid)+ if current is None:+ # Restricted or unmounted procfs must not orphan a live daemon.return True+ recorded = _read_pid_identity()+ if recorded.get("pid") == pid:+ return current == recorded+ # A legacy file has no historical identity to compare. Do not adopt an+ # arbitrary live process just because its PID was recycled. Once verified,+ # migrate the registration while the caller holds the state lock.+ is_daemon = _legacy_linux_daemon(pid)+ if is_daemon is False:+ return False+ if is_daemon:+ # Do not pair an old start tick with a replacement process's command.+ confirmed = _linux_process_identity(pid)+ if confirmed is not None and confirmed != current:+ return False+ if confirmed is not None:+ secure_write_json(_PID_FILE.with_suffix(".identity.json"), confirmed)+ return True@contextmanager@@ -98,6 +171,8 @@ def _clear_state_unlocked(pid: int) -> None:_PID_FILE.unlink(missing_ok=True)if _read_state().get("pid") == pid:_STATE_FILE.unlink(missing_ok=True)+ if _read_pid_identity().get("pid") == pid:+ _PID_FILE.with_suffix(".identity.json").unlink(missing_ok=True)def _read_pid_unlocked() -> int | None:@@ -158,6 +233,11 @@ def _write_pid_unlocked(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})")+ identity = _linux_process_identity(pid)+ if identity is not None:+ secure_write_json(_PID_FILE.with_suffix(".identity.json"), identity)+ else:+ _PID_FILE.with_suffix(".identity.json").unlink(missing_ok=True)secure_write_text(_PID_FILE, str(pid))if host or port is not None:state = {"pid": pid, "host": host, "port": port}diff --git a/tests/cli/test_daemon_cmd.py b/tests/cli/test_daemon_cmd.pyindex 9d8ee322..e0502530 100644--- a/tests/cli/test_daemon_cmd.py+++ b/tests/cli/test_daemon_cmd.py@@ -129,9 +129,13 @@ class TestPidLiveness:proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(10)"])try:pid_file = tmp_path / "server.pid"- pid_file.write_text(str(proc.pid))-- with patch("openjarvis.cli.daemon_cmd._PID_FILE", pid_file):+ with (+ patch("openjarvis.cli.daemon_cmd._PID_FILE", pid_file),+ patch(+ "openjarvis.cli.daemon_cmd._STATE_FILE", tmp_path / "server.json"+ ),+ ):+ _write_pid(proc.pid)assert _read_pid() == proc.pidassert pid_file.exists()diff --git a/tests/cli/test_daemon_identity.py b/tests/cli/test_daemon_identity.pynew file mode 100644index 00000000..426ee7ed--- /dev/null+++ b/tests/cli/test_daemon_identity.py@@ -0,0 +1,208 @@+"""Daemon registrations survive clock changes without accepting recycled PIDs."""++from __future__ import annotations++import json+import os+from pathlib import Path+from unittest.mock import Mock++import pytest+from click.testing import CliRunner++from openjarvis.cli import daemon_cmd+++def linux_process(tmp_path, monkeypatch):+ """Provide deterministic procfs data while using real registration files."""+ monkeypatch.setattr(daemon_cmd, "_PID_FILE", tmp_path / "server.pid")+ monkeypatch.setattr(daemon_cmd, "_STATE_FILE", tmp_path / "server.json")+ monkeypatch.setattr(daemon_cmd, "DEFAULT_CONFIG_DIR", tmp_path)+ monkeypatch.setattr(daemon_cmd.sys, "platform", "linux")+ monkeypatch.setattr(daemon_cmd, "_pid_alive", lambda pid: True)+ process = {+ "boot_id": "70ec59ac-d41e-48ea-81a4-673a7d1f996b",+ "starts": {4321: 10000, 9876: 20000},+ "argv": ["/usr/bin/python3", "-m", "openjarvis.cli", "serve"],+ "readable": True,+ }+ read_text = Path.read_text+ read_bytes = Path.read_bytes++ def proc_text(path, *args, **kwargs):+ if str(path).startswith("/proc/"):+ if not process["readable"]:+ raise PermissionError("procfs unavailable")+ if str(path) == "/proc/sys/kernel/random/boot_id":+ return process["boot_id"] + "\n"+ if path.name == "stat" and path.parent.name.isdecimal():+ pid = int(path.parent.name)+ # Fields 4..21 follow state; field 22 is the start tick count.+ fields = ["S", *(["0"] * 18), str(process["starts"][pid])]+ return f"{pid} (python (worker)) " + " ".join(fields)+ raise AssertionError(f"Unexpected wall-clock procfs read: {path}")+ return read_text(path, *args, **kwargs)++ def proc_bytes(path, *args, **kwargs):+ if str(path).startswith("/proc/"):+ if not process["readable"]:+ raise PermissionError("procfs unavailable")+ assert path.name == "cmdline"+ return b"\0".join(os.fsencode(arg) for arg in process["argv"]) + b"\0"+ return read_bytes(path, *args, **kwargs)++ monkeypatch.setattr(Path, "read_text", proc_text)+ monkeypatch.setattr(Path, "read_bytes", proc_bytes)+ return process++[email protected]("mtime", [1, 1700000100.5, 2000000000])+def test_clock_adjustment_does_not_discard_registered_daemon(linux_process, mtime):+ daemon_cmd._write_pid(4321, "127.0.0.1", 8899)+ identity = daemon_cmd._read_pid_identity()+ assert identity == {+ "pid": 4321,+ "boot_id": linux_process["boot_id"],+ "start_ticks": 10000,+ }++ os.utime(daemon_cmd._PID_FILE, (mtime, mtime))++ assert daemon_cmd._read_pid() == 4321+ assert daemon_cmd._bound_address() == ("127.0.0.1", 8899)+ assert daemon_cmd._read_pid_identity() == identity+++def test_recycled_pid_is_never_signaled(linux_process, monkeypatch):+ daemon_cmd._write_pid(4321, "127.0.0.1", 8899)+ # A one-tick difference is enough, even in the same wall-clock second.+ linux_process["starts"][4321] += 1+ terminate = Mock()+ monkeypatch.setattr(daemon_cmd, "terminate_process", terminate)++ result = CliRunner().invoke(daemon_cmd.stop)++ assert result.exit_code == 1+ assert "No running server" in result.output+ terminate.assert_not_called()+ assert not daemon_cmd._PID_FILE.exists()+ assert not daemon_cmd._STATE_FILE.exists()+ assert daemon_cmd._read_pid_identity() == {}+ daemon_cmd._write_pid(9876, "127.0.0.1", 8900)+ assert daemon_cmd._read_pid() == 9876+++def test_reboot_rejects_even_an_identical_pid_and_start_tick(linux_process):+ daemon_cmd._write_pid(4321, "127.0.0.1", 8899)+ linux_process["boot_id"] = "f7a07684-5a47-475b-b3da-0f507296996a"++ assert daemon_cmd._read_pid() is None+ assert not daemon_cmd._PID_FILE.exists()+++ "argv",+ [+ ["/venv/bin/jarvis", "serve"],+ ["/venv/bin/python3", "/venv/bin/jarvis", "--quiet", "serve"],+ ["/venv/bin/python3", "-u", "-m", "openjarvis.cli", "serve"],+ ],+)+def test_live_legacy_daemon_is_migrated_without_wall_clock(linux_process, argv):+ daemon_cmd._PID_FILE.write_text("4321")+ os.utime(daemon_cmd._PID_FILE, (1, 1))+ linux_process["argv"] = argv++ assert daemon_cmd._read_pid() == 4321+ assert daemon_cmd._read_pid_identity()["start_ticks"] == 10000+ linux_process["starts"][4321] += 1+ assert daemon_cmd._read_pid() is None+++ "argv",+ [+ ["/usr/bin/python3", "-c", "import time; time.sleep(30)"],+ ["/venv/bin/jarvis", "ask", "serve"],+ ["/usr/bin/python3", "-m", "other", "-m", "openjarvis.cli", "serve"],+ ],+)+def test_legacy_unrelated_process_is_not_adopted_or_signaled(+ linux_process, monkeypatch, argv+):+ daemon_cmd._PID_FILE.write_text("4321")+ linux_process["argv"] = argv+ terminate = Mock()+ monkeypatch.setattr(daemon_cmd, "terminate_process", terminate)++ result = CliRunner().invoke(daemon_cmd.stop)++ assert result.exit_code == 1+ terminate.assert_not_called()+ assert not daemon_cmd._PID_FILE.exists()++[email protected]("legacy", [False, True])+def test_unavailable_procfs_does_not_orphan_a_live_daemon(linux_process, legacy):+ if legacy:+ daemon_cmd._PID_FILE.write_text("4321")+ else:+ daemon_cmd._write_pid(4321, "127.0.0.1", 8899)+ identity = daemon_cmd._read_pid_identity()+ linux_process["readable"] = False++ assert daemon_cmd._read_pid() == 4321+ assert daemon_cmd._read_pid_identity() == identity+++def test_legacy_migration_rechecks_identity_after_reading_command(+ linux_process, monkeypatch+):+ daemon_cmd._PID_FILE.write_text("4321")+ read_bytes = Path.read_bytes++ def recycled_after_read(path, *args, **kwargs):+ result = read_bytes(path, *args, **kwargs)+ if str(path) == "/proc/4321/cmdline":+ linux_process["starts"][4321] += 1+ return result++ monkeypatch.setattr(Path, "read_bytes", recycled_after_read)++ assert daemon_cmd._read_pid() is None+ assert daemon_cmd._read_pid_identity() == {}+++def test_child_promotion_preserves_the_child_identity(linux_process):+ daemon_cmd._write_pid(4321, "127.0.0.1", 0, ready=False, launch_token="launch-a")+ daemon_cmd._write_pid(9876, "127.0.0.1", 8899, launch_token="launch-a")+ daemon_cmd._write_pid(4321, "127.0.0.1", 0, ready=False, launch_token="launch-a")++ assert daemon_cmd._read_pid() == 9876+ assert daemon_cmd._read_pid_identity()["start_ticks"] == 20000+ assert daemon_cmd._bound_address() == ("127.0.0.1", 8899)+ daemon_cmd.clear_server_state(4321)+ assert daemon_cmd._read_pid_identity()["pid"] == 9876++[email protected]("platform", ["darwin", "win32"])+def test_non_linux_legacy_liveness_is_unchanged(linux_process, monkeypatch, platform):+ # The mocked lock must still use this test host's filesystem locking API.+ monkeypatch.setattr(daemon_cmd.sys, "platform", platform)+ linux_process["readable"] = False+ daemon_cmd._write_pid(4321, "127.0.0.1", 8899)++ assert daemon_cmd._read_pid() == 4321+ assert daemon_cmd._read_pid_identity() == {}+++ "identity", [[], {"pid": True}, {"pid": 4321, "boot_id": "boot", "start_ticks": -1}]+)+def test_corrupt_identity_uses_legacy_verification(linux_process, identity):+ daemon_cmd._PID_FILE.write_text("4321")+ daemon_cmd._PID_FILE.with_suffix(".identity.json").write_text(json.dumps(identity))+ linux_process["argv"] = ["/usr/bin/sleep", "100"]++ assert daemon_cmd._read_pid() is None