Skip to content

The agent that grows with you

fix(telemetry): retired built-in values stop wedging the package too

Teknium0438ca2da53b
diff --git a/hermes_cli/observability/shared_metrics.py b/hermes_cli/observability/shared_metrics.py
index 0fb286c7e48..ff8bdfbedad 100644
--- a/hermes_cli/observability/shared_metrics.py
+++ b/hermes_cli/observability/shared_metrics.py
@@ -27,10 +27,9 @@ from .shared_metrics_contract import (
MODEL_ROUTE_METRIC,
SUM_METRICS,
client_resource_is_valid,
- conform_counter_dimensions,
counter_dimensions_are_valid,
- counter_dimensions_shape_is_known,
)
+from .shared_metrics_drift import conform_counter_dimensions, counter_dimensions_shape_is_known
_PACKAGE_SCHEMA_VERSION = "hermes.shared_metrics.v4"
@@ -605,6 +604,10 @@ class SharedMetricsStore:
period_start = datetime.fromisoformat(str(period_value)).replace(tzinfo=UTC)
if not client_resource_is_valid(resource):
raise ValueError("Unsupported shared-metrics client resource")
+ metrics = self._package_metrics(rows)
+ if not metrics: # every row was a retired value with no bucket: settle them, try the next period
+ self._mark_packaged(connection, rows, period_value, resource_values)
+ return self._create_package_in_transaction(connection, now)
payload = {
"schema_version": _PACKAGE_SCHEMA_VERSION,
"package_id": str(uuid.uuid4()),
@@ -613,7 +616,7 @@ class SharedMetricsStore:
"period_end": _isoformat(period_start + timedelta(days=1)),
"generated_at": _isoformat(now),
"resource": resource,
- "metrics": [self._package_metric(row) for row in rows],
+ "metrics": metrics,
}
connection.execute(
"INSERT INTO package_outbox( package_id, period_start, period_end, payload_json,"
@@ -631,6 +634,13 @@ class SharedMetricsStore:
" ON CONFLICT(name) DO UPDATE SET stamp = MAX(stamp, excluded.stamp)",
(payload["period_end"],),
)
+ self._mark_packaged(connection, rows, period_value, resource_values)
+ return payload
+
+ @staticmethod
+ def _mark_packaged(
+ connection: sqlite3.Connection, rows: list[sqlite3.Row], period_value: str, resource_values: tuple,
+ ) -> None:
for row in rows:
connection.execute(
"""
@@ -641,23 +651,38 @@ class SharedMetricsStore:
""",
(period_value, row["metric_name"], *resource_values, row["dimensions_json"]),
)
- return payload
+
+ @classmethod
+ def _package_metrics(cls, rows: list[sqlite3.Row]) -> list[dict[str, Any]]:
+ """Package rows, merging rows a re-bucket folded onto the same dimensions into one metric."""
+ merged: dict[tuple[str, str], dict[str, Any]] = {}
+ for row in rows:
+ metric = cls._package_metric(row)
+ if metric is None:
+ continue
+ key = (metric["name"], _compact_json(metric["dimensions"]))
+ if key in merged:
+ merged[key]["value"] += metric["value"]
+ else:
+ merged[key] = metric
+ return list(merged.values())
@staticmethod
- def _package_metric(row: sqlite3.Row) -> dict[str, Any]:
+ def _package_metric(row: sqlite3.Row) -> dict[str, Any] | None:
metric_name = str(row["metric_name"])
dimensions = json.loads(row["dimensions_json"])
# An unknown field set is tamper evidence and fails closed (must-not-be-exported). A known
- # shape whose values fell out of the contract is catalog drift between the recording and
- # packaging processes (#133017): re-bucket inside the closed enum rather than abort the
- # whole period's package; un-rebucketable value drift still fails closed.
+ # shape whose values fell out of the contract was recorded by an earlier build or catalog
+ # (#133017): re-bucket it inside the closed enum, or leave the row out when its field has no
+ # bucket, rather than abort the whole period's package. Either way no stale value leaves.
if not isinstance(dimensions, dict) or not counter_dimensions_shape_is_known(metric_name, dimensions):
raise ValueError(f"Unsupported dimensions for shared metric: {metric_name}")
if not counter_dimensions_are_valid(metric_name, dimensions):
conformed = conform_counter_dimensions(metric_name, dimensions)
if conformed is None:
- raise ValueError(f"Unsupported dimensions for shared metric: {metric_name}")
- logger.warning(
+ logger.info("Shared-metric %s row holds a retired value with no bucket; not packaged", metric_name)
+ return None
+ logger.info(
"Shared-metric %s row drifted out of the contract since it was recorded; "
"packaged with bucketed dimensions %s", metric_name, _compact_json(conformed),
)
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index 0f7e9cc75dd..af270d79bfd 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -1229,50 +1229,6 @@ def _extension_install_fields_agree(metric_name: str, dimensions: dict[str, Any]
# ---- end iuf c1 ----
-def counter_dimensions_shape_is_known(metric_name: str, dimensions: dict[str, Any]) -> bool:
- """Whether the row's field set matches a current or legacy contract shape (values aside).
-
- A row that fails this is structurally unknown — that is tamper evidence, not drift, and
- packaging keeps failing closed on it (see test_package_builder_rejects_tampered_dimensions).
- """
- fields = frozenset(dimensions)
- return fields == _METRIC_FIELDS.get(metric_name) or fields in _LEGACY_METRIC_FIELDS.get(metric_name, ())
-
-
-def conform_counter_dimensions(metric_name: str, dimensions: dict[str, Any]) -> dict[str, Any] | None:
- """Re-bucket out-of-contract enum values into the field's closed fallback, else ``None``.
-
- Catalog-backed enums are repo data: a value that was a catalog entry when the row was
- recorded (and passed record-time validation) can legitimately fall out of the catalog by
- packaging time — the recording and packaging processes snapshot it independently (#133017).
- Exporting the stale value would leak exactly the out-of-enum payload the closed enum exists
- to prevent, so it is bucketed to ``custom``/``other`` (whichever the field's enum defines),
- mirroring what the record-side normalizers do for names that were never in the catalog.
- Returns ``None`` — keep failing closed — when a value cannot be safely re-bucketed: fields
- whose enum defines no fallback bucket (those enums are code constants and do not drift),
- non-string values, or identifier fields that no longer round-trip through
- ``_metric_identifier`` (record-time validation already guarantees they did once).
- """
- conformed = dict(dimensions)
- identifiers = _IDENTIFIER_FIELDS.get(metric_name, {})
- contract = _COUNTER_DIMENSION_VALUES[metric_name]
- for field, value in conformed.items():
- if not isinstance(value, str):
- return None
- if field in identifiers:
- if value != _metric_identifier(value, max_length=identifiers[field]):
- return None
- continue
- allowed = contract[field]
- if value in allowed:
- continue
- fallback = "custom" if "custom" in allowed else "other" if "other" in allowed else None
- if fallback is None:
- return None
- conformed[field] = fallback
- return conformed
-
-
def _relay_metadata(
event: Any, schema_key: str, schema_version: str, *extra_keys: str
) -> dict | None:
diff --git a/hermes_cli/observability/shared_metrics_drift.py b/hermes_cli/observability/shared_metrics_drift.py
new file mode 100644
index 00000000000..1ef3aced148
--- /dev/null
+++ b/hermes_cli/observability/shared_metrics_drift.py
@@ -0,0 +1,63 @@
+"""Rows an earlier build or catalog stored whose values the current contract no longer lists.
+
+Packaging re-checks every pending row against the current contract, so a value that left a closed
+set after it was recorded (a catalog entry removed, a built-in tool moved to a plugin) is conformed
+here instead of aborting the whole period's package (#133017).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from .shared_metrics_contract import (
+ _COUNTER_DIMENSION_VALUES,
+ _IDENTIFIER_FIELDS,
+ _LEGACY_METRIC_FIELDS,
+ _METRIC_FIELDS,
+ _metric_identifier,
+)
+
+
+def counter_dimensions_shape_is_known(metric_name: str, dimensions: dict[str, Any]) -> bool:
+ """Whether the row's field set matches a current or legacy contract shape (values aside).
+
+ A row that fails this is structurally unknown — that is tamper evidence, not drift, and
+ packaging keeps failing closed on it (see test_package_builder_rejects_tampered_dimensions).
+ """
+ fields = frozenset(dimensions)
+ return fields == _METRIC_FIELDS.get(metric_name) or fields in _LEGACY_METRIC_FIELDS.get(metric_name, ())
+
+
+def conform_counter_dimensions(metric_name: str, dimensions: dict[str, Any]) -> dict[str, Any] | None:
+ """Re-bucket out-of-contract enum values into the field's closed fallback, else ``None``.
+
+ Catalog-backed enums are repo data: a value that was a catalog entry when the row was
+ recorded (and passed record-time validation) can legitimately fall out of the catalog by
+ packaging time — the recording and packaging processes snapshot it independently (#133017).
+ Exporting the stale value would leak exactly the out-of-enum payload the closed enum exists
+ to prevent, so it is bucketed to ``custom``/``other``/``unknown`` (the first the field's enum
+ defines), mirroring what the record-side normalizers do for names that were never in the
+ catalog. Code constants drift too: a built-in tool moved to a plugin (Spotify, Home Assistant)
+ or a removed reason value leaves rows an earlier build stored.
+ Returns ``None`` when a value cannot be safely re-bucketed: fields whose enum defines no
+ fallback bucket, non-string values, or identifier fields that no longer round-trip through
+ ``_metric_identifier`` (record-time validation already guarantees they did once).
+ """
+ conformed = dict(dimensions)
+ identifiers = _IDENTIFIER_FIELDS.get(metric_name, {})
+ contract = _COUNTER_DIMENSION_VALUES[metric_name]
+ for field, value in conformed.items():
+ if not isinstance(value, str):
+ return None
+ if field in identifiers:
+ if value != _metric_identifier(value, max_length=identifiers[field]):
+ return None
+ continue
+ allowed = contract[field]
+ if value in allowed:
+ continue
+ fallback = next((bucket for bucket in ("custom", "other", "unknown") if bucket in allowed), None)
+ if fallback is None:
+ return None
+ conformed[field] = fallback
+ return conformed
diff --git a/tests/hermes_cli/test_relay_shared_metrics.py b/tests/hermes_cli/test_relay_shared_metrics.py
index f2ade5bba69..b795f4e4ae0 100644
--- a/tests/hermes_cli/test_relay_shared_metrics.py
+++ b/tests/hermes_cli/test_relay_shared_metrics.py
@@ -1312,63 +1312,41 @@ def test_package_builder_buckets_values_that_drifted_out_of_the_catalog(tmp_path
assert store._create_package() is None
-def test_package_builder_fails_closed_on_enums_without_a_fallback_bucket(tmp_path, monkeypatch):
- """Value drift on an enum with no ``custom``/``other`` bucket is tamper evidence, not catalog
- drift — those enums are code constants — so the row keeps failing closed."""
- from hermes_cli.observability import shared_metrics_catalog as catalog_module
- from hermes_cli.observability.shared_metrics_contract import EXTENSION_INSTALL_METRIC
-
- database_path = tmp_path / "metrics.sqlite3"
- outbox_directory = tmp_path / "outbox"
- store = SharedMetricsStore(database_path, outbox_directory)
- monkeypatch.setattr(catalog_module, "plugin_catalog_names", lambda: frozenset({"browserpaw"}))
- store.record_counter(
- EXTENSION_INSTALL_METRIC,
- {"kind": "plugin", "name": "browserpaw", "outcome": "success", "source": "catalog"},
- _resource(),
+def test_package_builder_settles_rows_an_earlier_build_stored_with_retired_values(tmp_path):
+ """A built-in toolset or tool an earlier build shipped (Spotify, Home Assistant) is no longer in
+ the contract: rows holding it re-bucket (merged with their siblings) or, when the field has no
+ bucket, stay out, and the rest of the period still exports instead of wedging every package."""
+ from hermes_cli.observability.shared_metrics_contract import (
+ TOOL_ENABLED_UNUSED_METRIC, TOOL_UNAVAILABLE_METRIC,
)
- with sqlite3.connect(database_path) as connection:
- connection.execute(
- "UPDATE counter_aggregates SET dimensions_json = ? WHERE metric_name = ?",
- (
- json.dumps({
- "kind": "plugin", "name": "browserpaw", "outcome": "must-not-be-exported",
- "source": "catalog",
- }),
- EXTENSION_INSTALL_METRIC,
- ),
- )
- monkeypatch.setattr(catalog_module, "plugin_catalog_names", lambda: frozenset())
- with pytest.raises(ValueError, match="Unsupported dimensions"):
- store.create_and_export_package()
-
- assert list(outbox_directory.glob("*.json")) == []
-
-
-def test_package_builder_fails_closed_on_identifier_drift(tmp_path):
- """A known shape whose identifier field no longer round-trips through the identifier
- normalizer cannot be re-bucketed and keeps failing closed (must-not-be-exported)."""
database_path = tmp_path / "metrics.sqlite3"
outbox_directory = tmp_path / "outbox"
store = SharedMetricsStore(database_path, outbox_directory)
store.record_model_call(_dimensions(), _resource())
+ for dims in ({"toolset": "file", "used": "yes"}, {"toolset": "terminal", "used": "yes"}):
+ store.record_counter(TOOL_ENABLED_UNUSED_METRIC, dims, _resource())
+ store.record_counter(TOOL_UNAVAILABLE_METRIC, {**_dimensions(), "tool_name": "read_file"}, _resource())
+ retired = {
+ '{"toolset":"file","used":"yes"}': {"toolset": "retired-toolset-a", "used": "yes"},
+ '{"toolset":"terminal","used":"yes"}': {"toolset": "retired-toolset-b", "used": "yes"},
+ }
with sqlite3.connect(database_path) as connection:
- connection.execute(
- "UPDATE counter_aggregates SET dimensions_json = ? WHERE metric_name = ?",
- (
- json.dumps({
- "model": _dimensions()["model"],
- "provider": "p" * (PROVIDER_IDENTIFIER_MAX_LENGTH + 1),
- }),
- MODEL_ROUTE_METRIC,
- ),
- )
+ for old, dims in retired.items():
+ connection.execute("UPDATE counter_aggregates SET dimensions_json = ? WHERE dimensions_json = ?",
+ (json.dumps(dims, separators=(",", ":")), old))
+ connection.execute("UPDATE counter_aggregates SET dimensions_json = ? WHERE metric_name = ?",
+ (json.dumps({**_dimensions(), "tool_name": "retired_tool"}), TOOL_UNAVAILABLE_METRIC))
- with pytest.raises(ValueError, match="Unsupported dimensions"):
- store.create_and_export_package()
+ [package_path] = store.create_and_export_package()
- assert list(outbox_directory.glob("*.json")) == []
+ text = package_path.read_text(encoding="utf-8")
+ assert "retired" not in text
+ metrics = [(m["name"], m["dimensions"], m["value"]) for m in json.loads(text)["metrics"]]
+ assert (TOOL_ENABLED_UNUSED_METRIC, {"toolset": "custom", "used": "yes"}, 2) in metrics
+ assert [m for m in metrics if m[0] == TOOL_UNAVAILABLE_METRIC] == []
+ assert (MODEL_ROUTE_METRIC, _dimensions(), 1) in metrics
+ assert store._create_package() is None
def test_retention_prunes_only_expired_exported_history(tmp_path):