Skip to content

: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.

feat(metrics): return one MetricSeries per clause from the query endpoint (P2) (#63124)

Daniel Viscae9fdbd64e916
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 64ca1b4e8dfa..c5598f38ad0f 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -746,10 +746,6 @@ export class ApiRequest {
return this.metrics(projectId).addPathComponent('has_metrics')
}
- public metricsQuery(projectId?: ProjectType['id']): ApiRequest {
- return this.metrics(projectId).addPathComponent('query')
- }
-
public metricsValues(projectId?: ProjectType['id']): ApiRequest {
return this.metrics(projectId).addPathComponent('values')
}
@@ -2821,20 +2817,6 @@ const api = {
.get()
.then((response) => Boolean(response.hasMetrics))
},
- async query({
- query,
- signal,
- }: {
- query: {
- metricName: string
- aggregation: 'sum' | 'avg' | 'count' | 'p95'
- dateFrom: string
- dateTo?: string
- }
- signal?: AbortSignal
- }): Promise<{ results: { time: string; value: number }[] }> {
- return new ApiRequest().metricsQuery().create({ signal, data: { query } })
- },
async values({
search,
limit,
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index 9066453ef91f..747dca874bf3 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -5,43 +5,68 @@ allowed to import. Internal modules (query runners) stay behind this seam
so import-linter's strict-mode contract holds.
"""
-import datetime as dt
from typing import Any
from posthog.models import Team
+from products.metrics.backend.facade.contracts import MetricPoint, MetricQueryRequest, MetricSeries
+from products.metrics.backend.facade.enums import MetricAggregation
from products.metrics.backend.has_metrics_query_runner import team_has_metrics as _team_has_metrics
from products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner
from products.metrics.backend.metric_query_runner import MetricQueryRunner
+# MetricQueryRunner still speaks the legacy aggregation strings; this shrinks
+# as later PRs teach the runner the remaining MetricAggregation values.
+_RUNNER_AGGREGATIONS: dict[MetricAggregation, str] = {
+ MetricAggregation.SUM: "sum",
+ MetricAggregation.AVG: "avg",
+ MetricAggregation.COUNT: "count",
+}
+
def team_has_metrics(team: Team) -> bool:
"""Return True if the given team has ingested at least one metric."""
return _team_has_metrics(team)
-def query_metric(
- *,
- team: Team,
- metric_name: str,
- aggregation: str,
- date_from: dt.datetime,
- date_to: dt.datetime,
-) -> list[dict[str, Any]]:
- """Run a single-metric time-series query and return the bucketed points.
+def run_metric_query(*, team: Team, request: MetricQueryRequest) -> list[MetricSeries]:
+ """Execute a metric query and return one `MetricSeries` per
+ (clause, label-set) pair — a single ungrouped clause yields exactly one
+ series with empty labels, so consumers never branch on single-vs-multi.
- Returns a list of `{"time": iso_string, "value": float}` dicts ordered by
- time ascending. Raises `ValueError` for unsupported aggregations or an
- inverted date range — the presentation layer surfaces these as 400s.
+ Current scope: one clause; filters, group_by, interval, formula and the
+ rate/histogram aggregations raise `ValueError` until their PRs land.
+ The presentation layer surfaces `ValueError` as a 400.
"""
+ if len(request.clauses) != 1:
+ raise ValueError("multi-clause queries are not supported yet")
+ if request.formula is not None:
+ raise ValueError("formulas are not supported yet")
+ if request.interval is not None:
+ raise ValueError("explicit intervals are not supported yet")
+
+ clause = request.clauses[0]
+ if clause.filters:
+ raise ValueError("filters are not supported yet")
+ if clause.group_by:
+ raise ValueError("group_by is not supported yet")
+
+ if clause.aggregation == MetricAggregation.QUANTILE and clause.quantile == 0.95:
+ runner_aggregation = "p95"
+ elif clause.aggregation in _RUNNER_AGGREGATIONS:
+ runner_aggregation = _RUNNER_AGGREGATIONS[clause.aggregation]
+ else:
+ raise ValueError(f"aggregation {clause.aggregation.value!r} is not supported yet")
+
runner = MetricQueryRunner(
team=team,
- metric_name=metric_name,
- aggregation=aggregation,
- date_from=date_from,
- date_to=date_to,
+ metric_name=clause.metric_name,
+ aggregation=runner_aggregation,
+ date_from=request.date_from,
+ date_to=request.date_to,
)
- return runner.run()
+ points = tuple(MetricPoint(time=row["time"], value=row["value"]) for row in runner.run())
+ return [MetricSeries(labels={}, points=points, metric_name=clause.metric_name, clause=clause.name)]
def list_metric_names(
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index 3990cd8eda7e..f17179828d0f 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -5,6 +5,7 @@ recognisable.
"""
import datetime as dt
+from dataclasses import asdict
from django.utils import timezone
@@ -21,7 +22,9 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.event_usage import report_user_action
-from products.metrics.backend.facade.api import list_metric_names, query_metric, team_has_metrics
+from products.metrics.backend.facade.api import list_metric_names, run_metric_query, team_has_metrics
+from products.metrics.backend.facade.contracts import MetricQueryClause, MetricQueryRequest
+from products.metrics.backend.facade.enums import MetricAggregation
__all__ = ["MetricsViewSet"]
@@ -54,8 +57,29 @@ class _MetricQueryPointSerializer(serializers.Serializer):
value = serializers.FloatField(help_text="Aggregated value for the bucket.")
+class _MetricSeriesSerializer(serializers.Serializer):
+ labels = serializers.DictField(
+ child=serializers.CharField(),
+ help_text="Label values identifying this series. Empty for an ungrouped query.",
+ )
+ points = _MetricQueryPointSerializer(many=True, help_text="Time-bucketed points, ordered by time ascending.")
+ metric_name = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Metric the series was computed from. Null for formula results.",
+ )
+ clause = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Name of the query clause that produced this series.",
+ )
+
+
class _MetricQueryResponseSerializer(serializers.Serializer):
- results = _MetricQueryPointSerializer(many=True, help_text="Time-bucketed points, ordered by time ascending.")
+ results = _MetricSeriesSerializer(
+ many=True,
+ help_text="One series per (clause, label-set). A single ungrouped query returns exactly one series with empty labels.",
+ )
class _MetricNameSerializer(serializers.Serializer):
@@ -135,15 +159,29 @@ 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.
+ aggregation_raw: str = query_data["aggregation"]
+ if aggregation_raw == "p95":
+ aggregation, quantile = MetricAggregation.QUANTILE, 0.95
+ else:
+ aggregation, quantile = MetricAggregation(aggregation_raw), None
+
date_to: dt.datetime = query_data.get("dateTo") or timezone.now()
try:
- results = query_metric(
- team=self.team,
- metric_name=query_data["metricName"],
- aggregation=query_data["aggregation"],
+ metric_request = MetricQueryRequest(
+ clauses=(
+ MetricQueryClause(
+ name="a",
+ metric_name=query_data["metricName"],
+ aggregation=aggregation,
+ quantile=quantile,
+ ),
+ ),
date_from=query_data["dateFrom"],
date_to=date_to,
)
+ series = run_metric_query(team=self.team, request=metric_request)
except ValueError as exc:
raise ParseError(str(exc))
@@ -152,10 +190,11 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
"metrics query ran",
{
"aggregation": query_data["aggregation"],
- "result_count": len(results),
+ "series_count": len(series),
+ "result_count": sum(len(s.points) for s in series),
},
team=self.team,
request=request,
)
- return Response({"results": results}, status=status.HTTP_200_OK)
+ return Response({"results": [asdict(s) for s in series]}, status=status.HTTP_200_OK)
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index abe1537f2f0e..64a845d2c28c 100644
--- a/products/metrics/backend/tests/test_metric_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_query_runner.py
@@ -1,4 +1,5 @@
import datetime as dt
+from typing import Any
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
@@ -14,6 +15,9 @@ from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.client.connection import Workload
+from products.metrics.backend.facade.api import run_metric_query
+from products.metrics.backend.facade.contracts import MetricFilter, MetricGroupBy, MetricQueryClause, MetricQueryRequest
+from products.metrics.backend.facade.enums import FilterOp, MetricAggregation
from products.metrics.backend.metric_query_runner import MetricQueryRunner, _pick_interval, attribute_field
from products.metrics.backend.tests._seeder import seed_metric
@@ -179,7 +183,12 @@ class TestMetricsQueryAPI(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
body = response.json()
self.assertIn("results", body)
- self.assertEqual(sum(point["value"] for point in body["results"]), 3.0)
+ self.assertEqual(len(body["results"]), 1)
+ series = body["results"][0]
+ self.assertEqual(series["labels"], {})
+ self.assertEqual(series["metric_name"], "m1")
+ self.assertEqual(series["clause"], "a")
+ self.assertEqual(sum(point["value"] for point in series["points"]), 3.0)
class TestAttributeField(ClickhouseTestMixin, APIBaseTest):
@@ -273,3 +282,102 @@ class TestAttributeField(ClickhouseTestMixin, APIBaseTest):
)
value = self._select_attribute(attribute_field("nonexistent"), "m_auto_missing")
self.assertEqual(value, "")
+
+
+class TestRunMetricQueryFacade(ClickhouseTestMixin, APIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = True
+
+ def setUp(self):
+ super().setUp()
+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+
+ def _request(self, **overrides):
+ anchor = timezone.now().replace(microsecond=0)
+ defaults: dict[str, Any] = {
+ "clauses": (MetricQueryClause(name="a", metric_name="m1", aggregation=MetricAggregation.SUM),),
+ "date_from": anchor - dt.timedelta(hours=1),
+ "date_to": anchor,
+ }
+ defaults.update(overrides)
+ return MetricQueryRequest(**defaults)
+
+ def test_single_clause_returns_one_series_with_empty_labels(self):
+ anchor = timezone.now().replace(microsecond=0)
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="m1",
+ points=[(anchor - dt.timedelta(minutes=10), 1.5), (anchor - dt.timedelta(minutes=10), 2.5)],
+ )
+
+ series = run_metric_query(team=self.team, request=self._request())
+
+ self.assertEqual(len(series), 1)
+ self.assertEqual(series[0].labels, {})
+ self.assertEqual(series[0].metric_name, "m1")
+ self.assertEqual(series[0].clause, "a")
+ self.assertEqual(sum(p.value for p in series[0].points), 4.0)
+
+ def test_quantile_095_maps_to_p95(self):
+ anchor = timezone.now().replace(microsecond=0)
+ seed_metric(team_id=self.team.id, metric_name="m1", points=[(anchor - dt.timedelta(minutes=10), 5.0)])
+
+ series = run_metric_query(
+ team=self.team,
+ request=self._request(
+ clauses=(
+ MetricQueryClause(
+ name="a", metric_name="m1", aggregation=MetricAggregation.QUANTILE, quantile=0.95
+ ),
+ )
+ ),
+ )
+ self.assertEqual(len(series), 1)
+
+ @parameterized.expand(
+ [
+ (
+ "multi_clause",
+ {
+ "clauses": (
+ MetricQueryClause(name="a", metric_name="m1", aggregation=MetricAggregation.SUM),
+ MetricQueryClause(name="b", metric_name="m2", aggregation=MetricAggregation.SUM),
+ )
+ },
+ ),
+ ("formula", {"formula": "a / b"}),
+ ("interval", {"interval": "minute"}),
+ (
+ "filters",
+ {
+ "clauses": (
+ MetricQueryClause(
+ name="a",
+ metric_name="m1",
+ aggregation=MetricAggregation.SUM,
+ filters=(MetricFilter(key="env", op=FilterOp.EQ, value="prod"),),
+ ),
+ )
+ },
+ ),
+ (
+ "group_by",
+ {
+ "clauses": (
+ MetricQueryClause(
+ name="a",
+ metric_name="m1",
+ aggregation=MetricAggregation.SUM,
+ group_by=(MetricGroupBy(key="env"),),
+ ),
+ )
+ },
+ ),
+ (
+ "unsupported_aggregation",
+ {"clauses": (MetricQueryClause(name="a", metric_name="m1", aggregation=MetricAggregation.RATE),)},
+ ),
+ ]
+ )
+ def test_not_yet_supported_features_raise_value_error(self, _name, overrides):
+ with self.assertRaises(ValueError):
+ run_metric_query(team=self.team, request=self._request(**overrides))
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 543495402740..ab9e72fa05fe 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -1,18 +1,18 @@
-import { actions, kea, listeners, path, reducers, selectors } from 'kea'
+import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import api from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { dateStringToDayJs } from 'lib/utils'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { metricsQueryCreate } from 'products/metrics/frontend/generated/api'
+import type { _MetricSeriesApi } from 'products/metrics/frontend/generated/api.schemas'
import type { metricsViewerLogicType } from './metricsViewerLogicType'
export type MetricAggregation = 'sum' | 'avg' | 'count' | 'p95'
-export interface MetricsViewerPoint {
- time: string
- value: number
-}
+export type MetricsViewerSeries = _MetricSeriesApi
const DEFAULT_AGGREGATION: MetricAggregation = 'sum'
const DEFAULT_DATE_FROM = '-1h'
@@ -28,6 +28,9 @@ const resolveDate = (value: string | null | undefined): string | null => {
export const metricsViewerLogic = kea<metricsViewerLogicType>([
path(['products', 'metrics', 'frontend', 'components', 'metricsViewerLogic']),
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
actions({
setMetricName: (metricName: string) => ({ metricName }),
setAggregation: (aggregation: MetricAggregation) => ({ aggregation }),
@@ -61,7 +64,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
})),
loaders(({ values, actions }) => ({
queryResults: [
- [] as MetricsViewerPoint[],
+ [] as MetricsViewerSeries[],
{
fetchQueryResults: async (_, breakpoint) => {
const trimmedName = values.metricName.trim()
@@ -76,15 +79,18 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
const dateToISO = resolveDate(values.dateTo) ?? undefined
const controller = new AbortController()
actions.cancelInProgressQuery(controller)
- const response = await api.metrics.query({
- query: {
- metricName: trimmedName,
- aggregation: values.aggregation,
- dateFrom: dateFromISO,
- ...(dateToISO ? { dateTo: dateToISO } : {}),
+ const response = await metricsQueryCreate(
+ String(values.currentTeamId),
+ {
+ query: {
+ metricName: trimmedName,
+ aggregation: values.aggregation,
+ dateFrom: dateFromISO,
+ ...(dateToISO ? { dateTo: dateToISO } : {}),
+ },
},
- signal: controller.signal,
- })
+ { signal: controller.signal }
+ )
breakpoint()
actions.setQueryAbortController(null)
return response.results
@@ -94,7 +100,9 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
})),
selectors({
hasMetricName: [(s) => [s.metricName], (metricName) => metricName.trim().length > 0],
- sparklineValues: [(s) => [s.queryResults], (results) => results.map((p) => p.value)],
- sparklineLabels: [(s) => [s.queryResults], (results) => results.map((p) => p.time)],
+ // The viewer renders the first series only for now; group-by lands
+ // multi-series rendering in a later PR.
+ sparklineValues: [(s) => [s.queryResults], (results) => (results[0]?.points ?? []).map((p) => p.value)],
+ sparklineLabels: [(s) => [s.queryResults], (results) => (results[0]?.points ?? []).map((p) => p.time)],
}),
])
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index f7d6ac607fe1..a7eb8fbf7c3c 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -69,9 +69,31 @@ export interface _MetricQueryPointApi {
value: number
}
-export interface _MetricQueryResponseApi {
+/**
+ * Label values identifying this series. Empty for an ungrouped query.
+ */
+export type _MetricSeriesApiLabels = { [key: string]: string }
+
+export interface _MetricSeriesApi {
+ /** Label values identifying this series. Empty for an ungrouped query. */
+ labels: _MetricSeriesApiLabels
/** Time-bucketed points, ordered by time ascending. */
- results: _MetricQueryPointApi[]
+ points: _MetricQueryPointApi[]
+ /**
+ * Metric the series was computed from. Null for formula results.
+ * @nullable
+ */
+ metric_name?: string | null
+ /**
+ * Name of the query clause that produced this series.
+ * @nullable
+ */
+ clause?: string | null
+}
+
+export interface _MetricQueryResponseApi {
+ /** One series per (clause, label-set). A single ungrouped query returns exactly one series with empty labels. */
+ results: _MetricSeriesApi[]
}
export interface _MetricNameApi {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4d0fb1b2811c..f68d21f302c1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -45547,9 +45547,31 @@ export namespace Schemas {
query: _MetricQueryBody;
}
- export interface _MetricQueryResponse {
+ /**
+ * Label values identifying this series. Empty for an ungrouped query.
+ */
+ export type _MetricSeriesLabels = {[key: string]: string};
+
+ export interface _MetricSeries {
+ /** Label values identifying this series. Empty for an ungrouped query. */
+ labels: _MetricSeriesLabels;
/** Time-bucketed points, ordered by time ascending. */
- results: _MetricQueryPoint[];
+ points: _MetricQueryPoint[];
+ /**
+ * Metric the series was computed from. Null for formula results.
+ * @nullable
+ */
+ metric_name?: string | null;
+ /**
+ * Name of the query clause that produced this series.
+ * @nullable
+ */
+ clause?: string | null;
+ }
+
+ export interface _MetricQueryResponse {
+ /** One series per (clause, label-set). A single ungrouped query returns exactly one series with empty labels. */
+ results: _MetricSeries[];
}
/**