: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): rank picker names from metric_names (#110006)
Frank Hamand907acc0180bd
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex 731a850365d4..2365e90d6ca5 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -303,8 +303,7 @@ def list_metric_names() -> list[dict[str, Any]]:"""List distinct metric names for the team's picker.- Returns a list of `{"name": str, "metric_type": str}` dicts ordered by- most-recently-seen, with exact-name matches floated to the top.+ Returns a list of `{"name": str, "metric_type": str}` dicts.Passing `services` narrows the list to names those services reported.Raises `ValueError` for an out-of-range limit or too many services.diff --git a/products/metrics/backend/metric_names_query_runner.py b/products/metrics/backend/metric_names_query_runner.pyindex d9206d6cf1e2..d0d20bb07b65 100644--- a/products/metrics/backend/metric_names_query_runner.py+++ b/products/metrics/backend/metric_names_query_runner.py@@ -1,23 +1,4 @@-"""Distinct metric names for a team's picker UI.--Reads `metric_series` (one row per metric + label-set) rather than the raw-`metrics` datapoint table. Both are fed from the same Kafka Avro stream, so-they carry the same names, but the series table holds one row per series-where the datapoint table holds one per scrape, so it is orders of magnitude-smaller for the same window. It also sorts by `(team_id, metric_name,-series_fingerprint)` with a materialized `last_seen`, so the lookback needs no-scan over the datapoint rows.--No FINAL. ReplacingMergeTree duplicates share `(team_id, metric_name,-series_fingerprint)`, and `max(last_seen)` picks the row FINAL would keep, since-`last_seen` is the engine's version column. `metric_type` is an input to the-fingerprint (see `rust/capture-logs/src/metric_record.rs`), so every duplicate-of one fingerprint agrees on it and `any()` cannot return a stale type.--Surfaces `metric_type` alongside the name so the viewer can hint at the-type-appropriate default aggregation (gauge -> avg, counter/sum -> sum, etc.)-without a second round-trip.-"""+"""Distinct metric names for a team's picker UI."""import datetime as dtfrom collections.abc import Sequence@@ -29,7 +10,7 @@ from django.core.cache import cachefrom posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.database.schema.metrics import HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES-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 Workload@@ -40,8 +21,7 @@ from products.metrics.backend.metric_query_runner import points_queryfrom products.metrics.backend.metrics4_samples import reads_metrics4_onlyfrom products.metrics.backend.search import ilike_pattern-# Autocomplete tolerates partial results, so reads break at the budget instead-# of erroring the way the chart queries do. Mirrors MetricAttributeKeysQueryRunner.+# Autocomplete tolerates partial results, so reads break at the budget instead of erroring._QUERY_SETTINGS = HogQLGlobalSettings(max_bytes_to_read=HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES,read_overflow_mode="break",@@ -51,24 +31,15 @@ _SPARKLINE_QUERY_SETTINGS = HogQLGlobalSettings(read_overflow_mode="throw",)-# Short enough that a new metric shows up while someone is still wiring it up,-# long enough to absorb the burst of mounts a team generates in a working session.METRIC_NAMES_CACHE_TTL = 60-# Past this the picker is not scoped to anything a person can hold in their head,-# and the bound keeps one request from building an unbounded IN list.MAX_PICKER_SERVICES = 50-# Sparklines summarize this window, downsampled to at most this many points. A-# card only needs the recent shape, so the window is far shorter than the name-# lookback and the point count is bounded to keep one row small.SPARKLINE_WINDOW = dt.timedelta(hours=6)SPARKLINE_MAX_POINTS = 24def _isoformat(value: Any) -> str | None:- """ClickHouse hands back datetimes, but a driver or JSON round-trip can leave a- string. The API serializer accepts ISO either way, so normalize without assuming."""if value is None:return Nonereturn value.isoformat() if hasattr(value, "isoformat") else str(value)@@ -99,71 +70,70 @@ class MetricNamesQueryRunner:self.search = search.strip()self.limit = limitself.lookback = lookback- # Sorted and deduped so two callers that picked the same services in a- # different order share one cache entry. An empty string is a real- # selection: a sender that omits the `service.name` resource attribute- # lands in the group the overview labels "unknown".+ # Sorted so the same selection in a different order shares one cache entry.self.services = tuple(sorted(set(services)))- # Sparklines read the `metrics` data points, so the scan is the- # expensive part of a name lookup. Callers that only need the type- # (anomaly defaults) skip it.self.include_sparklines = include_sparklinesself.names = tuple(sorted(set(names)))- def _build_query(self) -> ast.SelectQuery:- # The alias is `last_seen_at`, not `last_seen`: HogQL registers select- # aliases before it resolves WHERE and prefers an alias over a table- # column, so `max(last_seen) AS last_seen` would put an aggregate in the- # WHERE clause.- lookback = ast.Call(name="toIntervalSecond", args=[ast.Constant(value=int(self.lookback.total_seconds()))])+ def _lookback_start(self) -> ast.Expr:+ # Hour-aligned to match `metric_names.time_bucket`, so both queries cover the same window.+ return parse_expr(+ "toStartOfHour(now() - toIntervalSecond({seconds}))",+ placeholders={"seconds": ast.Constant(value=int(self.lookback.total_seconds()))},+ )++ def _services_expr(self) -> ast.Expr:+ return ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["service_name"]),+ right=ast.Tuple(exprs=[ast.Constant(value=service) for service in self.services]),+ )+ def _build_query(self) -> ast.SelectQuery:if not self.search:- # With no search the ILIKE ('%%') and the exact-match sort key are- # both no-ops. They're dropped rather than passed as neutral- # constants: ClickHouse reads a bare integer in ORDER BY positionally.+ # A separate query, because ClickHouse reads a constant sort key as a column position.query = parse_select("""SELECTmetric_name AS name,- any(metric_type) AS metric_type,- any(unit) AS unit,- max(last_seen) AS last_seen_at- FROM posthog.metric_series- WHERE last_seen > now() - {lookback}+ uniqExact(service_name) AS matching_services+ FROM posthog.metric_names+ WHERE time_bucket >= {lookback_start}GROUP BY metric_name- ORDER BY last_seen_at DESC+ ORDER BY+ matching_services DESC,+ metric_name ASCLIMIT {limit}""",- placeholders={"lookback": lookback, "limit": ast.Constant(value=self.limit)},+ placeholders={"lookback_start": self._lookback_start(), "limit": ast.Constant(value=self.limit)},)else:query = parse_select("""SELECTmetric_name AS name,- any(metric_type) AS metric_type,- any(unit) AS unit,- max(last_seen) AS last_seen_at- FROM posthog.metric_series- WHERE last_seen > now() - {lookback}+ uniqExact(service_name) AS matching_services+ FROM posthog.metric_names+ WHERE time_bucket >= {lookback_start}AND metric_name ILIKE {search_pattern}GROUP BY metric_nameORDER BY- lower(metric_name) = lower({exact}) DESC,- last_seen_at DESC+ lower(metric_name) = lower({search}) DESC,+ startsWith(lower(metric_name), lower({search})) DESC,+ endsWith(lower(metric_name), lower({search})) DESC,+ matching_services DESC,+ metric_name ASCLIMIT {limit}""",placeholders={- "lookback": lookback,+ "lookback_start": self._lookback_start(),"search_pattern": ast.Constant(value=ilike_pattern(self.search)),- "exact": ast.Constant(value=self.search),+ "search": ast.Constant(value=self.search),"limit": ast.Constant(value=self.limit),},)assert isinstance(query, ast.SelectQuery)- # Both variants above filter on the lookback, so there is always a WHERE to- # extend; the assert is what tells the type checker so.assert query.where is not Noneif self.names:query.where = ast.And(@@ -177,93 +147,77 @@ class MetricNamesQueryRunner:])- # `metric_names` has one row per name and hour, sorted by hour, so it finds- # the recent names without a read of every series. It has no service column.- if not self.services and reads_metrics4_only(dt.datetime.now(dt.UTC) - self.lookback):- query.where = ast.And(- exprs=[- query.where,- ast.CompareOperation(- op=ast.CompareOperationOp.In,- left=ast.Field(chain=["metric_name"]),- right=self._recent_names_subquery(),- ),- ]- )-- # Appended to the parsed tree rather than written into both SQL variants- # above, so the scoped and unscoped pickers stay one query definition.- # `service_name` is the only filterable column with its own skip index- # (`idx_service_set`), which is what keeps a type-ahead affordable —- # attribute predicates read the label maps and belong in the chart query.if self.services:- query.where = ast.And(- exprs=[- query.where,- ast.CompareOperation(- op=ast.CompareOperationOp.In,- left=ast.Field(chain=["service_name"]),- right=ast.Tuple(exprs=[ast.Constant(value=service) for service in self.services]),- ),- ]- )+ query.where = ast.And(exprs=[query.where, self._services_expr()])return query- def _recent_names_subquery(self) -> ast.SelectQuery:- lookback = ast.Call(name="toIntervalSecond", args=[ast.Constant(value=int(self.lookback.total_seconds()))])- subquery = parse_select(+ def _details_query(self, names: Sequence[str]) -> ast.SelectQuery:+ # Not aliased `last_seen`: HogQL would resolve the WHERE's `last_seen` to the aggregate.+ query = parse_select("""- SELECT metric_name- FROM posthog.metric_names- WHERE time_bucket >= toStartOfHour(now() - {lookback})+ SELECT+ metric_name AS name,+ any(metric_type) AS metric_type,+ any(unit) AS unit,+ max(last_seen) AS last_seen_at+ FROM posthog.metric_series+ WHERE last_seen >= {lookback_start}+ AND metric_name IN {names}GROUP BY metric_name""",- placeholders={"lookback": lookback},+ placeholders={+ "lookback_start": self._lookback_start(),+ "names": ast.Tuple(exprs=[ast.Constant(value=name) for name in names]),+ },)- assert isinstance(subquery, ast.SelectQuery)- return subquery+ assert isinstance(query, ast.SelectQuery)+ assert query.where is not None+ if self.services:+ query.where = ast.And(exprs=[query.where, self._services_expr()])+ return querydef run(self) -> list[dict[str, Any]]:+ settings = _SPARKLINE_QUERY_SETTINGS if self.names else _QUERY_SETTINGSresponse = execute_hogql_query(query_type="MetricNamesQuery",query=self._build_query(),team=self.team,- workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now- settings=_SPARKLINE_QUERY_SETTINGS if self.names else _QUERY_SETTINGS,+ workload=Workload.LOGS,+ settings=settings,)-names = [row[0] for row in response.results]+ if not names:+ return []++ details_response = execute_hogql_query(+ query_type="MetricNamesDetailsQuery",+ query=self._details_query(names),+ team=self.team,+ workload=Workload.LOGS,+ settings=settings,+ )+ details = {row[0]: row[1:] for row in details_response.results}sparklines = self._sparklines(names) if self.include_sparklines else {}- return [- {- "name": row[0],- "metric_type": row[1],- "unit": row[2],- "last_seen": _isoformat(row[3]),- "sparkline": sparklines.get(row[0], []),- }- for row in response.results- ]+ rows = []+ for name in names:+ metric_type, unit, last_seen = details.get(name, ("", "", None))+ rows.append(+ {+ "name": name,+ "metric_type": metric_type,+ "unit": unit,+ "last_seen": _isoformat(last_seen),+ "sparkline": sparklines.get(name, []),+ }+ )+ return rowsdef _sparklines(self, names: Sequence[str]) -> dict[str, list[float]]:- """A small recent shape per metric, for the catalog cards.-- Reads the raw `metrics` data points. Each metric is bucketed onto a- fixed grid and averaged per bucket across its series; a card only shows- direction and spikes, so per-series fidelity is not worth the rows it- would cost. Only the names this page returned are read, so a scoped- picker never scans the whole table.- """if not names:return {}- # The grid anchors to the window start: bucket edges land on the window- # endpoints, so the window always holds exactly MAX_POINTS buckets (a- # bare toStartOfInterval aligns to wall-clock boundaries and a window- # starting mid-bucket intersects one extra). The anchor is computed here- # rather than from the query's `now()` so the predicate below and the- # grid agree on the same instant.+ # Buckets anchor to the window start, so the window holds exactly SPARKLINE_MAX_POINTS of them.bucket_seconds = max(int(SPARKLINE_WINDOW.total_seconds()) // SPARKLINE_MAX_POINTS, 1)window_start = dt.datetime.now(dt.UTC) - SPARKLINE_WINDOWquery = parse_select(@@ -279,8 +233,6 @@ class MetricNamesQueryRunner:placeholders={"bucket_seconds": ast.Constant(value=bucket_seconds),"window_start": ast.Constant(value=window_start),- # The point read also bounds `time_bucket` (the UTC hour), which- # lets ClickHouse skip everything older than the window."points": points_query(from_samples=reads_metrics4_only(window_start),columns=("metric_name", "timestamp", "value"),@@ -288,10 +240,7 @@ class MetricNamesQueryRunner:date_from=window_start,date_to=window_start + SPARKLINE_WINDOW,timezone=self.team.timezone,- # A sample carries no service column; its series_fingerprint is- # the link back to the series row that does. Without this scope,- # two services emitting one metric name share a card and a scoped- # catalog draws a shape blended across services.+ # Samples have no service column, so the service scope goes through the series.row_filters=(ast.CompareOperation(op=ast.CompareOperationOp.In,@@ -318,11 +267,6 @@ class MetricNamesQueryRunner:return sparklinesdef _series_scope_subquery(self, names: Sequence[str]) -> ast.SelectQuery:- """The series fingerprints, for these names, owned by the scoped services.-- Built as its own parsed query so the service predicate is attached with an- explicit And the way `_build_query` does, not spliced into the SQL text.- """lookback = ast.Call(name="toIntervalSecond", args=[ast.Constant(value=int(self.lookback.total_seconds()))])subquery = parse_select("""@@ -340,44 +284,21 @@ class MetricNamesQueryRunner:assert isinstance(subquery, ast.SelectQuery)assert subquery.where is not Noneif self.services:- subquery.where = ast.And(- exprs=[- subquery.where,- ast.CompareOperation(- op=ast.CompareOperationOp.In,- left=ast.Field(chain=["service_name"]),- right=ast.Tuple(exprs=[ast.Constant(value=service) for service in self.services]),- ),- ]- )+ subquery.where = ast.And(exprs=[subquery.where, self._services_expr()])return subquerydef cached_metric_names(team: Team, *, search: str = "", limit: int = 100, services: Sequence[str] = ()) -> list[dict[str, Any]]:- """Metric names for the picker, with the unsearched list cached per team.-- Only the empty-search prime is cached: every viewer mount issues it and the- answer is the same for everyone on the team. Searches are per-keystroke and- per-user, so caching them would fill the cache with single-hit entries.-- The service scope is part of the key, not a filter over one cached list: the- unscoped list is capped at `limit` names, so narrowing it in Python would hide- metrics that a scoped query returns.-- Only non-empty results are cached, matching `team_has_metrics`: a team that- just wired up OTel must not be pinned to an empty picker while the setup- prompt's poll has already let them through.- """+ """Metric names for the picker. Only non-empty, unsearched lists are cached."""runner = MetricNamesQueryRunner(team=team, search=search, limit=limit, services=services)if runner.search:return runner.run()- # `repr` of the sorted tuple, hashed: service names come from user data, so- # they can carry spaces and unicode that a memcached key cannot.+ # Hashed: service names can hold characters that a memcached key cannot.scope = sha256(repr(runner.services).encode()).hexdigest()[:16] if runner.services else "all"- cache_key = f"metrics:{team.id}:metric_names:v2:{limit}:{scope}"+ cache_key = f"metrics:{team.id}:metric_names:v3:{limit}:{scope}"cached = cache.get(cache_key)if cached is not None:return cacheddiff --git a/products/metrics/backend/tests/test_metric_names_query_runner.py b/products/metrics/backend/tests/test_metric_names_query_runner.pyindex 418d73e936a3..2e3164eeb735 100644--- a/products/metrics/backend/tests/test_metric_names_query_runner.py+++ b/products/metrics/backend/tests/test_metric_names_query_runner.py@@ -1,7 +1,7 @@import datetime as dtfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.core.cache import cachefrom django.utils import timezone@@ -183,6 +183,45 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):results = runner.run()self.assertEqual(results[0]["name"], "bar")+ @parameterized.expand(+ [+ (+ "search ranks exact, prefix, suffix, then service count, then name",+ "HTTP",+ [],+ ["http", "http.requests", "server.http", "b.http.x", "a.http.x", "c.http.x"],+ ),+ (+ "no search ranks by service count, then name",+ "",+ [],+ ["b.http.x", "a.http.x", "c.http.x", "http", "http.requests", "other", "server.http"],+ ),+ (+ "service scope counts the selected services only",+ "",+ ["web"],+ ["a.http.x", "b.http.x", "c.http.x", "http", "server.http"],+ ),+ ]+ )+ def test_sort_order(self, _name: str, search: str, services: list[str], expected: list[str]):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ for metric_name, metric_services in (+ ("c.http.x", ["web"]),+ ("a.http.x", ["web"]),+ ("b.http.x", ["web", "worker"]),+ ("server.http", ["web"]),+ ("http.requests", ["worker"]),+ ("http", ["web"]),+ ("other", ["worker"]),+ ):+ for service in metric_services:+ seed_metric(team_id=self.team.id, metric_name=metric_name, points=[(anchor, 1.0)], service_name=service)++ runner = MetricNamesQueryRunner(team=self.team, search=search, services=services, include_sparklines=False)+ self.assertEqual([row["name"] for row in runner.run()], expected)+def test_respects_team_isolation(self):anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)_seed_point(team_id=99999, metric_name="other.team.metric", value=1.0, timestamp=anchor)@@ -486,9 +525,11 @@ class TestMetricCatalogQueryRunner(ClickhouseTestMixin, APIBaseTest):_seed_point(team_id=self.team.id, metric_name="m1", value=1.0, timestamp=anchor)with patch("products.metrics.backend.metric_names_query_runner.execute_hogql_query") as execute:- execute.return_value.results = [("m1", "gauge", "", timezone.now())]+ execute.side_effect = [+ MagicMock(results=[("m1", 1)]),+ MagicMock(results=[("m1", "gauge", "", timezone.now())]),+ ]rows = MetricNamesQueryRunner(team=self.team, include_sparklines=False).run()- # One query for the names, none for the samples.- self.assertEqual(execute.call_count, 1)+ self.assertEqual(execute.call_count, 2)self.assertEqual(rows[0]["sparkline"], [])