The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(shared-metrics): count each connector batch entry once, not the batch
Siddharth Balyanc71fb6f1612c
diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.pyindex ab802a0c5bd..fec215441e7 100644--- a/hermes_cli/observability/relay_shared_metrics.py+++ b/hermes_cli/observability/relay_shared_metrics.py@@ -19,6 +19,7 @@ from hermes_cli.version_info import get_version_infofrom .shared_metrics import SharedMetricsStorefrom . import shared_metrics_contract as contract+from . import shared_metrics_connectors as connectors_from . import shared_metrics_efficiency as efffrom . import shared_metrics_engagement as engagement_from . import shared_metrics_fields as fields_@@ -189,6 +190,7 @@ class _MetricsSession:# Compression rotated this id away: close once its in-flight turn ends.retiring: bool = Falseefficiency: eff.SessionEfficiency = field(default_factory=eff.SessionEfficiency)+ connectors: connectors_.ConnectorSessionState = field(default_factory=connectors_.ConnectorSessionState)route_run: engagement_.RouteRun = field(default_factory=engagement_.RouteRun)api_calls: int = 0tool_call_total: int = 0@@ -467,10 +469,12 @@ class _Runtime:session, task = self._task_pair(event, start=True, allow_task_id_fallback=True)if session is None or task is None or not _text(event, "tool_call_id"):return- identity = self._tool_call_identity(event)+ if connectors_.is_connector_batch(event):+ return # each entry opens its own lifecycle; the wrapper counts only if no entry ranwith session.lock:if not self._admits(session, task, event):return+ identity = self._tool_call_identity(event, session, task_id)key = (task_id, *identity)if identity in task.completed_tool_call_ids or key in session.tool_calls:return@@ -512,7 +516,11 @@ class _Runtime:returntool_call = Noneif _text(event, "tool_call_id"):- observed_identity = self._tool_call_identity(event)+ base_identity = self._tool_call_identity(event)+ if session.connectors.batch_already_counted(task_id, event, base_identity):+ task.completed_tool_call_ids.add(base_identity)+ return+ observed_identity = self._tool_call_identity(event, session, task_id)if observed_identity in task.completed_tool_call_ids:returnidentity = observed_identity@@ -540,6 +548,9 @@ class _Runtime:if task.cost.user_turn:session.efficiency.tools.used.add(eff.toolset_metric_name(event.get("toolset")))self._finish_tool_call(task, tool_call, event)+ chain = session.connectors.observe(task_id, event, self._tool_call_identity(event))+ if chain is not None:+ self._mark(session, task, contract.CONNECTOR_CHAIN_MARK, chain)def record_skill_lifecycle(self, event: dict[str, Any]) -> None:"""Emit one allowlisted skill fact without its local identity."""@@ -770,9 +781,13 @@ class _Runtime:self._turn_sessions[(session.session_id, turn_id)] = session@staticmethod- def _tool_call_identity(event: dict[str, Any]) -> tuple[str, str, str]:- """Identify one provider-local tool call without exporting its IDs."""- return _text(event, "api_request_id"), _text(event, "turn_id"), _text(event, "tool_call_id")+ def _tool_call_identity(+ event: dict[str, Any], session: _MetricsSession | None = None, task_id: str = "",+ ) -> tuple[str, str, str]:+ """Identify one provider-local tool call without exporting its IDs. With ``session``, a+ connector entry of a ``tool_call`` batch gets its own identity (entries share the call id)."""+ base = _text(event, "api_request_id"), _text(event, "turn_id"), _text(event, "tool_call_id")+ return base if session is None else session.connectors.identity(task_id, event, base)@staticmethoddef _event_matches_task_turn(task: _TaskRun, event: dict[str, Any]) -> bool:@@ -917,6 +932,7 @@ class _Runtime:return Falseself._end_pending_tool_calls(session, task, event)self._end_pending_model_calls(session, {**event, "task_id": task_id})+ session.connectors.forget_task(task_id)fields = contract.task_terminal_fields({**task.start_fields, **event},duration_ms=_elapsed_ms(task.started_ns),diff --git a/hermes_cli/observability/shared_metrics_connectors.py b/hermes_cli/observability/shared_metrics_connectors.pynew file mode 100644index 00000000000..c4be7f2aab9--- /dev/null+++ b/hermes_cli/observability/shared_metrics_connectors.py@@ -0,0 +1,127 @@+"""Connector work in the shared metrics: per-entry tool counting, the search-to-execute chain, and+the batch and search rows.++A ``tool_call`` batch of connector entries reaches the hooks once per entry (same ``tool_call_id``)+and once more for the wrapper. Each entry is its own logical call, so entries get distinct identities+(``<id>#<n>`` in run order) and the wrapper is not counted once an entry was. Connector slugs, tool+names and query text never leave this module: rows carry only buckets and closed enums.+"""++from __future__ import annotations++import json+from dataclasses import dataclass, field+from typing import Any, Iterable++from . import shared_metrics_contract as contract+from .shared_metrics_contract import CONNECTOR_NAME_PREFIX++# Described names are kept per conversation to answer "was this tool described before it ran".+_MAX_DESCRIBED = 256+++def is_connector_name(name: Any) -> bool:+ return isinstance(name, str) and name.startswith(CONNECTOR_NAME_PREFIX)+++def _call_entries(args: Any) -> list[dict[str, Any]]:+ """The ``calls[]`` entries of a ``tool_call`` invocation; [] when the arguments do not parse."""+ if not isinstance(args, dict):+ return []+ from tools.tool_search_validation import normalize_tool_call_entries++ entries, err = normalize_tool_call_entries(args)+ return [] if err else entries+++def is_connector_batch(event: dict[str, Any]) -> bool:+ """A ``tool_call`` wrapper whose entries are all connector calls (each entry is counted itself)."""+ if event.get("tool_name") != "tool_call":+ return False+ entries = _call_entries(event.get("args"))+ return bool(entries) and all(is_connector_name(entry.get("name")) for entry in entries)+++@dataclass+class ConnectorSessionState:+ """Per-conversation connector state; the caller holds the session lock."""++ searches_since_execute: int = 0+ described: set[str] = field(default_factory=set)+ # (task_id, api_request_id, turn_id, tool_call_id) -> connector entries already counted.+ counted_entries: dict[tuple[str, str, str, str], int] = field(default_factory=dict)++ def identity(self, task_id: str, event: dict[str, Any], base: tuple[str, str, str]) -> tuple[str, str, str]:+ """``base`` for any call but a connector entry, which gets ``<id>#<n>`` (n = entries counted)."""+ if not is_connector_name(event.get("tool_name")) or not base[2]:+ return base+ return (base[0], base[1], f"{base[2]}#{self.counted_entries.get((task_id, *base), 0)}")++ def batch_already_counted(self, task_id: str, event: dict[str, Any], base: tuple[str, str, str]) -> bool:+ """True for a connector batch wrapper once one of its entries was counted."""+ return bool(self.counted_entries.get((task_id, *base))) and is_connector_batch(event)++ def observe(self, task_id: str, event: dict[str, Any], base: tuple[str, str, str]) -> dict[str, str] | None:+ """Update the chain after a counted call; the ``hermes.connector_chain.count`` fields for an entry."""+ name = event.get("tool_name")+ if name == "tool_search":+ self.searches_since_execute += 1+ return None+ if name == "tool_describe":+ names = (event.get("args") or {}).get("names") if isinstance(event.get("args"), dict) else None+ for described in names if isinstance(names, list) else ():+ if is_connector_name(described) and len(self.described) < _MAX_DESCRIBED:+ self.described.add(described)+ return None+ if not is_connector_name(name):+ return None+ if base[2]:+ key = (task_id, *base)+ self.counted_entries[key] = self.counted_entries.get(key, 0) + 1+ fields = {+ "described_first": "yes" if name in self.described else "no",+ "outcome": contract.tool_outcome(event),+ "searches_before_bucket": contract.count_bucket(self.searches_since_execute),+ }+ self.searches_since_execute = 0+ return fields++ def forget_task(self, task_id: str) -> None:+ for key in [key for key in self.counted_entries if key[0] == task_id]:+ del self.counted_entries[key]+++# ---- row builders ----------------------------------------------------------------------------++def tool_batch_fields(route: dict[str, str], tool_calls: Iterable[Any]) -> dict[str, str] | None:+ """One model reply's tool calls: how many logical calls (``tool_call`` entries counted one by+ one) and how many of them were connector calls. None for a reply with no calls."""+ total = connectors = 0+ for tc in tool_calls:+ fn = getattr(tc, "function", None)+ name = getattr(fn, "name", None)+ names = [name]+ if name == "tool_call":+ entries = _call_entries(_parsed_arguments(getattr(fn, "arguments", None)))+ names = [entry.get("name") for entry in entries] or [name]+ total += len(names)+ connectors += sum(1 for entry_name in names if is_connector_name(entry_name))+ if not total:+ return None+ share = "none" if not connectors else "all" if connectors == total else "some"+ return {**route, "connector_share": share, "size_bucket": contract.count_bucket(total)}+++def _parsed_arguments(raw: Any) -> Any:+ if isinstance(raw, dict):+ return raw+ try:+ return json.loads(raw) if isinstance(raw, str) else None+ except ValueError:+ return None+++def tool_search_fields(*, scope: str, hits: int, outcome: str) -> dict[str, str] | None:+ if scope not in contract.TOOL_SEARCH_SCOPES or outcome not in contract.TOOL_SEARCH_OUTCOMES:+ return None+ return {"hits_bucket": contract.count_bucket(hits), "outcome": outcome, "scope": scope}diff --git a/model_tools.py b/model_tools.pyindex 30a9c4a1a5a..4c14cda0912 100644--- a/model_tools.py+++ b/model_tools.py@@ -39,6 +39,17 @@ def suppress_post_tool_call_hook():finally:_post_tool_call_hook_suppressed.reset(token)++@contextmanager+def own_post_tool_call_hook():+ """Each entry of a connector ``tool_call`` batch is its own call and emits its own post-tool+ event, even inside an executor that suppressed the inner one for the wrapper."""+ token = _post_tool_call_hook_suppressed.set(False)+ try:+ yield+ finally:+ _post_tool_call_hook_suppressed.reset(token)+# Platform-bundle names already flagged in disabled_toolsets (advisory logged once per name)._WARNED_DISABLED_BUNDLES: set = set()diff --git a/tools/connectors/dispatch.py b/tools/connectors/dispatch.pyindex af615a89c79..3683fb5a70b 100644--- a/tools/connectors/dispatch.py+++ b/tools/connectors/dispatch.py@@ -20,7 +20,7 @@ def dispatch_connector_call(name, arguments, tool_call_id, turn_id=None):def dispatch_connector_batch(calls, ids, *, user_task, enabled_tools,middleware_trace, enabled_toolsets, disabled_toolsets):- from model_tools import handle_function_call+ from model_tools import handle_function_call, own_post_tool_call_hookfrom tools.interrupt import is_interruptedif len(calls) > MAX_CALLS_PER_DISPATCH:@@ -38,14 +38,15 @@ def dispatch_connector_batch(calls, ids, *, user_task, enabled_tools,partition.remote[offset:], "Stopped by the user before this call was made.",code="INTERRUPTED"))break- # Each entry must run its own policy and middleware.- payload = handle_function_call(- plan.name, plan.arguments, **asdict(ids), user_task=user_task,- enabled_tools=enabled_tools, tool_request_middleware_trace=list(middleware_trace),- skip_pre_tool_call_hook=False, skip_tool_request_middleware=False,- skip_tool_execution_middleware=False,- enabled_toolsets=enabled_toolsets, disabled_toolsets=disabled_toolsets,- )+ # Each entry must run its own policy and middleware, and report as its own call.+ with own_post_tool_call_hook():+ payload = handle_function_call(+ plan.name, plan.arguments, **asdict(ids), user_task=user_task,+ enabled_tools=enabled_tools, tool_request_middleware_trace=list(middleware_trace),+ skip_pre_tool_call_hook=False, skip_tool_request_middleware=False,+ skip_tool_execution_middleware=False,+ enabled_toolsets=enabled_toolsets, disabled_toolsets=disabled_toolsets,+ )try:value = json.loads(payload) if isinstance(payload, str) else payloadexcept ValueError: