The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): resolve agent.reconnect_attention_after at call time, not import time
treatux79465f33437a
diff --git a/gateway/run.py b/gateway/run.pyindex 776a4bcf8da..e00d58ff0a6 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -3225,7 +3225,6 @@ _RECONNECT_BACKOFF_CAP = 300# Seconds continuously in the reconnect queue before NEEDS_ATTENTION. Retrying never stops (transient# outages must self-heal); this only makes a permanently-failing loop loud. 0 disables.-_RECONNECT_ATTENTION_AFTER_SECONDS = _float_env("HERMES_RECONNECT_ATTENTION_AFTER_SECONDS", 7200)def _reconnect_backoff(attempt: int) -> int:@@ -3236,13 +3235,14 @@ def _reconnect_backoff(attempt: int) -> int:def _reconnect_needs_attention(info: dict, now: float) -> bool:"""True when a reconnect-queue entry has waited long enough for NEEDS_ATTENTION.``queued_at`` is re-stamped on each (re)entry, so only *continuous* failure escalates."""- if _RECONNECT_ATTENTION_AFTER_SECONDS <= 0:+ threshold = _float_env("HERMES_RECONNECT_ATTENTION_AFTER_SECONDS", 7200)+ if threshold <= 0:return False # escalation disabledqueued_at = info.get("queued_at")if queued_at is None:info["queued_at"] = nowreturn False- return (now - queued_at) >= _RECONNECT_ATTENTION_AFTER_SECONDS+ return (now - queued_at) >= threshold# "No session DB pinned": lets ``_session_db`` distinguish "resolve from profile scope" from adiff --git a/tests/gateway/test_adapter_connect_classification.py b/tests/gateway/test_adapter_connect_classification.pyindex ec9c7f9aa93..a74c5748d67 100644--- a/tests/gateway/test_adapter_connect_classification.py+++ b/tests/gateway/test_adapter_connect_classification.py@@ -290,17 +290,14 @@ class TestReconnectNeedsAttention:info = {"queued_at": now - 60}assert _reconnect_needs_attention(info, now) is False- def test_past_threshold_is_flagged(self):- import gateway.run as run_module-+ def test_past_threshold_is_flagged(self, monkeypatch):+ monkeypatch.setenv("HERMES_RECONNECT_ATTENTION_AFTER_SECONDS", "10")now = time.monotonic()- info = {"queued_at": now - (run_module._RECONNECT_ATTENTION_AFTER_SECONDS + 1)}+ info = {"queued_at": now - 11}assert _reconnect_needs_attention(info, now) is Truedef test_zero_threshold_disables_escalation(self, monkeypatch):- import gateway.run as run_module-- monkeypatch.setattr(run_module, "_RECONNECT_ATTENTION_AFTER_SECONDS", 0)+ monkeypatch.setenv("HERMES_RECONNECT_ATTENTION_AFTER_SECONDS", "0")info = {"queued_at": time.monotonic() - 999999}assert _reconnect_needs_attention(info, time.monotonic()) is False@@ -333,8 +330,6 @@ def _make_runner():class TestWatcherAttentionEscalation:@pytest.mark.asyncioasync def test_watcher_flags_long_queued_platform_and_keeps_retrying(self, monkeypatch):- import gateway.run as run_module-runner = _make_runner()status_writes = []monkeypatch.setattr(@@ -343,7 +338,8 @@ class TestWatcherAttentionEscalation:lambda platform, **kw: status_writes.append((platform, kw)),)- threshold = run_module._RECONNECT_ATTENTION_AFTER_SECONDS+ monkeypatch.setenv("HERMES_RECONNECT_ATTENTION_AFTER_SECONDS", "10")+ threshold = 10runner._failed_platforms[Platform.TELEGRAM] = {"config": PlatformConfig(enabled=True, token="test"),"attempts": 40,@@ -377,8 +373,6 @@ class TestWatcherAttentionEscalation:@pytest.mark.asyncioasync def test_watcher_flags_only_once(self, monkeypatch):- import gateway.run as run_module-runner = _make_runner()status_writes = []monkeypatch.setattr(@@ -387,7 +381,8 @@ class TestWatcherAttentionEscalation:lambda platform, **kw: status_writes.append((platform, kw)),)- threshold = run_module._RECONNECT_ATTENTION_AFTER_SECONDS+ monkeypatch.setenv("HERMES_RECONNECT_ATTENTION_AFTER_SECONDS", "10")+ threshold = 10runner._failed_platforms[Platform.TELEGRAM] = {"config": PlatformConfig(enabled=True, token="test"),"attempts": 40,diff --git a/tests/gateway/test_reconnect_attention_profile_scope.py b/tests/gateway/test_reconnect_attention_profile_scope.pynew file mode 100644index 00000000000..43be5dce0b5--- /dev/null+++ b/tests/gateway/test_reconnect_attention_profile_scope.py@@ -0,0 +1,107 @@+"""Profile-scope leak regression for reconnect attention threshold.++Issue: _RECONNECT_ATTENTION_AFTER_SECONDS was a module-level constant that+captured os.environ at import time. Under multiplex, switching profiles and+re-bridging config had no effect — the threshold stayed locked to the launch+profile's value.++Test: two HERMES_HOME dirs (A -> B) prove the threshold moves with the+active profile after the fix.+"""++from __future__ import annotations++import os+import subprocess+import sys+import textwrap+from pathlib import Path++import pytest+import yaml++PROJECT_ROOT = Path(__file__).resolve().parents[2]+++def _write_config(home: Path, agent_cfg: dict | None = None) -> None:+ cfg: dict = {}+ if agent_cfg:+ cfg["agent"] = agent_cfg+ (home / "config.yaml").write_text(yaml.safe_dump(cfg), encoding="utf-8")+++def test_reconnect_attention_respects_profile_switch(tmp_path: Path) -> None:+ """Bridging a different profile's config must update the reconnect threshold.++ Before the fix, _RECONNECT_ATTENTION_AFTER_SECONDS was cached at import time,+ so profile B inherited profile A's threshold silently.+ """+ home_a = tmp_path / "profile_a"+ home_b = tmp_path / "profile_b"+ home_a.mkdir()+ home_b.mkdir()++ _write_config(home_a, agent_cfg={"reconnect_attention_after": 10})+ _write_config(home_b, agent_cfg={"reconnect_attention_after": 20})++ script = textwrap.dedent(+ f"""+ import os, sys, time+ sys.path.insert(0, {str(PROJECT_ROOT)!r})++ from pathlib import Path+ from gateway import run+ from gateway.run import _bridge_config_to_env, _load_bridge_config++ # Simulate serving profile A first+ cfg_a = _load_bridge_config(Path({str(home_a / 'config.yaml')!r}))+ _bridge_config_to_env(cfg_a)++ # 15 s > A's threshold of 10 -> should flag+ info_a = {{"queued_at": time.monotonic() - 15}}+ assert run._reconnect_needs_attention(info_a, time.monotonic()) is True, \+ "A threshold 10: 15s should flag"++ # 5 s < A's threshold of 10 -> should not flag+ info_a_ok = {{"queued_at": time.monotonic() - 5}}+ assert run._reconnect_needs_attention(info_a_ok, time.monotonic()) is False, \+ "A threshold 10: 5s should not flag"++ # Switch to profile B (same process, multiplex scenario)+ cfg_b = _load_bridge_config(Path({str(home_b / 'config.yaml')!r}))+ _bridge_config_to_env(cfg_b)++ # 15 s < B's threshold of 20 -> must NOT flag after fix+ info_b = {{"queued_at": time.monotonic() - 15}}+ result = run._reconnect_needs_attention(info_b, time.monotonic())+ print(f"RESULT={{result}}")+ """+ )++ env = dict(os.environ)+ env["HERMES_HOME"] = str(home_a)+ # Keep interpreter paths required by stdlib / platform detection+ for k in (+ "PATH", "PYTHONPATH", "VIRTUAL_ENV", "HOME", "USERPROFILE",+ "HOMEDRIVE", "HOMEPATH", "LOCALAPPDATA", "APPDATA",+ "SYSTEMROOT", "TEMP", "TMP",+ ):+ if k in os.environ and k not in env:+ env[k] = os.environ[k]++ proc = subprocess.run(+ [sys.executable, "-c", script],+ env=env,+ capture_output=True,+ text=True,+ timeout=60,+ )+ if proc.returncode != 0:+ pytest.fail(+ f"Subscript failed (rc={proc.returncode})\n"+ f"stderr:\n{proc.stderr}\nstdout:\n{proc.stdout}"+ )+ assert "RESULT=False" in proc.stdout, (+ f"Expected False after B bridge (threshold 20, elapsed 15), got:\n"+ f"{proc.stdout}"+ )