: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): add Viewer tab with single-metric line chart (#60376)
Daniel Visca18a1335278ca
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 1a5dd65ebd67..ddc2fbf149b9 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -739,6 +739,10 @@ export class ApiRequest {return this.metrics(projectId).addPathComponent('has_metrics')}+ public metricsQuery(projectId?: ProjectType['id']): ApiRequest {+ return this.metrics(projectId).addPathComponent('query')+ }+// # Tracingpublic tracingSpans(): ApiRequest {return this.environmentsDetail().addPathComponent('tracing').addPathComponent('spans')@@ -2801,6 +2805,20 @@ 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 } })+ },},tracing: {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 45513a943f96..0bee1158371b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3063,6 +3063,9 @@ importers:'@posthog/icons':specifier: '*'+ '@posthog/products-error-tracking':+ specifier: workspace:*+ version: link:../error_tracking'@types/react':specifier: 18.3.27version: 18.3.27diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex cb26bf447b71..c2d99b4caf90 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -5,11 +5,39 @@ allowed to import. Internal modules (query runners) stay behind this seamso import-linter's strict-mode contract holds."""+import datetime as dt+from typing import Any+from posthog.models import Teamfrom products.metrics.backend.has_metrics_query_runner import team_has_metrics as _team_has_metrics+from products.metrics.backend.metric_query_runner import MetricQueryRunnerdef 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.++ 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.+ """+ runner = MetricQueryRunner(+ team=team,+ metric_name=metric_name,+ aggregation=aggregation,+ date_from=date_from,+ date_to=date_to,+ )+ return runner.run()diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.pynew file mode 100644index 000000000000..b11db0817134--- /dev/null+++ b/products/metrics/backend/metric_query_runner.py@@ -0,0 +1,134 @@+"""Single-metric time-series query runner.++Returns a list of `(time_bucket, value)` points for one metric over a date+range, with a choice of aggregation. Modelled after the logs+`SparklineQueryRunner` shape but flattened — we don't yet need the full+`AnalyticsQueryRunner[LogsQueryResponse]` infrastructure since this product+isn't going through HogQL `DataNode` caching, schema-gen or the data-viz+pipeline yet.+"""++import datetime as dt+from typing import Any++from posthog.hogql import ast+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.client.connection import Workload+from posthog.models import Team+++def _aggregation_expr(name: str) -> ast.Expr:+ """Build the HogQL AST for the supported aggregations.++ Kept as AST nodes (rather than string interpolation) so the+ `hogql-no-fstring` semgrep rule doesn't have to special-case this+ runner — the function name and percentile literal travel as a+ typed expression, not as substituted text.+ """+ value_field = ast.Field(chain=["value"])+ if name == "sum":+ return ast.Call(name="sum", args=[value_field])+ if name == "avg":+ return ast.Call(name="avg", args=[value_field])+ if name == "count":+ return ast.Call(name="count", args=[])+ if name == "p95":+ return ast.Call(name="quantile", params=[ast.Constant(value=0.95)], args=[value_field])+ raise ValueError(f"Unsupported aggregation: {name!r}")+++_ALLOWED_AGGREGATIONS: frozenset[str] = frozenset({"sum", "avg", "count", "p95"})++# Target ~60 buckets across the requested range — feels right for a chart.+_TARGET_BUCKET_COUNT = 60++# Order from finest to coarsest. The first interval that yields+# <= _TARGET_BUCKET_COUNT buckets wins.+_INTERVAL_LADDER: list[tuple[str, dt.timedelta, ast.Call]] = [+ ("second", dt.timedelta(seconds=1), ast.Call(name="toIntervalSecond", args=[ast.Constant(value=1)])),+ ("minute", dt.timedelta(minutes=1), ast.Call(name="toIntervalMinute", args=[ast.Constant(value=1)])),+ ("minute_5", dt.timedelta(minutes=5), ast.Call(name="toIntervalMinute", args=[ast.Constant(value=5)])),+ ("minute_15", dt.timedelta(minutes=15), ast.Call(name="toIntervalMinute", args=[ast.Constant(value=15)])),+ ("hour", dt.timedelta(hours=1), ast.Call(name="toIntervalHour", args=[ast.Constant(value=1)])),+ ("hour_6", dt.timedelta(hours=6), ast.Call(name="toIntervalHour", args=[ast.Constant(value=6)])),+ ("day", dt.timedelta(days=1), ast.Call(name="toIntervalDay", args=[ast.Constant(value=1)])),+ ("week", dt.timedelta(weeks=1), ast.Call(name="toIntervalWeek", args=[ast.Constant(value=1)])),+]+++def _pick_interval(date_from: dt.datetime, date_to: dt.datetime) -> str:+ """Pick the finest interval that keeps bucket count at or below the target."""+ span = date_to - date_from+ for name, step, _ in _INTERVAL_LADDER:+ if span / step <= _TARGET_BUCKET_COUNT:+ return name+ return _INTERVAL_LADDER[-1][0]+++def _interval_expr(name: str) -> ast.Call:+ for entry_name, _, expr in _INTERVAL_LADDER:+ if entry_name == name:+ return expr+ raise ValueError(f"Unknown interval: {name!r}")+++class MetricQueryRunner:+ def __init__(+ self,+ team: Team,+ metric_name: str,+ aggregation: str,+ date_from: dt.datetime,+ date_to: dt.datetime,+ ) -> None:+ if aggregation not in _ALLOWED_AGGREGATIONS:+ raise ValueError(f"Unsupported aggregation: {aggregation!r}")+ if date_to <= date_from:+ raise ValueError("date_to must be after date_from")++ self.team = team+ self.metric_name = metric_name+ self.aggregation = aggregation+ self.date_from = date_from+ self.date_to = date_to+ self.interval = _pick_interval(date_from, date_to)++ def run(self) -> list[dict[str, Any]]:+ # `metrics` is only registered under the `posthog.` HogQL namespace+ # (see posthog/hogql/database/database.py).+ query = parse_select(+ """+ SELECT+ toStartOfInterval(timestamp, {interval}) AS time,+ {aggregation} AS value+ FROM posthog.metrics+ WHERE metric_name = {metric_name}+ AND timestamp >= {date_from}+ AND timestamp < {date_to}+ GROUP BY time+ ORDER BY time ASC+ LIMIT 10000+ """,+ placeholders={+ "interval": _interval_expr(self.interval),+ "aggregation": _aggregation_expr(self.aggregation),+ "metric_name": ast.Constant(value=self.metric_name),+ "date_from": ast.Constant(value=self.date_from),+ "date_to": ast.Constant(value=self.date_to),+ },+ )+ assert isinstance(query, ast.SelectQuery)++ response = execute_hogql_query(+ query_type="MetricQuery",+ query=query,+ team=self.team,+ workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now+ )++ return [+ {"time": row[0].isoformat() if isinstance(row[0], dt.datetime) else row[0], "value": row[1]}+ for row in response.results+ ]diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex ebc0e48232a4..293a60a6a7a5 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -1,14 +1,18 @@"""DRF views for the alpha metrics product.Mirrors the shape of `products/logs/backend/api.py` so the two surfaces stay-recognisable. Today we only expose `has_metrics` — query/sparkline/etc. land-in follow-up PRs.+recognisable."""+import datetime as dt++from django.utils import timezone+from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import extend_schema-from rest_framework import status, viewsets+from rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import action+from rest_framework.exceptions import ParseErrorfrom rest_framework.request import Requestfrom rest_framework.response import Response@@ -17,11 +21,43 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.event_usage import report_user_action-from products.metrics.backend.facade.api import team_has_metrics+from products.metrics.backend.facade.api import query_metric, team_has_metrics__all__ = ["MetricsViewSet"]+class _MetricQueryBodySerializer(serializers.Serializer):+ metricName = serializers.CharField(+ max_length=255,+ help_text="Exact metric name to query (e.g. 'http.server.duration').",+ )+ aggregation = serializers.ChoiceField(+ choices=["sum", "avg", "count", "p95"],+ default="sum",+ help_text="Aggregation applied per time bucket.",+ )+ dateFrom = serializers.DateTimeField(+ help_text="Lower bound (inclusive) for the query range. ISO 8601.",+ )+ dateTo = serializers.DateTimeField(+ required=False,+ help_text="Upper bound (exclusive) for the query range. Defaults to now if omitted.",+ )+++class _MetricQueryRequestSerializer(serializers.Serializer):+ query = _MetricQueryBodySerializer(help_text="The metric query to execute.")+++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.")+++class _MetricQueryResponseSerializer(serializers.Serializer):+ results = _MetricQueryPointSerializer(many=True, help_text="Time-bucketed points, ordered by time ascending.")++@extend_schema(tags=["metrics"])class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "metrics"@@ -42,3 +78,37 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):)return Response({"hasMetrics": has_metrics}, status=status.HTTP_200_OK)++ @extend_schema(request=_MetricQueryRequestSerializer, responses={200: _MetricQueryResponseSerializer})+ @action(detail=False, methods=["POST"], required_scopes=["metrics:read"])+ def query(self, request: Request, *args, **kwargs) -> Response:+ tag_queries(product=Product.METRICS, feature=Feature.QUERY)++ body = _MetricQueryRequestSerializer(data=request.data)+ body.is_valid(raise_exception=True)+ query_data = body.validated_data["query"]++ 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"],+ date_from=query_data["dateFrom"],+ date_to=date_to,+ )+ except ValueError as exc:+ raise ParseError(str(exc))++ report_user_action(+ request.user,+ "metrics query ran",+ {+ "aggregation": query_data["aggregation"],+ "result_count": len(results),+ },+ team=self.team,+ request=request,+ )++ return Response({"results": results}, 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.pynew file mode 100644index 000000000000..5c4296591c4f--- /dev/null+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -0,0 +1,208 @@+import json+import datetime as dt++from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from django.utils import timezone++from parameterized import parameterized+from rest_framework import status++from posthog.clickhouse.client import sync_execute++from products.metrics.backend.metric_query_runner import MetricQueryRunner, _pick_interval+++def _insert_metric_row(+ *,+ team_id: int,+ metric_name: str,+ value: float,+ timestamp: dt.datetime,+ metric_type: str = "gauge",+) -> None:+ """Insert a single row into the local `metrics1` table.++ Uses the same shape `rust/capture-logs/src/metric_record.rs` emits, with+ fields the test doesn't care about set to empty/default.+ """+ row = {+ "uuid": "019e6bc4-4897-77d0-ab21-56ba3e2fe535",+ "team_id": team_id,+ "trace_id": "",+ "span_id": "",+ "trace_flags": 0,+ "timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),+ "observed_timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S.%f"),+ "service_name": "test-service",+ "metric_name": metric_name,+ "metric_type": metric_type,+ "value": value,+ "count": 1,+ "histogram_bounds": [],+ "histogram_counts": [],+ "unit": "",+ "aggregation_temporality": "cumulative",+ "is_monotonic": False,+ "resource_attributes": {},+ "instrumentation_scope": "",+ "attributes_map_str": {},+ "attributes_map_float": {},+ }+ sync_execute(f"INSERT INTO metrics1 FORMAT JSONEachRow {json.dumps(row)}")+++class TestPickInterval:+ @parameterized.expand(+ [+ # 60 buckets at 1 min each+ ("1h_range_picks_minute", dt.timedelta(hours=1), "minute"),+ # 24 buckets, comfortably under the ~60 target+ ("1d_range_picks_hour", dt.timedelta(days=1), "hour"),+ # 30 buckets; finer intervals all exceed the target+ ("30d_range_picks_day", dt.timedelta(days=30), "day"),+ ]+ )+ def test_pick_interval(self, _name: str, delta: dt.timedelta, expected: str) -> None:+ start = dt.datetime(2026, 1, 1, 0, 0, 0, tzinfo=dt.UTC)+ assert _pick_interval(start, start + delta) == expected+++class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")++ def test_rejects_unsupported_aggregation(self):+ with self.assertRaises(ValueError):+ MetricQueryRunner(+ team=self.team,+ metric_name="x",+ aggregation="median",+ date_from=timezone.now() - dt.timedelta(hours=1),+ date_to=timezone.now(),+ )++ def test_rejects_inverted_date_range(self):+ now = timezone.now()+ with self.assertRaises(ValueError):+ MetricQueryRunner(+ team=self.team,+ metric_name="x",+ aggregation="sum",+ date_from=now,+ date_to=now - dt.timedelta(hours=1),+ )++ def test_returns_empty_for_no_data(self):+ runner = MetricQueryRunner(+ team=self.team,+ metric_name="http.server.duration",+ aggregation="sum",+ date_from=timezone.now() - dt.timedelta(hours=1),+ date_to=timezone.now(),+ )+ self.assertEqual(runner.run(), [])++ def test_aggregates_sum_per_bucket(self):+ anchor = timezone.now().replace(microsecond=0)+ _insert_metric_row(+ team_id=self.team.id, metric_name="m1", value=2.0, timestamp=anchor - dt.timedelta(minutes=5)+ )+ _insert_metric_row(+ team_id=self.team.id, metric_name="m1", value=3.0, timestamp=anchor - dt.timedelta(minutes=5)+ )+ _insert_metric_row(+ team_id=self.team.id, metric_name="m1", value=4.0, timestamp=anchor - dt.timedelta(minutes=20)+ )+ # Different metric — should be filtered out.+ _insert_metric_row(+ team_id=self.team.id, metric_name="m2", value=99.0, timestamp=anchor - dt.timedelta(minutes=5)+ )++ runner = MetricQueryRunner(+ team=self.team,+ metric_name="m1",+ aggregation="sum",+ date_from=anchor - dt.timedelta(hours=1),+ date_to=anchor,+ )+ results = runner.run()++ values_by_bucket = {row["time"]: row["value"] for row in results}+ self.assertEqual(sum(values_by_bucket.values()), 9.0)++ def test_respects_team_isolation(self):+ anchor = timezone.now().replace(microsecond=0)+ _insert_metric_row(team_id=99999, metric_name="m1", value=5.0, timestamp=anchor - dt.timedelta(minutes=5))++ runner = MetricQueryRunner(+ team=self.team,+ metric_name="m1",+ aggregation="sum",+ date_from=anchor - dt.timedelta(hours=1),+ date_to=anchor,+ )+ self.assertEqual(runner.run(), [])+++class TestMetricsQueryAPI(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")++ def test_query_requires_authentication(self):+ self.client.logout()+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={"query": {"metricName": "m1", "aggregation": "sum", "dateFrom": "2026-01-01T00:00:00Z"}},+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_query_validates_required_fields(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={"query": {"aggregation": "sum", "dateFrom": "2026-01-01T00:00:00Z"}},+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_query_validates_aggregation_choice(self):+ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={"query": {"metricName": "m1", "aggregation": "median", "dateFrom": "2026-01-01T00:00:00Z"}},+ content_type="application/json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_query_returns_aggregated_points(self):+ anchor = timezone.now().replace(microsecond=0)+ _insert_metric_row(+ team_id=self.team.id, metric_name="m1", value=1.0, timestamp=anchor - dt.timedelta(minutes=10)+ )+ _insert_metric_row(+ team_id=self.team.id, metric_name="m1", value=2.0, timestamp=anchor - dt.timedelta(minutes=10)+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/metrics/query",+ data={+ "query": {+ "metricName": "m1",+ "aggregation": "sum",+ "dateFrom": (anchor - dt.timedelta(hours=1)).isoformat(),+ "dateTo": anchor.isoformat(),+ }+ },+ content_type="application/json",+ )++ 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)diff --git a/products/metrics/frontend/MetricsScene.tsx b/products/metrics/frontend/MetricsScene.tsxindex be847901c365..069477a38355 100644--- a/products/metrics/frontend/MetricsScene.tsx+++ b/products/metrics/frontend/MetricsScene.tsx@@ -1,6 +1,6 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'-import { LemonBanner } from '@posthog/lemon-ui'+import { LemonBanner, LemonTabs } from '@posthog/lemon-ui'import { sceneConfigurations } from 'scenes/scenes'import { Scene, SceneExport } from 'scenes/sceneTypes'@@ -11,11 +11,17 @@ import { ProductKey } from '~/queries/schema/schema-general'import { MetricsSetupPrompt } from './components/MetricsSetupPrompt'import { MetricsSqlEditor } from './components/MetricsSqlEditor'+import { MetricsViewer } from './components/MetricsViewer'import { metricsIngestionLogic } from './metricsIngestionLogic'-import { metricsSceneLogic } from './metricsSceneLogic'+import { MetricsSceneActiveTab, metricsSceneLogic } from './metricsSceneLogic'export const METRICS_LOGIC_KEY = 'metrics'+const TABS: { key: MetricsSceneActiveTab; label: string }[] = [+ { key: 'viewer', label: 'Viewer' },+ { key: 'sql', label: 'SQL' },+]+export const scene: SceneExport = {component: MetricsScene,logic: metricsSceneLogic,@@ -31,7 +37,8 @@ export function MetricsScene(): JSX.Element {}const MetricsSceneContent = (): JSX.Element => {- const { tabId } = useValues(metricsSceneLogic)+ const { tabId, activeTab } = useValues(metricsSceneLogic)+ const { setActiveTab } = useActions(metricsSceneLogic)const { teamHasMetricsCheckFailed } = useValues(metricsIngestionLogic)return (@@ -56,9 +63,11 @@ const MetricsSceneContent = (): JSX.Element => {Unable to verify metrics setup. If you haven't configured metrics yet, check out our setup guide.</LemonBanner>)}+ <LemonTabs<MetricsSceneActiveTab> activeKey={activeTab} onChange={setActiveTab} tabs={TABS} sceneInset /><MetricsSetupPrompt><div className="flex flex-col gap-2 py-2 flex-1 min-h-0">- <MetricsSqlEditor id={tabId} />+ {activeTab === 'viewer' && <MetricsViewer id={tabId} />}+ {activeTab === 'sql' && <MetricsSqlEditor id={tabId} />}</div></MetricsSetupPrompt></>diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxnew file mode 100644index 000000000000..27dcd08838c7--- /dev/null+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -0,0 +1,179 @@+import { useActions, useValues } from 'kea'+import { useCallback, useEffect, useMemo } from 'react'++import { LemonInput, LemonSelect, SpinnerOverlay } from '@posthog/lemon-ui'++import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'+import { AnyScaleOptions, Sparkline } from 'lib/components/Sparkline'+import { dayjs } from 'lib/dayjs'+import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils'++import { DateMappingOption } from '~/types'++import { MetricAggregation, metricsViewerLogic } from './metricsViewerLogic'++const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [+ { value: 'sum', label: 'Sum' },+ { value: 'avg', label: 'Average' },+ { value: 'count', label: 'Count' },+ { value: 'p95', label: 'p95' },+]++// Mirrors the curated set used by `LogsViewer/Filters/DateRangeFilter`.+const DATE_OPTIONS: DateMappingOption[] = [+ { key: CUSTOM_OPTION_KEY, values: [] },+ {+ key: 'Last 5 minutes',+ values: ['-5M'],+ getFormattedDate: (date: dayjs.Dayjs): string => date.subtract(5, 'minute').format(DATE_TIME_FORMAT),+ defaultInterval: 'minute',+ },+ {+ key: 'Last 30 minutes',+ values: ['-30M'],+ getFormattedDate: (date: dayjs.Dayjs): string => date.subtract(30, 'minute').format(DATE_TIME_FORMAT),+ defaultInterval: 'minute',+ },+ {+ key: 'Last 1 hour',+ values: ['-1h'],+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(1, 'h'), date.endOf('d')),+ defaultInterval: 'hour',+ },+ {+ key: 'Last 24 hours',+ values: ['-24h'],+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(24, 'h'), date.endOf('d')),+ defaultInterval: 'hour',+ },+ {+ key: 'Last 7 days',+ values: ['-7d'],+ getFormattedDate: (date: dayjs.Dayjs): string => formatDateRange(date.subtract(7, 'd'), date.endOf('d')),+ defaultInterval: 'day',+ },+]++export interface MetricsViewerProps {+ id: string+}++export const MetricsViewer = ({ id }: MetricsViewerProps): JSX.Element => {+ const logic = metricsViewerLogic({ tabId: id })+ const {+ metricName,+ aggregation,+ dateFrom,+ dateTo,+ sparklineValues,+ sparklineLabels,+ queryResultsLoading,+ hasMetricName,+ } = useValues(logic)+ const { setMetricName, setAggregation, setDateFrom, setDateTo, fetchQueryResults } = useActions(logic)++ // Refetch whenever any filter changes — the loader breakpoint debounces input.+ useEffect(() => {+ fetchQueryResults({})+ }, [metricName, aggregation, dateFrom, dateTo]) // eslint-disable-line react-hooks/exhaustive-deps++ // Mirrors the format/timeUnit ladder LogsSparkline uses so the X-axis density+ // matches the selected range.+ const { timeUnit, tickFormat } = useMemo(() => {+ if (!sparklineLabels.length) {+ return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }+ }+ const first = dayjs(sparklineLabels[0])+ const last = dayjs(sparklineLabels[sparklineLabels.length - 1])+ const hoursDiff = last.diff(first, 'hours')+ if (hoursDiff <= 1) {+ return { timeUnit: 'second' as const, tickFormat: 'HH:mm:ss' }+ }+ if (hoursDiff <= 6) {+ return { timeUnit: 'minute' as const, tickFormat: 'HH:mm:ss' }+ }+ if (hoursDiff <= 48) {+ return { timeUnit: 'hour' as const, tickFormat: 'HH:mm' }+ }+ return { timeUnit: 'day' as const, tickFormat: 'D MMM HH:mm' }+ }, [sparklineLabels])++ const withXScale = useCallback(+ (scale: AnyScaleOptions): AnyScaleOptions =>+ ({+ ...scale,+ type: 'timeseries',+ ticks: {+ display: true,+ maxRotation: 0,+ maxTicksLimit: 6,+ font: { size: 10, lineHeight: 1 },+ callback: function (value: string | number) {+ return dayjs(value).format(tickFormat)+ },+ },+ time: { unit: timeUnit },+ }) as AnyScaleOptions,+ [timeUnit, tickFormat]+ )++ const renderLabel = useCallback((label: string): string => dayjs(label).format('D MMM YYYY HH:mm:ss'), [])++ const hasResults = sparklineValues.length > 0++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center gap-2">+ <LemonInput+ size="small"+ placeholder="Metric name (e.g. http.server.duration)"+ value={metricName}+ onChange={setMetricName}+ className="min-w-[300px]"+ />+ <LemonSelect+ size="small"+ value={aggregation}+ options={AGGREGATION_OPTIONS}+ onChange={(value) => setAggregation(value as MetricAggregation)}+ />+ <DateFilter+ size="small"+ dateFrom={dateFrom}+ dateTo={dateTo}+ dateOptions={DATE_OPTIONS}+ onChange={(changedDateFrom, changedDateTo) => {+ setDateFrom(changedDateFrom)+ setDateTo(changedDateTo)+ }}+ allowTimePrecision+ allowFixedRangeWithTime+ allowedRollingDateOptions={['minutes', 'hours', 'days', 'weeks']}+ use24HourFormat+ />+ </div>+ <div className="relative h-[360px] border rounded p-3">+ {!hasMetricName ? (+ <div className="h-full flex items-center justify-center text-secondary text-sm">+ Enter a metric name to see its time series.+ </div>+ ) : hasResults ? (+ <Sparkline+ type="line"+ data={[{ name: aggregation, values: sparklineValues, color: 'data-color-1' }]}+ labels={sparklineLabels}+ className="w-full h-full"+ withXScale={withXScale}+ renderLabel={renderLabel}+ />+ ) : !queryResultsLoading ? (+ <div className="h-full flex items-center justify-center text-secondary text-sm">+ No data for this metric in the selected range.+ </div>+ ) : null}+ {queryResultsLoading && <SpinnerOverlay />}+ </div>+ </div>+ )+}diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxnew file mode 100644index 000000000000..35526d09e6a0--- /dev/null+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -0,0 +1,106 @@+import { actions, kea, key, listeners, path, props, 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 type { metricsViewerLogicType } from './metricsViewerLogicType'++export type MetricAggregation = 'sum' | 'avg' | 'count' | 'p95'++export interface MetricsViewerLogicProps {+ tabId: string+}++export interface MetricsViewerPoint {+ time: string+ value: number+}++const DEFAULT_AGGREGATION: MetricAggregation = 'sum'+const DEFAULT_DATE_FROM = '-1h'+const NEW_QUERY_STARTED_ERROR_MESSAGE = 'A new metrics query started, cancelling the previous one'++const resolveDate = (value: string | null | undefined): string | null => {+ if (!value) {+ return null+ }+ const dj = dateStringToDayJs(value) ?? dayjs(value)+ return dj.isValid() ? dj.toISOString() : null+}++export const metricsViewerLogic = kea<metricsViewerLogicType>([+ path(['products', 'metrics', 'frontend', 'components', 'metricsViewerLogic']),+ props({} as MetricsViewerLogicProps),+ key((p) => p.tabId),+ actions({+ setMetricName: (metricName: string) => ({ metricName }),+ setAggregation: (aggregation: MetricAggregation) => ({ aggregation }),+ setDateFrom: (dateFrom: string | null) => ({ dateFrom }),+ setDateTo: (dateTo: string | null) => ({ dateTo }),+ // AbortController plumbing mirrors logsViewerDataLogic: a `cancelInProgress`+ // action aborts the previous controller before storing the new one.+ setQueryAbortController: (controller: AbortController | null) => ({ controller }),+ cancelInProgressQuery: (controller: AbortController | null) => ({ controller }),+ }),+ reducers({+ metricName: ['' as string, { setMetricName: (_, { metricName }) => metricName }],+ aggregation: [+ DEFAULT_AGGREGATION as MetricAggregation,+ { setAggregation: (_, { aggregation }) => aggregation },+ ],+ dateFrom: [DEFAULT_DATE_FROM as string | null, { setDateFrom: (_, { dateFrom }) => dateFrom }],+ dateTo: [null as string | null, { setDateTo: (_, { dateTo }) => dateTo }],+ queryAbortController: [+ null as AbortController | null,+ { setQueryAbortController: (_, { controller }) => controller },+ ],+ }),+ listeners(({ actions, values }) => ({+ cancelInProgressQuery: ({ controller }) => {+ if (values.queryAbortController !== null) {+ values.queryAbortController.abort(NEW_QUERY_STARTED_ERROR_MESSAGE)+ }+ actions.setQueryAbortController(controller)+ },+ })),+ loaders(({ values, actions }) => ({+ queryResults: [+ [] as MetricsViewerPoint[],+ {+ fetchQueryResults: async (_, breakpoint) => {+ const trimmedName = values.metricName.trim()+ if (!trimmedName) {+ return []+ }+ const dateFromISO = resolveDate(values.dateFrom)+ if (!dateFromISO) {+ return []+ }+ await breakpoint(300)+ 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 } : {}),+ },+ signal: controller.signal,+ })+ breakpoint()+ actions.setQueryAbortController(null)+ return response.results+ },+ },+ ],+ })),+ 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)],+ }),+])diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex 09932c511581..dfe7f93c001d 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -23,4 +23,55 @@ export interface AppMetricsTotalsResponseApi {totals: AppMetricsTotalsResponseApiTotals}+/**+ * * `sum` - sum+ * `avg` - avg+ * `count` - count+ * `p95` - p95+ */+export type AggregationEnumApi = (typeof AggregationEnumApi)[keyof typeof AggregationEnumApi]++export const AggregationEnumApi = {+ Sum: 'sum',+ Avg: 'avg',+ Count: 'count',+ P95: 'p95',+} as const++export interface _MetricQueryBodyApi {+ /**+ * Exact metric name to query (e.g. 'http.server.duration').+ * @maxLength 255+ */+ metricName: string+ /** Aggregation applied per time bucket.++ * `sum` - sum+ * `avg` - avg+ * `count` - count+ * `p95` - p95 */+ aggregation?: AggregationEnumApi+ /** Lower bound (inclusive) for the query range. ISO 8601. */+ dateFrom: string+ /** Upper bound (exclusive) for the query range. Defaults to now if omitted. */+ dateTo?: string+}++export interface _MetricQueryRequestApi {+ /** The metric query to execute. */+ query: _MetricQueryBodyApi+}++export interface _MetricQueryPointApi {+ /** Bucket start as ISO 8601 timestamp. */+ time: string+ /** Aggregated value for the bucket. */+ value: number+}++export interface _MetricQueryResponseApi {+ /** Time-bucketed points, ordered by time ascending. */+ results: _MetricQueryPointApi[]+}+export type MetricsHasMetricsRetrieve200 = { [key: string]: unknown }diff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.tsindex 1779f299aa5d..4d411a62918b 100644--- a/products/metrics/frontend/generated/api.ts+++ b/products/metrics/frontend/generated/api.ts@@ -8,7 +8,13 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'* PostHog API - generated* OpenAPI spec version: 1.0.0*/-import type { AppMetricsResponseApi, AppMetricsTotalsResponseApi, MetricsHasMetricsRetrieve200 } from './api.schemas'+import type {+ AppMetricsResponseApi,+ AppMetricsTotalsResponseApi,+ MetricsHasMetricsRetrieve200,+ _MetricQueryRequestApi,+ _MetricQueryResponseApi,+} from './api.schemas'export const getEventFilterMetricsRetrieveUrl = (projectId: string) => {return `/api/environments/${projectId}/event_filter/metrics/`@@ -65,3 +71,20 @@ export const metricsHasMetricsRetrieve = async (method: 'GET',})}++export const getMetricsQueryCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/metrics/query/`+}++export const metricsQueryCreate = async (+ projectId: string,+ _metricQueryRequestApi: _MetricQueryRequestApi,+ options?: RequestInit+): Promise<_MetricQueryResponseApi> => {+ return apiMutator<_MetricQueryResponseApi>(getMetricsQueryCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(_metricQueryRequestApi),+ })+}diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.tsindex e8a15d4e1b52..160a1422e751 100644--- a/products/metrics/frontend/generated/api.zod.ts+++ b/products/metrics/frontend/generated/api.zod.ts@@ -7,3 +7,33 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+import * as zod from 'zod'++export const metricsQueryCreateBodyQueryOneMetricNameMax = 255++export const metricsQueryCreateBodyQueryOneAggregationDefault = `sum`++export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({+ query: zod+ .object({+ metricName: zod+ .string()+ .max(metricsQueryCreateBodyQueryOneMetricNameMax)+ .describe("Exact metric name to query (e.g. 'http.server.duration')."),+ aggregation: zod+ .enum(['sum', 'avg', 'count', 'p95'])+ .describe('\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95')+ .default(metricsQueryCreateBodyQueryOneAggregationDefault)+ .describe(+ 'Aggregation applied per time bucket.\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95'+ ),+ dateFrom: zod.iso+ .datetime({ offset: true })+ .describe('Lower bound (inclusive) for the query range. ISO 8601.'),+ dateTo: zod.iso+ .datetime({ offset: true })+ .optional()+ .describe('Upper bound (exclusive) for the query range. Defaults to now if omitted.'),+ })+ .describe('The metric query to execute.'),+})diff --git a/products/metrics/frontend/metricsSceneLogic.tsx b/products/metrics/frontend/metricsSceneLogic.tsxindex ce1ba457b2d1..60b3a3c16404 100644--- a/products/metrics/frontend/metricsSceneLogic.tsx+++ b/products/metrics/frontend/metricsSceneLogic.tsx@@ -1,13 +1,23 @@-import { actions, kea, listeners, path, props, selectors } from 'kea'+import { actions, kea, listeners, path, props, reducers, selectors } from 'kea'+import { router } from 'kea-router'+import { syncSearchParams, updateSearchParams } from '@posthog/products-error-tracking/frontend/utils'++import { tabAwareActionToUrl } from 'lib/logic/scenes/tabAwareActionToUrl'import { tabAwareScene } from 'lib/logic/scenes/tabAwareScene'+import { tabAwareUrlToAction } from 'lib/logic/scenes/tabAwareUrlToAction'import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'+import { Params } from 'scenes/sceneTypes'import type { metricsSceneLogicType } from './metricsSceneLogicType'export const getMetricsSqlEditorTabId = (id: string): string => `metrics-sql-editor-${id}`+export type MetricsSceneActiveTab = 'viewer' | 'sql'+const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['viewer', 'sql']+export const DEFAULT_ACTIVE_TAB: MetricsSceneActiveTab = 'viewer'+export interface MetricsLogicProps {tabId: string}@@ -17,11 +27,47 @@ export const metricsSceneLogic = kea<metricsSceneLogicType>([path(['products', 'metrics', 'frontend', 'metricsSceneLogic']),tabAwareScene(),actions({+ setActiveTab: (activeTab: MetricsSceneActiveTab) => ({ activeTab }),keepSqlEditorMounted: (editorTabId: string) => ({ editorTabId }),}),+ reducers({+ activeTab: [DEFAULT_ACTIVE_TAB as MetricsSceneActiveTab, { setActiveTab: (_, { activeTab }) => activeTab }],+ }),selectors({tabId: [(_, p) => [p.tabId], (tabId: string) => tabId],}),+ tabAwareUrlToAction(({ actions, values, cache }) => {+ const urlToAction = (_: any, params: Params): void => {+ if (cache.isSyncingUrl) {+ return+ }+ const requested = params.activeTab+ if (+ typeof requested === 'string' &&+ VALID_ACTIVE_TABS.includes(requested as MetricsSceneActiveTab) &&+ requested !== values.activeTab+ ) {+ actions.setActiveTab(requested as MetricsSceneActiveTab)+ }+ }+ return { '*': urlToAction }+ }),+ tabAwareActionToUrl(({ values, cache }) => {+ const syncUrl = (): [string, Params, Record<string, any>, { replace: boolean }] => {+ cache.isSyncingUrl = true+ const result = syncSearchParams(router, (params: Params) => {+ updateSearchParams(params, 'activeTab', values.activeTab, DEFAULT_ACTIVE_TAB)+ return params+ })+ queueMicrotask(() => {+ cache.isSyncingUrl = false+ })+ return result+ }+ return {+ setActiveTab: () => syncUrl(),+ }+ }),listeners(({ cache }) => ({keepSqlEditorMounted: ({ editorTabId }) => {if (cache.sqlEditorTabId === editorTabId) {diff --git a/products/metrics/package.json b/products/metrics/package.jsonindex 7a495e0c05df..de444b9545da 100644--- a/products/metrics/package.json+++ b/products/metrics/package.json@@ -12,6 +12,7 @@},"peerDependencies": {"@posthog/icons": "*",+ "@posthog/products-error-tracking": "workspace:*","@types/react": "*","clsx": "*","react": "*"diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c24feaae5398..fff929bacd76 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -3797,6 +3797,22 @@ export namespace Schemas {total_duration_nano: number;}+ /**+ * * `sum` - sum+ * `avg` - avg+ * `count` - count+ * `p95` - p95+ */+ export type AggregationEnum = typeof AggregationEnum[keyof typeof AggregationEnum];+++ export const AggregationEnum = {+ Sum: 'sum',+ Avg: 'avg',+ Count: 'count',+ P95: 'p95',+ } as const;+export interface InsightsThresholdBounds {/** Alert fires when the value drops below this number. */lower?: number | null;@@ -38609,6 +38625,42 @@ export namespace Schemas {refreshing: boolean;}+ export interface _MetricQueryBody {+ /**+ * Exact metric name to query (e.g. 'http.server.duration').+ * @maxLength 255+ */+ metricName: string;+ /** Aggregation applied per time bucket.++ * `sum` - sum+ * `avg` - avg+ * `count` - count+ * `p95` - p95 */+ aggregation?: AggregationEnum;+ /** Lower bound (inclusive) for the query range. ISO 8601. */+ dateFrom: string;+ /** Upper bound (exclusive) for the query range. Defaults to now if omitted. */+ dateTo?: string;+ }++ export interface _MetricQueryPoint {+ /** Bucket start as ISO 8601 timestamp. */+ time: string;+ /** Aggregated value for the bucket. */+ value: number;+ }++ export interface _MetricQueryRequest {+ /** The metric query to execute. */+ query: _MetricQueryBody;+ }++ export interface _MetricQueryResponse {+ /** Time-bucketed points, ordered by time ascending. */+ results: _MetricQueryPoint[];+ }+/*** * `span` - span* `span_attribute` - span_attribute