The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): stabilize host rendezvous process identity
JoaoMarcos4442fb720c7337
diff --git a/gateway/host_rendezvous.py b/gateway/host_rendezvous.pyindex f7c274fefd8..c799a100546 100644--- a/gateway/host_rendezvous.py+++ b/gateway/host_rendezvous.py@@ -15,17 +15,19 @@ which scopes to the **OS user**. That is the correct granularity: separate OS usseparate ``$HOME``s, separate ``~/.hermes`` profile roots, separate ports-by-convention andseparate credentials, so "one per host" means "one per host per OS user".-**Staleness is proved, never assumed.** A record carries ``(pid, createTime)``; a record whose-PID is dead, or whose PID is alive with a different process creation time (PID reuse), is-STALE and is ignored — an attaching client must never dial a recycled PID's port.+**Staleness is proved, never assumed.** New records pair the PID with the repository's stable+process-start fingerprint (boot-relative on Linux/WSL); ``createTime`` remains the legacy fallback.+A dead PID or a mismatched process incarnation is STALE and ignored — an attaching client must+never dial a recycled PID's port.**Relationship to ``spawn-ledger.json``** (``hermes_cli/process_identity.py``): the ledger staysthe append-only machine roster of every long-lived Hermes process (Desktop's attach ladder readsit) and is still written unchanged. It cannot be the host record: it has no lock, nosingle-writer semantics, no removal on exit, and no place to publish a protocol version oran authentication handle. The record here is authoritative for "who owns this host role"; the-ledger remains authoritative for "what is running". Both are written, and this module reuses the-ledger's ``(pid, create_time)`` liveness proof rather than inventing a second one.+ledger remains authoritative for "what is running". Both are written. New host records pair the+ledger's live-PID proof with ``gateway.status``'s canonical process-start fingerprint; legacy+records without that fingerprint keep the old ``(pid, create_time)`` proof."""from __future__ import annotations@@ -97,6 +99,10 @@ class HostRecord:#: WITHOUT a protocol bump on purpose, because a bump would make every live owner's record read#: as stale and a second gateway would start.home: str = ""+ #: 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.+ start_time: Optional[int] = Nonedef to_json(self) -> dict[str, Any]:return {@@ -104,6 +110,7 @@ class HostRecord:"home": self.home,"pid": self.pid,"createTime": self.create_time,+ "startTime": self.start_time,"host": self.host,"port": self.port,"protocolVersion": self.protocol_version,@@ -121,6 +128,7 @@ class HostRecord:if not isinstance(pid, int) or pid <= 0 or role not in _ROLES:return Nonecreate = payload.get("createTime")+ start = payload.get("startTime")port = payload.get("port")profiles = payload.get("profiles")version = payload.get("protocolVersion")@@ -128,6 +136,11 @@ class HostRecord:role=role,pid=pid,create_time=float(create) if isinstance(create, (int, float)) else None,+ start_time=(+ int(start)+ if isinstance(start, int) and not isinstance(start, bool) and start > 0+ else None+ ),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,@@ -223,6 +236,24 @@ def _pid_incarnation_matches(pid: int, create_time: Optional[float]) -> Optionalreturn _pid_alive_matches(pid, create_time)+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.+ """+ if 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)++def record_is_stale(record: Optional[HostRecord]) -> bool:"""A record nobody may attach to: absent, unknown protocol, dead PID, or PID reuse.@@ -237,12 +268,12 @@ def record_is_stale(record: Optional[HostRecord]) -> bool:return Trueif record.protocol_version != HOST_PROTOCOL_VERSION:return True- return _pid_incarnation_matches(record.pid, record.create_time) is False+ return _record_incarnation_matches(record) is Falsedef liveness_is_proven(record: HostRecord) -> bool:- """True only when the PID+createTime probe positively matched (never on ``None``)."""- return _pid_incarnation_matches(record.pid, record.create_time) is True+ """True only when the record's process-incarnation probe positively matched (never on ``None``)."""+ return _record_incarnation_matches(record) is Truedef dial_host(record: HostRecord) -> str:@@ -447,10 +478,13 @@ def publish_record(control socket."""role = _validated_role(role)+ from gateway.status import get_process_start_time+record = HostRecord(role=role,pid=os.getpid(),create_time=process_create_time(),+ start_time=get_process_start_time(os.getpid()),host=str(host or ""),port=int(port) if isinstance(port, int) and port > 0 else None,protocol_version=HOST_PROTOCOL_VERSION,@@ -492,7 +526,7 @@ def discard_dead_record(role: str) -> bool:record = read_record(role, include_stale=True)if record is None:return False- if record.pid != os.getpid() and _pid_incarnation_matches(record.pid, record.create_time) is not False:+ if record.pid != os.getpid() and _record_incarnation_matches(record) is not False:return Falsefor path in (record_path(role), token_path(role)):with contextlib.suppress(OSError):diff --git a/tests/gateway/test_host_rendezvous.py b/tests/gateway/test_host_rendezvous.pyindex 2c3e7702935..1a801c44d60 100644--- a/tests/gateway/test_host_rendezvous.py+++ b/tests/gateway/test_host_rendezvous.py@@ -108,6 +108,36 @@ def test_stale_record_is_never_attachable(host_dir, pid, create_time):assert hr.read_record(hr.ROLE_SERVE, include_stale=True) is not None[email protected]("linux")+def test_live_host_record_survives_wall_clock_create_time_drift(host_dir, monkeypatch):+ """WSL can shift psutil.create_time() for the same live PID while /proc start ticks stay fixed.++ The host record must keep recognizing that owner, but a changed stable start fingerprint must+ still be rejected as PID reuse.+ """+ record = hr.publish_record(hr.ROLE_GATEWAY, profiles=("default",), home=str(host_dir))+ assert record is not None++ # Model the exact WSL failure family: the legacy epoch check says the same PID changed,+ # while a liveness-only PID probe still proves the process itself is alive.+ monkeypatch.setattr(+ hr, "_pid_incarnation_matches",+ lambda _pid, create_time: True if create_time is None else False,+ )+ assert hr.record_is_stale(record) is False+ assert hr.liveness_is_proven(record) is True+ assert hr.read_record(hr.ROLE_GATEWAY) is not None++ assert record.start_time is not None+ from gateway import status++ monkeypatch.setattr(+ status, "get_process_start_time",+ lambda _pid: record.start_time + status.START_TIME_DRIFT_TOLERANCE + 1,+ )+ assert hr.record_is_stale(record) 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