Skip to content

The agent that grows with you

fix(gateway): let the host lock decide a legacy record that looks older than this boot

ethernetcf30efaf0f0d
diff --git a/gateway/host_rendezvous.py b/gateway/host_rendezvous.py
index 29d19662e68..66d3b5c58d4 100644
--- a/gateway/host_rendezvous.py
+++ b/gateway/host_rendezvous.py
@@ -244,11 +244,11 @@ def _pid_incarnation_matches(pid: int, create_time: Optional[float]) -> Optional
return _pid_alive_matches(pid, create_time)
-# A record published before ``bootEpoch`` existed cannot name its boot, but its ``create_time``
-# still says when the owner started. An owner started before this boot began cannot be alive in
-# it, so a tick match against such a record is a recycled early PID. Anchoring on boot time (not
-# on a live ``create_time`` reading) keeps #117505 intact: a wall-clock resync moves the live
-# reading of a running owner, never the point in time the record says it started.
+# A record published before ``bootEpoch`` existed cannot name its boot. Its ``createTime`` older
+# than this boot's start (``psutil.boot_time()``, minus this slack) means EITHER a reboot (the
+# owner is gone and its PID was recycled) OR a wall-clock step since the owner started (boot time
+# is wall clock minus uptime, so a forward step moves it past a running owner's saved start;
+# #117505). Clocks cannot tell those apart, so the host lock decides: a live gateway holds it.
_LEGACY_BOOT_SLACK_S = 120.0
@@ -262,6 +262,33 @@ def _boot_time() -> Optional[float]:
return None
+def _host_lock_is_free(role: str) -> Optional[bool]:
+ """True when no process holds the host lock for ``role``; ``None`` when it cannot be probed.
+
+ The probe takes the lock for an instant, so a gateway claiming it in that instant gets
+ HELD_BY_OTHER and its supervisor retries. Callers only reach this for a legacy record that
+ is already suspect, never on the normal attach path.
+ """
+ if owns_host_lock(role):
+ return False
+ from gateway.status import _release_file_lock, _try_acquire_file_lock
+
+ try:
+ ensure_host_state_dir()
+ handle = open(lock_path(role), "a+", encoding="utf-8") # windows-footgun: ok — flock handle, never read
+ except OSError:
+ logger.debug("host %s lock could not be probed", role, exc_info=True)
+ return None
+ try:
+ if not _try_acquire_file_lock(handle):
+ return False
+ _release_file_lock(handle)
+ return True
+ finally:
+ with contextlib.suppress(OSError):
+ handle.close()
+
+
def _current_boot_epoch() -> str:
"""Identity of this boot. Empty when /proc is unreadable — then the check is a no-op."""
try:
@@ -280,8 +307,8 @@ def _record_incarnation_matches(record: HostRecord) -> Optional[bool]:
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 that differs from this boot's, or
- (for legacy records with no epoch) a create_time from before this boot began, is a mismatch.
- Empty epoch is a no-op so macOS and pre-upgrade records are not false-staled. Do not infer
+ (for legacy records with no epoch) a create_time from before this boot began while nobody holds
+ the host lock, is a mismatch. Empty epoch is a no-op so macOS and pre-upgrade records are not false-staled. Do not infer
identity from argv. A record with neither create_time nor start_time proves nothing about
its pid, so it never vouches for one. Legacy records without a start fingerprint keep the
create-time check.
@@ -307,7 +334,11 @@ def _record_incarnation_matches(record: HostRecord) -> Optional[bool]:
if record.role == ROLE_GATEWAY and not recorded_epoch and record.create_time is not None:
boot = _boot_time()
if boot is not None and float(record.create_time) < boot - _LEGACY_BOOT_SLACK_S:
- return False
+ lock_free = _host_lock_is_free(record.role)
+ if lock_free is None:
+ return None
+ if lock_free:
+ return False
return True
diff --git a/tests/gateway/test_host_rendezvous.py b/tests/gateway/test_host_rendezvous.py
index fb1ab96f038..f3e21742249 100644
--- a/tests/gateway/test_host_rendezvous.py
+++ b/tests/gateway/test_host_rendezvous.py
@@ -136,11 +136,11 @@ def test_live_host_record_survives_wall_clock_create_time_drift(host_dir, monkey
@pytest.mark.platforms("posix")
-def test_reused_early_pid_after_reboot_is_not_the_gateway():
+def test_reused_early_pid_after_reboot_is_not_the_gateway(host_dir):
"""Boot-relative start ticks reset on reboot and collide within the 2s drift tolerance.
- A legacy record (no bootEpoch) whose createTime predates this boot cannot describe a live
- process. A record dated inside this boot stays live however far the live create_time
+ A legacy record (no bootEpoch) whose createTime predates this boot, with nobody holding the
+ host lock, cannot describe a live process. A record dated inside this boot stays live however far the live create_time
reading has since drifted from it (#117505), and a record with no incarnation proof at
all never vouches for the pid.
"""
@@ -178,6 +178,42 @@ def test_reused_early_pid_after_reboot_is_not_the_gateway():
child.wait(timeout=10)
+def test_live_legacy_owner_survives_a_clock_step_past_its_create_time(host_dir):
+ """A forward wall-clock step moves boot time past a running owner's saved createTime
+ (boot time is wall clock minus uptime). The host lock is held, so the owner stays live."""
+ import psutil
+
+ from gateway.status import get_process_start_time
+
+ env = {**os.environ, "HERMES_HOME": str(host_dir / "home"), "HERMES_GATEWAY_LOCK_DIR": str(host_dir / "locks")}
+ child = subprocess.Popen(
+ [sys.executable, "-c", _CHILD.format(tree=_tree())], env=env, cwd=_tree(),
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ assert child.stdout is not None
+ try:
+ assert json.loads(child.stdout.readline())["host"] is True
+ start = get_process_start_time(child.pid)
+ assert start is not None
+ record = hr.HostRecord(
+ role=hr.ROLE_GATEWAY,
+ pid=child.pid,
+ create_time=psutil.boot_time() - 3600.0,
+ start_time=int(start),
+ host="",
+ port=None,
+ protocol_version=hr.HOST_PROTOCOL_VERSION,
+ token_fingerprint="",
+ profiles=("default",),
+ updated_at="2026-01-01T00:00:00+00:00",
+ )
+ assert hr.liveness_is_proven(record) is True
+ assert hr.record_is_stale(record) is False
+ finally:
+ child.kill()
+ child.wait(timeout=10)
+
+
@pytest.mark.platforms("linux")
def test_boot_epoch_mismatch_rejects_a_tick_match(host_dir):
record = hr.publish_record(hr.ROLE_GATEWAY, profiles=("default",), home=str(host_dir))