Skip to content

The agent that grows with you

fix(telemetry): fewer rows per busy day and a smaller local store

teknium19b7db3105b3e
diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
index 5d99b30d228..cfda0b8df4f 100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
@@ -106,9 +106,15 @@
{
"$ref": "#/$defs/task_finished_counter"
},
+ {
+ "$ref": "#/$defs/task_duration_counter"
+ },
{
"$ref": "#/$defs/tool_call_counter"
},
+ {
+ "$ref": "#/$defs/tool_latency_counter"
+ },
{
"$ref": "#/$defs/tool_approval_counter"
},
@@ -537,84 +543,132 @@
"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"
- },
- "platform": {
- "$ref": "#/$defs/catalog_identifier"
- },
- "failure_class": {
- "$ref": "#/$defs/vocabulary_identifier"
+ "oneOf": [
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "end_reason",
+ "entrypoint",
+ "execution_surface",
+ "failure_class",
+ "outcome",
+ "platform",
+ "termination"
+ ],
+ "properties": {
+ "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"
+ },
+ "failure_class": {
+ "$ref": "#/$defs/vocabulary_identifier"
+ },
+ "outcome": {
+ "enum": [
+ "cancelled",
+ "failed",
+ "success",
+ "timed_out",
+ "unknown"
+ ]
+ },
+ "platform": {
+ "$ref": "#/$defs/catalog_identifier"
+ },
+ "termination": {
+ "enum": [
+ "none",
+ "system_aborted",
+ "timed_out",
+ "unknown",
+ "user_cancelled"
+ ]
+ }
+ }
+ },
+ {
+ "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"
+ }
+ }
}
- },
- "dependentRequired": {
- "failure_class": [
- "platform"
- ],
- "platform": [
- "failure_class"
- ]
- }
+ ]
},
"value": {
"type": "integer",
@@ -717,9 +771,7 @@
"additionalProperties": false,
"required": [
"approval_outcome",
- "latency_bucket",
"outcome",
- "retry_count_bucket",
"tool_category"
],
"properties": {
@@ -771,6 +823,14 @@
"web"
]
}
+ },
+ "dependentRequired": {
+ "latency_bucket": [
+ "retry_count_bucket"
+ ],
+ "retry_count_bucket": [
+ "latency_bucket"
+ ]
}
},
"value": {
@@ -4458,6 +4518,119 @@
"const": 1
}
}
+ },
+ "tool_latency_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.tool_call.latency"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "latency_bucket",
+ "retry_count_bucket",
+ "tool_category"
+ ],
+ "properties": {
+ "latency_bucket": {
+ "$ref": "#/$defs/tool_latency_bucket"
+ },
+ "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
+ }
+ }
+ },
+ "task_duration_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.task_run.duration"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "duration_bucket",
+ "execution_surface",
+ "outcome",
+ "retry_count_bucket"
+ ],
+ "properties": {
+ "duration_bucket": {
+ "$ref": "#/$defs/duration_bucket"
+ },
+ "execution_surface": {
+ "$ref": "#/$defs/execution_surface"
+ },
+ "outcome": {
+ "enum": [
+ "cancelled",
+ "failed",
+ "success",
+ "timed_out",
+ "unknown"
+ ]
+ },
+ "retry_count_bucket": {
+ "$ref": "#/$defs/count_bucket"
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
}
}
}
diff --git a/hermes_cli/observability/shared_metrics.py b/hermes_cli/observability/shared_metrics.py
index 558d201cf2c..650d87db6f9 100644
--- a/hermes_cli/observability/shared_metrics.py
+++ b/hermes_cli/observability/shared_metrics.py
@@ -666,7 +666,8 @@ class SharedMetricsStore:
package_id = str(row["package_id"])
path = self.outbox_directory / f"{package_id}.json"
atomic_json_write(
- path, json.loads(row["payload_json"]), indent=2, sort_keys=True, mode=0o600
+ path, json.loads(row["payload_json"]), indent=None, separators=(",", ":"),
+ sort_keys=True, mode=0o600,
)
with self._connection() as connection:
connection.execute(
@@ -701,6 +702,13 @@ class SharedMetricsStore:
)
with self._write() as connection:
+ # A package the ingest accepted or refused is never sent again, and its outbox file is
+ # the local history copy, so the database drops its duplicate of the body.
+ connection.execute(
+ "UPDATE package_outbox SET payload_json = ''"
+ " WHERE exported_at IS NOT NULL AND send_state IN ('sent', 'rejected')"
+ " AND payload_json != ''"
+ )
for package_id in removable_package_ids:
connection.execute(
"DELETE FROM package_outbox"
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index d51040c5eb4..edb0ff52f77 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -45,7 +45,9 @@ LEGACY_MODEL_CALL_METRIC = "hermes.model_call.count"
MODEL_ROUTE_METRIC = "hermes.model_route.count"
TASK_STARTED_METRIC = "hermes.task_run.started"
TASK_FINISHED_METRIC = "hermes.task_run.finished"
+TASK_DURATION_METRIC = "hermes.task_run.duration"
TOOL_CALL_METRIC = "hermes.tool_call.count"
+TOOL_LATENCY_METRIC = "hermes.tool_call.latency"
TOOL_APPROVAL_METRIC = "hermes.tool_approval.count"
SKILL_LIFECYCLE_METRIC = "hermes.skill.lifecycle.count"
SKILL_LOAD_METRIC = "hermes.skill.load.count"
@@ -683,6 +685,14 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
"outcome": TOOL_OUTCOMES, "retry_count_bucket": TOOL_RETRY_BUCKETS,
"tool_category": TOOL_CATEGORIES,
},
+ TOOL_LATENCY_METRIC: {
+ "latency_bucket": TOOL_LATENCY_BUCKETS, "retry_count_bucket": TOOL_RETRY_BUCKETS,
+ "tool_category": TOOL_CATEGORIES,
+ },
+ TASK_DURATION_METRIC: {
+ "duration_bucket": DURATION_BUCKETS, "execution_surface": EXECUTION_SURFACES,
+ "outcome": TASK_OUTCOMES, "retry_count_bucket": COUNT_BUCKETS,
+ },
TOOL_USAGE_METRIC: {
"error_class": TOOL_ERROR_CLASSES, "outcome": TOOL_OUTCOMES, "tool_name": TOOL_NAMES,
},
@@ -890,13 +900,24 @@ _METRIC_FIELDS: dict[str, frozenset[str]] = {
name: frozenset(contract) | frozenset(_IDENTIFIER_FIELDS.get(name, ()))
for name, contract in _COUNTER_DIMENSION_VALUES.items()
}
+# Fields v2 carried on the per-task and per-tool-call rows. Together they made nearly every task and
+# tool call its own row; v3 moves duration/retries/latency to the small split counters above (call
+# counts per task are already on hermes.task_cost.count). Their values stay in the contract so rows
+# recorded before an upgrade still validate and package.
+_TASK_FINISHED_V2_ONLY = frozenset(
+ {"duration_bucket", "model_call_count_bucket", "retry_count_bucket", "tool_call_count_bucket"}
+)
+_TOOL_CALL_V2_ONLY = frozenset({"latency_bucket", "retry_count_bucket"})
+_METRIC_FIELDS[TASK_FINISHED_METRIC] -= _TASK_FINISHED_V2_ONLY
+_METRIC_FIELDS[TOOL_CALL_METRIC] -= _TOOL_CALL_V2_ONLY
# Older field sets still accepted at packaging so counters recorded before an upgrade drain.
_LEGACY_METRIC_FIELDS: dict[str, tuple[frozenset[str], ...]] = {
MODEL_ROUTE_METRIC: (
frozenset(_MODEL_ROUTE_MAX_LENGTHS), _METRIC_FIELDS[MODEL_ROUTE_METRIC] - {"ttft_bucket"},
),
TASK_STARTED_METRIC: (_METRIC_FIELDS[TASK_STARTED_METRIC] - {"platform"},),
- TASK_FINISHED_METRIC: (_METRIC_FIELDS[TASK_FINISHED_METRIC] - {"failure_class", "platform"},),
+ TASK_FINISHED_METRIC: (frozenset(_COUNTER_DIMENSION_VALUES[TASK_FINISHED_METRIC]) - {"failure_class", "platform"},),
+ TOOL_CALL_METRIC: (frozenset(_COUNTER_DIMENSION_VALUES[TOOL_CALL_METRIC]),),
SKILL_LOAD_METRIC: (_METRIC_FIELDS[SKILL_LOAD_METRIC] - {"skill_name"},),
INSTALL_SNAPSHOT_METRIC: (_METRIC_FIELDS[INSTALL_SNAPSHOT_METRIC] - {
"display_language", "install_age_bucket", "main_provider", "messaging_platform_count_bucket",
@@ -1123,8 +1144,40 @@ def task_counter(event: Any) -> tuple[str, dict[str, str]] | None:
event, kind="scope", category="function", name=TASK_SCOPE, category_profile=None
):
return None
- phases = {"start": TASK_STARTED_METRIC, "end": TASK_FINISHED_METRIC}
- return _bounded_counter(phases.get(_event_text(event, "scope_category")), event)
+ phase = _event_text(event, "scope_category")
+ if phase == "start":
+ return _bounded_counter(TASK_STARTED_METRIC, event)
+ return _task_end_counter(event, TASK_FINISHED_METRIC) if phase == "end" else None
+
+
+def task_duration_counter(event: Any) -> tuple[str, dict[str, str]] | None:
+ """Return the duration/retry counter carried by the same task end event."""
+ if not _valid_shape(
+ event, kind="scope", scope_category="end", category="function", name=TASK_SCOPE,
+ category_profile=None,
+ ):
+ return None
+ return _task_end_counter(event, TASK_DURATION_METRIC)
+
+
+# The task end payload (task_terminal_fields) also carries per-task call counts for other Relay
+# subscribers; hermes.task_cost.count already buckets them, so no counter projects them here.
+_TASK_END_FIELDS = (
+ _METRIC_FIELDS[TASK_FINISHED_METRIC] | _METRIC_FIELDS[TASK_DURATION_METRIC]
+ | {"model_call_count_bucket", "tool_call_count_bucket"}
+)
+
+
+def _task_end_counter(event: Any, metric_name: str) -> tuple[str, dict[str, str]] | None:
+ """Project the task end event onto one counter; both projections must validate first."""
+ data = getattr(event, "data", None)
+ if not isinstance(data, dict) or set(data) != _TASK_END_FIELDS:
+ return None
+ projections = {
+ name: _bounded_dimensions(name, {f: data[f] for f in _METRIC_FIELDS[name]})
+ for name in (TASK_FINISHED_METRIC, TASK_DURATION_METRIC)
+ }
+ return (metric_name, projections[metric_name]) if all(projections.values()) else None
def tool_call_dimensions(event: Any) -> dict[str, str] | None:
@@ -1137,7 +1190,13 @@ def tool_usage_dimensions(event: Any) -> dict[str, str] | None:
return _tool_end_projection(event, TOOL_USAGE_METRIC)
-_TOOL_END_FIELDS = _METRIC_FIELDS[TOOL_CALL_METRIC] | _METRIC_FIELDS[TOOL_USAGE_METRIC]
+def tool_latency_dimensions(event: Any) -> dict[str, str] | None:
+ """Return the per-category latency/retry dimensions carried by the same tool end event."""
+ return _tool_end_projection(event, TOOL_LATENCY_METRIC)
+
+
+_TOOL_END_METRICS = (TOOL_CALL_METRIC, TOOL_USAGE_METRIC, TOOL_LATENCY_METRIC)
+_TOOL_END_FIELDS = frozenset().union(*(_METRIC_FIELDS[name] for name in _TOOL_END_METRICS))
def _tool_end_projection(event: Any, metric_name: str) -> dict[str, str] | None:
@@ -1152,7 +1211,7 @@ def _tool_end_projection(event: Any, metric_name: str) -> dict[str, str] | None:
return None
projections = {
name: _bounded_dimensions(name, {f: data[f] for f in _METRIC_FIELDS[name]})
- for name in (TOOL_CALL_METRIC, TOOL_USAGE_METRIC)
+ for name in _TOOL_END_METRICS
}
return projections[metric_name] if all(projections.values()) else None
diff --git a/hermes_cli/observability/shared_metrics_subscriber.py b/hermes_cli/observability/shared_metrics_subscriber.py
index 24bdbacc7bf..5c6a9e83762 100644
--- a/hermes_cli/observability/shared_metrics_subscriber.py
+++ b/hermes_cli/observability/shared_metrics_subscriber.py
@@ -23,6 +23,7 @@ from .shared_metrics_contract import (
INSTALL_SNAPSHOT_METRIC,
MODEL_ROUTE_METRIC,
TOOL_CALL_METRIC,
+ TOOL_LATENCY_METRIC,
TOOL_USAGE_METRIC,
client_active_counter,
client_resource,
@@ -32,22 +33,27 @@ from .shared_metrics_contract import (
model_token_counters,
skill_counter,
task_counter,
+ task_duration_counter,
tool_approval_counter,
tool_call_dimensions,
+ tool_latency_dimensions,
tool_usage_dimensions,
)
logger = logging.getLogger(__name__)
# Contract projections; each yields (metric_name, dimensions) or None. One tool end event feeds
-# both the category counter and the per-tool counter, so every match is recorded.
+# the category, per-tool and latency counters (one task end event the task and duration counters),
+# so every match is recorded.
_COUNTERS = (
client_active_counter,
install_snapshot_counter,
lambda event: _named(MODEL_ROUTE_METRIC, model_call_dimensions(event)),
lambda event: _named(TOOL_CALL_METRIC, tool_call_dimensions(event)),
lambda event: _named(TOOL_USAGE_METRIC, tool_usage_dimensions(event)),
+ lambda event: _named(TOOL_LATENCY_METRIC, tool_latency_dimensions(event)),
task_counter,
+ task_duration_counter,
tool_approval_counter,
skill_counter,
decision_counter,
diff --git a/scripts/smoke_nemo_relay_shared_metrics.py b/scripts/smoke_nemo_relay_shared_metrics.py
index b7bbc76238a..80ee2f2ae8d 100644
--- a/scripts/smoke_nemo_relay_shared_metrics.py
+++ b/scripts/smoke_nemo_relay_shared_metrics.py
@@ -341,10 +341,12 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:
"hermes.skill.load.count",
"hermes.startup.latency",
"hermes.task_cost.count",
+ "hermes.task_run.duration",
"hermes.task_run.finished",
"hermes.task_run.started",
"hermes.tool.usage.count",
"hermes.tool_call.count",
+ "hermes.tool_call.latency",
"hermes.tool_enabled_unused.count",
"hermes.tool_output_truncation.count",
"hermes.tool_overhead.count",
@@ -363,21 +365,17 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:
raise AssertionError(
f"Unexpected client-active counter: {by_name['hermes.client.active']}"
)
- [model] = by_name["hermes.model_route.count"]
+ # Two primary calls; each lands in whatever TTFT bucket the host's load put it in.
+ models = by_name["hermes.model_route.count"]
expected_model = {
- "name": "hermes.model_route.count",
- "dimensions": {
- "call_role": "primary",
- "error_class": "none",
- "model": "custom",
- "outcome": "success",
- "provider": "custom",
- "ttft_bucket": "lt_500ms",
- },
- "value": 2,
- "packaged_value": 2,
+ "call_role": "primary", "error_class": "none", "model": "custom", "outcome": "success",
+ "provider": "custom",
}
- if model != expected_model:
+ if (
+ any({k: v for k, v in m["dimensions"].items() if k != "ttft_bucket"} != expected_model for m in models)
+ or sum(m["value"] for m in models) != 2
+ or sum(m["packaged_value"] for m in models) != 2
+ ):
raise AssertionError(
f"Unexpected model counter: {by_name['hermes.model_route.count']}"
)
@@ -397,17 +395,13 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:
)
[terminal] = by_name["hermes.task_run.finished"]
expected_terminal_dimensions = {
- "duration_bucket": terminal["dimensions"].get("duration_bucket"),
"end_reason": "completed",
"entrypoint": "interactive",
"execution_surface": "cli",
"failure_class": "none",
- "model_call_count_bucket": "2",
"outcome": "success",
"platform": "none",
- "retry_count_bucket": "0",
"termination": "none",
- "tool_call_count_bucket": "1",
}
if (
terminal["dimensions"] != expected_terminal_dimensions
@@ -415,6 +409,15 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:
or terminal["packaged_value"] != 1
):
raise AssertionError(f"Unexpected task terminal counter: {terminal}")
+ [duration] = by_name["hermes.task_run.duration"]
+ if duration["dimensions"] != {
+ "duration_bucket": duration["dimensions"].get("duration_bucket"),
+ "execution_surface": "cli", "outcome": "success", "retry_count_bucket": "0",
+ } or duration["value"] != 1:
+ raise AssertionError(f"Unexpected task duration counter: {duration}")
+ [cost] = by_name["hermes.task_cost.count"]
+ if (cost["dimensions"]["api_calls_bucket"], cost["dimensions"]["tool_calls_bucket"]) != ("2", "1"):
+ raise AssertionError(f"Unexpected task cost counter: {cost}")
if [c["dimensions"] for c in by_name["hermes.tool.usage.count"]] != [
{"error_class": "none", "outcome": "success", "tool_name": "read_file"}
]:
@@ -449,15 +452,13 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:
raise AssertionError(f"Missing install milestones: {sorted(milestones)}")
[tool] = by_name["hermes.tool_call.count"]
expected_tool_dimensions = {
- "approval_outcome": "not_required",
- "latency_bucket": tool["dimensions"].get("latency_bucket"),
- "outcome": "success",
- "retry_count_bucket": "unknown",
- "tool_category": "file",
+ "approval_outcome": "not_required", "outcome": "success", "tool_category": "file",
}
+ [latency] = by_name["hermes.tool_call.latency"]
if (
tool["dimensions"] != expected_tool_dimensions
- or tool["dimensions"]["latency_bucket"] == "unknown"
+ or latency["dimensions"]["latency_bucket"] == "unknown"
+ or (latency["dimensions"]["retry_count_bucket"], latency["dimensions"]["tool_category"]) != ("unknown", "file")
or tool["value"] != 1
or tool["packaged_value"] != 1
):
@@ -564,10 +565,12 @@ def _validate_packages(
"hermes.skill.load.count",
"hermes.startup.latency",
"hermes.task_cost.count",
+ "hermes.task_run.duration",
"hermes.task_run.finished",
"hermes.task_run.started",
"hermes.tool.usage.count",
"hermes.tool_call.count",
+ "hermes.tool_call.latency",
"hermes.tool_enabled_unused.count",
"hermes.tool_output_truncation.count",
"hermes.tool_overhead.count",
@@ -586,44 +589,33 @@ def _validate_packages(
raise AssertionError(
f"Unexpected client-active metric: {metrics['hermes.client.active']}"
)
- [model] = metrics["hermes.model_route.count"]
- if model["dimensions"] != {
- "call_role": "primary",
- "error_class": "none",
- "model": "custom",
- "outcome": "success",
- "provider": "custom",
- "ttft_bucket": "lt_500ms",
- } or model["value"] != 2:
+ models = metrics["hermes.model_route.count"]
+ if any(
+ {k: v for k, v in m["dimensions"].items() if k != "ttft_bucket"} != {
+ "call_role": "primary", "error_class": "none", "model": "custom", "outcome": "success",
+ "provider": "custom",
+ }
+ for m in models
+ ) or sum(m["value"] for m in models) != 2:
raise AssertionError(
f"Unexpected model metric: {metrics['hermes.model_route.count']}"
)
[terminal] = metrics["hermes.task_run.finished"]
if terminal["dimensions"] != {
- "duration_bucket": terminal["dimensions"].get("duration_bucket"),
"end_reason": "completed",
"entrypoint": "interactive",
"execution_surface": "cli",
"failure_class": "none",
- "model_call_count_bucket": "2",
"outcome": "success",
"platform": "none",
- "retry_count_bucket": "0",
"termination": "none",
- "tool_call_count_bucket": "1",
}:
raise AssertionError(f"Unexpected task terminal metric: {terminal}")
[tool] = metrics["hermes.tool_call.count"]
if (
tool["dimensions"]
- != {
- "approval_outcome": "not_required",
- "latency_bucket": tool["dimensions"].get("latency_bucket"),
- "outcome": "success",
- "retry_count_bucket": "unknown",
- "tool_category": "file",
- }
- or tool["dimensions"]["latency_bucket"] == "unknown"
+ != {"approval_outcome": "not_required", "outcome": "success", "tool_category": "file"}
+ or metrics["hermes.tool_call.latency"][0]["dimensions"]["latency_bucket"] == "unknown"
):
raise AssertionError(f"Unexpected tool metric: {tool}")
lifecycle = metrics["hermes.skill.lifecycle.count"]
diff --git a/tests/hermes_cli/test_relay_shared_metrics.py b/tests/hermes_cli/test_relay_shared_metrics.py
index eb2d044cd80..a22602e003f 100644
--- a/tests/hermes_cli/test_relay_shared_metrics.py
+++ b/tests/hermes_cli/test_relay_shared_metrics.py
@@ -58,10 +58,13 @@ from hermes_cli.observability.shared_metrics_contract import (
skill_counter,
skill_lifecycle_fields,
skill_load_fields,
+ task_counter,
+ task_duration_counter,
task_terminal_fields,
tool_approval_counter,
tool_approval_outcome,
tool_call_dimensions,
+ tool_latency_dimensions,
tool_usage_dimensions,
tool_category,
tool_latency_bucket,
@@ -97,7 +100,9 @@ def _package_dimension_schema() -> dict[str, object]:
def _task_dimension_schema(kind: str) -> dict[str, object]:
schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
- return schema["$defs"][kind]["properties"]["dimensions"]
+ dimensions = schema["$defs"][kind]["properties"]["dimensions"]
+ # The terminal counter lists its current v3 shape first, then the v2 shape it still drains.
+ return dimensions["oneOf"][0] if "oneOf" in dimensions else dimensions
def _tool_dimension_schema(kind: str) -> dict[str, object]:
@@ -848,11 +853,10 @@ def test_tool_subscriber_contract_accepts_only_bounded_events():
},
)
assert tool_call_dimensions(terminal) == {
- "approval_outcome": "approved",
- "latency_bucket": "250ms_to_500ms",
- "outcome": "success",
- "retry_count_bucket": "0",
- "tool_category": "terminal",
+ "approval_outcome": "approved", "outcome": "success", "tool_category": "terminal",
+ }
+ assert tool_latency_dimensions(terminal) == {
+ "latency_bucket": "250ms_to_500ms", "retry_count_bucket": "0", "tool_category": "terminal",
}
assert tool_usage_dimensions(terminal) == {
"error_class": "none", "outcome": "success", "tool_name": "terminal",
@@ -1094,17 +1098,60 @@ def test_store_exports_task_started_and_terminal_counters(tmp_path):
tool_call_count=2,
retry_count=0,
)
- store.record_counter("hermes.task_run.finished", terminal, _resource())
+ end = SimpleNamespace(
+ kind="scope", category="function", category_profile=None, name="hermes.task_run",
+ scope_category="end", metadata={"hermes.metrics.schema_version": "hermes.metrics.event.v3"},
+ data=terminal,
+ )
+ for counter in (task_counter(end), task_duration_counter(end)):
+ store.record_counter(*counter, _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.duration",
"hermes.task_run.finished",
"hermes.task_run.started",
}
+def test_v2_task_and_tool_rows_recorded_before_an_upgrade_still_package(tmp_path):
+ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
+ store.record_counter("hermes.task_run.finished", {
+ "duration_bucket": "1s_to_5s", "end_reason": "completed", "entrypoint": "interactive",
+ "execution_surface": "cli", "model_call_count_bucket": "1", "outcome": "success",
+ "retry_count_bucket": "0", "termination": "none", "tool_call_count_bucket": "2",
+ }, _resource())
+ store.record_counter("hermes.tool_call.count", {
+ "approval_outcome": "not_required", "latency_bucket": "lt_100ms", "outcome": "success",
+ "retry_count_bucket": "0", "tool_category": "file",
+ }, _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.tool_call.count",
+ }
+
+
+def test_sent_package_keeps_its_file_but_not_a_second_copy_in_the_database(tmp_path):
+ store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
+ store.record_model_call(_dimensions(), _resource())
+ [sent_path] = store.create_and_export_package()
+ with sqlite3.connect(store.database_path) as connection:
+ connection.execute("UPDATE package_outbox SET send_state = 'sent'")
+ store.record_model_call(_dimensions(), _resource())
+ [pending_path] = store.create_and_export_package()
+
+ with sqlite3.connect(store.database_path) as connection:
+ bodies = dict(connection.execute("SELECT package_id, payload_json FROM package_outbox"))
+ assert bodies[sent_path.stem] == ""
+ assert json.loads(bodies[pending_path.stem]) == json.loads(pending_path.read_text(encoding="utf-8"))
+ _schema_validator().validate(json.loads(sent_path.read_text(encoding="utf-8")))
+
+
def test_package_schema_rejects_unknown_fields(tmp_path):
store = SharedMetricsStore(tmp_path / "metrics.sqlite3", tmp_path / "outbox")
store.record_model_call(_dimensions(), _resource())
diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
index 6e53e8d143d..372178f0c4c 100644
--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py
+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
@@ -414,11 +414,13 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_pa
"hermes.install.snapshot",
"hermes.model_route.count",
"hermes.task_cost.count",
+ "hermes.task_run.duration",
"hermes.task_run.finished",
"hermes.task_run.started",
"hermes.tool.usage.count",
"hermes.tool_approval.count",
"hermes.tool_call.count",
+ "hermes.tool_call.latency",
}
assert metrics["hermes.tool.usage.count"]["dimensions"] == {
"error_class": "none", "outcome": "success", "tool_name": "terminal",
@@ -445,13 +447,14 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_pa
"type": "counter",
"dimensions": {
"approval_outcome": "approved",
- "latency_bucket": "250ms_to_500ms",
"outcome": "success",
- "retry_count_bucket": "0",
"tool_category": "terminal",
},
"value": 1,
}
+ assert metrics["hermes.tool_call.latency"]["dimensions"] == {
+ "latency_bucket": "250ms_to_500ms", "retry_count_bucket": "0", "tool_category": "terminal",
+ }
assert metrics["hermes.tool_approval.count"] == {
"name": "hermes.tool_approval.count",
"type": "counter",
@@ -471,29 +474,30 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_pa
},
"value": 1,
}
- terminal = metrics["hermes.task_run.finished"]["dimensions"]
- assert terminal["duration_bucket"] in {
- "lt_1s",
- "1s_to_5s",
- "5s_to_30s",
- "30s_to_2m",
- "2m_to_10m",
- "gte_10m",
- }
- assert {
- key: value for key, value in terminal.items() if key != "duration_bucket"
- } == {
+ assert metrics["hermes.task_run.finished"]["dimensions"] == {
"end_reason": "completed",
"entrypoint": "interactive",
"execution_surface": "cli",
"failure_class": "none",
- "model_call_count_bucket": "1",
"outcome": "success",
"platform": "none",
- "retry_count_bucket": "1",
"termination": "none",
- "tool_call_count_bucket": "1",
}
+ duration = metrics["hermes.task_run.duration"]["dimensions"]
+ assert duration["duration_bucket"] in {
+ "lt_1s",
+ "1s_to_5s",
+ "5s_to_30s",
+ "30s_to_2m",
+ "2m_to_10m",
+ "gte_10m",
+ }
+ assert {key: value for key, value in duration.items() if key != "duration_bucket"} == {
+ "execution_surface": "cli", "outcome": "success", "retry_count_bucket": "1",
+ }
+ # Per-task call counts ride on the task cost row now.
+ assert metrics["hermes.task_cost.count"]["dimensions"]["api_calls_bucket"] == "1"
+ assert metrics["hermes.task_cost.count"]["dimensions"]["tool_calls_bucket"] == "1"
def test_real_binding_drives_lifecycle_aggregation_export_and_snapshot(
@@ -699,25 +703,27 @@ def test_real_binding_drives_lifecycle_aggregation_export_and_snapshot(
}
assert tool_by_outcome["success"] == {
"approval_outcome": "approved",
- "latency_bucket": "100ms_to_250ms",
"outcome": "success",
- "retry_count_bucket": "0",
"tool_category": "terminal",
}
assert tool_by_outcome["failed"] == {
"approval_outcome": "not_required",
- "latency_bucket": "500ms_to_1s",
"outcome": "failed",
- "retry_count_bucket": "unknown",
"tool_category": "file",
}
assert tool_by_outcome["cancelled"] == {
"approval_outcome": "not_required",
- "latency_bucket": "gte_30s",
"outcome": "cancelled",
- "retry_count_bucket": "unknown",
"tool_category": "browser",
}
+ assert {
+ tuple(counter["dimensions"][f] for f in ("tool_category", "latency_bucket", "retry_count_bucket"))
+ for counter in by_metric["hermes.tool_call.latency"]
+ } == {
+ ("terminal", "100ms_to_250ms", "0"),
+ ("file", "500ms_to_1s", "unknown"),
+ ("browser", "gte_30s", "unknown"),
+ }
assert len(by_metric["hermes.tool_approval.count"]) == 1
approval_counter = by_metric["hermes.tool_approval.count"][0]
assert approval_counter["dimensions"] == {
@@ -731,8 +737,12 @@ def test_real_binding_drives_lifecycle_aggregation_export_and_snapshot(
for counter in by_metric["hermes.task_run.finished"]
}
assert set(terminal_by_outcome) == {"success", "failed", "cancelled"}
- assert terminal_by_outcome["success"]["dimensions"]["retry_count_bucket"] == "1"
- assert terminal_by_outcome["success"]["dimensions"]["tool_call_count_bucket"] == "1"
+ duration_by_outcome = {
+ counter["dimensions"]["outcome"]: counter["dimensions"]
+ for counter in by_metric["hermes.task_run.duration"]
+ }
+ assert set(duration_by_outcome) == {"success", "failed", "cancelled"}
+ assert duration_by_outcome["success"]["retry_count_bucket"] == "1"
assert terminal_by_outcome["failed"]["dimensions"]["end_reason"] == (
"system_aborted"
)
@@ -864,11 +874,12 @@ def test_real_binding_correlates_plugin_approval_denial_to_tool_metric(
assert len(tool_metrics) == 1
assert tool_metrics[0]["dimensions"] == {
"approval_outcome": "denied",
- "latency_bucket": "lt_100ms",
"outcome": "blocked",
- "retry_count_bucket": "unknown",
"tool_category": "file",
}
+ assert [
+ counter["dimensions"] for counter in snapshot if counter["metric_name"] == "hermes.tool_call.latency"
+ ] == [{"latency_bucket": "lt_100ms", "retry_count_bucket": "unknown", "tool_category": "file"}]
approval_metrics = [
counter
for counter in snapshot
@@ -943,11 +954,12 @@ def test_real_binding_aggregates_tool_and_approval_timeouts(
]
assert tool_metric["dimensions"] == {
"approval_outcome": "timed_out",
- "latency_bucket": "gte_30s",
"outcome": "timed_out",
- "retry_count_bucket": "unknown",
"tool_category": "terminal",
}
+ assert [
+ counter["dimensions"] for counter in snapshot if counter["metric_name"] == "hermes.tool_call.latency"
+ ] == [{"latency_bucket": "gte_30s", "retry_count_bucket": "unknown", "tool_category": "terminal"}]
[approval_metric] = [
counter
for counter in snapshot
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index 302ef85d782..176e942fd23 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -198,12 +198,16 @@ surface and entrypoint values plus, for gateway tasks, the built-in messaging
`platform` (`telegram`, `discord`, `slack`, ...; platforms Hermes ships under
`plugins/platforms/` by name, a `plugin-catalog/` platform by its catalog entry
name only when the installer's own record proves a catalog install, every other
-plugin platform `plugin`, every other surface `none`). The terminal counter contains bounded
-outcome, end reason, termination status, duration, logical model-call count,
-terminal tool-call count, and provider-retry count buckets, and a
-`failure_class` for failed tasks: the provider `FailoverReason` when the turn
-died on a classified API error, otherwise a local class (`empty_response`,
-`context_compression`, `repeated_errors`, `exception`, `other`, ...). Raw exit
+plugin platform `plugin`, every other surface `none`). The terminal counter
+(`hermes.task_run.finished`) contains the start fields plus bounded outcome, end
+reason, termination status, and a `failure_class` for failed tasks: the provider
+`FailoverReason` when the turn died on a classified API error, otherwise a local
+class (`empty_response`, `context_compression`, `repeated_errors`, `exception`,
+`other`, ...). The same end event feeds `hermes.task_run.duration` with execution
+surface, outcome, duration bucket and provider-retry count bucket. Package v2
+carried duration, retries and per-task model/tool call counts on the terminal row
+itself, which made almost every task its own row; call counts per turn live on
+`hermes.task_cost.count`. Raw exit
reasons never leave the machine. Retries are additional
provider attempts for the same Hermes API request ID; they do not inflate the
logical model-call count. Tool calls are deduplicated by their Hermes tool-call
@@ -214,7 +218,9 @@ conversation session during context compression.
Each tool invocation is represented by a Relay tool lifecycle named
`hermes.tool_call`. The terminal counter contains only bounded tool category,
-outcome, approval outcome, latency, and explicit retry-count buckets. Hermes
+outcome and approval outcome; the same event feeds `hermes.tool_call.latency`
+with tool category, latency bucket and explicit retry-count bucket (package v2
+carried latency and retries on the terminal row, one row per few calls). Hermes
derives the category from the toolset already declared in its runtime registry;
custom and unrecognized toolsets collapse to `other` rather than exporting
tool or plugin names. The same terminal event also feeds
@@ -466,7 +472,10 @@ $HERMES_HOME/telemetry/shared_metrics/outbox/*.json
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. Each package records the Hermes version,
+are written with atomic replacement as compact JSON (`jq .` pretty-prints one).
+Once the ingest has accepted or refused a package, the database keeps only its
+send state and drops its copy of the body; the file is the local history copy.
+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
@@ -474,8 +483,9 @@ 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 schemas v1 and v2 remain unchanged for existing outbox files. New
-packages use v3, which also accepts the v2 field sets of `hermes.model_route.count`
-and the task counters so counters recorded before an upgrade drain safely.
+packages use v3, which also accepts the v2 field sets of `hermes.model_route.count`,
+`hermes.tool_call.count` and the task counters so counters recorded before an upgrade
+drain safely.
Vocabularies derived from in-repo registries (tool names, platforms, memory
providers, error classes) are bounded by pattern in the JSON schema; the
authoritative allowlist is `shared_metrics_contract.py`.