: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(dashboards): load metrics tables with many label values and show query errors (#122946)
Daniel Visca0c7d7ab52e25
diff --git a/products/dashboards/backend/api/test/test_metrics_table_widget.py b/products/dashboards/backend/api/test/test_metrics_table_widget.pyindex 4ee8d0719088..27701c76dc92 100644--- a/products/dashboards/backend/api/test/test_metrics_table_widget.py+++ b/products/dashboards/backend/api/test/test_metrics_table_widget.py@@ -1,6 +1,7 @@import datetime as dtfrom typing import Any+import pytestfrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import patch@@ -18,6 +19,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom products.dashboards.backend.constants import METRICS_TABLE_SPARKLINE_POINTSfrom products.dashboards.backend.widget_registry import METRICS_TABLE_WIDGET_TYPE, validate_widget_config+from products.metrics.backend.facade.contracts import MetricQueryTooManyRowsErrorfrom products.metrics.backend.facade.testing import seed_metric, truncate_metrics_tablesQUEUE_COLUMN = {"label": "Queue depth", "metricName": "queue_depth", "aggregation": "avg"}@@ -251,3 +253,57 @@ class TestMetricsTableWidgetRun(ClickhouseTestMixin, APIBaseTest):result = self._run({"groupBy": "route", "columns": columns, "dateRange": {"date_from": "-1h"}})assert [row["values"] for row in result["rows"]] == [[10.0, 4.0]]++ @patch("products.metrics.backend.metric_query_runner._ROW_LIMIT", 60)+ def test_too_many_label_values_retry_with_fewer_buckets(self) -> None:+ for route in ("/r1", "/r2", "/r3", "/r4", "/r5"):+ seed_metric(+ team_id=self.team.id,+ metric_name="busy_workers",+ points=[(self.now - dt.timedelta(minutes=minute), 2.0) for minute in range(1, 60)],+ labels={"route": route},+ )+ column = {"label": "Busy", "metricName": "busy_workers", "aggregation": "avg"}++ result = self._run({"groupBy": "route", "columns": [column], "dateRange": {"date_from": "-1h"}})++ assert result.get("queryError") is None+ assert result["totalCount"] == 5+ assert [row["values"][0] for row in result["rows"]] == [2.0] * 5++ @parameterized.expand(+ [+ ("histogram", ValueError("histogram bounds differ across the selected series/time range")),+ ("row budget", MetricQueryTooManyRowsError("query produced too many (time bucket, series) rows")),+ ]+ )+ def test_metrics_query_errors_reach_the_tile_as_a_readable_message(self, _name: str, error: Exception) -> None:+ with patch("products.dashboards.backend.widgets.metrics_table.run_metric_query", side_effect=error):+ result = self._run({"groupBy": "route", "columns": [QUEUE_COLUMN]})++ assert result["queryError"] == str(error)+ assert result["rows"] == []++ def test_increase_column_shows_the_same_total_after_the_retry(self) -> None:+ for route in ("/c1", "/c2", "/c3", "/c4", "/c5"):+ seed_metric(+ team_id=self.team.id,+ metric_name="jobs_done_total",+ points=[(self.now - dt.timedelta(minutes=59 - minute), 60.0 * minute) for minute in range(60)],+ labels={"route": route},+ metric_type="sum",+ is_monotonic=True,+ )+ config = {+ "groupBy": "route",+ "columns": [{"label": "Jobs", "metricName": "jobs_done_total", "aggregation": "increase"}],+ "dateRange": {"date_from": "-1h"},+ }++ full_buckets = self._run(config)+ with patch("products.metrics.backend.metric_query_runner._ROW_LIMIT", 60):+ retried = self._run(config)++ assert [row["values"][0] for row in retried["rows"]] == pytest.approx(+ [row["values"][0] for row in full_buckets["rows"]], rel=0.25+ )diff --git a/products/dashboards/backend/constants.py b/products/dashboards/backend/constants.pyindex 4ac8176385ad..3b7727b4a794 100644--- a/products/dashboards/backend/constants.py+++ b/products/dashboards/backend/constants.py@@ -30,6 +30,9 @@ METRICS_TABLE_DEFAULT_LIMIT = 25# Points per sparkline, and also the bucket count of the query. A query returns one row per bucket and label# value, and the metrics query fails above its row budget, so fewer buckets leave room for more label values.METRICS_TABLE_SPARKLINE_POINTS = 30+# A label with many values can go past the metrics row budget at METRICS_TABLE_SPARKLINE_POINTS buckets.+# The widget then retries once with this many buckets: shorter sparklines, the same row values.+METRICS_TABLE_RETRY_BUCKETS = 6# Metrics queries span at most 31 days, so the longer widget presets are not allowed.METRICS_TABLE_UNSUPPORTED_DATE_FROM_VALUES = frozenset({"-90d"})diff --git a/products/dashboards/backend/widgets/metrics_table.py b/products/dashboards/backend/widgets/metrics_table.pyindex 8907a010d09b..d1fb2f3d95e9 100644--- a/products/dashboards/backend/widgets/metrics_table.py+++ b/products/dashboards/backend/widgets/metrics_table.py@@ -12,7 +12,7 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.utils import relative_date_parse-from products.dashboards.backend.constants import METRICS_TABLE_SPARKLINE_POINTS+from products.dashboards.backend.constants import METRICS_TABLE_RETRY_BUCKETS, METRICS_TABLE_SPARKLINE_POINTSfrom products.dashboards.backend.feature_flags import widget_flag_enabledfrom products.dashboards.backend.widget_specs.configs import METRICS_TABLE_WIDGET_TYPEfrom products.dashboards.backend.widget_specs.registry import validate_widget_config@@ -27,6 +27,7 @@ from products.metrics.backend.facade.contracts import (MetricGroupBy,MetricQueryClause,MetricQueryRequest,+ MetricQueryTooManyRowsError,MetricSeries,)from products.metrics.backend.facade.enums import FilterOp, MetricAggregation, MetricRangeFunction@@ -54,6 +55,11 @@ def _clause(index: int, column: dict[str, Any], group_by: str) -> MetricQueryCla)+def _sum(values: list[float]) -> float | None:+ finite = [value for value in values if math.isfinite(value)]+ return sum(finite) if finite else None++def _mean(values: list[float]) -> float | None:finite = [value for value in values if math.isfinite(value)]return sum(finite) / len(finite) if finite else None@@ -100,22 +106,43 @@ def run_metrics_table_widget(date_from_value = (typed_config.get("dateRange") or {}).get("date_from") or DEFAULT_METRICS_TABLE_DATE_FROMdate_from = relative_date_parse(date_from_value, team.timezone_info)date_to = timezone.now()- request = MetricQueryRequest(- clauses=tuple(_clause(index, column, group_by) for index, column in enumerate(columns)),- date_from=date_from,- date_to=date_to,- interval=pick_metric_query_interval(- date_from=date_from, date_to=date_to, max_buckets=METRICS_TABLE_SPARKLINE_POINTS- ),- # Columns share one bucket grid, so a zero fill would pull a column's average down with the- # buckets that only another column has data in.- zero_fill=False,- )- with (- tags_context(product=Product.METRICS, feature=Feature.QUERY, team_id=team.pk),- metric_query_concurrency_slots(team),- ):- series = run_metric_query(team=team, request=request)+ clauses = tuple(_clause(index, column, group_by) for index, column in enumerate(columns))++ def run(max_buckets: int) -> list[MetricSeries]:+ request = MetricQueryRequest(+ clauses=clauses,+ date_from=date_from,+ date_to=date_to,+ interval=pick_metric_query_interval(date_from=date_from, date_to=date_to, max_buckets=max_buckets),+ # Columns share one bucket grid, so a zero fill would pull a column's average down with the+ # buckets that only another column has data in.+ zero_fill=False,+ )+ with (+ tags_context(product=Product.METRICS, feature=Feature.QUERY, team_id=team.pk),+ metric_query_concurrency_slots(team),+ ):+ return run_metric_query(team=team, request=request)++ try:+ try:+ series = run(METRICS_TABLE_SPARKLINE_POINTS)+ except MetricQueryTooManyRowsError:+ series = run(METRICS_TABLE_RETRY_BUCKETS)+ except ValueError as error:+ # The metrics query reports a problem the user can fix (too many label values, mixed histogram+ # layouts) with a ValueError. Show it on the tile instead of the generic widget error.+ return {+ "needsConfiguration": False,+ "groupBy": group_by,+ "columns": [+ {"label": column["label"], "aggregation": column["aggregation"], "unit": None} for column in columns+ ],+ "rows": [],+ "totalCount": 0,+ "hasMore": False,+ "queryError": str(error),+ }rows_by_key: dict[str, dict[str, Any]] = {}units: list[str | None] = [None] * len(columns)@@ -128,7 +155,10 @@ def run_metrics_table_widget(row = rows_by_key.setdefault(key, {"key": key, "values": [None] * len(columns), "sparklines": [[] for _ in columns]})- row["values"][index] = _mean([point.value for point in item.points if point.value is not None])+ values = [point.value for point in item.points if point.value is not None]+ # An increase bucket holds the change in that bucket, so the total over the range does not depend on+ # the bucket size. Every other calculation is a level per bucket, so its mean does not either.+ row["values"][index] = _sum(values) if columns[index]["aggregation"] == "increase" else _mean(values)row["sparklines"][index] = _sparkline(item)ordered = _order_rows(diff --git a/products/dashboards/frontend/widgets/metrics/EditMetricsTableWidgetModal.tsx b/products/dashboards/frontend/widgets/metrics/EditMetricsTableWidgetModal.tsxindex 942189cb6a96..c68d461a0213 100644--- a/products/dashboards/frontend/widgets/metrics/EditMetricsTableWidgetModal.tsx+++ b/products/dashboards/frontend/widgets/metrics/EditMetricsTableWidgetModal.tsx@@ -31,7 +31,7 @@ type MetricsTableFilterOp = NonNullable<MetricsTableFilter['op']>const AGGREGATION_OPTIONS: LemonSelectOptions<MetricsTableAggregation> = [{ value: 'rate', label: 'Rate per second (counter)' },- { value: 'increase', label: 'Increase (counter)' },+ { value: 'increase', label: 'Total increase (counter)' },{ value: 'histogram_quantile', label: 'Percentile (histogram)' },{ value: 'avg', label: 'Average' },{ value: 'sum', label: 'Sum' },diff --git a/products/dashboards/frontend/widgets/metrics/MetricsTableWidget.tsx b/products/dashboards/frontend/widgets/metrics/MetricsTableWidget.tsxindex 9f0970151950..24261a1b74ff 100644--- a/products/dashboards/frontend/widgets/metrics/MetricsTableWidget.tsx+++ b/products/dashboards/frontend/widgets/metrics/MetricsTableWidget.tsx@@ -39,6 +39,8 @@ export type MetricsTableWidgetResult = {rows?: MetricsTableResultRow[]totalCount?: numberhasMore?: boolean+ /** Set when the metrics query refused the config, with the reason to show. */+ queryError?: string | null}const WIDGET_LIST_COUNT_ROWS = { singular: 'row', plural: 'rows' }@@ -205,6 +207,22 @@ export function MetricsTableWidget({ result, loading, config, tileId }: Dashboar)}+ if (payload.queryError) {+ return (+ <WidgetCardContent>+ <WidgetCardBodyMessage>+ <div className="flex max-w-sm flex-col items-center gap-1 px-2 text-balance">+ <p className="m-0 text-base font-semibold text-primary">This table can't load</p>+ <p className="m-0 text-sm text-muted">{payload.queryError}</p>+ <p className="m-0 text-sm text-muted">+ Try a shorter date range, a label with fewer values, or a filter in the widget settings.+ </p>+ </div>+ </WidgetCardBodyMessage>+ </WidgetCardContent>+ )+ }+const rows = payload.rows ?? []if (rows.length === 0) {return (diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.pyindex 15bd6960373c..b3f4a2cdf55c 100644--- a/products/metrics/backend/facade/contracts.py+++ b/products/metrics/backend/facade/contracts.py@@ -44,6 +44,14 @@ from .enums import (MAX_CLAUSES_PER_QUERY = 10MAX_SPARKLINE_BATCH_SIZE = 20++class MetricQueryTooManyRowsError(ValueError):+ """The query has more (time bucket, series) rows than the row budget allows.++ A caller can retry with a coarser interval, because fewer buckets give fewer rows.+ """++# Private-alpha gate. Every read surface (viewset, query runner, MCP tools)# must check the same flag, or one of them becomes a bypass.METRICS_FEATURE_FLAG = "metrics"diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.pyindex 1f4e11533dc0..801afc94a33a 100644--- a/products/metrics/backend/metric_query_runner.py+++ b/products/metrics/backend/metric_query_runner.py@@ -21,7 +21,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.client.connection import Workloadfrom posthog.models import Team-from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy+from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryTooManyRowsErrorfrom products.metrics.backend.facade.enums import FilterOp, MetricTypefrom products.metrics.backend.metrics4_samples import metric_name_expr, samples_points_query@@ -614,7 +614,7 @@ class MetricQueryRunner:def _raise_on_truncation(self, results: list[Any]) -> None:"""Raise an error when the row limit drops recent buckets."""if len(results) >= self._row_limit:- raise ValueError(+ raise MetricQueryTooManyRowsError("query produced too many (time bucket, series) rows; ""use a coarser interval, a narrower range, an aggregation, or a lower-cardinality group_by")