The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): every reader that trusts a host record as a live owner checks the host lock
Teknium8a465ede756a
diff --git a/gateway/host_attach.py b/gateway/host_attach.pyindex 88fe4a8312d..4d6d41f8980 100644--- a/gateway/host_attach.py+++ b/gateway/host_attach.py@@ -200,17 +200,9 @@ def _probe_host_gateway(wait_for_channel: float) -> Optional[HostGateway]:return None# Liveness BEFORE the dial. A record we cannot prove live must not make us open a socket at an# address it chose; proving the PID first is also what keeps a stale record from naming a peer.- if not hr.liveness_is_proven(record):- return None- # Every live publisher holds host-gateway.lock for its lifetime; the OS releases it on- # death. A leftover record can still name a live pid (recycle, or start-tick collision- # after reboot). If the flock is free, that pid is not the owner — treating it as a- # silent-but-live gateway is the never-expiring transient refuse (#138343, #133744).- if hr.host_lock_is_held(record.role) is False:- logger.info(- "Host record names pid %s but the host lock is free; treating the owner as gone.",- record.pid,- )+ # A free host lock falsifies a pid that merely looks alive: treating it as a silent-but-live+ # gateway is the never-expiring transient refuse (#138343, #133744).+ if not hr.record_names_live_owner(record):return Nonehome = record_home(record)deadline = time.monotonic() + max(0.0, wait_for_channel)diff --git a/gateway/host_rendezvous.py b/gateway/host_rendezvous.pyindex 94641d22c1a..3659c784d23 100644--- a/gateway/host_rendezvous.py+++ b/gateway/host_rendezvous.py@@ -491,6 +491,21 @@ def host_lock_is_held(role: str) -> Optional[bool]:return _probe_lock_file(handle)+def record_names_live_owner(record: HostRecord) -> bool:+ """True when ``record``'s incarnation is proven AND its host lock is not observed free.++ The publisher holds the host lock for its whole life and the OS drops it on death, so a free+ flock falsifies a record whose pid merely looks alive (recycle, start-tick collision after a+ reboot — #138343, #133744). Every reader that trusts a record as a running owner uses this.+ """+ if not liveness_is_proven(record):+ return False+ if host_lock_is_held(record.role) is False:+ logger.debug("host %s record names pid %s but the host lock is free", record.role, record.pid)+ return False+ return True++def publish_record(role: str,*,diff --git a/gateway/host_topology.py b/gateway/host_topology.pyindex 9cfeb82f1f8..d8438654967 100644--- a/gateway/host_topology.py+++ b/gateway/host_topology.py@@ -66,7 +66,7 @@ def _from_host_record() -> Optional[HostGatewayTopology]:# turn a leftover record into a permanent "running" lie on every surface. A record with no# recorded createTime is exactly that — ``_same_incarnation`` treats ``None`` as "matches", so# liveness_is_proven() would bless ANY process that happens to hold the recorded PID today.- if record.create_time is None or not hr.liveness_is_proven(record):+ if record.create_time is None or not hr.record_names_live_owner(record):return Nonefrom gateway.host_attach import launched_by_other_tenant, record_homefrom hermes_constants import get_hermes_homediff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex 11b213bca14..8d578cd8e94 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -1387,7 +1387,7 @@ class GatewayShutdownMixin(GatewaySessionEndMixin):try:from gateway import host_rendezvous as hrrecord = hr.read_record(hr.ROLE_GATEWAY)- if record is not None and hr.liveness_is_proven(record) and len(record.profiles) > 1:+ if record is not None and hr.record_names_live_owner(record) and len(record.profiles) > 1:multiplex = Trueexcept Exception:multiplex = Falsediff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex ddc9330b38f..19b3f60f258 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -1039,7 +1039,7 @@ def _restart_argv_is_host_gateway(argv: list[str]) -> bool:try:from gateway import host_rendezvous as hrrecord = hr.read_record(hr.ROLE_GATEWAY)- if record is not None and hr.liveness_is_proven(record) and len(record.profiles) > 1:+ if record is not None and hr.record_names_live_owner(record) and len(record.profiles) > 1:return Trueexcept Exception:passdiff --git a/tests/gateway/test_host_topology.py b/tests/gateway/test_host_topology.pyindex b3fb8b70ba4..0c57fd4f6b7 100644--- a/tests/gateway/test_host_topology.py+++ b/tests/gateway/test_host_topology.py@@ -19,8 +19,11 @@ def host_gateway(tmp_path, monkeypatch):locks.mkdir()monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(locks))monkeypatch.setattr("hermes_constants.get_default_hermes_root", lambda: root)+ # A live owner holds the host lock for its lifetime (run.py claims before it publishes).+ assert hr.claim_host_lock(hr.ROLE_GATEWAY)[0] is hr.HostLockOutcome.ACQUIREDhr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "coder"))- return root+ yield root+ hr.release_host_lock(hr.ROLE_GATEWAY)def test_default_home_is_reported_as_served_by_the_host_gateway(host_gateway):@@ -74,7 +77,7 @@ def test_record_without_createtime_is_never_the_host_gateway(host_gateway, monkeassert host_topology.host_gateway_topology() is None-def test_topology_ignores_another_tenants_record_and_reads_the_launch_homes_state(tmp_path, monkeypatch):+def test_topology_ignores_another_tenants_record_and_reads_the_launch_homes_state(tmp_path, monkeypatch, request):"""#121352 reporting half: a record from ANOTHER Hermes root is not this tenant's host gateway(doctor / cron status / the dashboard ladder), and a NAMED-hosted multiplexer's platforms are readfrom the home that launched it, not from a stale standalone record at the default root."""@@ -91,6 +94,9 @@ def test_topology_ignores_another_tenants_record_and_reads_the_launch_homes_statmonkeypatch.setenv("HERMES_HOME", str(root_b))monkeypatch.setattr("hermes_constants._default_hermes_root_memo", None)+ # A live owner holds the host lock for its lifetime (run.py claims before it publishes).+ assert hr.claim_host_lock(hr.ROLE_GATEWAY)[0] is hr.HostLockOutcome.ACQUIRED+ request.addfinalizer(lambda: hr.release_host_lock(hr.ROLE_GATEWAY))hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "coder"), home=str(root_a))assert host_topology.host_gateway_topology() is None@@ -106,3 +112,39 @@ def test_topology_ignores_another_tenants_record_and_reads_the_launch_homes_statresolved = status.multiplexer_liveness_for_profile(root_b)assert resolved is not None and resolved[0] == os.getpid()assert set(resolved[1]["platforms"]) == {"telegram"}+++def test_a_live_looking_pid_with_a_free_host_lock_is_not_the_host_gateway(tmp_path, monkeypatch):+ """#133744 start-tick collision: createTime matches a recycled pid after a reboot, yet nothing+ holds the host lock. Topology/status (and the update/shutdown multiplex checks that share the+ predicate) must not report that pid as the running host gateway."""+ import json+ import subprocess+ import sys++ from gateway import host_rendezvous as hr+ from gateway import host_topology+ from gateway.status import get_process_start_time++ root = tmp_path / "hermes"+ root.mkdir()+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))+ monkeypatch.setenv("HERMES_HOME", str(root))+ monkeypatch.setattr("hermes_constants._default_hermes_root_memo", None)+ monkeypatch.setattr("hermes_cli.gateway_multiplex_served.live_default_gateway_pid", lambda: None)+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])+ try:+ hr.ensure_host_state_dir()+ hr.record_path(hr.ROLE_GATEWAY).write_text(json.dumps({+ "role": hr.ROLE_GATEWAY, "home": str(root), "pid": child.pid,+ "createTime": hr.process_create_time(child.pid),+ "startTime": get_process_start_time(child.pid), "host": "", "port": None,+ "protocolVersion": hr.HOST_PROTOCOL_VERSION, "tokenFingerprint": "",+ "profiles": ["default", "coder"], "updatedAt": "",+ }), encoding="utf-8")+ record = hr.read_record(hr.ROLE_GATEWAY)+ assert record is not None and hr.liveness_is_proven(record) # the pid really looks alive+ assert host_topology.host_gateway_topology() is None+ finally:+ child.kill()+ child.wait(timeout=10)diff --git a/tests/hermes_cli/test_cron_satellite_diagnostics.py b/tests/hermes_cli/test_cron_satellite_diagnostics.pyindex fa1f5a2dec5..ad23bdd7817 100644--- a/tests/hermes_cli/test_cron_satellite_diagnostics.py+++ b/tests/hermes_cli/test_cron_satellite_diagnostics.py@@ -84,7 +84,7 @@ def test_status_preserves_profile_health_contract(served_root, capsys, monkeypatassert "STALLED" not in output-def test_host_record_rung_names_the_roster_and_a_runnable_restart(served_root, capsys, monkeypatch):+def test_host_record_rung_names_the_roster_and_a_runnable_restart(served_root, capsys, monkeypatch, request):"""The OTHER rung: a published host record answers before the config-derived one.Both rungs print a "Scheduler host: the host gateway…" line, so they are only distinguishable@@ -96,6 +96,9 @@ def test_host_record_rung_names_the_roster_and_a_runnable_restart(served_root, cfrom gateway import host_rendezvous as hrfrom hermes_cli import cron+ # A live owner holds the host lock for its lifetime (run.py claims before it publishes).+ assert hr.claim_host_lock(hr.ROLE_GATEWAY)[0] is hr.HostLockOutcome.ACQUIRED+ request.addfinalizer(lambda: hr.release_host_lock(hr.ROLE_GATEWAY))hr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "probe"))cron.cron_status()diff --git a/tests/hermes_cli/test_multiplex_host_topology_reporting.py b/tests/hermes_cli/test_multiplex_host_topology_reporting.pyindex 51a40f7feba..9bb8aee8e5a 100644--- a/tests/hermes_cli/test_multiplex_host_topology_reporting.py+++ b/tests/hermes_cli/test_multiplex_host_topology_reporting.py@@ -32,8 +32,11 @@ def served_host(tmp_path, monkeypatch):monkeypatch.setattr("hermes_constants.get_default_hermes_root", lambda: root)monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", list)monkeypatch.setattr("gateway.status.is_gateway_runtime_lock_active", lambda lock_path=None: False)+ # A live owner holds the host lock for its lifetime (run.py claims before it publishes).+ assert hr.claim_host_lock(hr.ROLE_GATEWAY)[0] is hr.HostLockOutcome.ACQUIREDhr.publish_record(hr.ROLE_GATEWAY, profiles=("default", "served"))- return root+ yield root+ hr.release_host_lock(hr.ROLE_GATEWAY)def test_cron_status_names_the_host_gateway_for_a_served_profile(served_host, capsys, monkeypatch):