:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): add attribute_field helper and seed_metric fixture (P0) (#61953)
Daniel Viscadc0f47fd3370
diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.pyindex b11db0817134..0636cc99aab6 100644--- a/products/metrics/backend/metric_query_runner.py+++ b/products/metrics/backend/metric_query_runner.py@@ -9,15 +9,61 @@ pipeline yet."""import datetime as dt-from typing import Any+from typing import Any, Literalfrom posthog.hogql import ast-from posthog.hogql.parser import parse_select+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workloadfrom posthog.models import Team+AttributeScope = Literal["resource", "attribute", "auto"]++_ALLOWED_ATTRIBUTE_SCOPES: frozenset[str] = frozenset({"resource", "attribute", "auto"})+++def attribute_field(name: str, *, scope: AttributeScope = "auto") -> ast.Expr:+ """Build the HogQL AST node that accesses a metric attribute by name.++ This is the single seam between the upcoming filter / group-by / rate /+ histogram-quantile work (PR3-PR6) and the underlying `metrics1` storage+ shape. When the Snuffle-style streams-table rewrite lands, only this+ function changes — every call site keeps working.++ `scope` resolves *where* the attribute lives:++ - ``"resource"`` — look in ``resource_attributes`` only (Prometheus-style+ `service.name`, `k8s.pod.name` — set once per scrape target).+ - ``"attribute"`` — look in ``attributes`` only (the alias view of+ ``attributes_map_str`` that strips the 5-char ``__str`` type tag from+ each key). Per-data-point labels like ``http.method`` live here.+ - ``"auto"`` (default) — try resource first, fall back to attribute if+ empty. Map lookups in ClickHouse return ``''`` for missing keys, not+ NULL, so the fallback compares against the empty string.++ The empty-string fallback is documented behaviour, not a bug: it means+ callers cannot meaningfully filter for "attribute equals empty string"+ in auto scope. Use an explicit scope for that edge case.+ """+ if scope not in _ALLOWED_ATTRIBUTE_SCOPES:+ raise ValueError(f"Unknown attribute scope: {scope!r}")++ name_constant = ast.Constant(value=name)++ # arrayElement, not subscript: HogQL prints `field[...]` on a+ # StringJSONDatabaseField as JSONExtractRaw, which is illegal on the+ # physical Map columns. arrayElement passes through and is ClickHouse's+ # native Map accessor ('' for missing keys).+ if scope == "resource":+ return parse_expr("arrayElement(resource_attributes, {name})", placeholders={"name": name_constant})+ if scope == "attribute":+ return parse_expr("arrayElement(attributes, {name})", placeholders={"name": name_constant})+ return parse_expr(+ "if(arrayElement(resource_attributes, {name}) != '', arrayElement(resource_attributes, {name}), arrayElement(attributes, {name}))",+ placeholders={"name": name_constant},+ )+def _aggregation_expr(name: str) -> ast.Expr:"""Build the HogQL AST for the supported aggregations.diff --git a/products/metrics/backend/tests/_seeder.py b/products/metrics/backend/tests/_seeder.pynew file mode 100644index 000000000000..18bc2a33d479--- /dev/null+++ b/products/metrics/backend/tests/_seeder.py@@ -0,0 +1,91 @@+"""Test-only metric row seeder for `metrics1`.++Inserts rows directly via `sync_execute` rather than driving the OTLP pipe,+so tests don't depend on capture-logs + metrics-ingestion-consumer running.++The shape mirrors what `rust/capture-logs/src/metric_record.rs` emits — every+later query-runner PR (filters, group-by, rate, histogram_quantile) leans on+this to plant deterministic fixtures with specific labels and timestamps.+"""++from __future__ import annotations++import json+import uuid+import datetime as dt+from collections.abc import Iterable, Mapping+from typing import Any++from posthog.clickhouse.client import sync_execute+++def _attribute_map_str_with_type_tags(labels: Mapping[str, str]) -> dict[str, str]:+ """`attributes_map_str` stores keys with a trailing 5-char type tag (e.g.+ `container__str`), matching the Kafka MV's `concat(k, '__str')`. The+ ClickHouse table exposes a stripped ALIAS column `attributes` via+ `left(k, -5)`. The seeder accepts user-friendly names (`container`) and+ appends the `__str` tag so lookups via the ALIAS work as expected.+ """+ return {f"{key}__str": value for key, value in labels.items()}+++def seed_metric(+ *,+ team_id: int,+ metric_name: str,+ points: Iterable[tuple[dt.datetime, float]],+ labels: Mapping[str, str] | None = None,+ resource_labels: Mapping[str, str] | None = None,+ metric_type: str = "gauge",+ service_name: str = "test-service",+ aggregation_temporality: str = "cumulative",+ is_monotonic: bool = False,+ histogram_bounds: list[float] | None = None,+ histogram_counts: list[int] | None = None,+ unit: str = "",+) -> None:+ """Insert one row per `(timestamp, value)` point into `metrics1`.++ `labels` populates the per-data-point `attributes_map_str` map (with the+ `__str` type-tag suffix the schema expects). `resource_labels` populates+ `resource_attributes` directly — those are tag-free.++ Histogram inputs (`histogram_bounds`, `histogram_counts`) are passed+ through verbatim; only relevant when `metric_type='histogram'`.+ """+ attributes_map_str = _attribute_map_str_with_type_tags(labels or {})+ resource_attributes = dict(resource_labels or {})++ rows: list[dict[str, Any]] = []+ for timestamp, value in points:+ rows.append(+ {+ "uuid": str(uuid.uuid4()),+ "team_id": team_id,+ "trace_id": "",+ "span_id": "",+ "trace_flags": 0,+ "timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),+ "observed_timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),+ "service_name": service_name,+ "metric_name": metric_name,+ "metric_type": metric_type,+ "value": value,+ "count": 1,+ "histogram_bounds": histogram_bounds or [],+ "histogram_counts": histogram_counts or [],+ "unit": unit,+ "aggregation_temporality": aggregation_temporality,+ "is_monotonic": is_monotonic,+ "resource_attributes": resource_attributes,+ "instrumentation_scope": "",+ "attributes_map_str": attributes_map_str,+ "attributes_map_float": {},+ }+ )++ if not rows:+ return++ payload = "\n".join(json.dumps(row) for row in rows)+ sync_execute(f"INSERT INTO metrics1 FORMAT JSONEachRow {payload}")diff --git a/products/metrics/backend/tests/test_metric_names_query_runner.py b/products/metrics/backend/tests/test_metric_names_query_runner.pyindex d5e7814a8da1..45527ea58d15 100644--- a/products/metrics/backend/tests/test_metric_names_query_runner.py+++ b/products/metrics/backend/tests/test_metric_names_query_runner.py@@ -9,7 +9,18 @@ from rest_framework import statusfrom posthog.clickhouse.client import sync_executefrom products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner-from products.metrics.backend.tests.test_metric_query_runner import _insert_metric_row+from products.metrics.backend.tests._seeder import seed_metric+++def _seed_point(+ *,+ team_id: int,+ metric_name: str,+ value: float,+ timestamp: dt.datetime,+ metric_type: str = "gauge",+) -> None:+ seed_metric(team_id=team_id, metric_name=metric_name, points=[(timestamp, value)], metric_type=metric_type)class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):@@ -35,21 +46,21 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_returns_distinct_names_with_metric_type(self):anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)- _insert_metric_row(+ _seed_point(team_id=self.team.id,metric_name="http.server.duration",value=1.0,timestamp=anchor,metric_type="histogram",)- _insert_metric_row(+ _seed_point(team_id=self.team.id,metric_name="http.server.duration",value=2.0,timestamp=anchor,metric_type="histogram",)- _insert_metric_row(+ _seed_point(team_id=self.team.id,metric_name="queue.depth",value=12.0,@@ -69,8 +80,8 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_search_filters_by_substring(self):anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)- _insert_metric_row(team_id=self.team.id, metric_name="http.server.duration", value=1.0, timestamp=anchor)- _insert_metric_row(team_id=self.team.id, metric_name="queue.depth", value=12.0, timestamp=anchor)+ _seed_point(team_id=self.team.id, metric_name="http.server.duration", value=1.0, timestamp=anchor)+ _seed_point(team_id=self.team.id, metric_name="queue.depth", value=12.0, timestamp=anchor)runner = MetricNamesQueryRunner(team=self.team, search="server")results = runner.run()@@ -78,13 +89,13 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_exact_match_floats_to_top(self):anchor = timezone.now().replace(microsecond=0)- _insert_metric_row(+ _seed_point(team_id=self.team.id,metric_name="foo.bar",value=1.0,timestamp=anchor - dt.timedelta(minutes=10),)- _insert_metric_row(+ _seed_point(team_id=self.team.id,metric_name="bar",value=2.0,@@ -97,7 +108,7 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_respects_team_isolation(self):anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)- _insert_metric_row(team_id=99999, metric_name="other.team.metric", value=1.0, timestamp=anchor)+ _seed_point(team_id=99999, metric_name="other.team.metric", value=1.0, timestamp=anchor)runner = MetricNamesQueryRunner(team=self.team)self.assertEqual(runner.run(), [])@@ -105,8 +116,8 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_lookback_excludes_old_data(self):old = timezone.now().replace(microsecond=0) - dt.timedelta(days=14)recent = timezone.now().replace(microsecond=0) - dt.timedelta(hours=1)- _insert_metric_row(team_id=self.team.id, metric_name="old.metric", value=1.0, timestamp=old)- _insert_metric_row(team_id=self.team.id, metric_name="recent.metric", value=2.0, timestamp=recent)+ _seed_point(team_id=self.team.id, metric_name="old.metric", value=1.0, timestamp=old)+ _seed_point(team_id=self.team.id, metric_name="recent.metric", value=2.0, timestamp=recent)runner = MetricNamesQueryRunner(team=self.team, lookback=dt.timedelta(days=7))names = [row["name"] for row in runner.run()]@@ -133,8 +144,8 @@ class TestMetricsValuesAPI(ClickhouseTestMixin, APIBaseTest):def test_values_returns_metric_names(self):anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)- _insert_metric_row(team_id=self.team.id, metric_name="m1", value=1.0, timestamp=anchor)- _insert_metric_row(team_id=self.team.id, metric_name="m2", value=2.0, timestamp=anchor, metric_type="gauge")+ _seed_point(team_id=self.team.id, metric_name="m1", value=1.0, timestamp=anchor)+ _seed_point(team_id=self.team.id, metric_name="m2", value=2.0, timestamp=anchor, metric_type="gauge")response = self.client.get(f"/api/projects/{self.team.id}/metrics/values")self.assertEqual(response.status_code, status.HTTP_200_OK)@@ -144,8 +155,8 @@ class TestMetricsValuesAPI(ClickhouseTestMixin, APIBaseTest):def test_values_search_param(self):anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)- _insert_metric_row(team_id=self.team.id, metric_name="http.duration", value=1.0, timestamp=anchor)- _insert_metric_row(team_id=self.team.id, metric_name="queue.depth", value=2.0, timestamp=anchor)+ _seed_point(team_id=self.team.id, metric_name="http.duration", value=1.0, timestamp=anchor)+ _seed_point(team_id=self.team.id, metric_name="queue.depth", value=2.0, timestamp=anchor)response = self.client.get(f"/api/projects/{self.team.id}/metrics/values?value=http")self.assertEqual(response.status_code, status.HTTP_200_OK)diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.pyindex 5c4296591c4f..abe1537f2f0e 100644--- a/products/metrics/backend/tests/test_metric_query_runner.py+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -1,4 +1,3 @@-import jsonimport datetime as dtfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin@@ -8,48 +7,15 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status-from posthog.clickhouse.client import sync_execute--from products.metrics.backend.metric_query_runner import MetricQueryRunner, _pick_interval-+from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query-def _insert_metric_row(- *,- team_id: int,- metric_name: str,- value: float,- timestamp: dt.datetime,- metric_type: str = "gauge",-) -> None:- """Insert a single row into the local `metrics1` table.+from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.connection import Workload- Uses the same shape `rust/capture-logs/src/metric_record.rs` emits, with- fields the test doesn't care about set to empty/default.- """- row = {- "uuid": "019e6bc4-4897-77d0-ab21-56ba3e2fe535",- "team_id": team_id,- "trace_id": "",- "span_id": "",- "trace_flags": 0,- "timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),- "observed_timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),- "service_name": "test-service",- "metric_name": metric_name,- "metric_type": metric_type,- "value": value,- "count": 1,- "histogram_bounds": [],- "histogram_counts": [],- "unit": "",- "aggregation_temporality": "cumulative",- "is_monotonic": False,- "resource_attributes": {},- "instrumentation_scope": "",- "attributes_map_str": {},- "attributes_map_float": {},- }- sync_execute(f"INSERT INTO metrics1 FORMAT JSONEachRow {json.dumps(row)}")+from products.metrics.backend.metric_query_runner import MetricQueryRunner, _pick_interval, attribute_field+from products.metrics.backend.tests._seeder import seed_metricclass TestPickInterval:@@ -108,18 +74,20 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_aggregates_sum_per_bucket(self):anchor = timezone.now().replace(microsecond=0)- _insert_metric_row(- team_id=self.team.id, metric_name="m1", value=2.0, timestamp=anchor - dt.timedelta(minutes=5)- )- _insert_metric_row(- team_id=self.team.id, metric_name="m1", value=3.0, timestamp=anchor - dt.timedelta(minutes=5)- )- _insert_metric_row(- team_id=self.team.id, metric_name="m1", value=4.0, timestamp=anchor - dt.timedelta(minutes=20)+ seed_metric(+ team_id=self.team.id,+ metric_name="m1",+ points=[+ (anchor - dt.timedelta(minutes=5), 2.0),+ (anchor - dt.timedelta(minutes=5), 3.0),+ (anchor - dt.timedelta(minutes=20), 4.0),+ ],)# Different metric — should be filtered out.- _insert_metric_row(- team_id=self.team.id, metric_name="m2", value=99.0, timestamp=anchor - dt.timedelta(minutes=5)+ seed_metric(+ team_id=self.team.id,+ metric_name="m2",+ points=[(anchor - dt.timedelta(minutes=5), 99.0)],)runner = MetricQueryRunner(@@ -136,7 +104,11 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):def test_respects_team_isolation(self):anchor = timezone.now().replace(microsecond=0)- _insert_metric_row(team_id=99999, metric_name="m1", value=5.0, timestamp=anchor - dt.timedelta(minutes=5))+ seed_metric(+ team_id=99999,+ metric_name="m1",+ points=[(anchor - dt.timedelta(minutes=5), 5.0)],+ )runner = MetricQueryRunner(team=self.team,@@ -182,11 +154,13 @@ class TestMetricsQueryAPI(ClickhouseTestMixin, APIBaseTest):def test_query_returns_aggregated_points(self):anchor = timezone.now().replace(microsecond=0)- _insert_metric_row(- team_id=self.team.id, metric_name="m1", value=1.0, timestamp=anchor - dt.timedelta(minutes=10)- )- _insert_metric_row(- team_id=self.team.id, metric_name="m1", value=2.0, timestamp=anchor - dt.timedelta(minutes=10)+ seed_metric(+ team_id=self.team.id,+ metric_name="m1",+ points=[+ (anchor - dt.timedelta(minutes=10), 1.0),+ (anchor - dt.timedelta(minutes=10), 2.0),+ ],)response = self.client.post(@@ -206,3 +180,96 @@ class TestMetricsQueryAPI(ClickhouseTestMixin, APIBaseTest):body = response.json()self.assertIn("results", body)self.assertEqual(sum(point["value"] for point in body["results"]), 3.0)+++class TestAttributeField(ClickhouseTestMixin, APIBaseTest):+ """End-to-end tests for the `attribute_field` helper.++ The helper builds an AST node; correctness depends on what ClickHouse+ actually returns, so we execute a real query against `posthog.metrics`+ for each scope and assert the resolved value.+ """++ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")++ def _select_attribute(self, expr: ast.Expr, metric_name: str) -> str | None:+ query = parse_select(+ """+ SELECT {expr} AS value FROM posthog.metrics+ WHERE metric_name = {metric_name} LIMIT 1+ """,+ placeholders={"expr": expr, "metric_name": ast.Constant(value=metric_name)},+ )+ assert isinstance(query, ast.SelectQuery)+ response = execute_hogql_query(+ query_type="AttributeFieldTest",+ query=query,+ team=self.team,+ workload=Workload.LOGS,+ )+ if not response.results:+ return None+ return response.results[0][0]++ def test_rejects_unknown_scope(self):+ with self.assertRaises(ValueError):+ attribute_field("container", scope="bogus") # type: ignore[arg-type]++ def test_resource_scope_reads_resource_attributes(self):+ anchor = timezone.now().replace(microsecond=0)+ seed_metric(+ team_id=self.team.id,+ metric_name="m_resource",+ points=[(anchor, 1.0)],+ resource_labels={"service_name": "logs-ingestion"},+ )+ value = self._select_attribute(attribute_field("service_name", scope="resource"), "m_resource")+ self.assertEqual(value, "logs-ingestion")++ def test_attribute_scope_reads_attributes_via_alias(self):+ anchor = timezone.now().replace(microsecond=0)+ seed_metric(+ team_id=self.team.id,+ metric_name="m_attribute",+ points=[(anchor, 1.0)],+ labels={"http_method": "POST"},+ )+ value = self._select_attribute(attribute_field("http_method", scope="attribute"), "m_attribute")+ self.assertEqual(value, "POST")++ def test_auto_scope_prefers_resource_when_present(self):+ anchor = timezone.now().replace(microsecond=0)+ seed_metric(+ team_id=self.team.id,+ metric_name="m_auto_resource",+ points=[(anchor, 1.0)],+ resource_labels={"container": "capture-logs"},+ labels={"container": "should-not-win"},+ )+ value = self._select_attribute(attribute_field("container"), "m_auto_resource")+ self.assertEqual(value, "capture-logs")++ def test_auto_scope_falls_back_to_attribute_when_resource_empty(self):+ anchor = timezone.now().replace(microsecond=0)+ seed_metric(+ team_id=self.team.id,+ metric_name="m_auto_attribute",+ points=[(anchor, 1.0)],+ labels={"endpoint": "/api/projects/2/metrics/query"},+ )+ value = self._select_attribute(attribute_field("endpoint"), "m_auto_attribute")+ self.assertEqual(value, "/api/projects/2/metrics/query")++ def test_auto_scope_returns_empty_when_neither_present(self):+ anchor = timezone.now().replace(microsecond=0)+ seed_metric(+ team_id=self.team.id,+ metric_name="m_auto_missing",+ points=[(anchor, 1.0)],+ )+ value = self._select_attribute(attribute_field("nonexistent"), "m_auto_missing")+ self.assertEqual(value, "")