The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telemetry): count a failed platform connect once per outage, not per watcher retry
Teknium155cab9773e3
diff --git a/hermes_cli/observability/shared_metrics_gateway.py b/hermes_cli/observability/shared_metrics_gateway.pyindex 3bb3d009d4d..16f33c1c0c0 100644--- a/hermes_cli/observability/shared_metrics_gateway.py+++ b/hermes_cli/observability/shared_metrics_gateway.py@@ -19,7 +19,7 @@ import threadingimport timefrom collections import OrderedDictfrom concurrent.futures import Future, ThreadPoolExecutor-from datetime import datetime+from datetime import datetime, timezonefrom typing import Any, Callablelogger = logging.getLogger(__name__)@@ -187,14 +187,34 @@ def _in_home(home: Any, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Noreset_hermes_home_override(token)+# (profile home, platform) -> UTC day of the open failed-connect episode. Touched only on the FIFO worker.+_failing_connects: dict[tuple[str, str], str] = {}+++def _record_connect(platform: Any, event: str, *, exc: BaseException | None, fatal_code: Any, terminal: bool) -> None:+ from hermes_constants import get_hermes_home++ key, day = (str(get_hermes_home()), _platform(platform)), datetime.now(timezone.utc).date().isoformat()+ if event != "connect_failed" or terminal:+ counted = _failing_connects.pop(key, None) == day+ else:+ counted = _failing_connects.get(key) == day+ _failing_connects[key] = day+ if not (counted and event == "connect_failed"): # else: a watcher retry already counted today+ _record_health(platform, event, exc=exc, fatal_code=fatal_code)++def record_platform_connect(adapter: Any, platform: Any, *, is_reconnect: bool, ok: bool, exc: BaseException | None = None,) -> None:"""One adapter connect attempt (cold start or reconnect watcher), from the runner's single- connect seam. A failed attempt is ``connect_failed`` whichever path made it."""+ connect seam. ``connect_failed`` counts a failed EPISODE once per profile, platform and UTC day:+ the watcher's backoff retries are not new failures, so the next row is the success that ends+ it (or the next day it is still failing). A non-retryable failure ends its episode."""event = ("reconnect" if is_reconnect else "connect_ok") if ok else "connect_failed"fatal_code = None if ok or exc is not None else getattr(adapter, "fatal_error_code", None)- _submit(_record_health, platform, event, exc=exc, fatal_code=fatal_code)+ terminal = not ok and exc is None and bool(fatal_code) and not getattr(adapter, "fatal_error_retryable", True)+ _submit(_record_connect, platform, event, exc=exc, fatal_code=fatal_code, terminal=terminal)# The user turned the platform off (relay opt-out revokes its credential): not a lost connection.diff --git a/tests/gateway/test_platform_shared_metrics.py b/tests/gateway/test_platform_shared_metrics.pyindex 4a53e8368f8..44ee2780653 100644--- a/tests/gateway/test_platform_shared_metrics.py+++ b/tests/gateway/test_platform_shared_metrics.py@@ -25,6 +25,7 @@ def rows(monkeypatch):monkeypatch.setattr("gateway.platforms.base.random.uniform", lambda *_: 0.0)smg._reply_clocks.clear()smg._chat_homes.clear()+ smg._failing_connects.clear()def read(metric, *, with_home=False):@@ -65,7 +66,7 @@ class _Runner(GatewayAdapterLifecycleMixin):def _connect(adapter, **kw):try:- return asyncio.run(_Runner()._connect_adapter_with_timeout(adapter, Platform.TELEGRAM, **kw))+ return asyncio.run(_Runner()._connect_adapter_with_timeout(adapter, adapter.platform, **kw))except Exception as exc:return type(exc).__name__@@ -83,6 +84,23 @@ def test_every_connect_attempt_records_one_health_row_with_a_closed_error_class(]+def test_a_reconnect_backoff_loop_is_one_failed_connect_until_it_recovers(rows):+ outage = ConnectionResetError("network down")+ assert _connect(_Adapter(connect=outage)) == "ConnectionResetError" # cold start+ for _ in range(5): # the watcher's backoff retries during the same outage+ assert _connect(_Adapter(connect=outage), is_reconnect=True) == "ConnectionResetError"+ assert _connect(_Adapter(platform=Platform.DISCORD, connect=outage)) == "ConnectionResetError"+ assert _connect(_Adapter(), is_reconnect=True) is True+ assert _connect(_Adapter(connect=outage), is_reconnect=True) == "ConnectionResetError" # a new outage+ smg.drain()+ smg._failing_connects.update(dict.fromkeys(smg._failing_connects, "2000-01-01")) # ...still down a day later+ assert _connect(_Adapter(connect=outage), is_reconnect=True) == "ConnectionResetError"+ assert [(r["event"], r["platform"]) for r in rows("hermes.platform.health")] == [+ ("connect_failed", "telegram"), ("connect_failed", "discord"),+ ("reconnect", "telegram"), ("connect_failed", "telegram"), ("connect_failed", "telegram"),+ ]++def test_one_logical_delivery_is_one_row_whatever_the_retries(rows):flaky = _Adapter([SendResult(success=False, error="ConnectionError: reset", retryable=True)])assert asyncio.run(flaky._send_with_retry("42", "hi", base_delay=0)).success