Skip to content

The agent that grows with you

Merge updated skill metrics into client resource metrics

Alex Fournier9b8d4133db05
diff --cc docs/observability/relay-shared-metrics.md
index 7d68f36b299,0d14abe519a..182608dc225
--- a/docs/observability/relay-shared-metrics.md
+++ b/docs/observability/relay-shared-metrics.md
@@@ -123,13 -126,12 +126,16 @@@ $HERMES_HOME/telemetry/shared_metrics/o
The database keeps transactional aggregate and package-outbox state. Package
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.
+are written with atomic replacement. Each package records the Hermes version,
+OS family, architecture, and install method as bounded client resources.
+Unrecognized platform or installation values are exported as `unknown`; raw
+platform strings, hostnames, and paths are never included. 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
diff --cc hermes_cli/observability/schemas/hermes.shared_metrics.v2.schema.json
index 00000000000,92562288534..1416581a2ae
mode 000000,100644..100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v2.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v2.schema.json
@@@ -1,0 -1,658 +1,673 @@@
+ {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "urn:hermes-agent:schema:shared-metrics:v2",
+ "title": "Hermes Shared Metrics Package v2",
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "schema_version",
+ "package_id",
+ "install_id",
+ "period_start",
+ "period_end",
+ "generated_at",
+ "resource",
+ "metrics"
+ ],
+ "properties": {
+ "schema_version": {
+ "const": "hermes.shared_metrics.v2"
+ },
+ "package_id": {
+ "$ref": "#/$defs/uuid"
+ },
+ "install_id": {
+ "description": "Random persistent identifier scoped to one HERMES_HOME; local-only in schema v2.",
+ "$ref": "#/$defs/uuid"
+ },
+ "period_start": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "period_end": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "generated_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "resource": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
- "hermes_version"
++ "architecture",
++ "hermes_version",
++ "install_method",
++ "os_family"
+ ],
+ "properties": {
++ "architecture": {
++ "type": "string",
++ "enum": ["arm", "arm64", "unknown", "x86", "x86_64"]
++ },
+ "hermes_version": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64
++ },
++ "install_method": {
++ "type": "string",
++ "enum": ["docker", "git", "homebrew", "nixos", "pip", "unknown"]
++ },
++ "os_family": {
++ "type": "string",
++ "enum": ["linux", "macos", "unknown", "windows"]
+ }
+ }
+ },
+ "metrics": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "oneOf": [
+ {
+ "$ref": "#/$defs/model_call_counter"
+ },
+ {
+ "$ref": "#/$defs/model_route_counter"
+ },
+ {
+ "$ref": "#/$defs/task_started_counter"
+ },
+ {
+ "$ref": "#/$defs/task_finished_counter"
+ },
+ {
+ "$ref": "#/$defs/tool_call_counter"
+ },
+ {
+ "$ref": "#/$defs/tool_approval_counter"
+ },
+ {
+ "$ref": "#/$defs/skill_lifecycle_counter"
+ },
+ {
+ "$ref": "#/$defs/skill_load_counter"
+ }
+ ]
+ }
+ }
+ },
+ "$defs": {
+ "uuid": {
+ "type": "string",
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
+ },
+ "model_call_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.model_call.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "call_role",
+ "locality",
+ "model_family",
+ "outcome",
+ "provider_family"
+ ],
+ "properties": {
+ "call_role": {
+ "const": "primary"
+ },
+ "locality": {
+ "enum": [
+ "local",
+ "remote",
+ "unknown"
+ ]
+ },
+ "model_family": {
+ "enum": [
+ "claude",
+ "deepseek",
+ "gemini",
+ "gemma",
+ "glm",
+ "gpt",
+ "grok",
+ "kimi",
+ "llama",
+ "minimax",
+ "mimo",
+ "mistral",
+ "nemotron",
+ "nova",
+ "o1",
+ "o3",
+ "o4",
+ "qwen",
+ "step",
+ "trinity",
+ "unknown"
+ ]
+ },
+ "outcome": {
+ "enum": [
+ "cancelled",
+ "failed",
+ "success"
+ ]
+ },
+ "provider_family": {
+ "enum": [
+ "aggregator",
+ "custom",
+ "direct",
+ "local",
+ "unknown"
+ ]
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "model_route_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.model_route.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "model",
+ "provider"
+ ],
+ "properties": {
+ "model": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256,
+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"
+ },
+ "provider": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64,
+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "task_started_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.task_run.started"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "entrypoint",
+ "execution_surface"
+ ],
+ "properties": {
+ "entrypoint": {
+ "$ref": "#/$defs/task_entrypoint"
+ },
+ "execution_surface": {
+ "$ref": "#/$defs/execution_surface"
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "task_finished_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.task_run.finished"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "duration_bucket",
+ "end_reason",
+ "entrypoint",
+ "execution_surface",
+ "model_call_count_bucket",
+ "outcome",
+ "retry_count_bucket",
+ "termination",
+ "tool_call_count_bucket"
+ ],
+ "properties": {
+ "duration_bucket": {
+ "$ref": "#/$defs/duration_bucket"
+ },
+ "end_reason": {
+ "enum": [
+ "approval_denied",
+ "completed",
+ "failed",
+ "guardrail_blocked",
+ "iteration_limit",
+ "system_aborted",
+ "timed_out",
+ "unknown",
+ "user_cancelled"
+ ]
+ },
+ "entrypoint": {
+ "$ref": "#/$defs/task_entrypoint"
+ },
+ "execution_surface": {
+ "$ref": "#/$defs/execution_surface"
+ },
+ "model_call_count_bucket": {
+ "$ref": "#/$defs/count_bucket"
+ },
+ "outcome": {
+ "enum": [
+ "cancelled",
+ "failed",
+ "success",
+ "timed_out",
+ "unknown"
+ ]
+ },
+ "retry_count_bucket": {
+ "$ref": "#/$defs/count_bucket"
+ },
+ "termination": {
+ "enum": [
+ "none",
+ "system_aborted",
+ "timed_out",
+ "unknown",
+ "user_cancelled"
+ ]
+ },
+ "tool_call_count_bucket": {
+ "$ref": "#/$defs/count_bucket"
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "execution_surface": {
+ "enum": [
+ "api",
+ "batch",
+ "cli",
+ "desktop",
+ "gateway",
+ "other",
+ "python",
+ "scheduled_task",
+ "tui",
+ "unknown"
+ ]
+ },
+ "task_entrypoint": {
+ "enum": [
+ "api",
+ "background",
+ "batch",
+ "delegated",
+ "gateway_message",
+ "interactive",
+ "other",
+ "python",
+ "scheduled_task",
+ "unknown"
+ ]
+ },
+ "duration_bucket": {
+ "enum": [
+ "1s_to_5s",
+ "2m_to_10m",
+ "30s_to_2m",
+ "5s_to_30s",
+ "gte_10m",
+ "lt_1s"
+ ]
+ },
+ "count_bucket": {
+ "enum": [
+ "0",
+ "1",
+ "2",
+ "3_to_5",
+ "6_to_10",
+ "gte_11"
+ ]
+ },
+ "tool_latency_bucket": {
+ "enum": [
+ "100ms_to_250ms",
+ "10s_to_30s",
+ "1s_to_2s",
+ "250ms_to_500ms",
+ "2s_to_5s",
+ "500ms_to_1s",
+ "5s_to_10s",
+ "gte_30s",
+ "lt_100ms",
+ "unknown"
+ ]
+ },
+ "tool_retry_bucket": {
+ "enum": [
+ "0",
+ "1",
+ "2",
+ "3_to_5",
+ "6_to_10",
+ "gte_11",
+ "unknown"
+ ]
+ },
+ "tool_call_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.tool_call.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "approval_outcome",
+ "latency_bucket",
+ "outcome",
+ "retry_count_bucket",
+ "tool_category"
+ ],
+ "properties": {
+ "approval_outcome": {
+ "enum": [
+ "approved",
+ "denied",
+ "not_required",
+ "timed_out",
+ "unknown"
+ ]
+ },
+ "latency_bucket": {
+ "$ref": "#/$defs/tool_latency_bucket"
+ },
+ "outcome": {
+ "enum": [
+ "blocked",
+ "cancelled",
+ "failed",
+ "success",
+ "timed_out",
+ "unknown"
+ ]
+ },
+ "retry_count_bucket": {
+ "$ref": "#/$defs/tool_retry_bucket"
+ },
+ "tool_category": {
+ "enum": [
+ "browser",
+ "code_execution",
+ "communication",
+ "computer_use",
+ "delegation",
+ "file",
+ "home_automation",
+ "mcp",
+ "media",
+ "memory",
+ "other",
+ "planning",
+ "project",
+ "scheduler",
+ "skill",
+ "terminal",
+ "unknown",
+ "web"
+ ]
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "tool_approval_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.tool_approval.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "attribution",
+ "outcome"
+ ],
+ "properties": {
+ "attribution": {
+ "enum": [
+ "tool_call",
+ "unattributed"
+ ]
+ },
+ "outcome": {
+ "enum": [
+ "approved",
+ "denied",
+ "timed_out",
+ "unknown"
+ ]
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "skill_lifecycle_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.skill.lifecycle.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "action",
+ "provenance"
+ ],
+ "properties": {
+ "action": {
+ "enum": [
+ "archived",
+ "created",
+ "edited",
+ "installed",
+ "patched",
+ "restored",
+ "stale"
+ ]
+ },
+ "provenance": {
+ "$ref": "#/$defs/skill_provenance"
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "skill_load_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.skill.load.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "post_patch_state",
+ "provenance",
+ "reuse_state",
+ "use_count_bucket"
+ ],
+ "properties": {
+ "post_patch_state": {
+ "enum": [
+ "no_new_patch",
+ "not_applicable",
+ "reused_after_patch"
+ ]
+ },
+ "provenance": {
+ "$ref": "#/$defs/skill_provenance"
+ },
+ "reuse_state": {
+ "enum": [
+ "first_use",
+ "reused"
+ ]
+ },
+ "use_count_bucket": {
+ "$ref": "#/$defs/count_bucket"
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "skill_provenance": {
+ "enum": [
+ "agent_created",
+ "external",
+ "installed",
+ "local",
+ "unknown"
+ ]
+ }
+ }
+ }
diff --cc hermes_cli/observability/shared_metrics.py
index bf78ac2cef0,186924576d9..f488c0d8224
--- a/hermes_cli/observability/shared_metrics.py
+++ b/hermes_cli/observability/shared_metrics.py
@@@ -18,14 -18,13 +18,14 @@@ from utils import atomic_json_writ
from .shared_metrics_contract import (
COUNTER_METRICS,
- MODEL_CALL_METRIC,
+ MODEL_ROUTE_METRIC,
+ client_resource_is_valid,
counter_dimensions_are_valid,
)
- _PACKAGE_SCHEMA_VERSION = "hermes.shared_metrics.v1"
+ _PACKAGE_SCHEMA_VERSION = "hermes.shared_metrics.v2"
-_STORE_SCHEMA_VERSION = "1"
+_STORE_SCHEMA_VERSION = "2"
_BUSY_TIMEOUT_MS = 250
_SCHEMA_BUSY_TIMEOUT_MS = 5_000
_LOCAL_HISTORY_RETENTION_DAYS = 30
@@@ -60,10 -59,10 +60,10 @@@ class SharedMetricsStore
def record_model_call(
self,
dimensions: dict[str, str],
- hermes_version: str,
+ resource: dict[str, str],
) -> None:
"""Increment the terminal model-call counter for the current UTC day."""
- self.record_counter(MODEL_CALL_METRIC, dimensions, resource)
- self.record_counter(MODEL_ROUTE_METRIC, dimensions, hermes_version)
++ self.record_counter(MODEL_ROUTE_METRIC, dimensions, resource)
def record_counter(
self,
diff --cc hermes_cli/observability/shared_metrics_contract.py
index c70032c2aa9,0d8d3bbbb4e..2bbea8e1de0
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@@ -172,99 -178,49 +178,142 @@@ SKILL_POST_PATCH_STATES: frozenset[str
"not_applicable",
"reused_after_patch",
})
+CLIENT_OS_FAMILIES: frozenset[str] = frozenset({
+ "linux",
+ "macos",
+ "unknown",
+ "windows",
+})
+CLIENT_ARCHITECTURES: frozenset[str] = frozenset({
+ "arm",
+ "arm64",
+ "unknown",
+ "x86",
+ "x86_64",
+})
+CLIENT_INSTALL_METHODS: frozenset[str] = frozenset({
+ "docker",
+ "git",
+ "homebrew",
+ "nixos",
+ "pip",
+ "unknown",
+})
+CLIENT_RESOURCE_KEYS: frozenset[str] = frozenset({
+ "architecture",
+ "hermes_version",
+ "install_method",
+ "os_family",
+})
+
+def client_os_family(value: Any) -> str:
+ """Map a platform system name to the shared-metrics OS taxonomy."""
+ normalized = str(value or "").strip().lower()
+ return {
+ "darwin": "macos",
+ "linux": "linux",
+ "macos": "macos",
+ "windows": "windows",
+ }.get(normalized, "unknown")
+
+
+def client_architecture(value: Any) -> str:
+ """Map a machine architecture to the shared-metrics taxonomy."""
+ normalized = str(value or "").strip().lower().replace("-", "_")
+ if normalized in {"amd64", "x64", "x86_64"}:
+ return "x86_64"
+ if normalized in {"aarch64", "arm64"}:
+ return "arm64"
+ if normalized in {"i386", "i486", "i586", "i686", "x86"}:
+ return "x86"
+ if normalized.startswith("armv"):
+ return "arm"
+ return "unknown"
+
+
+def client_install_method(value: Any) -> str:
+ """Return an allowlisted Hermes installation method."""
+ normalized = str(value or "").strip().lower()
++ if normalized == "nix":
++ return "nixos"
+ return normalized if normalized in CLIENT_INSTALL_METHODS else "unknown"
+
+
+def client_resource(
+ hermes_version: Any,
+ *,
+ os_name: Any,
+ architecture: Any,
+ install_method: Any,
+) -> dict[str, str]:
+ """Build the bounded client resource attached to aggregate packages."""
+ normalized_version = str(hermes_version or "").strip()
+ if not normalized_version or len(normalized_version) > 64:
+ normalized_version = "unknown"
+ return {
+ "architecture": client_architecture(architecture),
+ "hermes_version": normalized_version,
+ "install_method": client_install_method(install_method),
+ "os_family": client_os_family(os_name),
+ }
+
+
+def client_resource_is_valid(resource: Any) -> bool:
+ """Return whether a package resource exactly matches the bounded contract."""
+ if not isinstance(resource, dict) or set(resource) != CLIENT_RESOURCE_KEYS:
+ return False
+ version = resource.get("hermes_version")
+ return (
+ isinstance(version, str)
+ and 0 < len(version) <= 64
+ and resource.get("os_family") in CLIENT_OS_FAMILIES
+ and resource.get("architecture") in CLIENT_ARCHITECTURES
+ and resource.get("install_method") in CLIENT_INSTALL_METHODS
+ )
+
+ _LEGACY_PROVIDER_FAMILIES = frozenset({
+ "aggregator",
+ "custom",
+ "direct",
+ "local",
+ "unknown",
+ })
+ _LEGACY_MODEL_LOCALITIES = frozenset({"local", "remote", "unknown"})
+ _LEGACY_MODEL_OUTCOMES = frozenset({"cancelled", "failed", "success"})
+ _LEGACY_MODEL_FAMILIES = frozenset({
+ "claude",
+ "deepseek",
+ "gemini",
+ "gemma",
+ "glm",
+ "gpt",
+ "grok",
+ "kimi",
+ "llama",
+ "minimax",
+ "mimo",
+ "mistral",
+ "nemotron",
+ "nova",
+ "o1",
+ "o3",
+ "o4",
+ "qwen",
+ "step",
+ "trinity",
+ "unknown",
+ })
+
_COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
+ # Retained only so pre-v2 pending rows remain packageable.
+ LEGACY_MODEL_CALL_METRIC: {
+ "call_role": frozenset({"primary"}),
+ "locality": _LEGACY_MODEL_LOCALITIES,
+ "model_family": _LEGACY_MODEL_FAMILIES,
+ "outcome": _LEGACY_MODEL_OUTCOMES,
+ "provider_family": _LEGACY_PROVIDER_FAMILIES,
+ },
TASK_STARTED_METRIC: {
"entrypoint": TASK_ENTRYPOINTS,
"execution_surface": EXECUTION_SURFACES,
diff --cc hermes_cli/observability/shared_metrics_subscriber.py
index ee23b11aad0,b1ae16141e6..742edd9ca98
--- a/hermes_cli/observability/shared_metrics_subscriber.py
+++ b/hermes_cli/observability/shared_metrics_subscriber.py
@@@ -12,9 -10,8 +12,9 @@@ from hermes_cli.config import detect_in
from .shared_metrics import SharedMetricsStore
from .shared_metrics_contract import (
- MODEL_CALL_METRIC,
+ MODEL_ROUTE_METRIC,
TOOL_CALL_METRIC,
+ client_resource,
model_call_dimensions,
skill_counter,
task_counter,
diff --cc tests/agent/test_auxiliary_relay.py
index 8a3c8be3df1,5af8ef0c60e..b2b06e94f7e
--- a/tests/agent/test_auxiliary_relay.py
+++ b/tests/agent/test_auxiliary_relay.py
@@@ -270,17 -241,23 +241,23 @@@ def test_auxiliary_provider_fallback_re
)
try:
- with pytest.raises(RuntimeError, match="invalid response"):
- run("compression")
-
- assert outcomes == ["failed"]
- assert turn.logical_llm_calls == {}
-
- relay_runtime.SESSION_COORDINATOR.end_turn(turn, outcome="success")
-
- assert outcomes == ["failed", "success"]
+ result = run("compression")
+ relay.subscribers.flush()
finally:
- turn.lease.host.release_managed_execution(consumer)
+ turn.lease.host.release_managed_execution(subscriber_name)
+ relay.subscribers.deregister(subscriber_name)
+
+ assert result.choices[0].message.content == "recovered"
+ snapshot = store.counter_snapshot()
+ assert len(snapshot) == 1
+ assert snapshot[0]["metric_name"] == MODEL_ROUTE_METRIC
- assert snapshot[0]["hermes_version"] == "test-version"
++ assert snapshot[0]["resource"]["hermes_version"] == "test-version"
+ assert snapshot[0]["dimensions"] == {
+ "model": "accepted/model",
+ "provider": "openrouter",
+ }
+ assert snapshot[0]["value"] == 1
+ assert snapshot[0]["packaged_value"] == 0
@pytest.mark.asyncio
diff --cc tests/hermes_cli/test_relay_shared_metrics.py
index f47889e9902,6e4eaca2e80..b84fe06b7b9
--- a/tests/hermes_cli/test_relay_shared_metrics.py
+++ b/tests/hermes_cli/test_relay_shared_metrics.py
@@@ -112,20 -111,15 +118,29 @@@ def _dimensions() -> dict[str, str]
}
+def _resource(
+ hermes_version: str = "test-version",
+ *,
+ os_family: str = "linux",
+ architecture: str = "x86_64",
+ install_method: str = "git",
+) -> dict[str, str]:
+ return {
+ "architecture": architecture,
+ "hermes_version": hermes_version,
+ "install_method": install_method,
+ "os_family": os_family,
+ }
+
+ def _legacy_dimensions() -> dict[str, str]:
+ return {
+ "call_role": "primary",
+ "locality": "remote",
+ "model_family": "claude",
+ "outcome": "success",
+ "provider_family": "direct",
+ }
+
def _record_model_calls_in_process(
database_path: str,
@@@ -154,11 -148,11 +169,11 @@@ def test_model_call_counter_survives_re
_schema_validator().validate(first_package)
uuid.UUID(first_package["package_id"])
uuid.UUID(first_package["install_id"])
- assert first_package["schema_version"] == "hermes.shared_metrics.v1"
+ assert first_package["schema_version"] == "hermes.shared_metrics.v2"
- assert first_package["resource"] == {"hermes_version": "test-version"}
+ assert first_package["resource"] == _resource()
assert first_package["metrics"] == [
{
- "name": "hermes.model_call.count",
+ "name": MODEL_ROUTE_METRIC,
"type": "counter",
"dimensions": _dimensions(),
"value": 2,
@@@ -183,6 -177,120 +198,134 @@@
assert restarted.counter_snapshot()[0]["packaged_value"] == 3
+ def test_v2_package_preserves_pending_v1_model_counters(tmp_path):
+ database_path = tmp_path / "metrics.sqlite3"
+ outbox_directory = tmp_path / "outbox"
+ store = SharedMetricsStore(database_path, outbox_directory)
+ period_start = shared_metrics_module._utc_now().date().isoformat()
+ legacy_dimensions_json = json.dumps(
+ _legacy_dimensions(),
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+ with sqlite3.connect(database_path) as connection:
+ connection.execute(
+ """
+ INSERT INTO counter_aggregates(
+ period_start,
+ metric_name,
+ hermes_version,
++ os_family,
++ architecture,
++ install_method,
+ dimensions_json,
+ value,
+ packaged_value
- ) VALUES (?, ?, ?, ?, 3, 0)
++ ) VALUES (?, ?, ?, ?, ?, ?, ?, 3, 0)
+ """,
+ (
+ period_start,
+ LEGACY_MODEL_CALL_METRIC,
+ "test-version",
++ "unknown",
++ "unknown",
++ "unknown",
+ legacy_dimensions_json,
+ ),
+ )
- store.record_model_call(_dimensions(), "test-version")
++ store.record_model_call(
++ _dimensions(),
++ _resource(
++ "test-version",
++ os_family="unknown",
++ architecture="unknown",
++ install_method="unknown",
++ ),
++ )
+
+ [package_path] = store.create_and_export_package()
+ package = json.loads(package_path.read_text(encoding="utf-8"))
+ _schema_validator().validate(package)
+
+ assert package["schema_version"] == "hermes.shared_metrics.v2"
+ assert package["metrics"] == [
+ {
+ "name": LEGACY_MODEL_CALL_METRIC,
+ "type": "counter",
+ "dimensions": _legacy_dimensions(),
+ "value": 3,
+ },
+ {
+ "name": MODEL_ROUTE_METRIC,
+ "type": "counter",
+ "dimensions": _dimensions(),
+ "value": 1,
+ },
+ ]
+ assert all(
+ row["value"] == row["packaged_value"] for row in store.counter_snapshot()
+ )
+
+
+ def test_v1_outbox_package_exports_unchanged_after_upgrade(tmp_path):
+ database_path = tmp_path / "metrics.sqlite3"
+ outbox_directory = tmp_path / "outbox"
+ store = SharedMetricsStore(database_path, outbox_directory)
+ package_id = str(uuid.uuid4())
+ payload = {
+ "schema_version": "hermes.shared_metrics.v1",
+ "package_id": package_id,
+ "install_id": str(uuid.uuid4()),
+ "period_start": "2026-07-28T00:00:00Z",
+ "period_end": "2026-07-29T00:00:00Z",
+ "generated_at": "2026-07-29T01:00:00Z",
+ "resource": {"hermes_version": "legacy-version"},
+ "metrics": [
+ {
+ "name": LEGACY_MODEL_CALL_METRIC,
+ "type": "counter",
+ "dimensions": _legacy_dimensions(),
+ "value": 2,
+ }
+ ],
+ }
+ payload_json = json.dumps(payload, sort_keys=True, separators=(",", ":"))
+ _schema_validator(LEGACY_SCHEMA_PATH).validate(payload)
+ with sqlite3.connect(database_path) as connection:
+ connection.execute(
+ """
+ INSERT INTO package_outbox(
+ package_id,
+ period_start,
+ period_end,
+ payload_json,
+ created_at
+ ) VALUES (?, ?, ?, ?, ?)
+ """,
+ (
+ package_id,
+ payload["period_start"],
+ payload["period_end"],
+ payload_json,
+ payload["generated_at"],
+ ),
+ )
+
+ assert store.create_and_export_package() == [
+ outbox_directory / f"{package_id}.json"
+ ]
+ exported = json.loads(
+ (outbox_directory / f"{package_id}.json").read_text(encoding="utf-8")
+ )
+ assert exported == payload
+ with sqlite3.connect(database_path) as connection:
+ [persisted_payload_json] = connection.execute(
+ "SELECT payload_json FROM package_outbox WHERE package_id = ?",
+ (package_id,),
+ ).fetchone()
+ assert persisted_payload_json == payload_json
+
+
def test_due_export_runs_once_per_utc_day_and_catches_up_pending_deltas(
tmp_path, monkeypatch
):
@@@ -200,8 -308,8 +343,8 @@@
assert len(list((tmp_path / "outbox").glob("*.json"))) == 1
assert store.counter_snapshot()[0] == {
"period_start": "2026-07-28",
- "metric_name": "hermes.model_call.count",
+ "metric_name": MODEL_ROUTE_METRIC,
- "hermes_version": "test-version",
+ "resource": _resource(),
"dimensions": _dimensions(),
"value": 2,
"packaged_value": 1,
@@@ -230,62 -340,20 +375,72 @@@ def test_package_schema_matches_the_mod
assert "enum" not in properties["provider"]
+def test_client_resource_classification_is_bounded():
+ assert client_os_family("Darwin") == "macos"
+ assert client_os_family("Windows") == "windows"
+ assert client_architecture("AMD64") == "x86_64"
+ assert client_architecture("aarch64") == "arm64"
+ assert client_architecture("armv7l") == "arm"
+ assert client_install_method("Homebrew") == "homebrew"
++ assert client_install_method("nix") == "nixos"
+
+ assert client_resource(
+ "",
+ os_name="privacy-os-canary",
+ architecture="privacy-arch-canary",
+ install_method="privacy-install-canary",
+ ) == _resource(
+ "unknown",
+ os_family="unknown",
+ architecture="unknown",
+ install_method="unknown",
+ )
+
-
+def test_package_schema_matches_the_client_resource_contract():
+ schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
+ resource = schema["properties"]["resource"]
+
- # Existing v1 outbox entries predate the bounded client dimensions. New
- # packages always populate every property, while the schema remains able
- # to validate those immutable queued payloads.
- assert set(resource["required"]) == {"hermes_version"}
++ # Every v2 package records the complete bounded client resource.\n assert set(resource["required"]) == {\n "architecture",\n "hermes_version",\n "install_method",\n "os_family",\n }
+ assert set(resource["properties"]) == {
+ "architecture",
+ "hermes_version",
+ "install_method",
+ "os_family",
+ }
+ assert set(resource["properties"]["os_family"]["enum"]) == CLIENT_OS_FAMILIES
+ assert set(resource["properties"]["architecture"]["enum"]) == (CLIENT_ARCHITECTURES)
+ assert set(resource["properties"]["install_method"]["enum"]) == (
+ CLIENT_INSTALL_METHODS
+ )
+
-
+def test_package_schema_matches_the_task_contract():
+ schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
+ start = _task_dimension_schema("task_started_counter")["properties"]
+ terminal = _task_dimension_schema("task_finished_counter")["properties"]
+
+ assert set(schema["$defs"]["execution_surface"]["enum"]) == EXECUTION_SURFACES
+ assert set(schema["$defs"]["task_entrypoint"]["enum"]) == TASK_ENTRYPOINTS
+ assert set(schema["$defs"]["duration_bucket"]["enum"]) == DURATION_BUCKETS
+ assert set(schema["$defs"]["count_bucket"]["enum"]) == COUNT_BUCKETS
+ assert start["entrypoint"] == {"$ref": "#/$defs/task_entrypoint"}
+ assert set(terminal["end_reason"]["enum"]) == TASK_END_REASONS
+ assert set(terminal["outcome"]["enum"]) == TASK_OUTCOMES
+ assert set(terminal["termination"]["enum"]) == TASK_TERMINATIONS
+
+ def test_v1_package_schema_retains_the_legacy_model_contract():
+ schema = json.loads(LEGACY_SCHEMA_PATH.read_text(encoding="utf-8"))
+ model_counter = schema["$defs"]["model_call_counter"]
+
+ assert schema["properties"]["schema_version"]["const"] == "hermes.shared_metrics.v1"
+ assert model_counter["properties"]["name"]["const"] == LEGACY_MODEL_CALL_METRIC
+ assert set(model_counter["properties"]["dimensions"]["properties"]) == {
+ "call_role",
+ "locality",
+ "model_family",
+ "outcome",
+ "provider_family",
+ }
+
def test_package_schema_matches_the_tool_contract():
schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
@@@ -793,286 -704,47 +791,265 @@@ def test_skill_event_fields_are_bounded
is None
)
-
+def test_store_rejects_an_unsupported_schema_version(tmp_path):
+ database_path = tmp_path / "metrics.sqlite3"
+ with sqlite3.connect(database_path) as connection:
+ connection.execute(
+ "CREATE TABLE telemetry_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)"
+ )
+ connection.execute(
+ "INSERT INTO telemetry_state(key, value) VALUES ('schema_version', '999')"
+ )
+
+ with pytest.raises(RuntimeError, match="Unsupported shared-metrics store schema"):
+ SharedMetricsStore(database_path, tmp_path / "outbox")
+
+ with sqlite3.connect(database_path) as connection:
+ [schema_version] = connection.execute(
+ "SELECT value FROM telemetry_state WHERE key = 'schema_version'"
+ ).fetchone()
+ assert schema_version == "999"
+
-
+def test_store_migrates_v1_counters_with_unknown_client_dimensions(tmp_path):
+ database_path = tmp_path / "metrics.sqlite3"
+ outbox_directory = tmp_path / "outbox"
+ install_id = str(uuid.uuid4())
+ with sqlite3.connect(database_path) as connection:
+ connection.execute(
+ "CREATE TABLE telemetry_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)"
+ )
+ connection.executemany(
+ "INSERT INTO telemetry_state(key, value) VALUES (?, ?)",
+ [("schema_version", "1"), ("install_id", install_id)],
+ )
+ connection.execute(
+ """
+ CREATE TABLE counter_aggregates (
+ period_start TEXT NOT NULL,
+ metric_name TEXT NOT NULL,
+ hermes_version TEXT NOT NULL,
+ dimensions_json TEXT NOT NULL,
+ value INTEGER NOT NULL,
+ packaged_value INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (
+ period_start,
+ metric_name,
+ hermes_version,
+ dimensions_json
+ )
+ )
+ """
+ )
+ connection.execute(
+ """
+ INSERT INTO counter_aggregates(
+ period_start,
+ metric_name,
+ hermes_version,
+ dimensions_json,
+ value,
+ packaged_value
+ ) VALUES (?, ?, ?, ?, ?, ?)
+ """,
+ (
+ "2026-07-21",
- "hermes.model_call.count",
++ LEGACY_MODEL_CALL_METRIC,
+ "old-version",
- json.dumps(_dimensions(), sort_keys=True, separators=(",", ":")),
++ json.dumps(
++ _legacy_dimensions(),
++ sort_keys=True,
++ separators=(",", ":"),
++ ),
+ 3,
+ 1,
+ ),
+ )
+
+ store = SharedMetricsStore(database_path, outbox_directory)
+
+ [counter] = store.counter_snapshot()
+ assert counter["resource"] == _resource(
+ "old-version",
+ os_family="unknown",
+ architecture="unknown",
+ install_method="unknown",
+ )
+ assert counter["value"] == 3
+ assert counter["packaged_value"] == 1
+ [package_path] = store.create_and_export_package()
+ package = json.loads(package_path.read_text(encoding="utf-8"))
+ _schema_validator().validate(package)
+ assert package["install_id"] == install_id
+ assert package["metrics"][0]["value"] == 2
+
-
+def test_pending_metrics_keep_the_client_resource_recorded_at_event_time(tmp_path):
+ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
+ resource_a = _resource("version-a", architecture="arm64", install_method="pip")
+ resource_b = _resource("version-a", os_family="macos")
+ store.record_model_call(_dimensions(), resource_a)
+ store.record_model_call(_dimensions(), resource_b)
+
+ packages = [
+ json.loads(path.read_text(encoding="utf-8"))
+ for path in store.create_and_export_package()
+ ]
+
+ assert {tuple(sorted(package["resource"].items())) for package in packages} == {
+ tuple(sorted(resource_a.items())),
+ tuple(sorted(resource_b.items())),
+ }
+ assert all(package["metrics"][0]["value"] == 1 for package in packages)
+
-
- def test_legacy_v1_outbox_package_remains_exportable_and_schema_valid(tmp_path):
- store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
- package_id = str(uuid.uuid4())
- payload = {
- "schema_version": "hermes.shared_metrics.v1",
- "package_id": package_id,
- "install_id": str(uuid.uuid4()),
- "period_start": "2026-07-21T00:00:00Z",
- "period_end": "2026-07-22T00:00:00Z",
- "generated_at": "2026-07-22T00:00:00Z",
- "resource": {"hermes_version": "old-version"},
- "metrics": [
- {
- "name": "hermes.model_call.count",
- "type": "counter",
- "dimensions": _dimensions(),
- "value": 1,
- }
- ],
- }
- with sqlite3.connect(store.database_path) as connection:
- connection.execute(
- """
- INSERT INTO package_outbox(
- package_id,
- period_start,
- period_end,
- payload_json,
- created_at,
- exported_at
- ) VALUES (?, ?, ?, ?, ?, NULL)
- """,
- (
- package_id,
- payload["period_start"],
- payload["period_end"],
- json.dumps(payload),
- payload["generated_at"],
- ),
- )
-
- [package_path] = store.create_and_export_package()
- exported = json.loads(package_path.read_text(encoding="utf-8"))
-
- assert exported == payload
- _schema_validator().validate(exported)
-
-
+def test_store_exports_task_started_and_terminal_counters(tmp_path):
+ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
+ store.record_counter(
+ "hermes.task_run.started",
+ {"entrypoint": "interactive", "execution_surface": "cli"},
+ _resource(),
+ )
+ terminal = task_terminal_fields(
+ {
+ "platform": "cli",
+ "completed": True,
+ "turn_exit_reason": "text_response(stop)",
+ },
+ duration_ms=2_000,
+ model_call_count=1,
+ tool_call_count=2,
+ retry_count=0,
+ )
+ store.record_counter("hermes.task_run.finished", terminal, _resource())
+
+ [package_path] = store.create_and_export_package()
+ package = json.loads(package_path.read_text(encoding="utf-8"))
+ _schema_validator().validate(package)
+
+ assert {metric["name"] for metric in package["metrics"]} == {
+ "hermes.task_run.finished",
+ "hermes.task_run.started",
+ }
+
-
+def test_package_schema_rejects_unknown_fields(tmp_path):
+ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
+ store.record_model_call(_dimensions(), _resource())
+ [package_path] = store.create_and_export_package()
+ package = json.loads(package_path.read_text(encoding="utf-8"))
+ invalid_package = deepcopy(package)
+ invalid_package["prompt"] = "must-not-be-accepted"
+
+ jsonschema = pytest.importorskip("jsonschema")
+ with pytest.raises(jsonschema.ValidationError):
+ _schema_validator().validate(invalid_package)
+
+ def test_store_does_not_record_the_retired_model_metric(tmp_path):
+ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
+
+ with pytest.raises(ValueError, match="Unsupported shared metric"):
+ store.record_counter(
+ LEGACY_MODEL_CALL_METRIC,
+ _legacy_dimensions(),
- "test-version",
++ _resource(),
++ )
++
++ assert store.counter_snapshot() == []
++
+
+def test_store_rejects_dimensions_outside_the_metric_contract(tmp_path):
+ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
+
+ with pytest.raises(ValueError, match="Unsupported dimensions"):
+ store.record_counter(
- "hermes.model_call.count",
++ MODEL_ROUTE_METRIC,
+ {"prompt": "must-not-be-persisted"},
+ _resource(),
)
assert store.counter_snapshot() == []
-
+def test_store_rejects_client_resources_outside_the_contract(tmp_path):
+ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
+
+ with pytest.raises(ValueError, match="Unsupported shared-metrics client resource"):
+ store.record_model_call(
+ _dimensions(),
+ {
+ **_resource(),
+ "architecture": "privacy-architecture-canary",
+ },
+ )
+
+ assert store.counter_snapshot() == []
+
-
+def test_package_builder_rejects_tampered_dimensions(tmp_path):
+ database_path = tmp_path / "metrics.sqlite3"
+ outbox_directory = tmp_path / "outbox"
+ store = SharedMetricsStore(database_path, outbox_directory)
+ store.record_model_call(_dimensions(), _resource())
+ with sqlite3.connect(database_path) as connection:
+ connection.execute(
+ "UPDATE counter_aggregates SET dimensions_json = ?",
+ (json.dumps({"prompt": "must-not-be-exported"}),),
+ )
+
+ with pytest.raises(ValueError, match="Unsupported dimensions"):
+ store.create_and_export_package()
+
+ assert list(outbox_directory.glob("*.json")) == []
+
+
+def test_package_builder_rejects_tampered_client_resources(tmp_path):
+ database_path = tmp_path / "metrics.sqlite3"
+ outbox_directory = tmp_path / "outbox"
+ store = SharedMetricsStore(database_path, outbox_directory)
+ store.record_model_call(_dimensions(), _resource())
+ with sqlite3.connect(database_path) as connection:
+ connection.execute(
+ "UPDATE counter_aggregates SET os_family = ?",
+ ("privacy-os-canary",),
+ )
+
+ with pytest.raises(
+ ValueError,
+ match="Unsupported shared-metrics client resource",
+ ):
+ store.create_and_export_package()
+ assert list(outbox_directory.glob("*.json")) == []
+def test_pending_package_retry_reuses_the_same_package_and_file(tmp_path):
+ database_path = tmp_path / "metrics.sqlite3"
+ outbox_directory = tmp_path / "outbox"
+ store = SharedMetricsStore(database_path, outbox_directory)
+ store.record_model_call(_dimensions(), _resource())
+ [package_path] = store.create_and_export_package()
+ original_payload = package_path.read_bytes()
- with sqlite3.connect(database_path) as connection:
- connection.execute("UPDATE package_outbox SET exported_at = NULL")
- restarted = SharedMetricsStore(database_path, outbox_directory)
- assert restarted.create_and_export_package() == [package_path]
- assert package_path.read_bytes() == original_payload
- assert list(outbox_directory.glob("*.json")) == [package_path]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
def test_retention_prunes_only_expired_exported_history(tmp_path):
@@@ -1134,87 -806,10 +1111,87 @@@
assert aggregate_versions == {"current-version", "pending-version"}
+def test_retention_failure_does_not_fail_a_committed_export(tmp_path, monkeypatch):
+ store = SharedMetricsStore(
+ tmp_path / "metrics.sqlite3",
+ tmp_path / "outbox",
+ )
+ store.record_model_call(_dimensions(), _resource())
+
+ def fail_pruning():
+ raise OSError("retention unavailable")
+
+ monkeypatch.setattr(store, "_prune_expired_history", fail_pruning)
+
+ [package_path] = store.create_and_export_package()
+ assert package_path.exists()
+ assert store.counter_snapshot()[0]["packaged_value"] == 1
+def test_file_export_failure_retries_committed_outbox_without_duplicate_delta(
+ tmp_path, monkeypatch
+):
+ database_path = tmp_path / "metrics.sqlite3"
+ outbox_directory = tmp_path / "outbox"
+ store = SharedMetricsStore(database_path, outbox_directory)
+ store.record_model_call(_dimensions(), _resource())
+
+ def fail_write(*_args, **_kwargs):
+ raise OSError("simulated atomic export failure")
+ module_globals = SharedMetricsStore._export_pending_packages.__globals__
+ original_write = module_globals["atomic_json_write"]
+ monkeypatch.setitem(module_globals, "atomic_json_write", fail_write)
+ with pytest.raises(OSError, match="simulated atomic export failure"):
+ store.create_and_export_package()
+
+ with sqlite3.connect(database_path) as connection:
+ package_id, exported_at = connection.execute(
+ "SELECT package_id, exported_at FROM package_outbox"
+ ).fetchone()
+ assert exported_at is None
+ assert store.counter_snapshot()[0]["packaged_value"] == 1
+ assert list(outbox_directory.glob("*.json")) == []
+
+ monkeypatch.setitem(module_globals, "atomic_json_write", original_write)
+ assert store.create_and_export_package() == [
+ outbox_directory / f"{package_id}.json"
+ ]
+ assert len(list(outbox_directory.glob("*.json"))) == 1
+ assert store.create_and_export_package() == []
+
+
+def test_package_export_does_not_chase_concurrent_updates(tmp_path, monkeypatch):
+ database_path = tmp_path / "metrics.sqlite3"
+ outbox_directory = tmp_path / "outbox"
+ store = SharedMetricsStore(database_path, outbox_directory)
+ store.record_model_call(_dimensions(), _resource())
+ original_create = store._create_package
+ create_calls = 0
+
+ def create_and_record_another():
+ nonlocal create_calls
+ create_calls += 1
+ package = original_create()
+ if create_calls == 1:
+ store.record_model_call(_dimensions(), _resource())
+ return package
+
+ monkeypatch.setattr(store, "_create_package", create_and_record_another)
+ first_paths = store.create_and_export_package()
+
+ assert create_calls == 1
+ assert len(first_paths) == 1
+ [counter] = store.counter_snapshot()
- assert counter["metric_name"] == "hermes.model_call.count"
++ assert counter["metric_name"] == MODEL_ROUTE_METRIC
+ assert counter["dimensions"] == _dimensions()
+ assert counter["value"] == 2
+ assert counter["packaged_value"] == 1
+
+ second_paths = store.create_and_export_package()
+ assert len(second_paths) == 1
+ assert store.counter_snapshot()[0]["packaged_value"] == 2
def test_concurrent_package_builders_commit_one_delta(tmp_path):