Skip to content

The agent that grows with you

fix(telemetry): local-server aliases and unknown providers never ship model ids

teknium1093c10a2eef9
diff --git a/gateway/slash_commands_model.py b/gateway/slash_commands_model.py
index 182ceb00beb..0b9c02492e4 100644
--- a/gateway/slash_commands_model.py
+++ b/gateway/slash_commands_model.py
@@ -74,6 +74,9 @@ class _ModelSwitchContext:
restore_snapshot: Optional[dict] = None
current_model: str = ""
current_provider: str = "openrouter"
+ # The provider actually configured/overridden (None = unset): ``current_provider`` defaults to
+ # openrouter for switch_model, which must not label the configured model in metrics.
+ route_provider: Optional[str] = None
current_base_url: str = ""
current_api_key: str = ""
user_provs: Any = None
@@ -91,6 +94,7 @@ class _ModelSwitchContext:
if isinstance(model_cfg, dict):
self.current_model = model_cfg.get("default", "")
self.current_provider = model_cfg.get("provider", self.current_provider)
+ self.route_provider = model_cfg.get("provider")
self.current_base_url = model_cfg.get("base_url", "")
self.user_provs = cfg.get("providers")
try:
@@ -109,6 +113,7 @@ class _ModelSwitchContext:
if override:
self.current_model = override.get("model", self.current_model)
self.current_provider = override.get("provider", self.current_provider)
+ self.route_provider = override.get("provider", self.route_provider)
self.current_base_url = override.get("base_url", self.current_base_url)
self.current_api_key = override.get("api_key", self.current_api_key)
@@ -373,16 +378,31 @@ class GatewayModelCommandsMixin:
lock = self.__dict__["_model_switch_lock_obj"] = asyncio.Lock()
return lock
+ def _record_switch_metrics(self, result, ctx: _ModelSwitchContext, source) -> None:
+ """Slash dispatch does not install the routed profile's scope, so a multiplexed runner binds
+ the owning home for the switch row and its switch_away friction."""
+ from hermes_cli.observability.shared_metrics_events import record_model_switch
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ home = None
+ if getattr(getattr(self, "config", None), "multiplex_profiles", False):
+ with contextlib.suppress(Exception):
+ home = self._resolve_profile_home_for_source(source)
+ token = set_hermes_home_override(str(home)) if home else None
+ try:
+ record_model_switch(
+ from_provider=ctx.route_provider, to_provider=result.target_provider, surface="gateway",
+ from_model=ctx.current_model)
+ finally:
+ if token is not None:
+ reset_hermes_home_override(token)
+
async def _commit_model_switch_locked(self, result, ctx: _ModelSwitchContext, *, source, picker: bool) -> str:
one_turn = False if picker else ctx.one_turn
error = self._switch_cached_agent_model(result, ctx, picker)
if error is not None:
return error
- from hermes_cli.observability.shared_metrics_events import record_model_switch
-
- record_model_switch(
- from_provider=ctx.current_provider, to_provider=result.target_provider, surface="gateway",
- from_model=ctx.current_model)
+ self._record_switch_metrics(result, ctx, source)
global_error = await self._record_model_switch(result, ctx, source=source, one_turn=one_turn, picker=picker)
reply = await self._model_switch_confirmation(
result, ctx, one_turn=one_turn, picker=picker, global_error=global_error,
diff --git a/hermes_cli/observability/shared_metrics_catalog.py b/hermes_cli/observability/shared_metrics_catalog.py
index 0f83ce8b998..52627a37114 100644
--- a/hermes_cli/observability/shared_metrics_catalog.py
+++ b/hermes_cli/observability/shared_metrics_catalog.py
@@ -101,6 +101,16 @@ def user_named_model_providers() -> frozenset[str]:
) | {CUSTOM}
+def custom_provider_aliases() -> frozenset[str]:
+ """Provider ids Hermes routes through the generic ``custom`` provider (``ollama``, ``vllm``,
+ ``llamacpp``...): shipped names, but the server and its model ids are the user's own."""
+ from hermes_cli import auth, models, providers
+
+ tables = (providers.ALIASES, getattr(auth, "_PROVIDER_ALIASES", {}), getattr(models, "_PROVIDER_ALIASES", {}))
+ return frozenset(alias for table in tables for alias, canon in table.items() if canon == CUSTOM)
+
+
# ---- v4 gateway ----
@functools.cache
def bundled_platform_names() -> frozenset[str]:
@@ -229,13 +239,14 @@ def aux_task_metric_name(raw: object) -> str:
def provider_metric_name(raw: object) -> str:
- """A shipped provider id; user-named providers (``custom:<name>``, unknown ids) read ``custom``."""
+ """A shipped provider id; user-named providers (``custom:<name>``, unknown ids) and the local
+ server aliases of ``custom`` read ``custom``."""
from .shared_metrics_contract import PROVIDER_IDENTIFIER_MAX_LENGTH, _metric_identifier
name = _metric_identifier(raw, max_length=PROVIDER_IDENTIFIER_MAX_LENGTH)
if name == "unknown":
return name
- if name.startswith(CUSTOM):
+ if name.startswith(CUSTOM) or name in _safe(custom_provider_aliases):
return CUSTOM
return name if name in _safe(provider_names) or _models_dev_provider(name) else CUSTOM
@@ -253,13 +264,16 @@ def _models_dev_provider(name: str) -> bool:
def model_metric_name(raw: object, provider: str, *, max_length: int) -> str:
"""The model id for a shipped remote provider; ``custom`` when the user names it (custom
- endpoint, loopback server) or it looks like a filesystem path or URL."""
+ endpoint, loopback server), the provider is unknown (nothing proves the id is public), or it
+ looks like a filesystem path or URL."""
from .shared_metrics_contract import _metric_identifier
if provider in _safe(user_named_model_providers):
return CUSTOM
model = _metric_identifier(raw, max_length=max_length)
- if "://" in model or ":/" in model or model.endswith((".gguf", ".bin", ".safetensors")):
+ if model == "unknown":
+ return model
+ if provider == "unknown" or "://" in model or ":/" in model or model.endswith((".gguf", ".bin", ".safetensors")):
return CUSTOM
return model
diff --git a/tests/hermes_cli/test_shared_metrics_model_attribution.py b/tests/hermes_cli/test_shared_metrics_model_attribution.py
new file mode 100644
index 00000000000..f2cfa8e4f0f
--- /dev/null
+++ b/tests/hermes_cli/test_shared_metrics_model_attribution.py
@@ -0,0 +1,173 @@
+"""Provider/model attribution invariants for the per-model shared metrics: which route a row names,
+that user-named models never leave the machine, which profile records it, and how often."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli import lifecycle
+from hermes_cli.observability import relay_shared_metrics
+from tests.hermes_cli.test_relay_shared_metrics_runtime import ( # noqa: F401 - fixture
+ _stored_values,
+ direct_runtime,
+)
+
+SECRET = "acme-internal-secret-v2"
+PUBLIC = "anthropic/claude-sonnet-4"
+# The stored install snapshot reflects the fixture's config; the snapshot built from the probed
+# config is checked separately.
+_PROVIDER_FIELDS = ("provider", "from_provider")
+
+
+def _flush() -> None:
+ for runtime in list(relay_shared_metrics._RUNTIMES.values()):
+ runtime.relay.subscribers.flush()
+
+
+def _all_rows(home) -> list[tuple[str, dict]]:
+ from hermes_cli.observability.shared_metrics import SharedMetricsStore
+
+ root = home / "telemetry" / "shared_metrics"
+ if not (root / "metrics.sqlite3").exists():
+ return []
+ store = SharedMetricsStore(root / "metrics.sqlite3", root / "outbox")
+ return [(c["metric_name"], c["dimensions"]) for c in store.counter_snapshot()]
+
+
+def _turn(session_id, task_id, provider, model, *, prompt_tokens=1_000, context_length=200_000, **start):
+ base = {"session_id": session_id, "task_id": task_id, "api_request_id": f"{task_id}-r",
+ "provider": provider, "model": model}
+ lifecycle.invoke_hook("pre_llm_call", **base, platform="cli", **start)
+ lifecycle.invoke_hook("pre_api_request", **base)
+ lifecycle.invoke_hook("post_api_request", **base, usage={"prompt_tokens": prompt_tokens, "output_tokens": 5},
+ context_length=context_length)
+ relay_shared_metrics.finish_task_run(session_id=session_id, task_id=task_id, platform="cli",
+ result={"completed": True})
+
+
+def _emit_every_model_metric(provider, model) -> dict:
+ """Drive every emitter that carries a provider/model dimension through its real entry point."""
+ from hermes_cli.observability import shared_metrics_events as events
+ from hermes_cli.observability.shared_metrics_model import record_model_friction, record_tool_call_quality
+ from hermes_cli.observability.shared_metrics_snapshot import collect_install_snapshot
+
+ _turn("s1", "t1", provider, model) # model_route, model_tokens (primary), context_peak
+ lifecycle.invoke_hook("post_auxiliary_call", session_id="s1", provider=provider, model=model,
+ aux_task="compression", usage={"input_tokens": 10})
+ events.record_fallback(from_provider=provider, to_provider="openrouter", reason="rate_limit")
+ events.record_model_switch(from_provider=provider, to_provider="openrouter", surface="cli", from_model=model)
+ events.record_setup_completed(surface="cli", provider=provider)
+ record_model_friction("retry", session_id="not-seen", provider=provider, model=model)
+ agent = SimpleNamespace(provider=provider, model=model, valid_tool_names={"todo"}, tools=[])
+ record_tool_call_quality(agent, [SimpleNamespace(function=SimpleNamespace(name="todo", arguments="{}"))], set())
+ lifecycle.finalize_session(session_id="s1")
+ _flush()
+ return collect_install_snapshot({"model": {"provider": provider, "default": model}})
+
+
+_MODEL_METRICS = {
+ "hermes.model_route.count", "hermes.model_tokens.sum", "hermes.context_peak.count",
+ "hermes.fallback.count", "hermes.model_switch.count", "hermes.setup.completed",
+ "hermes.model_friction.count", "hermes.model_tool_quality.count",
+}
+
+
[email protected]("provider", [
+ "ollama", "local", "vllm", "llamacpp", "llama.cpp", "custom:acme-lab", None, "", "acme-gpu-box",
+])
+def test_user_named_models_never_leave_in_any_model_metric(direct_runtime, tmp_path, provider):
+ """Local-server aliases of ``custom``, a missing provider and unknown ids all read custom/unknown
+ with model ``custom`` in every provider/model-bearing metric; the raw id is nowhere."""
+ snapshot = _emit_every_model_metric(provider, SECRET)
+ rows = _all_rows(tmp_path / "hermes-home")
+
+ assert SECRET not in json.dumps(rows) + json.dumps(snapshot)
+ assert _MODEL_METRICS <= {name for name, _ in rows}
+ assert snapshot["main_provider"] in {"custom", "unknown", "none"}
+ for name, dims in rows:
+ for key in _PROVIDER_FIELDS:
+ if key in dims:
+ assert dims[key] in {"custom", "unknown", "none"}, (name, dims)
+ if "model" in dims:
+ assert dims["model"] == "custom", (name, dims)
+
+
+def test_shipped_provider_and_public_model_are_reported_as_is(direct_runtime, tmp_path):
+ snapshot = _emit_every_model_metric("openrouter", PUBLIC)
+ rows = _all_rows(tmp_path / "hermes-home")
+
+ assert snapshot["main_provider"] == "openrouter"
+ assert _MODEL_METRICS <= {name for name, _ in rows}
+ for name, dims in rows:
+ for key in _PROVIDER_FIELDS:
+ if key in dims:
+ assert dims[key] == "openrouter", (name, dims)
+ if "model" in dims:
+ assert dims["model"] == PUBLIC, (name, dims)
+
+
+def _gateway_runner(multiplex_home=None):
+ from gateway.slash_commands_model import GatewayModelCommandsMixin
+
+ class Runner(GatewayModelCommandsMixin):
+ def __init__(self):
+ self.config = SimpleNamespace(multiplex_profiles=multiplex_home is not None)
+
+ def _resolve_profile_home_for_source(self, source):
+ return multiplex_home
+
+ def _switch_cached_agent_model(self, result, ctx, picker):
+ return None
+
+ async def _record_model_switch(self, *a, **k):
+ return None
+
+ async def _model_switch_confirmation(self, *a, **k):
+ return "ok"
+
+ return Runner()
+
+
+def _gateway_switch(runner, config_path):
+ from gateway.slash_commands_model import _ModelSwitchContext
+
+ ctx = _ModelSwitchContext(session_key="k", source=None, config_path=config_path, persist_global=False)
+ ctx.read_config()
+ result = SimpleNamespace(target_provider="anthropic", new_model="claude-opus-4")
+ asyncio.run(runner._commit_model_switch_locked(result, ctx, source=None, picker=True))
+ _flush()
+
+
[email protected](("model_block", "expected"), [
+ (" provider: vllm\n default: acme-private-llama\n", ("custom", "custom")),
+ (" default: acme-private-llama\n base_url: http://10.0.0.5:8000/v1\n", ("unknown", "custom")),
+ (f" provider: openrouter\n default: {PUBLIC}\n", ("openrouter", PUBLIC)),
+])
+def test_gateway_switch_reports_the_configured_route_not_the_switch_default(
+ direct_runtime, tmp_path, model_block, expected,
+):
+ """Gateway /model reads config.yaml: an unset provider must not borrow switch_model's
+ ``openrouter`` default, and a local alias must not ship the configured model id."""
+ cfg = tmp_path / "gw-config.yaml"
+ cfg.write_text("model:\n" + model_block)
+ _gateway_switch(_gateway_runner(), cfg)
+
+ assert _stored_values(tmp_path, "hermes.model_friction.count") == [
+ ({"model": expected[1], "provider": expected[0], "signal": "switch_away"}, 1)]
+ assert _stored_values(tmp_path, "hermes.model_switch.count") == [
+ ({"execution_surface": "gateway", "from_provider": expected[0], "to_provider": "anthropic"}, 1)]
+
+
+def test_multiplexed_gateway_switch_records_in_the_owning_profile(direct_runtime, tmp_path):
+ home_b = tmp_path / "profiles" / "b"
+ home_b.mkdir(parents=True)
+ cfg = home_b / "config.yaml"
+ cfg.write_text(f"model:\n provider: openrouter\n default: {PUBLIC}\n")
+ _gateway_switch(_gateway_runner(multiplex_home=home_b), cfg)
+
+ assert not _all_rows(tmp_path / "hermes-home")
+ assert sorted(name for name, _ in _all_rows(home_b)) == ["hermes.model_friction.count", "hermes.model_switch.count"]
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index 9e5af8b2ced..24b8cdff5bf 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -324,7 +324,9 @@ local database, so each fires once per install however many processes reach it.
#### Per-model quality, friction and context pressure
Provider and model follow the model-route rules: a provider Hermes ships and its
-model id; custom endpoints and loopback servers read `custom`.
+model id; custom endpoints, the local-server aliases of `custom` (`ollama`, `local`,
+`vllm`, `llamacpp`, `llama.cpp`) and loopback servers read `custom`, and a model
+whose provider is unknown reads `custom`.
| Metric | Dimensions | Question it answers |
|---|---|---|