: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): return explicit null gaps for non-finite aggregates (#69422)
Daniel Visca318c68b2ed93
diff --git a/products/metrics/backend/anomaly.py b/products/metrics/backend/anomaly.pyindex 120f15c25f84..150383f539f1 100644--- a/products/metrics/backend/anomaly.py+++ b/products/metrics/backend/anomaly.py@@ -106,6 +106,8 @@ def _find_onset(for point in points:if _parse_point_time(point.time) < anomaly_from:continue+ if point.value is None:+ continue # non-representable aggregate — can't evidence an onsetdeviation = point.value - baseline_meanif direction == "down":deviation = -deviation@@ -169,8 +171,10 @@ def characterize_anomaly(rows = _run()points = [MetricPoint(time=row["time"], value=row["value"]) for row in rows]point_times = [_parse_point_time(p.time) for p in points]- baseline_values = [p.value for p, t in zip(points, point_times) if baseline_from <= t < baseline_to]- anomaly_values = [p.value for p, t in zip(points, point_times) if t >= anomaly_from]+ baseline_values = [+ p.value for p, t in zip(points, point_times) if baseline_from <= t < baseline_to and p.value is not None+ ]+ anomaly_values = [p.value for p, t in zip(points, point_times) if t >= anomaly_from and p.value is not None]baseline_mean = _mean(baseline_values)baseline_stddev = statistics.pstdev(baseline_values) if len(baseline_values) > 1 else 0.0@@ -297,6 +301,8 @@ def _find_top_movers(else:continue # gap between an explicit baseline and the anomalylabel = row["labels"].get(key, "")+ if row["value"] is None:+ continue # non-representable aggregate (overflow) — not evidence for either windowper_label.setdefault(label, {"baseline": [], "anomaly": []})[bucket].append(row["value"])for label, windows in per_label.items():baseline_value = _mean(windows["baseline"])diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex 808d2dd39ca6..3bc431f7ebec 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -5,6 +5,7 @@ allowed to import. Internal modules (query runners) stay behind this seamso import-linter's strict-mode contract holds."""+import mathimport datetime as dtfrom typing import Any@@ -57,7 +58,7 @@ def _assemble_series("""Split bucketed rows into one series per label-set, zero-filled ontothe shared grid so every series (and later, every clause of a formula)has identical timestamps."""- by_labels: dict[tuple[tuple[str, str], ...], dict[str, float]] = {}+ by_labels: dict[tuple[tuple[str, str], ...], dict[str, float | None]] = {}for row in rows:key = tuple(sorted(row["labels"].items()))by_labels.setdefault(key, {})[row["time"]] = row["value"]@@ -66,7 +67,9 @@ def _assemble_series(# high-cardinality group-by never materializes label_sets x grid points# only to throw most of them away. Zero-filled points contribute nothing# to the magnitude, so the ranking is identical either way.- ranked = sorted(by_labels.items(), key=lambda item: (-sum(abs(v) for v in item[1].values()), item[0]))+ ranked = sorted(+ by_labels.items(), key=lambda item: (-sum(abs(v) for v in item[1].values() if v is not None), item[0])+ )return [MetricSeries(labels=dict(key),@@ -88,6 +91,22 @@ def _resolve_runner_aggregation(clause: MetricQueryClause) -> str:raise ValueError(f"aggregation {clause.aggregation.value!r} is not supported yet")+def _evaluate_formula_point(+ node: Any, per_clause_points: dict[str, tuple[MetricPoint, ...]], index: int+) -> float | None:+ """One formula grid point. A null (gap) in any input propagates as a+ gap, and a result the formula overflowed to inf/NaN becomes a gap too —+ same policy as the per-clause aggregates."""+ values: dict[str, float] = {}+ for name, pts in per_clause_points.items():+ value = pts[index].value+ if value is None:+ return None+ values[name] = value+ result = evaluate(node, values)+ return result if math.isfinite(result) else None++def _evaluate_formula(formula_text: str, series_by_clause: dict[str, list[MetricSeries]], grid: list[str]) -> list[MetricSeries]:@@ -122,10 +141,7 @@ def _evaluate_formula(for name in series_by_clause}points = tuple(- MetricPoint(- time=time,- value=evaluate(node, {name: pts[index].value for name, pts in per_clause_points.items()}),- )+ MetricPoint(time=time, value=_evaluate_formula_point(node, per_clause_points, index))for index, time in enumerate(grid))result.append(MetricSeries(labels=dict(label_set), points=points, metric_name=None, clause="formula"))diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.pyindex 479abf947e95..435c66e2435a 100644--- a/products/metrics/backend/facade/contracts.py+++ b/products/metrics/backend/facade/contracts.py@@ -102,10 +102,12 @@ class MetricQueryRequest:@dataclass(frozen=True, slots=True)class MetricPoint:- """One bucketed datapoint. `time` is the bucket start, ISO 8601."""+ """One bucketed datapoint. `time` is the bucket start, ISO 8601.+ `value` is None when the bucket's aggregate isn't representable (e.g.+ a float overflow to inf) — consumers render a gap."""time: str- value: float+ value: float | None@dataclass(frozen=True, slots=True)diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.pyindex ba8b7eb9364a..716e66f3f73f 100644--- a/products/metrics/backend/metric_query_runner.py+++ b/products/metrics/backend/metric_query_runner.py@@ -9,6 +9,7 @@ pipeline yet."""import re+import mathimport datetime as dtfrom collections.abc import Sequencefrom typing import Any, Literal@@ -121,6 +122,16 @@ def _aggregation_expr(name: str) -> ast.Expr:raise ValueError(f"Unsupported aggregation: {name!r}")+def _finite_or_none(value: float | None) -> float | None:+ """ClickHouse float aggregates can overflow to inf/-inf (or produce NaN);+ a non-finite value has no JSON representation and downstream renderers+ turn it into null anyway. Make the null explicit and deterministic here —+ consumers render it as a gap."""+ if value is None or not math.isfinite(value):+ return None+ return value++_ALLOWED_AGGREGATIONS: frozenset[str] = frozenset({"sum", "avg", "count", "p95", "rate", "increase", "histogram_quantile"})@@ -289,7 +300,7 @@ class MetricQueryRunner:rows.append({"time": row[0].isoformat() if isinstance(row[0], dt.datetime) else row[0],- "value": row[1 + group_count],+ "value": _finite_or_none(row[1 + group_count]),"labels": {group.key: row[1 + index] for index, group in enumerate(self.group_by)},})@@ -330,7 +341,7 @@ class MetricQueryRunner:rows.append({"time": row[0].isoformat() if isinstance(row[0], dt.datetime) else row[0],- "value": _histogram_quantile(self.quantile, bounds, counts),+ "value": _finite_or_none(_histogram_quantile(self.quantile, bounds, counts)),"labels": {group.key: row[1 + index] for index, group in enumerate(self.group_by)},})diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex bb8f13446fc3..37e8ac11cf3e 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -211,7 +211,10 @@ def _build_clause(data: dict, *, name: str) -> MetricQueryClause:class _MetricQueryPointSerializer(serializers.Serializer):time = serializers.CharField(help_text="Bucket start as ISO 8601 timestamp.")- value = serializers.FloatField(help_text="Aggregated value for the bucket.")+ value = serializers.FloatField(+ allow_null=True,+ help_text="Aggregated value for the bucket. Null when the aggregate isn't representable (e.g. float overflow) — render as a gap.",+ )class _MetricSeriesSerializer(serializers.Serializer):diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.pyindex 387eb95f36e0..bbe070b9eb13 100644--- a/products/metrics/backend/tests/test_metric_query_runner.py+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -1164,3 +1164,101 @@ class TestMultiClauseAndFormulas(ClickhouseTestMixin, APIBaseTest):content_type="application/json",)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+++class TestNonFiniteAggregates(ClickhouseTestMixin, APIBaseTest):+ """ClickHouse float aggregates can overflow to inf (two 1e308 samples in+ one bucket). A Python `inf` leaking into the response is at best invalid+ JSON ("Infinity") and at worst a silent null downstream — the API contract+ is an explicit null gap instead."""++ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")+ self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)++ def _seed_huge(self, count: int) -> None:+ seed_metric(+ team_id=self.team.id,+ metric_name="m_huge",+ points=[(self.anchor + dt.timedelta(seconds=i), 1e308) for i in range(count)],+ )++ def _run(self, aggregation: str) -> list[dict[str, Any]]:+ return MetricQueryRunner(+ team=self.team,+ metric_name="m_huge",+ aggregation=aggregation,+ date_from=self.anchor - dt.timedelta(minutes=5),+ date_to=self.anchor + dt.timedelta(minutes=5),+ ).run()++ @parameterized.expand([("sum",), ("avg",)])+ def test_overflowing_bucket_returns_null_gap(self, aggregation: str):+ self._seed_huge(2)+ rows = self._run(aggregation)+ assert [row["value"] for row in rows] == [None]++ def test_large_finite_value_survives(self):+ self._seed_huge(1)+ rows = self._run("avg")+ assert [row["value"] for row in rows] == [1e308]++ def test_overflow_serializes_as_json_null_via_api(self):+ self._seed_huge(2)+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={+ "query": {+ "metricName": "m_huge",+ "aggregation": "sum",+ "dateFrom": (self.anchor - dt.timedelta(minutes=5)).isoformat(),+ "dateTo": (self.anchor + dt.timedelta(minutes=5)).isoformat(),+ }+ },+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ values = [p["value"] for p in response.json()["results"][0]["points"]]+ assert values == [None]++ def test_formula_overflow_returns_null_gap(self):+ self._seed_huge(1)+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={+ "query": {+ "clauses": [{"name": "a", "metricName": "m_huge", "aggregation": "avg"}],+ "formula": "a * a",+ "dateFrom": (self.anchor - dt.timedelta(minutes=5)).isoformat(),+ "dateTo": (self.anchor + dt.timedelta(minutes=5)).isoformat(),+ }+ },+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ values = [p["value"] for p in response.json()["results"][0]["points"]]+ assert values == [None]++ def test_formula_propagates_clause_null_gap(self):+ # Two 1e308 points sum to inf, so the CLAUSE aggregate is already a+ # null gap before the formula runs — exercising the input-None guard+ # in _evaluate_formula_point, not the formula-overflow branch above.+ self._seed_huge(2)+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={+ "query": {+ "clauses": [{"name": "a", "metricName": "m_huge", "aggregation": "sum"}],+ "formula": "a + 1",+ "dateFrom": (self.anchor - dt.timedelta(minutes=5)).isoformat(),+ "dateTo": (self.anchor + dt.timedelta(minutes=5)).isoformat(),+ }+ },+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ values = [p["value"] for p in response.json()["results"][0]["points"]]+ assert values == [None]diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex df845d30f9ab..6966d568a8e8 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -238,13 +238,15 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([(results: MetricsViewerSeries[], metricName: string): SparklineTimeSeries[] =>results.map((series, index) => ({name: formatSeriesName(series, metricName),- values: series.points.map((p) => p.value),+ // A null value is a gap (non-representable aggregate); Sparkline+ // takes plain numbers, so gaps chart as 0 for now.+ values: series.points.map((p) => p.value ?? 0),color: seriesColor(index),})),],sparklineValues: [(s) => [s.currentSeries],- (series: MetricsViewerSeries | undefined) => (series?.points ?? []).map((p) => p.value),+ (series: MetricsViewerSeries | undefined) => (series?.points ?? []).map((p) => p.value ?? 0),],sparklineLabels: [(s) => [s.currentSeries],diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex 465043330384..af0e76f8e4ed 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -173,8 +173,11 @@ export interface _MetricAnomalyDimensionApi {export interface _MetricQueryPointApi {/** Bucket start as ISO 8601 timestamp. */time: string- /** Aggregated value for the bucket. */- value: number+ /**+ * Aggregated value for the bucket. Null when the aggregate isn't representable (e.g. float overflow) — render as a gap.+ * @nullable+ */+ value: number | null}/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 88763cae698a..c114eb14c4c6 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -57279,8 +57279,11 @@ export namespace Schemas {export interface _MetricQueryPoint {/** Bucket start as ISO 8601 timestamp. */time: string;- /** Aggregated value for the bucket. */- value: number;+ /**+ * Aggregated value for the bucket. Null when the aggregate isn't representable (e.g. float overflow) — render as a gap.+ * @nullable+ */+ value: number | null;}/**