The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telemetry): relay reply latency, secondary-profile disconnects, side-effect-free classification
teknium185ab6b510bbd
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.pyindex 64d2659d459..5daa88e9842 100644--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@ -1510,6 +1510,9 @@ class GatewayAdapterLifecycleMixin:)returnprofile_map.pop(platform, None)+ # The notification may arrive outside the profile's scope: the row is that profile's.+ if (profile_home := self._routed_profile_home(profile_name)) is not UNRESOLVED_PROFILE_HOME:+ record_platform_disconnect(adapter, hermes_home=profile_home)await self._safe_adapter_disconnect(adapter, platform)if not self._running:returndiff --git a/hermes_cli/observability/shared_metrics_gateway.py b/hermes_cli/observability/shared_metrics_gateway.pyindex b38fa108112..2629035b715 100644--- a/hermes_cli/observability/shared_metrics_gateway.py+++ b/hermes_cli/observability/shared_metrics_gateway.py@@ -85,9 +85,13 @@ _SEND_KIND_CLASSES = {def _status_code(exc: BaseException | None) -> int | None:- for holder in (exc, getattr(exc, "response", None)):+ # Stored values only, never a property: a deprecated one warns (websockets' ``code``), and a+ # classifier must not run library code against the adapter's live exception.+ from inspect import getattr_static++ for holder in (exc, getattr_static(exc, "response", None)):for attr in ("status_code", "status", "code"):- value = getattr(holder, attr, None)+ value = getattr_static(holder, attr, None)if isinstance(value, int) and not isinstance(value, bool) and 100 <= value <= 599:return valuereturn None@@ -163,22 +167,48 @@ def platform_health_fields(*, platform: Any, event: str, error_class: str) -> di}+def _record_health(platform: Any, event: str, *, exc: BaseException | None = None, fatal_code: Any = None) -> None:+ # Classified on the worker: whatever an exception carries, the caller re-raising it never sees us.+ error_class = "none" if event in {"connect_ok", "reconnect"} else connect_error_class(exc=exc, fatal_code=fatal_code)+ _emit("PLATFORM_HEALTH_MARK", platform_health_fields, platform=platform, event=event, error_class=error_class)+++def _in_home(home: Any, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> None:+ """Run ``fn`` scoped to ``home`` (the profile that owns the row), or the submitting context's scope."""+ if home is None:+ fn(*args, **kwargs)+ return+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ token = set_hermes_home_override(str(home))+ try:+ fn(*args, **kwargs)+ finally:+ reset_hermes_home_override(token)++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 singleconnect seam. A failed attempt is ``connect_failed`` whichever path made it."""event = ("reconnect" if is_reconnect else "connect_ok") if ok else "connect_failed"- error_class = "none" if ok else connect_error_class(- exc=exc, fatal_code=None if exc is not None else getattr(adapter, "fatal_error_code", None))- _submit(_emit, "PLATFORM_HEALTH_MARK", platform_health_fields,- platform=platform, event=event, error_class=error_class)+ 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)-def record_platform_disconnect(adapter: Any) -> None:- """A live adapter lost its connection after startup (its fatal-error handler owned it)."""- _submit(_emit, "PLATFORM_HEALTH_MARK", platform_health_fields, platform=adapter, event="disconnect",- error_class=connect_error_class(fatal_code=getattr(adapter, "fatal_error_code", None)))+# The user turned the platform off (relay opt-out revokes its credential): not a lost connection.+_USER_CHOSEN_FATAL_CODES = frozenset({"relay_disabled"})+++def record_platform_disconnect(adapter: Any, *, hermes_home: Any = None) -> None:+ """A live adapter lost its connection after startup (its fatal-error handler owned it).+ ``hermes_home``: the owning profile, for handlers that run outside its scope (multiplexed+ secondaries)."""+ fatal_code = getattr(adapter, "fatal_error_code", None)+ if fatal_code in _USER_CHOSEN_FATAL_CODES:+ return+ _submit(_in_home, hermes_home, _record_health, adapter, "disconnect", fatal_code=fatal_code)# ---- hermes.platform.delivery + hermes.gateway.reply_latency ----@@ -202,18 +232,20 @@ def records_delivery(send: Callable[..., Any]) -> Callable[..., Any]:try:result = await send(self, *args, **kwargs)except Exception as exc:- _submit(_emit, "PLATFORM_DELIVERY_MARK", delivery_fields,- platform=self, failure_class=delivery_failure_class(exc=exc))+ _submit(_record_delivery, self, exc=exc)raise- success = getattr(result, "success", None)- if isinstance(success, bool):- _submit(_emit, "PLATFORM_DELIVERY_MARK", delivery_fields, platform=self,- failure_class="none" if success else delivery_failure_class(result))+ if isinstance(getattr(result, "success", None), bool):+ _submit(_record_delivery, self, result)return resultreturn wrapper+def _record_delivery(adapter: Any, result: Any = None, *, exc: BaseException | None = None) -> None:+ failure_class = "none" if exc is None and result.success else delivery_failure_class(result, exc)+ _emit("PLATFORM_DELIVERY_MARK", delivery_fields, platform=adapter, failure_class=failure_class)++def stops_reply_clock(send_or_edit: Callable[..., Any]) -> Callable[..., Any]:"""Stream consumer transport: the first delivered visible text (frame, draft or message)."""@@ -234,6 +266,9 @@ _REPLY_CLOCK_MAX_AGE = 3600.0# send side may run outside the turn's scope, so the start side records whose row it is._reply_clocks: OrderedDict[tuple[str, str], tuple[float, str]] = OrderedDict()_reply_lock = threading.Lock()+# One connector adapter fronting several platforms: the turn started under the platform the message+# came in on (``discord``), its reply leaves through this adapter.+_FRONTING_PLATFORMS = frozenset({"relay"})def _clock_key(platform: Any, chat_id: Any) -> tuple[str, str] | None:@@ -263,10 +298,14 @@ def stop_reply_clock(adapter: Any, chat_id: Any, result: Any = None) -> None:returnwith _reply_lock:started = _reply_clocks.pop(key, None)+ if started is None and key[0] in _FRONTING_PLATFORMS:+ fronted = [k for k in _reply_clocks if k[1] == key[1]]+ started = _reply_clocks.pop(fronted[0]) if len(fronted) == 1 else None# A turn that ended without a reply leaves its clock behind; an unrelated send hours later# must not be read as that turn's reply.if started is not None and time.monotonic() - started[0] <= _REPLY_CLOCK_MAX_AGE:- _submit(_record_reply_latency, adapter, time.monotonic() - started[0], started[1])+ _submit(_in_home, started[1], _emit, "REPLY_LATENCY_MARK", reply_latency_fields,+ platform=adapter, seconds=time.monotonic() - started[0])def reply_latency_fields(*, platform: Any, seconds: float) -> dict[str, str]:@@ -278,16 +317,6 @@ def reply_latency_fields(*, platform: Any, seconds: float) -> dict[str, str]:}-def _record_reply_latency(adapter: Any, seconds: float, home: str) -> None:- from hermes_constants import reset_hermes_home_override, set_hermes_home_override-- token = set_hermes_home_override(home)- try:- _emit("REPLY_LATENCY_MARK", reply_latency_fields, platform=adapter, seconds=seconds)- finally:- reset_hermes_home_override(token)--# ---- hermes.cron.run ----_CRON_NOTES_MAX = 512diff --git a/tests/gateway/test_platform_shared_metrics.py b/tests/gateway/test_platform_shared_metrics.pyindex 83724eb43d2..73f5506e44f 100644--- a/tests/gateway/test_platform_shared_metrics.py+++ b/tests/gateway/test_platform_shared_metrics.py@@ -1,6 +1,7 @@"""Gateway platform health / delivery / first-reply shared metrics through the real runner seams."""import asyncio+import warningsfrom types import SimpleNamespaceimport pytest@@ -12,28 +13,30 @@ from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfigfrom hermes_cli.observability import relay_shared_metrics as rsmfrom hermes_cli.observability import shared_metrics_contract as contractfrom hermes_cli.observability import shared_metrics_gateway as smg+from hermes_constants import get_hermes_home@pytest.fixturedef rows(monkeypatch):got = []monkeypatch.setattr(rsm, "enabled", lambda: True)- monkeypatch.setattr(rsm, "record_process_mark", lambda mark, data: got.append((mark, dict(data))))+ monkeypatch.setattr(rsm, "record_process_mark",+ lambda mark, data: got.append((mark, dict(data), str(get_hermes_home()))))monkeypatch.setattr("gateway.platforms.base.random.uniform", lambda *_: 0.0)smg._reply_clocks.clear()- def read(metric):+ def read(metric, *, with_home=False):smg.drain()- found = [data for mark, data in got if contract._DECISION_MARK_METRICS[mark] == metric]- assert all(contract.counter_dimensions_are_valid(metric, data) for data in found)- return found+ found = [(home, data) for mark, data, home in got if contract._DECISION_MARK_METRICS[mark] == metric]+ assert all(contract.counter_dimensions_are_valid(metric, data) for _, data in found)+ return found if with_home else [data for _, data in found]return readclass _Adapter(BasePlatformAdapter):- def __init__(self, results=(), connect: object = True):- super().__init__(PlatformConfig(enabled=True, token="test"), Platform.TELEGRAM)+ def __init__(self, results=(), connect: object = True, platform=Platform.TELEGRAM):+ super().__init__(PlatformConfig(enabled=True, token="test"), platform)self.results, self._connect = list(results), connectasync def connect(self, *, is_reconnect: bool = False) -> bool:@@ -105,3 +108,87 @@ def test_first_reply_latency_is_one_row_per_turn_stopped_only_by_reply_text(rowssmg.start_reply_clock(SimpleNamespace(platform=Platform.TELEGRAM, chat_id="7"), internal=True)asyncio.run(adapter.send_final_ledgered(event, "k", "background notice", {}, reply_to=None))assert rows("hermes.gateway.reply_latency") == [{"first_response_bucket": "lt_2s", "platform": "telegram"}] * 2+++def test_a_relay_delivered_turn_stops_the_clock_its_inbound_started(rows):+ # The connector's inbound names the platform it came from; the reply leaves through the relay.+ relay = _Adapter(platform=Platform.RELAY)+ smg.start_reply_clock(SimpleNamespace(platform=Platform.DISCORD, chat_id="c1"))+ consumer = GatewayStreamConsumer(relay, "c1", StreamConsumerConfig(cursor=""))+ assert asyncio.run(consumer._send_or_edit("first streamed chunk"))+ event = MessageEvent(text="hi", message_type=MessageType.TEXT, message_id="in-2",+ source=SimpleNamespace(platform=Platform.SLACK, chat_id="C2", thread_id=None))+ smg.start_reply_clock(event.source)+ asyncio.run(relay.send_final_ledgered(event, "k", "final answer", {}, reply_to=None))+ assert rows("hermes.gateway.reply_latency") == [{"first_response_bucket": "lt_2s", "platform": "relay"}] * 2+ assert not smg._reply_clocks+++class _FatalRunner(GatewayAdapterLifecycleMixin):+ def __init__(self):+ self.adapters, self._failed_platforms, self._running = {}, {}, True+ self.delivery_router, self.config = SimpleNamespace(adapters={}), SimpleNamespace(platforms={})+ self._profile_adapters, self._profile_failed_platforms = {}, {}++ def _update_platform_runtime_status(self, *args, **kwargs):+ pass++ async def _safe_adapter_disconnect(self, *args, **kwargs):+ pass++ async def stop(self):+ pass+++def _fatal(adapter, code, *, retryable=False):+ adapter._set_fatal_error(code, "boom", retryable=retryable)+ return adapter+++def test_fatal_handlers_count_lost_connections_in_the_owning_profile_only(rows, tmp_path, monkeypatch):+ home_b = tmp_path / "profiles" / "b"+ monkeypatch.setattr(_FatalRunner, "_routed_profile_home", staticmethod(lambda name: home_b))+ runner = _FatalRunner()+ secondary = _fatal(_Adapter(), "telegram_network_error")+ runner._profile_adapters["b"] = {Platform.TELEGRAM: secondary}+ # The secondary's notification arrives on a task scoped to the launch profile, not to b.+ asyncio.run(runner._handle_profile_adapter_fatal_error("b", Platform.TELEGRAM, secondary))+ for code in ("relay_disabled", "telegram_auth_error"): # the user's relay opt-out is not a disconnect+ primary = _fatal(_Adapter(platform=Platform.RELAY), code)+ runner.adapters[Platform.RELAY] = primary+ asyncio.run(runner._handle_adapter_fatal_error_impl(primary))+ launch_home = str(get_hermes_home())+ assert rows("hermes.platform.health", with_home=True) == [+ (str(home_b), {"error_class": "network", "event": "disconnect", "platform": "telegram"}),+ (launch_home, {"error_class": "auth", "event": "disconnect", "platform": "relay"}),+ ]+++class _ClosedWithDeprecatedCode(ConnectionError):+ """websockets-style: the status lives behind a deprecated property."""++ @property+ def code(self):+ warnings.warn("ConnectionClosed.code is deprecated", DeprecationWarning, stacklevel=2)+ return 1011++ @property+ def status_code(self):+ raise RuntimeError("no response attached")+++def test_classifying_a_connect_failure_never_replaces_the_adapters_exception(rows):+ raised = _ClosedWithDeprecatedCode()++ async def attempt():+ try:+ await _Runner()._connect_adapter_with_timeout(_Adapter(connect=raised), Platform.TELEGRAM)+ except BaseException as exc:+ return exc++ with warnings.catch_warnings():+ warnings.simplefilter("error")+ seen = asyncio.run(attempt())+ assert seen is raised and seen.__context__ is None+ assert rows("hermes.platform.health") == [+ {"error_class": "network", "event": "connect_failed", "platform": "telegram"}]