: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): histogram_quantile from OTel explicit-bounds buckets (P6) (#63128)
Daniel Visca6461b6e809e6
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex 2ee96b508304..d3657ca821e5 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -83,6 +83,8 @@ def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricSif clause.aggregation == MetricAggregation.QUANTILE and clause.quantile == 0.95:runner_aggregation = "p95"+ elif clause.aggregation == MetricAggregation.HISTOGRAM_QUANTILE:+ runner_aggregation = "histogram_quantile"elif clause.aggregation in _RUNNER_AGGREGATIONS:runner_aggregation = _RUNNER_AGGREGATIONS[clause.aggregation]else:@@ -97,6 +99,7 @@ def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricSfilters=clause.filters,group_by=clause.group_by,interval=request.interval,+ quantile=clause.quantile if runner_aggregation == "histogram_quantile" else None,)rows = runner.run()if not rows:diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.pyindex 125b272b994e..2db45c041857 100644--- a/products/metrics/backend/metric_query_runner.py+++ b/products/metrics/backend/metric_query_runner.py@@ -89,7 +89,36 @@ def _aggregation_expr(name: str) -> ast.Expr:raise ValueError(f"Unsupported aggregation: {name!r}")-_ALLOWED_AGGREGATIONS: frozenset[str] = frozenset({"sum", "avg", "count", "p95", "rate", "increase"})+_ALLOWED_AGGREGATIONS: frozenset[str] = frozenset(+ {"sum", "avg", "count", "p95", "rate", "increase", "histogram_quantile"}+)+++def _histogram_quantile(quantile: float, bounds: list[float], counts: list[float]) -> float:+ """Prometheus-style quantile from explicit-bounds bucket counts.++ `counts` has one entry per bound plus an overflow bucket. Linear+ interpolation inside the bucket containing the rank; the overflow+ bucket clamps to the highest finite bound; the first bucket's lower+ edge is assumed 0 (negative-bound histograms get bounds[0]).+ """+ total = sum(counts)+ if total <= 0 or not bounds:+ return 0.0+ rank = quantile * total+ cumulative = 0.0+ for index, count in enumerate(counts):+ cumulative += count+ if cumulative >= rank:+ if index >= len(bounds):+ return bounds[-1]+ upper = bounds[index]+ lower = bounds[index - 1] if index > 0 else min(0.0, bounds[0])+ if count == 0:+ return upper+ return lower + (upper - lower) * (rank - (cumulative - count)) / count+ return bounds[-1]+# Target ~60 buckets across the requested range — feels right for a chart._TARGET_BUCKET_COUNT = 60@@ -164,6 +193,7 @@ class MetricQueryRunner:filters: Sequence[MetricFilter] = (),group_by: Sequence[MetricGroupBy] = (),interval: str | None = None,+ quantile: float | None = None,) -> None:if aggregation not in _ALLOWED_AGGREGATIONS:raise ValueError(f"Unsupported aggregation: {aggregation!r}")@@ -171,6 +201,9 @@ class MetricQueryRunner:raise ValueError("date_to must be after date_from")if interval is not None and interval not in {name for name, _, _ in _INTERVAL_LADDER}:raise ValueError(f"Unknown interval: {interval!r}")+ if aggregation == "histogram_quantile":+ if quantile is None or not 0.0 < quantile < 1.0:+ raise ValueError("histogram_quantile requires a quantile in (0, 1)")self.team = teamself.metric_name = metric_name@@ -180,10 +213,13 @@ class MetricQueryRunner:self.filters = tuple(filters)self.group_by = tuple(group_by)self.interval = interval or _pick_interval(date_from, date_to)+ self.quantile = quantiledef run(self) -> list[dict[str, Any]]:"""Bucketed rows: `{"time", "value", "labels"}`. `labels` carries oneentry per group_by key (always `{}` without group_by)."""+ if self.aggregation == "histogram_quantile":+ return self._run_histogram_quantile()if self.aggregation in ("rate", "increase"):query = self._build_counter_query()else:@@ -208,6 +244,40 @@ class MetricQueryRunner:)return rows+ def _run_histogram_quantile(self) -> list[dict[str, Any]]:+ """ClickHouse sums the per-le distributions (temporality-aware,+ per-series deltas like rate/increase); the quantile interpolation+ happens here in Python where it is exact and unit-testable."""+ assert self.quantile is not None+ query = self._build_histogram_query()+ response = execute_hogql_query(+ query_type="MetricQuery",+ query=query,+ team=self.team,+ workload=Workload.LOGS,+ )++ group_count = len(self.group_by)+ distinct_bounds = {tuple(variant) for row in response.results for variant in row[2 + group_count] if variant}+ if len(distinct_bounds) > 1:+ raise ValueError(+ "histogram bounds differ across the selected series/time range; "+ "narrow the query with filters so all series share one bucket layout"+ )++ rows: list[dict[str, Any]] = []+ for row in response.results:+ bounds = list(row[1 + group_count])+ counts = list(row[3 + group_count])+ rows.append(+ {+ "time": row[0].isoformat() if isinstance(row[0], dt.datetime) else row[0],+ "value": _histogram_quantile(self.quantile, bounds, counts),+ "labels": {group.key: row[1 + index] for index, group in enumerate(self.group_by)},+ }+ )+ return rows+def _splice_group_columns(self, query: ast.SelectQuery) -> None:"""Insert the group_by label columns between `time` and `value` —parse_select placeholders can't express a variable column count."""@@ -317,3 +387,64 @@ class MetricQueryRunner:assert isinstance(query, ast.SelectQuery)self._splice_group_columns(query)return query++ def _build_histogram_query(self) -> ast.SelectQuery:+ """Per-time-bucket summed bucket-count distributions for histogram+ rows, with the same per-series temporality/reset handling as+ rate/increase applied element-wise to the counts array."""+ query = parse_select(+ """+ SELECT+ toStartOfInterval(sample_timestamp, {interval}) AS time,+ any(histogram_bounds) AS bounds,+ groupUniqArray(histogram_bounds) AS bounds_variants,+ sumForEach(contribution_counts) AS counts+ FROM (+ SELECT+ timestamp AS sample_timestamp,+ attributes AS attributes,+ resource_attributes AS resource_attributes,+ histogram_bounds AS histogram_bounds,+ multiIf(+ aggregation_temporality = 'delta', counts_f,+ empty(prev_counts), arrayMap(x -> 0.0, counts_f),+ length(prev_counts) != length(counts_f), counts_f,+ arrayAll((c, p) -> c >= p, counts_f, prev_counts), arrayMap((c, p) -> c - p, counts_f, prev_counts),+ counts_f+ ) AS contribution_counts+ FROM (+ SELECT+ timestamp,+ aggregation_temporality,+ attributes,+ resource_attributes,+ histogram_bounds,+ arrayMap(x -> toFloat(x), histogram_counts) AS counts_f,+ lagInFrame(arrayMap(x -> toFloat(x), histogram_counts)) OVER (+ PARTITION BY service_name, resource_fingerprint, toString(attributes)+ ORDER BY timestamp ASC+ ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING+ ) AS prev_counts+ FROM posthog.metrics+ WHERE metric_name = {metric_name}+ AND timestamp >= {date_from}+ AND timestamp < {date_to}+ AND notEmpty(histogram_counts)+ AND {filters}+ )+ )+ GROUP BY time+ ORDER BY time ASC+ LIMIT 10000+ """,+ placeholders={+ "interval": _interval_expr(self.interval),+ "metric_name": ast.Constant(value=self.metric_name),+ "date_from": ast.Constant(value=self.date_from),+ "date_to": ast.Constant(value=self.date_to),+ "filters": _filters_expr(self.filters),+ },+ )+ assert isinstance(query, ast.SelectQuery)+ self._splice_group_columns(query)+ return querydiff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex 8b03bbb3fec8..e661c56de522 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -68,9 +68,16 @@ class _MetricQueryBodySerializer(serializers.Serializer):help_text="Exact metric name to query (e.g. 'http.server.duration').",)aggregation = serializers.ChoiceField(- choices=["sum", "avg", "count", "p95", "rate", "increase"],+ choices=["sum", "avg", "count", "p95", "rate", "increase", "histogram_quantile"],default="sum",- help_text="Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is).",+ help_text="Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.",+ )+ quantile = serializers.FloatField(+ required=False,+ allow_null=True,+ min_value=0.0,+ max_value=1.0,+ help_text="Quantile in (0, 1) for 'histogram_quantile' (e.g. 0.95). Ignored for other aggregations.",)filters = _MetricFilterSerializer(many=True,@@ -210,11 +217,14 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):body.is_valid(raise_exception=True)query_data = body.validated_data["query"]- # The wire aggregation "p95" is contract QUANTILE(0.95); the richer- # request fields (filters, group_by, formula) arrive in later PRs.+ # The wire aggregation "p95" is contract QUANTILE(0.95).aggregation_raw: str = query_data["aggregation"]if aggregation_raw == "p95":aggregation, quantile = MetricAggregation.QUANTILE, 0.95+ elif aggregation_raw == "histogram_quantile":+ aggregation, quantile = MetricAggregation.HISTOGRAM_QUANTILE, query_data.get("quantile")+ if quantile is None:+ raise ParseError("histogram_quantile requires 'quantile'")else:aggregation, quantile = MetricAggregation(aggregation_raw), Nonediff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.pyindex 82695c6c8b83..30c12802036e 100644--- a/products/metrics/backend/tests/test_metric_query_runner.py+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -19,7 +19,12 @@ from posthog.clickhouse.client.connection import Workloadfrom products.metrics.backend.facade.api import run_metric_queryfrom products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequestfrom products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation-from products.metrics.backend.metric_query_runner import MetricQueryRunner, _pick_interval, attribute_field+from products.metrics.backend.metric_query_runner import (+ MetricQueryRunner,+ _histogram_quantile,+ _pick_interval,+ attribute_field,+)from products.metrics.backend.tests._seeder import seed_metric@@ -751,3 +756,140 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):[p["value"] for p in response.json()["results"][0]["points"]],[30.0],)+++class TestHistogramQuantileInterpolation:+ @parameterized.expand(+ [+ # bounds [0.1, 0.5, 1.0], counts [10, 10, 10, 0] (no overflow):+ # p50 -> rank 15, second bucket [0.1, 0.5], 5/10 through -> 0.3+ ("p50_mid_bucket", 0.5, [0.1, 0.5, 1.0], [10.0, 10.0, 10.0, 0.0], 0.3),+ # p25 -> rank 7.5, first bucket [0, 0.1], 7.5/10 through -> 0.075+ ("p25_first_bucket", 0.25, [0.1, 0.5, 1.0], [10.0, 10.0, 10.0, 0.0], 0.075),+ # rank lands in the overflow bucket -> clamp to highest bound+ ("overflow_clamps", 0.99, [0.1, 0.5, 1.0], [1.0, 1.0, 1.0, 10.0], 1.0),+ ("empty_counts", 0.5, [0.1, 0.5], [0.0, 0.0, 0.0], 0.0),+ ("no_bounds", 0.5, [], [10.0], 0.0),+ ]+ )+ def test_interpolation(self, _name, q, bounds, counts, expected):+ assert abs(_histogram_quantile(q, bounds, counts) - expected) < 1e-9+++class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ BOUNDS = [0.1, 0.5, 1.0]++ 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_histogram(self, points_with_counts, temporality="cumulative", bounds=None, **kwargs):+ for timestamp, counts in points_with_counts:+ seed_metric(+ team_id=self.team.id,+ metric_name="latency",+ metric_type="histogram",+ aggregation_temporality=temporality,+ histogram_bounds=bounds or self.BOUNDS,+ histogram_counts=counts,+ points=[(timestamp, 0.0)],+ **kwargs,+ )++ def _run(self, quantile=0.5, **overrides):+ defaults: dict[str, Any] = {+ "team": self.team,+ "metric_name": "latency",+ "aggregation": "histogram_quantile",+ "quantile": quantile,+ "date_from": self.anchor - dt.timedelta(minutes=1),+ "date_to": self.anchor + dt.timedelta(minutes=2),+ "interval": "minute",+ }+ defaults.update(overrides)+ return MetricQueryRunner(**defaults).run()++ def test_requires_quantile(self):+ with self.assertRaises(ValueError):+ self._run(quantile=None)+ with self.assertRaises(ValueError):+ self._run(quantile=1.5)++ def test_delta_histogram_p50(self):+ self._seed_histogram(+ [+ (self.anchor + dt.timedelta(seconds=0), [10, 10, 10, 0]),+ (self.anchor + dt.timedelta(seconds=30), [10, 10, 10, 0]),+ ],+ temporality="delta",+ )+ rows = self._run(0.5)+ # combined counts [20, 20, 20, 0]: rank 30, mid of second bucket+ self.assertEqual(len(rows), 1)+ self.assertAlmostEqual(rows[0]["value"], 0.3)++ def test_cumulative_histogram_diffs_per_series(self):+ # Cumulative counts grow; first sample contributes nothing.+ self._seed_histogram(+ [+ (self.anchor + dt.timedelta(seconds=0), [100, 100, 100, 0]),+ (self.anchor + dt.timedelta(seconds=30), [110, 110, 110, 0]),+ ],+ temporality="cumulative",+ )+ rows = self._run(0.5)+ # window contribution [10, 10, 10, 0] -> p50 = 0.3+ self.assertEqual(len(rows), 1)+ self.assertAlmostEqual(rows[0]["value"], 0.3)++ def test_mismatched_bounds_raise(self):+ self._seed_histogram([(self.anchor + dt.timedelta(seconds=0), [1, 1, 1, 0])], temporality="delta")+ self._seed_histogram(+ [(self.anchor + dt.timedelta(seconds=10), [1, 1, 1, 0])],+ temporality="delta",+ bounds=[0.2, 0.6, 2.0],+ resource_labels={"k8s.pod.name": "other"},+ )+ with self.assertRaises(ValueError):+ self._run(0.5)++ def test_histogram_quantile_via_api(self):+ self._seed_histogram(+ [(self.anchor + dt.timedelta(seconds=0), [10, 10, 10, 0])],+ temporality="delta",+ )+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={+ "query": {+ "metricName": "latency",+ "aggregation": "histogram_quantile",+ "quantile": 0.5,+ "interval": "minute",+ "dateFrom": (self.anchor - dt.timedelta(minutes=1)).isoformat(),+ "dateTo": (self.anchor + dt.timedelta(minutes=2)).isoformat(),+ }+ },+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ points = response.json()["results"][0]["points"]+ self.assertEqual(len(points), 1)+ self.assertAlmostEqual(points[0]["value"], 0.3)++ def test_histogram_quantile_via_api_requires_quantile(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={+ "query": {+ "metricName": "latency",+ "aggregation": "histogram_quantile",+ "dateFrom": (self.anchor - dt.timedelta(minutes=1)).isoformat(),+ }+ },+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex 0e09c4b19bb5..1490834a5801 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -30,6 +30,7 @@ export interface AppMetricsTotalsResponseApi {* * `p95` - p95* * `rate` - rate* * `increase` - increase+ * * `histogram_quantile` - histogram_quantile*/export type AggregationEnumApi = (typeof AggregationEnumApi)[keyof typeof AggregationEnumApi]@@ -40,6 +41,7 @@ export const AggregationEnumApi = {P95: 'p95',Rate: 'rate',Increase: 'increase',+ HistogramQuantile: 'histogram_quantile',} as const/**@@ -136,15 +138,23 @@ export interface _MetricQueryBodyApi {* @maxLength 255*/metricName: string- /** Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is).+ /** Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.** * `sum` - sum* * `avg` - avg* * `count` - count* * `p95` - p95* * `rate` - rate- * * `increase` - increase */+ * * `increase` - increase+ * * `histogram_quantile` - histogram_quantile */aggregation?: AggregationEnumApi+ /**+ * Quantile in (0, 1) for 'histogram_quantile' (e.g. 0.95). Ignored for other aggregations.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ quantile?: number | null/** Label predicates ANDed together. Rows must satisfy every filter. */filters?: _MetricFilterApi[]/** Labels to split the result into separate series by. Series share one time grid and are capped at the 100 largest. */diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.tsindex 0dba4aa53b3b..725aac479825 100644--- a/products/metrics/frontend/generated/api.zod.ts+++ b/products/metrics/frontend/generated/api.zod.ts@@ -12,6 +12,9 @@ import * as zod from 'zod'export const metricsQueryCreateBodyQueryOneMetricNameMax = 255export const metricsQueryCreateBodyQueryOneAggregationDefault = `sum`+export const metricsQueryCreateBodyQueryOneQuantileMin = 0+export const metricsQueryCreateBodyQueryOneQuantileMax = 1+export const metricsQueryCreateBodyQueryOneFiltersItemKeyMax = 255export const metricsQueryCreateBodyQueryOneFiltersItemOpDefault = `eq`@@ -28,14 +31,20 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({.max(metricsQueryCreateBodyQueryOneMetricNameMax).describe("Exact metric name to query (e.g. 'http.server.duration')."),aggregation: zod- .enum(['sum', 'avg', 'count', 'p95', 'rate', 'increase'])+ .enum(['sum', 'avg', 'count', 'p95', 'rate', 'increase', 'histogram_quantile']).describe(- '\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase'+ '\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase\n\* `histogram_quantile` - histogram_quantile').default(metricsQueryCreateBodyQueryOneAggregationDefault).describe(- "Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is).\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase"+ "Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase\n\* `histogram_quantile` - histogram_quantile"),+ quantile: zod+ .number()+ .min(metricsQueryCreateBodyQueryOneQuantileMin)+ .max(metricsQueryCreateBodyQueryOneQuantileMax)+ .nullish()+ .describe("Quantile in (0, 1) for 'histogram_quantile' (e.g. 0.95). Ignored for other aggregations."),filters: zod.array(zod.object({diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 69b814e9c1d0..b15176e3e2c4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8225,6 +8225,7 @@ export namespace Schemas {* * `p95` - p95* * `rate` - rate* * `increase` - increase+ * * `histogram_quantile` - histogram_quantile*/export type AggregationEnum = typeof AggregationEnum[keyof typeof AggregationEnum];@@ -8236,6 +8237,7 @@ export namespace Schemas {P95: 'p95',Rate: 'rate',Increase: 'increase',+ HistogramQuantile: 'histogram_quantile',} as const;export interface InsightsThresholdBounds {@@ -48283,15 +48285,23 @@ export namespace Schemas {* @maxLength 255*/metricName: string;- /** Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is).+ /** Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is). 'histogram_quantile' interpolates from OTel histogram buckets and requires 'quantile'.** * `sum` - sum* * `avg` - avg* * `count` - count* * `p95` - p95* * `rate` - rate- * * `increase` - increase */+ * * `increase` - increase+ * * `histogram_quantile` - histogram_quantile */aggregation?: AggregationEnum;+ /**+ * Quantile in (0, 1) for 'histogram_quantile' (e.g. 0.95). Ignored for other aggregations.+ * @minimum 0+ * @maximum 1+ * @nullable+ */+ quantile?: number | null;/** Label predicates ANDed together. Rows must satisfy every filter. */filters?: _MetricFilter[];/** Labels to split the result into separate series by. Series share one time grid and are capped at the 100 largest. */