Skip to content
Merged
21 changes: 15 additions & 6 deletions docs/observability/relay-shared-metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,16 @@ Hermes turn, API, and tool hooks

Hermes sends an empty `LLMRequest` into the metrics-owned lifecycle. This does
not describe the separate managed-execution call through the native runtime
documented above. The terminal metrics event contains only bounded model
family, provider family, locality, call role, and outcome values. Prompts,
responses, exact model IDs, endpoints, errors, session IDs, task IDs, and
request IDs are not included in the metrics event or package.
documented above. The terminal metrics event contains the model identifier and
provider route that Hermes used for the logical call, such as
`nvidia/nemotron-3-ultra` through `openrouter`. These identifiers are
lowercased and structurally bounded, but they are not normalized through a
checked-in model catalog. Pricing and model-family classification belong to
the metrics backend. Prompts, responses, endpoints, errors, session IDs, task
IDs, and request IDs are not included in the metrics event or package.
New calls use `hermes.model_route.count`. The previous
`hermes.model_call.count` contract remains readable only so pending local
counters created by older builds can be exported without losing data.

Each task run is a Relay `Function` scope named `hermes.task_run`, parented to
the owning Hermes session. The start counter contains only bounded execution
Expand All @@ -96,6 +102,9 @@ files are immutable delta documents that conform to a closed JSON schema and
are written with atomic replacement. Fully packaged aggregate rows and
successfully exported package rows and files are retained locally for 30 days.
Pending package rows and counters with unexported deltas are never pruned.
Package schema v1 remains unchanged for existing outbox files. New packages
use v2, which accepts both the retired model-call contract and the current
model-route contract so upgrades can drain pending counters safely.

Each package contains an `install_id` generated as a random UUID. Despite the
schema field name, its current scope is one `HERMES_HOME`, so it is more
Expand Down Expand Up @@ -123,5 +132,5 @@ The script uses the installed `nemo-relay` dependency by default. Pass
binding.

The smoke verifies the model request reached the local server, model and task
counters were stored, one package was exported, and prompt, response, and
exact-model canaries are absent from the package.
counters were stored with the expected model and provider, one package was
exported, and prompt and response canaries are absent from the package.
109 changes: 77 additions & 32 deletions hermes_cli/observability/relay_shared_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@

from .shared_metrics import SharedMetricsStore
from .shared_metrics_contract import (
MODEL_CALL_PROFILE_MODEL,
MODEL_CALL_SCOPE,
SCHEMA_KEY,
SCHEMA_VERSION,
SUBSCRIBER_NAME,
TASK_SCOPE,
model_call_fields,
model_call_outcome,
task_start_fields,
task_terminal_fields,
)
Expand Down Expand Up @@ -81,7 +81,7 @@ class _MetricsSession:
relay_session: relay_runtime.RelaySession
lock: threading.RLock = field(default_factory=threading.RLock, repr=False)
closing: bool = False
model_calls: dict[str, _ModelCall] = field(default_factory=dict)
model_calls: dict[tuple[str, str], _ModelCall] = field(default_factory=dict)
tasks: dict[str, _TaskRun] = field(default_factory=dict)


