The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(connectors): batch entries dispatch under their own call ids
Siddharth Balyan242439977bf2
diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.pyindex fec215441e7..43b9137c9d6 100644--- a/hermes_cli/observability/relay_shared_metrics.py+++ b/hermes_cli/observability/relay_shared_metrics.py@@ -208,6 +208,7 @@ class _PeakLineage:tally: engagement_.SessionTally = field(default_factory=engagement_.SessionTally)run: engagement_.RouteRun = field(default_factory=engagement_.RouteRun)spent: deque | None = None+ connectors: connectors_.ConnectorSessionState | None = None# Backstop: conversations whose rotated-to segment a surface never closed are flushed past this many.@@ -471,10 +472,10 @@ class _Runtime:returnif connectors_.is_connector_batch(event):return # each entry opens its own lifecycle; the wrapper counts only if no entry ran+ identity = self._tool_call_identity(event)with 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@@ -516,11 +517,11 @@ class _Runtime:returntool_call = Noneif _text(event, "tool_call_id"):- 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)+ observed_identity = self._tool_call_identity(event)+ if connectors_.is_connector_batch(event) and connectors_.batch_entry_ran(+ task.completed_tool_call_ids, observed_identity):+ task.completed_tool_call_ids.add(observed_identity)return- observed_identity = self._tool_call_identity(event, session, task_id)if observed_identity in task.completed_tool_call_ids:returnidentity = observed_identity@@ -548,7 +549,7 @@ 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))+ chain = session.connectors.observe(event)if chain is not None:self._mark(session, task, contract.CONNECTOR_CHAIN_MARK, chain)@@ -781,13 +782,9 @@ class _Runtime:self._turn_sessions[(session.session_id, turn_id)] = session@staticmethod- 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)+ 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")@staticmethoddef _event_matches_task_turn(task: _TaskRun, event: dict[str, Any]) -> bool:@@ -932,7 +929,6 @@ 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),@@ -1070,7 +1066,8 @@ class _Runtime:if old is None:return # a segment this process never served: the new id is its own conversationkey = old_id- self._lineages[key] = _PeakLineage(open={old_id}, run=old.route_run, spent=old.efficiency.spent)+ self._lineages[key] = _PeakLineage(+ open={old_id}, run=old.route_run, spent=old.efficiency.spent, connectors=old.connectors)self._lineage_of[old_id] = keyself._lineages[key].open.add(new_id)self._lineage_of[new_id] = key@@ -1093,10 +1090,15 @@ class _Runtime:return lineage.spent if lineage is not None else Nonedef _share_spent(self, session: _MetricsSession) -> None:- """A rotated-to segment's /undo and /retry reach the turns the earlier segments spent."""+ """A rotated-to segment's /undo and /retry reach the turns the earlier segments spent, and its+ connector chain continues the earlier segments' searches and descriptions."""spent = self._lineage_spent(session.session_id)if spent is not None:session.efficiency.spent = spent+ with self._lineage_lock:+ lineage = self._lineages.get(self._lineage_of.get(session.session_id, ""))+ if lineage is not None and lineage.connectors is not None:+ session.connectors = lineage.connectorsdef _with_route_run(self, session_id: str, own: engagement_.RouteRun | None, update: Callable[[engagement_.RouteRun], Any],diff --git a/hermes_cli/observability/shared_metrics_connectors.py b/hermes_cli/observability/shared_metrics_connectors.pyindex c4be7f2aab9..3f966abdbe7 100644--- a/hermes_cli/observability/shared_metrics_connectors.py+++ b/hermes_cli/observability/shared_metrics_connectors.py@@ -1,10 +1,9 @@-"""Connector work in the shared metrics: per-entry tool counting, the search-to-execute chain, and-the batch and search rows.+"""Connector work in the shared metrics: 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.+Each entry of a connector ``tool_call`` batch dispatches with its own call id (``<id>#<position>``,+``tools/connectors/dispatch.py``), so entries count as their own calls; the wrapper's post under the+bare id is dropped once an entry ran. Connector slugs, tool names and query text never leave this+module: rows carry only buckets and closed enums."""from __future__ import annotations@@ -42,42 +41,41 @@ def is_connector_batch(event: dict[str, Any]) -> bool:return bool(entries) and all(is_connector_name(entry.get("name")) for entry in entries)+def batch_entry_ran(identities: Iterable[tuple[str, str, str]], wrapper: tuple[str, str, str]) -> bool:+ """Whether an entry of the batch whose wrapper has identity ``wrapper`` was already counted."""+ prefix = f"{wrapper[2]}#"+ return bool(wrapper[2]) and any(+ identity[2].startswith(prefix) and identity[:2] == wrapper[:2] for identity in identities)+++def _described_names(args: Any) -> list[str]:+ """``tool_describe`` names as its dispatcher reads them: a bare string is one name, items stripped."""+ names = args.get("names") if isinstance(args, dict) else None+ names = [names] if isinstance(names, str) else names if isinstance(names, list) else []+ return [str(name or "").strip() for name in names]++@dataclassclass ConnectorSessionState:- """Per-conversation connector state; the caller holds the session lock."""+ """Per-conversation chain state; the caller holds the session lock. Compression hands it to the+ rotated-to segment so the chain spans the whole conversation."""searches_since_execute: int = 0described: 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:+ def observe(self, event: dict[str, Any]) -> 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 += 1return Noneif 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 ():+ for described in _described_names(event.get("args")):if is_connector_name(described) and len(self.described) < _MAX_DESCRIBED:self.described.add(described)return Noneif not is_connector_name(name):return None- if base[2]:- key = (task_id, *base)- self.counted_entries[key] = self.counted_entries.get(key, 0) + 1fields = {"described_first": "yes" if name in self.described else "no","outcome": contract.tool_outcome(event),@@ -86,10 +84,6 @@ class ConnectorSessionState:self.searches_since_execute = 0return 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 ----------------------------------------------------------------------------diff --git a/model_tools.py b/model_tools.pyindex 4c14cda0912..8dd93efc5ea 100644--- a/model_tools.py+++ b/model_tools.py@@ -31,20 +31,10 @@ _post_tool_call_hook_suppressed: ContextVar[bool] = ContextVar("post_tool_call_h@contextmanager-def suppress_post_tool_call_hook():- """Let an outer executor own the terminal post-tool event."""- token = _post_tool_call_hook_suppressed.set(True)- try:- yield- 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)+def suppress_post_tool_call_hook(suppressed: bool = True):+ """Let an outer executor own the terminal post-tool event. ``suppressed=False`` re-enables it+ inside such a block, for calls that are their own (each entry of a connector batch)."""+ token = _post_tool_call_hook_suppressed.set(suppressed)try:yieldfinally:diff --git a/tests/hermes_cli/test_shared_metrics_connectors.py b/tests/hermes_cli/test_shared_metrics_connectors.pyindex a37a9fcf577..18e996fc3cc 100644--- a/tests/hermes_cli/test_shared_metrics_connectors.py+++ b/tests/hermes_cli/test_shared_metrics_connectors.py@@ -83,13 +83,15 @@ def test_batch_row_counts_logical_calls_and_the_connector_share():def _connector_batch_hooks(entries, *, wrapper_result="ok"):- """The hook sequence a connector batch produces: pre/post per entry, then the wrapper's post."""+ """The hook sequence a connector batch produces: pre/post per entry under ``<id>#<position>``,+ then the wrapper's post under the bare id."""call = {**_BASE, "tool_call_id": "tc1"}- for name, result in entries:- lifecycle.invoke_hook("pre_tool_call", **call, tool_name=name, args={})+ for position, (name, result) in enumerate(entries):+ entry = {**call, "tool_call_id": f"tc1#{position}"}+ lifecycle.invoke_hook("pre_tool_call", **entry, tool_name=name, args={})failed = isinstance(result, dict)lifecycle.invoke_hook(- "post_tool_call", **call, tool_name=name, args={}, result=json.dumps(result if failed else {"ok": 1}),+ "post_tool_call", **entry, tool_name=name, args={}, result=json.dumps(result if failed else {"ok": 1}),status="error" if failed else "ok", error_type="tool_error" if failed else None)lifecycle.invoke_hook("post_tool_call", **call, tool_name="tool_call", status=wrapper_result, result="{}",@@ -154,6 +156,42 @@ def test_chain_row_counts_searches_since_the_last_execute_and_whether_the_tool_w]+def test_a_plugin_approval_on_a_connector_entry_is_attributed_to_that_entry(fake_relay):+ lifecycle.invoke_hook("pre_llm_call", **_BASE)+ entry = {**_BASE, "tool_call_id": "tc1#0", "tool_name": "connectors__gmail__SEND_EMAIL", "args": {}}+ lifecycle.invoke_hook("pre_tool_call", **entry)+ lifecycle.invoke_hook("post_approval_response", **_BASE, tool_call_id="tc1#0", choice="once")+ lifecycle.invoke_hook("post_tool_call", **entry, result="{}", status="ok")+ _end_turn()+ [approval] = [event[2]["data"] for event in fake_relay.events+ if event[0] == "scope.event" and event[1] == contract.TOOL_APPROVAL_MARK]+ assert approval == {"attribution": "tool_call", "outcome": "approved"}+ [end] = [event[2] for event in fake_relay.events if event[0] == "tool.call_end"]+ assert end["approval_outcome"] == "approved"+++def test_the_chain_survives_a_compression_rotation(fake_relay):+ from hermes_cli.observability import relay_shared_metrics++ lifecycle.invoke_hook("pre_llm_call", **_BASE)+ for n, (name, args) in enumerate([+ ("tool_search", {"queries": ["mail"]}),+ ("tool_describe", {"names": " connectors__gmail__SEND_EMAIL "}), # bare string, padded+ ]):+ call = {**_BASE, "tool_call_id": f"c{n}", "tool_name": name, "args": args}+ lifecycle.invoke_hook("pre_tool_call", **call)+ lifecycle.invoke_hook("post_tool_call", **call, result="{}", status="ok")+ relay_shared_metrics.rotate_segment("s1", "s2")+ rotated = {**_BASE, "session_id": "s2", "task_id": "t2", "turn_id": "turn-2"}+ lifecycle.invoke_hook("pre_llm_call", **rotated)+ call = {**rotated, "tool_call_id": "c9", "tool_name": "connectors__gmail__SEND_EMAIL", "args": {}}+ lifecycle.invoke_hook("pre_tool_call", **call)+ lifecycle.invoke_hook("post_tool_call", **call, result="{}", status="ok")+ [chain] = [event[2]["data"] for event in fake_relay.events+ if event[0] == "scope.event" and event[1] == contract.CONNECTOR_CHAIN_MARK]+ assert chain == {"described_first": "yes", "outcome": "success", "searches_before_bucket": "1"}++def test_entries_report_their_own_post_even_under_the_executor_suppression(monkeypatch):"""The sequential executor suppresses the inner post_tool_call for the call it owns; connectorentries are their own calls and must still report, or each entry's lifecycle never closes."""@@ -165,18 +203,25 @@ def test_entries_report_their_own_post_even_under_the_executor_suppression(monkemonkeypatch.setattr(config, "connectors_available", lambda: True)monkeypatch.setattr(bridge, "connectors_available", lambda: True)invalidate_check_fn_cache()- monkeypatch.setattr(bridge, "run_remote", lambda plans, _id, **_kw: [- {"index": plan.position, "name": plan.name, "response": {"ok": 1}} for plan in plans])+ gateway_ids = []++ def fake_remote(plans, dispatch_id, **_kw):+ gateway_ids.append(dispatch_id)+ return [{"index": plan.position, "name": plan.name, "response": {"ok": 1}} for plan in plans]++ monkeypatch.setattr(bridge, "run_remote", fake_remote)posts = []monkeypatch.setattr(lc, "has_hook", lambda name: True)- monkeypatch.setattr(lc, "invoke_hook", lambda name, **kw: posts.append(kw["tool_name"]) or []- if name == "post_tool_call" else [])+ monkeypatch.setattr(lc, "invoke_hook", lambda name, **kw: posts.append((kw["tool_name"], kw["tool_call_id"]))+ or [] if name == "post_tool_call" else [])calls = [{"name": "connectors__gmail__SEND_EMAIL", "arguments": {}},{"name": "connectors__slack__POST", "arguments": {}}]with model_tools.suppress_post_tool_call_hook():model_tools.handle_function_call("tool_call", {"calls": calls}, tool_call_id="tc1",enabled_toolsets=["connections"])- assert posts == ["connectors__gmail__SEND_EMAIL", "connectors__slack__POST"]+ # Each entry reports under its own id, so a trace observer never folds entries together.+ assert posts == [("connectors__gmail__SEND_EMAIL", "tc1#0"), ("connectors__slack__POST", "tc1#1")]+ assert gateway_ids == ["tc1#0", "tc1#1"]def test_a_package_with_each_new_row_validates_against_the_v4_schema(tmp_path, monkeypatch):diff --git a/tests/tools/test_connector_dispatch_policy.py b/tests/tools/test_connector_dispatch_policy.pyindex e2c29cba32d..1bfd24ecb2c 100644--- a/tests/tools/test_connector_dispatch_policy.py+++ b/tests/tools/test_connector_dispatch_policy.py@@ -31,7 +31,7 @@ def test_remote_entries_run_request_hook_and_execution_policies(monkeypatch, bloevents.append(("hook", name))assert args == {"body": "request-rewrite"}assert kw["middleware_trace"] == [{"source": "test-policy"}]- assert kw["tool_call_id"] == "policy-call"+ assert kw["tool_call_id"] == f"policy-call#{[denied, rewritten].index(name)}" # each entry is its own callif name == denied and blocked_by == "hook":return "hook denied", Nonereturn None, {"body": "hook-rewrite"}diff --git a/tools/connectors/dispatch.py b/tools/connectors/dispatch.pyindex 3683fb5a70b..cd8ba8c2fbe 100644--- a/tools/connectors/dispatch.py+++ b/tools/connectors/dispatch.py@@ -20,7 +20,9 @@ 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, own_post_tool_call_hook+ from dataclasses import replace++ from model_tools import handle_function_call, suppress_post_tool_call_hookfrom tools.interrupt import is_interruptedif len(calls) > MAX_CALLS_PER_DISPATCH:@@ -38,10 +40,12 @@ 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, and report as its own call.- with own_post_tool_call_hook():+ # Each entry is its own call: its own policy, middleware, hooks and call id (``<id>#<position>``),+ # so observers never fold an entry into the wrapper or into a sibling entry.+ entry_ids = replace(ids, tool_call_id=f"{ids.tool_call_id}#{plan.position}") if ids.tool_call_id else ids+ with suppress_post_tool_call_hook(False):payload = handle_function_call(- plan.name, plan.arguments, **asdict(ids), user_task=user_task,+ plan.name, plan.arguments, **asdict(entry_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,