The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): reject a recycled PID that only matches start ticks
kinoko-senpaie68c489c96d0
diff --git a/gateway/host_rendezvous.py b/gateway/host_rendezvous.pyindex ee1f8c2dd2a..577f027978a 100644--- a/gateway/host_rendezvous.py+++ b/gateway/host_rendezvous.py@@ -102,7 +102,13 @@ class HostRecord:#: Stable process-start fingerprint. On Linux/WSL this is boot-relative /proc start ticks,#: so a wall-clock resync cannot make a live owner look like a recycled PID. Optional for#: records written by older Hermes versions, which still fall back to create_time.+ #: NOT unique across reboots — pair it with ``boot_epoch``.start_time: Optional[int] = None+ #: Instantiation epoch (boot id + PID 1 start). Distinguishes a pre-reboot owner from an+ #: early-boot process that reused its PID and landed inside the start-tick drift tolerance.+ #: Absent on older records; added WITHOUT a protocol bump, because a bump would make every+ #: live owner's record read as stale and a second gateway would start.+ boot_epoch: str = ""def to_json(self) -> dict[str, Any]:return {@@ -111,6 +117,7 @@ class HostRecord:"pid": self.pid,"createTime": self.create_time,"startTime": self.start_time,+ "bootEpoch": self.boot_epoch,"host": self.host,"port": self.port,"protocolVersion": self.protocol_version,@@ -141,6 +148,7 @@ class HostRecord:if isinstance(start, int) and not isinstance(start, bool) and start > 0else None),+ boot_epoch=str(payload.get("bootEpoch") or ""),host=str(payload.get("host") or ""),port=int(port) if isinstance(port, int) and 0 < port <= 65535 else None,protocol_version=version if isinstance(version, int) else 0,@@ -236,22 +244,97 @@ def _pid_incarnation_matches(pid: int, create_time: Optional[float]) -> Optionalreturn _pid_alive_matches(pid, create_time)+# Wall-clock create_time drifts by seconds on WSL (#117505). A reboot moves it by minutes+# and resets boot-relative start ticks, so a tick match within START_TIME_DRIFT_TOLERANCE+# after reboot is a recycled early PID, not the owner. 120s is far outside that drift and+# inside every reboot gap that has actually wedged a supervised gateway.+_LEGACY_CREATE_TIME_REBOOT_GAP_S = 120.0+++def _current_boot_epoch() -> str:+ """Identity of this boot. Empty when /proc is unreadable — then the check is a no-op."""+ try:+ from gateway.drain_control import current_instantiation_epoch++ return current_instantiation_epoch() or ""+ except Exception:+ logger.debug("boot epoch unreadable; host liveness will not use it", exc_info=True)+ return ""+++def _read_process_cmdline(pid: int) -> str:+ """Command line of ``pid``, or ``""`` when it cannot be read. Never raises."""+ try:+ raw = Path(f"/proc/{pid}/cmdline").read_bytes()+ if raw:+ return raw.replace(b"\x00", b" ").decode("utf-8", "replace")+ except OSError:+ pass+ try:+ import psutil++ return " ".join(psutil.Process(int(pid)).cmdline())+ except Exception:+ logger.debug("cmdline unreadable for pid %s", pid, exc_info=True)+ return ""+++def _cmdline_contradicts_gateway(pid: int) -> bool:+ """True only when the live command line is readable and cannot be a Hermes gateway.++ Unreadable cmdline, and this process, are not contradictions: a missing ``/proc`` or a+ test that publishes its own PID must not false-stale a live owner. A recycled PID whose+ start ticks fall inside the drift tolerance (``mpris-proxy`` after reboot) is.+ """+ if pid == os.getpid():+ return False+ cmd = _read_process_cmdline(pid).lower()+ if not cmd:+ return False+ return "hermes" not in cmd and "gateway" not in cmd++def _record_incarnation_matches(record: HostRecord) -> Optional[bool]:"""Whether the record still names the same live process incarnation.New records prefer the canonical start fingerprint: on Linux/WSL it comes from /proc start- ticks and is immune to wall-clock shifts that move psutil.create_time(). Legacy records keep- the create-time check until their owner republishes them.+ ticks and is immune to wall-clock shifts that move psutil.create_time(). Those ticks are+ NOT unique across reboots — they reset, and an early-boot PID reused within the drift+ tolerance looks like the dead owner. A published boot epoch, a command line that is not+ a gateway, or (for legacy records) a create_time gap past reboot scale, is a mismatch.+ Legacy records without a start fingerprint keep the create-time check."""+ recorded_epoch = getattr(record, "boot_epoch", "") or ""+ epoch = _current_boot_epoch()+ if recorded_epoch and epoch and recorded_epoch != epoch:+ return Falseif record.start_time is None:- return _pid_incarnation_matches(record.pid, record.create_time)- alive = _pid_incarnation_matches(record.pid, None)- if alive is not True:- return alive- from gateway.status import get_process_start_time, start_time_fingerprints_match-- current = get_process_start_time(record.pid)- return None if current is None else start_time_fingerprints_match(record.start_time, current)+ matched = _pid_incarnation_matches(record.pid, record.create_time)+ else:+ alive = _pid_incarnation_matches(record.pid, None)+ if alive is not True:+ return alive+ from gateway.status import get_process_start_time, start_time_fingerprints_match++ current = get_process_start_time(record.pid)+ matched = None if current is None else start_time_fingerprints_match(record.start_time, current)+ if matched is not True:+ return matched+ if record.role == ROLE_GATEWAY and _cmdline_contradicts_gateway(record.pid):+ return False+ if (+ record.role == ROLE_GATEWAY+ and not recorded_epoch+ and record.start_time is not None+ and record.create_time is not None+ ):+ live_create = process_create_time(record.pid)+ if (+ live_create is not None+ and abs(float(live_create) - float(record.create_time)) > _LEGACY_CREATE_TIME_REBOOT_GAP_S+ ):+ return False+ return Truedef record_is_stale(record: Optional[HostRecord]) -> bool:@@ -485,6 +568,7 @@ def publish_record(pid=os.getpid(),create_time=process_create_time(),start_time=get_process_start_time(os.getpid()),+ boot_epoch=_current_boot_epoch(),host=str(host or ""),port=int(port) if isinstance(port, int) and port > 0 else None,protocol_version=HOST_PROTOCOL_VERSION,diff --git a/tests/gateway/test_host_rendezvous.py b/tests/gateway/test_host_rendezvous.pyindex a592721fdd2..aa27d489f3a 100644--- a/tests/gateway/test_host_rendezvous.py+++ b/tests/gateway/test_host_rendezvous.py@@ -135,6 +135,45 @@ def test_live_host_record_survives_wall_clock_create_time_drift(host_dir, monkeyassert hr.record_is_stale(record) is True[email protected]("posix")+def test_reused_early_pid_after_reboot_is_not_the_gateway(monkeypatch):+ """Boot-relative start ticks reset on reboot and collide within the 2s drift tolerance.++ A legacy record (no bootEpoch) whose live PID is not a Hermes gateway must not keep a+ supervised unit in the transient-refuse loop. PID 1674 / ticks 827 vs 845 is the shape+ that wedged systemd against mpris-proxy.+ """+ record = hr.HostRecord(+ role=hr.ROLE_GATEWAY,+ pid=1674,+ create_time=1_700_000_000.0,+ start_time=827,+ host="",+ port=None,+ protocol_version=hr.HOST_PROTOCOL_VERSION,+ token_fingerprint="",+ profiles=("default",),+ updated_at="2026-01-01T00:00:00+00:00",+ )+ monkeypatch.setattr(hr, "_pid_incarnation_matches", lambda pid, create_time: True)+ monkeypatch.setattr(hr, "_cmdline_contradicts_gateway", lambda pid: True)+ from gateway import status++ monkeypatch.setattr(status, "get_process_start_time", lambda pid: 845)+ assert hr.liveness_is_proven(record) is False+ assert hr.record_is_stale(record) is True++[email protected]("posix")+def test_boot_epoch_mismatch_rejects_a_tick_match(host_dir):+ record = hr.publish_record(hr.ROLE_GATEWAY, profiles=("default",), home=str(host_dir))+ assert record is not None and record.boot_epoch+ foreign = dataclasses.replace(record, boot_epoch=record.boot_epoch + "-other-boot")+ assert hr.liveness_is_proven(record) is True+ assert hr.liveness_is_proven(foreign) is False+ assert hr.record_is_stale(foreign) is True++@pytest.mark.platforms("posix") # POSIX signal dispositiondef test_sigterm_removes_the_record_and_its_live_session_token(host_dir):"""SIGTERM is the NORMAL stop (systemd stop, docker stop, the update relaunch) and it does not