Skip to content

The agent that grows with you

fix(local-runtime): identify the managed server by boot-relative start time

emozilla22b75e0b857f
diff --git a/hermes_cli/local_runtime/recovery.py b/hermes_cli/local_runtime/recovery.py
index fd8f1926e32..c4a08b94357 100644
--- a/hermes_cli/local_runtime/recovery.py
+++ b/hermes_cli/local_runtime/recovery.py
@@ -37,6 +37,19 @@ def _valid_birth(value) -> bool:
return type(value) in (int, float) and math.isfinite(value) and value > 0
+def _same_birth(proc, state: dict, prefix: str = "") -> bool:
+ """Linux derives psutil's create_time from /proc/stat's boot time, which moves whenever the
+ clock is stepped (WSL re-syncs within minutes), so a live process stops matching its record.
+ The start_time fingerprint is boot-relative there; create_time is for records that predate it."""
+ from gateway.status import get_process_start_time, start_time_fingerprints_match
+
+ recorded = state.get(f"{prefix}start_time")
+ if not _valid_birth(recorded):
+ return proc.create_time() == state[f"{prefix}create_time"]
+ current = get_process_start_time(proc.pid)
+ return current is not None and start_time_fingerprints_match(recorded, current)
+
+
def recorded_process(state: dict):
"""Match a modern process incarnation, never just its reusable PID."""
try:
@@ -48,7 +61,7 @@ def recorded_process(state: dict):
or owner_created > created or not isinstance(exe, str) or not exe):
return None
proc = psutil.Process(pid)
- if (not proc.is_running() or proc.create_time() != created
+ if (not proc.is_running() or not _same_birth(proc, state)
or Path(proc.exe()) != Path(exe)):
return None
# Windows retains the original parent PID; POSIX reparents orphans.
@@ -57,7 +70,7 @@ def recorded_process(state: dict):
parent = proc.parent()
if parent is not None:
if parent.pid == owner_pid:
- if parent.create_time() != owner_created:
+ if not _same_birth(parent, state, "owner_"):
return None
elif os.name == "nt" or not _owner_is_dead(state):
return None # POSIX may reparent a router whose recorded owner exited.
@@ -74,7 +87,7 @@ def _owner_is_dead(state: dict) -> bool:
try:
owner = psutil.Process(pid)
# A newer incarnation proves the recorded owner has exited.
- return owner.create_time() > created or not owner.is_running()
+ return not owner.is_running() or not _same_birth(owner, state, "owner_")
except psutil.NoSuchProcess:
return True
except (KeyError, TypeError, ValueError, OverflowError, OSError, psutil.Error):
diff --git a/hermes_cli/local_runtime/supervisor.py b/hermes_cli/local_runtime/supervisor.py
index e95839ec552..d782a067c2e 100644
--- a/hermes_cli/local_runtime/supervisor.py
+++ b/hermes_cli/local_runtime/supervisor.py
@@ -223,13 +223,17 @@ class LlamaServerSupervisor:
def _write_state(self) -> None:
import os
import psutil
+ from gateway.status import get_process_start_time
from utils import atomic_json_write
proc = psutil.Process(self.proc.pid)
+ # create_time stays for runtimes that predate start_time.
self._state = {"base_url": self.base_url, "api_key": self.api_key,
"pid": proc.pid, "create_time": proc.create_time(),
+ "start_time": get_process_start_time(proc.pid),
"executable": proc.exe(), "owner_pid": os.getpid(),
- "owner_create_time": psutil.Process().create_time()}
+ "owner_create_time": psutil.Process().create_time(),
+ "owner_start_time": get_process_start_time(os.getpid())}
path = state_path()
from hermes_constants import mkdir_under_hermes_home
mkdir_under_hermes_home(path.parent)
diff --git a/tests/hermes_cli/test_local_runtime_recovery.py b/tests/hermes_cli/test_local_runtime_recovery.py
index 2fab899d9f3..0d3accad57c 100644
--- a/tests/hermes_cli/test_local_runtime_recovery.py
+++ b/tests/hermes_cli/test_local_runtime_recovery.py
@@ -392,6 +392,31 @@ print(json.dumps({'pid': proc.pid, 'create_time': proc.create_time(), 'executabl
owner.stdout.close()
+def test_clock_step_keeps_the_recorded_router(tmp_path, monkeypatch):
+ """psutil's create_time moves with /proc/stat's boot time when the clock is stepped (WSL
+ re-syncs within minutes); the live router must still resolve, and a reused PID must not."""
+ import psutil._pslinux
+ from hermes_cli.local_runtime import endpoint, supervisor
+
+ monkeypatch.setattr(supervisor, "runtimes_root", lambda: tmp_path)
+ sup = supervisor.LlamaServerSupervisor(tmp_path, tmp_path, port=59998)
+ proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ try:
+ sup.proc = proc
+ sup._write_state()
+ stepped = psutil._pslinux.boot_time() + 22
+ monkeypatch.setattr(psutil._pslinux, "boot_time", lambda: stepped)
+ assert endpoint._state_endpoint() == {"base_url": sup.base_url, "api_key": sup.api_key}
+
+ state = json.loads(supervisor.state_path().read_text())
+ supervisor.state_path().write_text(json.dumps({**state, "start_time": state["start_time"] - 1000}))
+ assert endpoint._state_endpoint() is None
+ finally:
+ proc.kill()
+ proc.wait(timeout=5)
+
+
@pytest.mark.platforms("windows")
@pytest.mark.parametrize("damage", ["valid", "birth", "exe", "bool-pid", "bool-birth", "nan", "inf", "owner-bool", "owner-nan", "parent", "partial", "list", "invalid", "unreadable"])
def test_retained_endpoint_validates_identity(tmp_path, monkeypatch, damage):