: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
fix(metrics): fast attribute keys when no metric is selected (#110165)
Frank Hamanda72de199dd2d
diff --git a/products/metrics/backend/metric_attributes_query_runner.py b/products/metrics/backend/metric_attributes_query_runner.pyindex 468bfcc13fb6..190d97782a69 100644--- a/products/metrics/backend/metric_attributes_query_runner.py+++ b/products/metrics/backend/metric_attributes_query_runner.py@@ -1,7 +1,8 @@"""Attribute key/value autocomplete for the metrics filter bar.-Keys count distinct attribute values from recent metadata, without reading raw samples.-Values use the `metric_attributes` aggregate table.+Keys for one metric count distinct attribute values from recent series metadata.+Keys across all metrics and values use the `metric_attributes` aggregate table:+scanning series metadata without a metric name reads every attribute map.Both queries merge metric attributes and resource attributes."""@@ -71,12 +72,57 @@ class MetricAttributeKeysQueryRunner:self.team = teamself.metric_name = metric_name.strip()self.search = search.strip()- self.date_from, self.date_to = _resolve_window(date_from, date_to)- self.date_from += _TIME_BUCKET_INTERVAL+ self.bucket_date_from, self.date_to = _resolve_window(date_from, date_to)+ self.date_from = self.bucket_date_from + _TIME_BUCKET_INTERVALself.limit = _validate_limit(limit)def run(self) -> list[dict[str, Any]]:- query = parse_select(+ query = self._series_query() if self.metric_name else self._aggregate_query()++ response = execute_hogql_query(+ query_type="MetricAttributeKeysQuery",+ query=query,+ team=self.team,+ workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now+ settings=_QUERY_SETTINGS,+ )++ results = [{"name": row[0], "value_count": int(row[1])} for row in response.results]+ search_lower = self.search.lower()+ if not results and (search_lower in "service_name" or search_lower in "service.name"):+ results.append({"name": "service_name", "value_count": 0})+ return results++ def _aggregate_query(self) -> ast.SelectQuery | ast.SelectSetQuery:+ # Like the series query, the window end is not enforced: keys come from recent data.+ return parse_select(+ """+ SELECT attribute_key, value_count+ FROM (+ SELECT attribute_key, uniq(attribute_value) AS value_count+ FROM posthog.metric_attributes+ WHERE time_bucket >= {date_from}+ AND attribute_key ILIKE {search_pattern}+ GROUP BY attribute_key+ UNION ALL+ SELECT 'service_name' AS attribute_key, uniq(service_name) AS value_count+ FROM posthog.metric_attributes+ WHERE time_bucket >= {date_from}+ AND ('service_name' ILIKE {search_pattern} OR 'service.name' ILIKE {search_pattern})+ HAVING value_count > 0+ )+ ORDER BY value_count DESC, attribute_key ASC+ LIMIT {limit}+ """,+ placeholders={+ "date_from": ast.Constant(value=self.bucket_date_from),+ "search_pattern": ast.Constant(value=ilike_pattern(self.search)),+ "limit": ast.Constant(value=self.limit),+ },+ )++ def _series_query(self) -> ast.SelectQuery | ast.SelectSetQuery:+ return parse_select("""SELECTarrayJoin(arrayDistinct(arrayConcat(@@ -97,34 +143,15 @@ class MetricAttributeKeysQueryRunner:""",placeholders={"date_from": ast.Constant(value=self.date_from),- "metric_name_filter": (- ast.Constant(value=True)- if not self.metric_name- else ast.CompareOperation(- op=ast.CompareOperationOp.Eq,- left=ast.Field(chain=["metric_name"]),- right=ast.Constant(value=self.metric_name),- )+ "metric_name_filter": ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["metric_name"]),+ right=ast.Constant(value=self.metric_name),),"search_pattern": ast.Constant(value=ilike_pattern(self.search)),"limit": ast.Constant(value=self.limit),},)- assert isinstance(query, ast.SelectQuery)-- response = execute_hogql_query(- query_type="MetricAttributeKeysQuery",- query=query,- team=self.team,- workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now- settings=_QUERY_SETTINGS,- )-- results = [{"name": row[0], "value_count": int(row[1])} for row in response.results]- search_lower = self.search.lower()- if not results and (search_lower in "service_name" or search_lower in "service.name"):- results.append({"name": "service_name", "value_count": 0})- return resultsclass MetricAttributeValuesQueryRunner:diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex f2abb77dacdd..aacdba9ab09c 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -581,9 +581,7 @@ class _MetricAttributeKeySerializer(serializers.Serializer):name = serializers.CharField(help_text="Attribute key as it appears on the team's metrics (e.g. 'env', 'k8s.pod.name').")- value_count = serializers.IntegerField(- help_text="Number of distinct values for this attribute in recent series metadata."- )+ value_count = serializers.IntegerField(help_text="Number of distinct values for this attribute in recent data.")class _MetricAttributeKeysResponseSerializer(serializers.Serializer):diff --git a/products/metrics/frontend/components/MetricsClauseRow.tsx b/products/metrics/frontend/components/MetricsClauseRow.tsxindex bc108382ddce..54189c621f76 100644--- a/products/metrics/frontend/components/MetricsClauseRow.tsx+++ b/products/metrics/frontend/components/MetricsClauseRow.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import { useMemo } from 'react'import { IconEllipsis, IconInfo } from '@posthog/icons'import { LemonButton, LemonMenu, LemonSelect, LemonTag, Tooltip } from '@posthog/lemon-ui'@@ -60,6 +61,13 @@ export function MetricsClauseRow({removeClause,} = useActions(metricsViewerLogic)+ // Scoping attribute suggestions to the clause's metric lets the backend prune by metric name.+ const metricName = clause.metricName.trim()+ const clauseEndpointFilters = useMemo(+ () => (metricName ? { ...attributeEndpointFilters, metricName } : attributeEndpointFilters),+ [attributeEndpointFilters, metricName]+ )+const select = (): void => {if (!isActive) {setActiveClauseIndex(index)@@ -153,7 +161,7 @@ export function MetricsClauseRow({rootKey={`metrics-viewer-filters-${clause.name}`}group={clause.filterGroup.values[0] as UniversalFiltersGroup}taxonomicGroupTypes={[TaxonomicFilterGroupType.MetricAttributes]}- endpointFilters={attributeEndpointFilters}+ endpointFilters={clauseEndpointFilters}onChange={(group) => {if (!disabledReason) {withSelect(setFilterGroup)({ type: FilterLogicalOperator.And, values: [group] })diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex d5a8d2ad8d51..c272af48f380 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -40,7 +40,7 @@ export interface _MetricAttributeValuesResponseApi {export interface _MetricAttributeKeyApi {/** Attribute key as it appears on the team's metrics (e.g. 'env', 'k8s.pod.name'). */name: string- /** Number of distinct values for this attribute in recent series metadata. */+ /** Number of distinct values for this attribute in recent data. */value_count: number}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9e9023c3c7ac..5a2509349b8c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -108410,7 +108410,7 @@ export namespace Schemas {export interface _MetricAttributeKey {/** Attribute key as it appears on the team's metrics (e.g. 'env', 'k8s.pod.name'). */name: string;- /** Number of distinct values for this attribute in recent series metadata. */+ /** Number of distinct values for this attribute in recent data. */value_count: number;}