The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telemetry): re-bucket catalog-drifted shared-metric rows instead of aborting the package
liuhao1024a1d8264f0977
diff --git a/hermes_cli/observability/shared_metrics.py b/hermes_cli/observability/shared_metrics.pyindex 86084f0715d..0fb286c7e48 100644--- a/hermes_cli/observability/shared_metrics.py+++ b/hermes_cli/observability/shared_metrics.py@@ -27,7 +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,)@@ -645,10 +647,21 @@ class SharedMetricsStore:def _package_metric(row: sqlite3.Row) -> dict[str, Any]:metric_name = str(row["metric_name"])dimensions = json.loads(row["dimensions_json"])- if not isinstance(dimensions, dict) or not counter_dimensions_are_valid(- metric_name, dimensions- ):+ # 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.+ 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(+ "Shared-metric %s row drifted out of the contract since it was recorded; "+ "packaged with bucketed dimensions %s", metric_name, _compact_json(conformed),+ )+ dimensions = conformedreturn {"name": metric_name, "type": "counter", "dimensions": dimensions,"value": row["value"] - row["packaged_value"],diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.pyindex af270d79bfd..0f7e9cc75dd 100644--- a/hermes_cli/observability/shared_metrics_contract.py+++ b/hermes_cli/observability/shared_metrics_contract.py@@ -1229,6 +1229,50 @@ 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/tests/hermes_cli/test_relay_shared_metrics.py b/tests/hermes_cli/test_relay_shared_metrics.pyindex a1a130305da..f2ade5bba69 100644--- a/tests/hermes_cli/test_relay_shared_metrics.py+++ b/tests/hermes_cli/test_relay_shared_metrics.py@@ -1278,6 +1278,99 @@ def test_package_builder_rejects_tampered_client_resources(tmp_path):assert list(outbox_directory.glob("*.json")) == []+def test_package_builder_buckets_values_that_drifted_out_of_the_catalog(tmp_path, monkeypatch):+ """A catalog-backed value that left the catalog between the recording and packaging+ processes re-buckets to ``custom`` instead of aborting the whole period's package, and+ every other metric in the period still exports (#133017)."""+ 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)+ # Recording process: the plugin was a catalog entry, so the row passes record-time+ # validation and is persisted under its real name.+ monkeypatch.setattr(catalog_module, "plugin_catalog_names", lambda: frozenset({"later-removed-plugin"}))+ store.record_counter(+ EXTENSION_INSTALL_METRIC,+ {"kind": "plugin", "name": "later-removed-plugin", "outcome": "success", "source": "catalog"},+ _resource(),+ )+ store.record_model_call(_dimensions(), _resource())+ # Packaging process (a later run): the catalog moved on and no longer lists the plugin.+ monkeypatch.setattr(catalog_module, "plugin_catalog_names", lambda: frozenset())++ [package_path] = store.create_and_export_package()++ payload = json.loads(package_path.read_text(encoding="utf-8"))+ metrics = {metric["name"]: metric for metric in payload["metrics"]}+ assert metrics[EXTENSION_INSTALL_METRIC]["dimensions"] == {+ "kind": "plugin", "name": "custom", "outcome": "success", "source": "catalog",+ }+ assert metrics[MODEL_ROUTE_METRIC]["dimensions"] == _dimensions()+ # The drifted row settles like any other instead of wedging the period forever.+ 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(),+ )+ 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())+ 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,+ ),+ )++ with pytest.raises(ValueError, match="Unsupported dimensions"):+ store.create_and_export_package()++ assert list(outbox_directory.glob("*.json")) == []++def test_retention_prunes_only_expired_exported_history(tmp_path):database_path = tmp_path / "metrics.sqlite3"outbox_directory = tmp_path / "outbox"