Expand Down Expand Up @@ -230,25 +230,26 @@ def start_model_call(self, event: dict[str, Any]) -> None:
session = self.ensure_session(event)
if session is None:
return
request_id = str(event.get("api_request_id") or "")
if not request_id:
model_call_key = self._new_model_call_key(event)
if model_call_key is None:
return
_, request_id = model_call_key
fields = model_call_fields(event)
retry_ordinal = _retry_ordinal(event)
model_family = fields["model_family"]
with session.lock:
if session.closing:
return
if task is not None:
self._remember_turn(session, task, event)
existing = session.model_calls.get(request_id)
existing = session.model_calls.get(model_call_key)
if existing is not None:
existing.fields = fields
if task is not None:
if retry_ordinal is None or existing.retry_ordinal is None:
task.retry_count += 1
elif retry_ordinal > existing.retry_ordinal:
task.retry_count += retry_ordinal - existing.retry_ordinal
# Every repeated start for one logical request is another
# physical attempt. Provider fallback resets Hermes's
# provider-local retry ordinal, so ordinal deltas are not a
# reliable task-level retry counter.
task.retry_count += 1
if retry_ordinal is not None:
existing.retry_ordinal = max(
existing.retry_ordinal or 0,
Expand All @@ -268,7 +269,7 @@ def start_model_call(self, event: dict[str, Any]) -> None:
self.relay.LLMRequest({}, {}),
handle=task.handle,
metadata=self._event_metadata(),
model_name=model_family,
model_name=MODEL_CALL_PROFILE_MODEL,
)
else:
handle = self._run_in_session(
Expand All @@ -278,15 +279,33 @@ def start_model_call(self, event: dict[str, Any]) -> None:
self.relay.LLMRequest({}, {}),
handle=session.relay_session.handle,
metadata=self._event_metadata(),
model_name=model_family,
model_name=MODEL_CALL_PROFILE_MODEL,
)
session.model_calls[request_id] = _ModelCall(
session.model_calls[model_call_key] = _ModelCall(
handle=handle,
task_id=str(event.get("task_id") or ""),
fields=fields,
retry_ordinal=retry_ordinal,
)

def record_model_call_error(self, event: dict[str, Any]) -> None:
"""Retain the latest attempt error without closing the logical call."""
session = self._task_session(event, allow_task_id_fallback=True)
if session is None:
session = self._session(event)
if session is None:
return
with session.lock:
if session.closing:
return
model_call_key = self._existing_model_call_key(session, event)
if model_call_key is None:
return
model_call = session.model_calls.get(model_call_key)
if model_call is None:
return
model_call.fields = model_call_fields(event)

def record_tool_call(self, event: dict[str, Any]) -> None:
"""Count one unique tool invocation under its owning task."""
task_id = str(event.get("task_id") or "")
Expand All @@ -307,25 +326,26 @@ def record_tool_call(self, event: dict[str, Any]) -> None:
else:
task.unidentified_tool_calls += 1

def end_model_call(self, event: dict[str, Any], outcome: str | None = None) -> None:
def end_model_call(self, event: dict[str, Any]) -> None:
session = self._task_session(event, allow_task_id_fallback=True)
if session is None:
session = self._session(event)
if session is None:
return
request_id = str(event.get("api_request_id") or "")
with session.lock:
if session.closing:
return
model_call = session.model_calls.get(request_id)
model_call_key = self._existing_model_call_key(session, event)
if model_call_key is None:
return
model_call = session.model_calls.get(model_call_key)
if model_call is None:
return
fields = model_call_fields(event)
model_call.fields = fields
self._finish_model_call(
session,
request_id,
outcome or model_call_outcome(event),
model_call_key,
)

def end_pending_model_calls(self, event: dict[str, Any]) -> None:
Expand Down Expand Up @@ -529,10 +549,9 @@ def _remember_turn(
def _finish_model_call(
self,
session: _MetricsSession,
request_id: str,
outcome: str,
model_call_key: tuple[str, str],
) -> None:
model_call = session.model_calls.pop(request_id, None)
model_call = session.model_calls.pop(model_call_key, None)
if model_call is None:
return
try:
Expand All @@ -542,15 +561,15 @@ def _finish_model_call(
task,
self.relay.llm.call_end,
model_call.handle,
{**model_call.fields, "outcome": outcome},
model_call.fields,
metadata=self._event_metadata(),
)
else:
self._run_in_session(
session,
self.relay.llm.call_end,
model_call.handle,
{**model_call.fields, "outcome": outcome},
model_call.fields,
metadata=self._event_metadata(),
)
except Exception:
Expand All @@ -564,14 +583,41 @@ def _end_pending_model_calls(
event: dict[str, Any],
) -> None:
task_id = str(event.get("task_id") or "")
request_ids = [
request_id
for request_id, model_call in session.model_calls.items()
model_call_keys = [
model_call_key
for model_call_key, model_call in session.model_calls.items()
if not task_id or model_call.task_id == task_id
]
outcome = "cancelled" if event.get("interrupted") else "failed"
for request_id in request_ids:
self._finish_model_call(session, request_id, outcome)
for model_call_key in model_call_keys:
self._finish_model_call(
session,
model_call_key,
)

@staticmethod
def _new_model_call_key(event: dict[str, Any]) -> tuple[str, str] | None:
request_id = str(event.get("api_request_id") or "")
if not request_id:
return None
return str(event.get("task_id") or ""), request_id

@classmethod
def _existing_model_call_key(
cls,
session: _MetricsSession,
event: dict[str, Any],
) -> tuple[str, str] | None:
key = cls._new_model_call_key(event)
if key is None:
return None
if key in session.model_calls:
return key
if key[0]:
return None
candidates = [
candidate for candidate in session.model_calls if candidate[1] == key[1]
]
return candidates[0] if len(candidates) == 1 else None

def _finish_task(
self,
Expand Down Expand Up @@ -682,10 +728,9 @@ def observe_lifecycle(hook_name: str, **kwargs: Any) -> None:
elif hook_name == "post_tool_call":
runtime.record_tool_call(kwargs)
elif hook_name == "post_api_request":
runtime.end_model_call(kwargs, "success")
runtime.end_model_call(kwargs)
elif hook_name == "api_request_error":
if kwargs.get("retryable") is False:
runtime.end_model_call(kwargs, "failed")
runtime.record_model_call_error(kwargs)
elif hook_name == "on_session_end":
runtime.finish_task(kwargs)
elif hook_name == "subagent_stop":
Expand Down
Loading
Loading