Skip to content

The agent that grows with you

fix(gateway): a free host lock falsifies a leftover rendezvous owner

joaomarcos5fdf0e80474c
diff --git a/gateway/host_attach.py b/gateway/host_attach.py
index 4ae6794a0b5..88fe4a8312d 100644
--- a/gateway/host_attach.py
+++ b/gateway/host_attach.py
@@ -202,6 +202,16 @@ def _probe_host_gateway(wait_for_channel: float) -> Optional[HostGateway]:
# 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,
+ )
+ return None
home = record_home(record)
deadline = time.monotonic() + max(0.0, wait_for_channel)
while True:
diff --git a/gateway/host_rendezvous.py b/gateway/host_rendezvous.py
index ee1f8c2dd2a..94641d22c1a 100644
--- a/gateway/host_rendezvous.py
+++ b/gateway/host_rendezvous.py
@@ -272,7 +272,14 @@ def record_is_stale(record: Optional[HostRecord]) -> bool:
def liveness_is_proven(record: HostRecord) -> bool:
- """True only when the record's process-incarnation probe positively matched (never on ``None``)."""
+ """True only when the record's process-incarnation probe positively matched (never on ``None``).
+
+ A record with neither ``createTime`` nor ``startTime`` cannot prove incarnation:
+ ``_same_incarnation`` treats a missing create_time as a match, so a recycled pid would
+ otherwise look alive forever. Topology already refused that shape; attach did not.
+ """
+ if record.create_time is None and record.start_time is None:
+ return False
return _record_incarnation_matches(record) is True
@@ -462,6 +469,28 @@ def owns_host_lock(role: str) -> bool:
return _lock_handles.get(_lock_key(_validated_role(role))) is not None
+def host_lock_is_held(role: str) -> Optional[bool]:
+ """Whether any process currently holds the host lock for ``role``.
+
+ ``True`` / ``False`` when the flock can be observed; ``None`` when the lock file cannot
+ be opened. Never retains a lock. This process's handle is authoritative: re-probing our
+ own flock succeeds on POSIX, so a second open would lie.
+ """
+ role = _validated_role(role)
+ if owns_host_lock(role):
+ return True
+ path = lock_path(role)
+ if not path.exists():
+ return False
+ try:
+ handle = open(path, "a+", encoding="utf-8")
+ except OSError:
+ return None
+ from gateway.status import _probe_lock_file
+
+ return _probe_lock_file(handle)
+
+
def publish_record(
role: str,
*,
@@ -527,7 +556,10 @@ def discard_dead_record(role: str) -> bool:
if record is None:
return False
if record.pid != os.getpid() and _record_incarnation_matches(record) is not False:
- return False
+ # A recycled pid can still look like the same incarnation. The publisher holds the
+ # host lock for its life, so a free flock is proof the recorded owner is gone.
+ if host_lock_is_held(role) is not False:
+ return False
for path in (record_path(role), token_path(role)):
with contextlib.suppress(OSError):
path.unlink(missing_ok=True)
diff --git a/tests/gateway/test_host_attach_lifecycle.py b/tests/gateway/test_host_attach_lifecycle.py
index 5773d50bd93..e7724823021 100644
--- a/tests/gateway/test_host_attach_lifecycle.py
+++ b/tests/gateway/test_host_attach_lifecycle.py
@@ -51,11 +51,15 @@ def owner_pid(tmp_path, monkeypatch):
try:
yield child.pid
finally:
+ hr.release_host_lock(hr.ROLE_GATEWAY)
child.terminate()
child.wait(timeout=10)
def _publish(pid: int, home: Path, profiles: tuple[str, ...]) -> None:
+ # A live owner holds the host lock for its lifetime; a record without that flock is a corpse.
+ outcome, _ = hr.claim_host_lock(hr.ROLE_GATEWAY)
+ assert outcome is hr.HostLockOutcome.ACQUIRED
payload = {
"role": hr.ROLE_GATEWAY,
"home": str(home),
diff --git a/tests/gateway/test_host_rendezvous.py b/tests/gateway/test_host_rendezvous.py
index a592721fdd2..583bcde7839 100644
--- a/tests/gateway/test_host_rendezvous.py
+++ b/tests/gateway/test_host_rendezvous.py
@@ -226,3 +226,73 @@ def test_relative_xdg_state_home_is_ignored(monkeypatch, tmp_path):
assert status._get_lock_dir().is_absolute()
assert status._get_lock_dir() == tmp_path / ".local" / "state" / "hermes" / status._LOCKS_DIRNAME
+
+
+def _gateway_record(*, pid: int, create_time, start_time, home: str) -> hr.HostRecord:
+ return hr.HostRecord(
+ role=hr.ROLE_GATEWAY,
+ pid=pid,
+ create_time=create_time,
+ start_time=start_time,
+ host="",
+ port=None,
+ protocol_version=hr.HOST_PROTOCOL_VERSION,
+ token_fingerprint="",
+ profiles=("default",),
+ updated_at="2026-01-01T00:00:00+00:00",
+ home=home,
+ )
+
+
+def test_missing_incarnation_fields_do_not_prove_a_live_pid(host_dir):
+ """``_same_incarnation`` treats ``create_time=None`` as a match, so a recycled pid looks live.
+
+ A record with neither createTime nor startTime therefore cannot prove incarnation — the
+ attach path used that false proof to refuse forever (#138343). Topology already rejected
+ this shape; the shared liveness predicate did not.
+ """
+ record = _gateway_record(
+ pid=os.getpid(), create_time=None, start_time=None, home=str(host_dir),
+ )
+ assert hr.liveness_is_proven(record) is False
+
+
+def test_free_host_lock_means_attach_does_not_treat_a_recycled_pid_as_owner(host_dir, monkeypatch):
+ """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, and ``decide()`` must START instead of the
+ never-expiring transient refuse that wedged supervised units in #138343 / #133744.
+ """
+ from gateway.host_attach import START, decide, invalidate_host_gateway_cache
+ from gateway.status import get_process_start_time
+
+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
+ try:
+ record = _gateway_record(
+ pid=child.pid,
+ create_time=hr.process_create_time(child.pid),
+ start_time=get_process_start_time(child.pid),
+ home=str(host_dir),
+ )
+ hr.ensure_host_state_dir()
+ hr.record_path(hr.ROLE_GATEWAY).write_text(json.dumps(record.to_json()), encoding="utf-8")
+ monkeypatch.setattr("gateway.host_attach._identify", lambda home: None)
+ invalidate_host_gateway_cache()
+ home = host_dir / "home"
+ home.mkdir()
+ decision = decide(home)
+ assert decision.outcome == START
+ assert decision.owner is None
+ finally:
+ child.kill()
+ child.wait(timeout=10)
+
+
+def test_holding_the_host_lock_keeps_a_matching_incarnation_live(host_dir):
+ """The boot-race window: lock is claimed before the socket binds, so a silent socket stays transient."""
+ assert hr.claim_host_lock(hr.ROLE_GATEWAY)[0] is hr.HostLockOutcome.ACQUIRED
+ record = hr.publish_record(hr.ROLE_GATEWAY, profiles=("default",), home=str(host_dir))
+ assert record is not None
+ assert hr.host_lock_is_held(hr.ROLE_GATEWAY) is True
+ assert hr.liveness_is_proven(record) is True