: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 overview tab with ingestion status and service rollup (#87918)
Daniel Visca1518c8f396ff
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 763c76de1741..8d92186a6251 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6355,7 +6355,7 @@ snapshots:scenes-app-experiments--experiment-with-multi-step-funnel-metric--dark:hash: v1.k794b7964.980b559b32f54de08e32932b4d9e14e203c2ff084a7dd0fd16bce311dff6540e.RjlN-Zl7Betwf5MoCvu-4XAx75Dqu5OI8f_qbvOsQ20scenes-app-experiments--experiment-with-multi-step-funnel-metric--light:- hash: v1.k794b7964.367868849fda12a0ca273c93bb6ad407a9b2cf0d76399547554cb9573b148a52.dBY6JqKOHSKACw47AmxmGDfiFgohjeuEVq_JspPeh8k+ hash: v1.k794b7964.af14f7a5b3dfaf6798b66f81b80bb8ce6feb4e1052f198e93b2049956b2b0ab4.FvGIr17gWYEfiUdDTzI1vdffBD9QoChjzNbJukXbmZIscenes-app-experiments--experiment-with-multiple-metrics--dark:hash: v1.k794b7964.9a8e12167e506eda2587fc1ff4009fcd04818d71d5ebca5edae3886763cebf4f.pXfxrh4O5h1ylZCuDBDE0p_FcTT05xwy3XxaCdX1Tnwscenes-app-experiments--experiment-with-multiple-metrics--light:diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex a5f7d077b7f5..fce7cabb5ac8 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -26,6 +26,7 @@ from products.metrics.backend.facade.contracts import (MetricQueryClause,MetricQueryRequest,MetricSeries,+ MetricsOverview,)from products.metrics.backend.facade.enums import FilterOp, MetricAggregation, MetricTypefrom products.metrics.backend.formula import evaluate, parse_formula@@ -38,6 +39,7 @@ from products.metrics.backend.metric_attributes_query_runner import (from products.metrics.backend.metric_event_samples_query_runner import MetricEventSamplesQueryRunnerfrom products.metrics.backend.metric_names_query_runner import cached_metric_namesfrom products.metrics.backend.metric_query_runner import MetricQueryRunner+from products.metrics.backend.metrics_overview_query_runner import MetricsOverviewQueryRunner# MetricQueryRunner still speaks the legacy aggregation strings; this shrinks# as later PRs teach the runner the remaining MetricAggregation values.@@ -228,6 +230,17 @@ def list_metric_names(return cached_metric_names(team=team, search=search, limit=limit)+def get_metrics_overview(*, team: Team, lookback: dt.timedelta | None = None) -> MetricsOverview:+ """Ingestion rollup for the overview page: freshness of the newest+ datapoint plus window-scoped metric/series counts per service.++ Raises `ValueError` for a non-positive lookback.+ """+ if lookback is None:+ return MetricsOverviewQueryRunner(team=team).run()+ return MetricsOverviewQueryRunner(team=team, lookback=lookback).run()++def list_metric_attribute_keys(*,team: Team,diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.pyindex 435427d73891..73aaaa7f3d76 100644--- a/products/metrics/backend/facade/contracts.py+++ b/products/metrics/backend/facade/contracts.py@@ -309,6 +309,34 @@ class IncidentContext:object.__setattr__(self, "fired_at", self.fired_at.astimezone(dt.UTC))+@dataclass(frozen=True, slots=True)+class MetricsServiceOverview:+ """One service's ingestion rollup inside the overview window."""++ service_name: str+ metric_names: int+ series: int+ last_seen: str # ISO 8601+++@dataclass(frozen=True, slots=True)+class MetricsOverview:+ """The landing-page answer to "is anything ingesting": how fresh the+ newest datapoint is, plus window-scoped inventory counts per service.++ `last_seen` deliberately ignores the window — when ingestion stops, the+ window-scoped numbers go to zero but the status strip still needs to say+ how long ago the last datapoint arrived. None means never ingested (or+ everything aged past the series table's retention).+ """++ last_seen: str | None # ISO 8601+ metric_names: int+ series: int+ lookback_seconds: int+ services: tuple[MetricsServiceOverview, ...]++@dataclass(frozen=True, slots=True)class MetricSampleView:"""One raw reading, as it sits in storage before any reduction."""diff --git a/products/metrics/backend/metrics_overview_query_runner.py b/products/metrics/backend/metrics_overview_query_runner.pynew file mode 100644index 000000000000..21f8fd9d534a--- /dev/null+++ b/products/metrics/backend/metrics_overview_query_runner.py@@ -0,0 +1,143 @@+"""Ingestion rollup for the metrics overview page.++Reads `metric_series` only — one row per (metric, label-set) with a+materialized `last_seen`, sorted by `(team_id, metric_name,+series_fingerprint)` — so the landing page never scans the raw datapoint+table. Two queries: an unwindowed pass for freshness plus window-scoped+inventory counts, and a windowed GROUP BY service.++No FINAL, same argument as `MetricNamesQueryRunner`: ReplacingMergeTree+duplicates share the fingerprint, `max(last_seen)` picks the row FINAL would+keep, and `uniqExact(series_fingerprint)` counts duplicates once. The+freshness pass filters inside the aggregates rather than in WHERE because+`last_seen` must be the max over ALL retained series: when ingestion stops,+the window counts go to zero but the status strip still needs to say how+long ago the last datapoint arrived.+"""++import datetime as dt++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.database.schema.metrics import HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.client.connection import Workload+from posthog.dataclasses import frozen+from posthog.models import Team++from products.metrics.backend.facade.contracts import MetricsOverview, MetricsServiceOverview++# The overview tolerates partial results, so reads break at the budget instead+# of erroring the way the chart queries do. Mirrors MetricNamesQueryRunner.+_QUERY_SETTINGS = HogQLGlobalSettings(+ max_bytes_to_read=HOGQL_MAX_BYTES_TO_READ_FOR_METRICS_USER_QUERIES,+ read_overflow_mode="break",+)++# More services than this stops being an overview; the largest win.+MAX_SERVICES = 500++DEFAULT_LOOKBACK = dt.timedelta(days=1)+++@frozen+class _OverviewTotals:+ """Project-wide freshness and inventory counts, before the per-service split.++ `metric_names` and `series` are both counts of the window, so they are named+ rather than positional — swapping them would misreport the project silently.+ """++ last_seen: str | None+ metric_names: int+ series: int+++class MetricsOverviewQueryRunner:+ def __init__(self, team: Team, *, lookback: dt.timedelta = DEFAULT_LOOKBACK) -> None:+ if lookback <= dt.timedelta(0):+ raise ValueError("lookback must be positive")++ self.team = team+ self.lookback = lookback++ def _lookback_interval(self) -> ast.Call:+ return ast.Call(name="toIntervalSecond", args=[ast.Constant(value=int(self.lookback.total_seconds()))])++ def _run_totals(self) -> _OverviewTotals:+ # `last_seen_at`, not `last_seen`: HogQL registers select aliases before+ # resolving the aggregate filters and would shadow the table column.+ query = parse_select(+ """+ SELECT+ max(toNullable(last_seen)) AS last_seen_at,+ uniqExactIf(metric_name, last_seen > now() - {lookback}) AS metric_names,+ uniqExactIf(series_fingerprint, last_seen > now() - {lookback}) AS active_series+ FROM posthog.metric_series+ """,+ placeholders={"lookback": self._lookback_interval()},+ )+ assert isinstance(query, ast.SelectQuery)++ response = execute_hogql_query(+ query_type="MetricsOverviewTotalsQuery",+ query=query,+ team=self.team,+ workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now+ settings=_QUERY_SETTINGS,+ )+ if not response.results:+ return _OverviewTotals(last_seen=None, metric_names=0, series=0)+ last_seen, metric_names, series = response.results[0]+ return _OverviewTotals(+ last_seen=last_seen.isoformat() if last_seen is not None else None,+ metric_names=int(metric_names),+ series=int(series),+ )++ def _run_services(self) -> tuple[MetricsServiceOverview, ...]:+ query = parse_select(+ """+ SELECT+ service_name,+ uniqExact(metric_name) AS metric_names,+ uniqExact(series_fingerprint) AS series,+ max(last_seen) AS last_seen_at+ FROM posthog.metric_series+ WHERE last_seen > now() - {lookback}+ GROUP BY service_name+ ORDER BY series DESC, service_name ASC+ LIMIT {limit}+ """,+ placeholders={"lookback": self._lookback_interval(), "limit": ast.Constant(value=MAX_SERVICES)},+ )+ assert isinstance(query, ast.SelectQuery)++ response = execute_hogql_query(+ query_type="MetricsOverviewServicesQuery",+ query=query,+ team=self.team,+ workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now+ settings=_QUERY_SETTINGS,+ )+ return tuple(+ MetricsServiceOverview(+ service_name=row[0],+ metric_names=int(row[1]),+ series=int(row[2]),+ last_seen=row[3].isoformat(),+ )+ for row in response.results+ )++ def run(self) -> MetricsOverview:+ totals = self._run_totals()+ return MetricsOverview(+ last_seen=totals.last_seen,+ metric_names=totals.metric_names,+ series=totals.series,+ lookback_seconds=int(self.lookback.total_seconds()),+ services=self._run_services() if totals.last_seen is not None else (),+ )diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex 727e6b666688..e35e9f1d4545 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -26,6 +26,7 @@ from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRfrom products.metrics.backend.facade.api import (characterize_metric_anomaly,explain_metric_bucket,+ get_metrics_overview,list_metric_attribute_keys,list_metric_attribute_values,list_metric_event_samples,@@ -362,6 +363,33 @@ class _HasMetricsResponseSerializer(serializers.Serializer):hasMetrics = serializers.BooleanField(help_text="Whether the team has ingested any metrics.")+class _MetricsOverviewServiceSerializer(serializers.Serializer):+ service_name = serializers.CharField(help_text="Service that reported metrics inside the window.")+ metric_names = serializers.IntegerField(help_text="Distinct metric names this service reported in the window.")+ series = serializers.IntegerField(+ help_text="Distinct series (metric + label-set combinations) this service reported in the window."+ )+ last_seen = serializers.CharField(help_text="When this service's newest datapoint arrived, ISO 8601.")+++class _MetricsOverviewResponseSerializer(serializers.Serializer):+ last_seen = serializers.CharField(+ allow_null=True,+ help_text="When the newest datapoint arrived across all series, ISO 8601. Unlike the counts this ignores the window, so it still answers 'when did ingestion stop'. Null when nothing was ever ingested.",+ )+ metric_names = serializers.IntegerField(help_text="Distinct metric names reported inside the window.")+ series = serializers.IntegerField(+ help_text="Distinct series (metric + label-set combinations) reported inside the window."+ )+ lookback_seconds = serializers.IntegerField(+ help_text="Length of the rollup window in seconds, so consumers can label the counts."+ )+ services = _MetricsOverviewServiceSerializer(+ many=True,+ help_text="Per-service rollup for the window, largest series count first. Capped at the 500 largest.",+ )++class _MetricValuesParamsSerializer(serializers.Serializer):value = serializers.CharField(required=False,@@ -710,6 +738,33 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):return Response({"hasMetrics": has_metrics}, status=status.HTTP_200_OK)+ @extend_schema(responses={200: _MetricsOverviewResponseSerializer})+ @action(+ detail=False,+ methods=["GET"],+ required_scopes=["metrics:read"],+ throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],+ )+ def overview(self, request: Request, *args, **kwargs) -> Response:+ """Ingestion rollup for the overview page: freshness of the newest+ datapoint plus per-service metric/series counts over the last day."""+ tag_queries(product=Product.METRICS, feature=Feature.QUERY)++ overview = get_metrics_overview(team=self.team)++ report_user_action(+ request.user,+ "metrics overview viewed",+ {+ "service_count": len(overview.services),+ "has_ingested": overview.last_seen is not None,+ },+ team=self.team,+ request=request,+ )++ return Response(asdict(overview), status=status.HTTP_200_OK)+@extend_schema(parameters=[_MetricValuesParamsSerializer],responses={200: _MetricNamesResponseSerializer},diff --git a/products/metrics/backend/tests/test_metrics_overview_query_runner.py b/products/metrics/backend/tests/test_metrics_overview_query_runner.pynew file mode 100644index 000000000000..b8133edb1003--- /dev/null+++ b/products/metrics/backend/tests/test_metrics_overview_query_runner.py@@ -0,0 +1,149 @@+import datetime as dt++from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from django.utils import timezone++from rest_framework import status++from products.metrics.backend.metrics_overview_query_runner import MetricsOverviewQueryRunner+from products.metrics.backend.tests._seeder import seed_metric, seed_metric_event, truncate_metrics_tables+++class TestMetricsOverviewQueryRunner(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ truncate_metrics_tables()++ def test_rejects_non_positive_lookback(self):+ with self.assertRaises(ValueError):+ MetricsOverviewQueryRunner(team=self.team, lookback=dt.timedelta(0))++ def test_returns_empty_overview_for_no_data(self):+ overview = MetricsOverviewQueryRunner(team=self.team).run()++ self.assertIsNone(overview.last_seen)+ self.assertEqual(overview.metric_names, 0)+ self.assertEqual(overview.series, 0)+ self.assertEqual(overview.services, ())++ def test_rolls_up_services_within_the_window(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ # "api" reports two series of one metric (distinct label-sets) plus a+ # second metric; "worker" reports one metric. Distinct label-sets are+ # what makes series != metric_names, so a runner that counts the wrong+ # column collapses one of the two numbers.+ seed_metric(team_id=self.team.id, metric_name="http.duration", points=[(anchor, 1.0)], service_name="api")+ seed_metric(+ team_id=self.team.id,+ metric_name="http.duration",+ points=[(anchor - dt.timedelta(minutes=1), 2.0)],+ labels={"route": "/checkout"},+ service_name="api",+ )+ seed_metric(team_id=self.team.id, metric_name="queue.depth", points=[(anchor, 3.0)], service_name="api")+ seed_metric(team_id=self.team.id, metric_name="jobs.processed", points=[(anchor, 4.0)], service_name="worker")++ overview = MetricsOverviewQueryRunner(team=self.team).run()++ self.assertEqual(overview.metric_names, 3)+ self.assertEqual(overview.series, 4)+ assert overview.last_seen is not None+ self.assertEqual(dt.datetime.fromisoformat(overview.last_seen), anchor)++ self.assertEqual([s.service_name for s in overview.services], ["api", "worker"])+ api_row = overview.services[0]+ self.assertEqual(api_row.metric_names, 2)+ self.assertEqual(api_row.series, 3)+ self.assertEqual(dt.datetime.fromisoformat(api_row.last_seen), anchor)++ def test_quiet_project_keeps_overall_last_seen_but_lists_no_services(self):+ # The ingestion-stopped case: data exists but nothing reported inside+ # the window. The status strip needs last_seen to say how long ago+ # ingestion stopped, while the window-scoped numbers go to zero.+ stale = timezone.now().replace(microsecond=0) - dt.timedelta(days=3)+ seed_metric(team_id=self.team.id, metric_name="http.duration", points=[(stale, 1.0)], service_name="api")++ overview = MetricsOverviewQueryRunner(team=self.team, lookback=dt.timedelta(days=1)).run()++ assert overview.last_seen is not None+ self.assertEqual(dt.datetime.fromisoformat(overview.last_seen), stale)+ self.assertEqual(overview.metric_names, 0)+ self.assertEqual(overview.series, 0)+ self.assertEqual(overview.services, ())++ def test_window_excludes_stale_services(self):+ recent = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ stale = timezone.now().replace(microsecond=0) - dt.timedelta(days=3)+ seed_metric(team_id=self.team.id, metric_name="fresh.metric", points=[(recent, 1.0)], service_name="fresh")+ seed_metric(team_id=self.team.id, metric_name="old.metric", points=[(stale, 1.0)], service_name="stale")++ overview = MetricsOverviewQueryRunner(team=self.team, lookback=dt.timedelta(days=1)).run()++ self.assertEqual([s.service_name for s in overview.services], ["fresh"])+ self.assertEqual(overview.metric_names, 1)+ self.assertEqual(overview.series, 1)++ def test_dedupes_replacing_merge_tree_parts_without_final(self):+ # Two seeds of one label-set land two unmerged ReplacingMergeTree parts+ # for one fingerprint; the overview must still count one series.+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ for offset in (10, 1):+ seed_metric_event(+ team_id=self.team.id,+ metric_name="queue.depth",+ points=[(anchor - dt.timedelta(minutes=offset), 3.0)],+ metric_type="gauge",+ service_name="api",+ )++ overview = MetricsOverviewQueryRunner(team=self.team).run()++ self.assertEqual(overview.series, 1)+ self.assertEqual(overview.metric_names, 1)+ self.assertEqual([(s.service_name, s.series) for s in overview.services], [("api", 1)])++ def test_respects_team_isolation(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ seed_metric(team_id=99999, metric_name="other.team.metric", points=[(anchor, 1.0)])++ overview = MetricsOverviewQueryRunner(team=self.team).run()++ self.assertIsNone(overview.last_seen)+ self.assertEqual(overview.services, ())+++class TestMetricsOverviewAPI(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ truncate_metrics_tables()++ def test_overview_requires_authentication(self):+ self.client.logout()+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/overview")+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_overview_returns_empty_shape_for_no_data(self):+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/overview")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ body = response.json()+ self.assertIsNone(body["last_seen"])+ self.assertEqual(body["services"], [])++ def test_overview_returns_service_rollup(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ seed_metric(team_id=self.team.id, metric_name="http.duration", points=[(anchor, 1.0)], service_name="api")++ response = self.client.get(f"/api/projects/{self.team.id}/metrics/overview")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ body = response.json()+ self.assertEqual(body["metric_names"], 1)+ self.assertEqual(body["series"], 1)+ self.assertGreater(body["lookback_seconds"], 0)+ self.assertEqual(len(body["services"]), 1)+ self.assertEqual(body["services"][0]["service_name"], "api")+ self.assertEqual(dt.datetime.fromisoformat(body["services"][0]["last_seen"]), anchor)diff --git a/products/metrics/frontend/MetricsScene.tsx b/products/metrics/frontend/MetricsScene.tsxindex 1f673c32d80a..d13812178925 100644--- a/products/metrics/frontend/MetricsScene.tsx+++ b/products/metrics/frontend/MetricsScene.tsx@@ -14,6 +14,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'import { metricNamePickerLogic } from './components/metricNamePickerLogic'import { MetricsFundamentals } from './components/MetricsFundamentals'+import { MetricsOverview } from './components/MetricsOverview'import { MetricsSetupPrompt } from './components/MetricsSetupPrompt'import { MetricsSqlEditor } from './components/MetricsSqlEditor'import { metricsUsageTrackingLogic } from './components/metricsUsageTrackingLogic'@@ -25,6 +26,7 @@ import { MetricsSceneActiveTab, metricsSceneLogic } from './metricsSceneLogic'export const METRICS_LOGIC_KEY = 'metrics'const TABS: { key: MetricsSceneActiveTab; label: string; 'data-attr': string }[] = [+ { key: 'overview', label: 'Overview', 'data-attr': 'metrics-scene-tab-overview' },{ key: 'viewer', label: 'Viewer', 'data-attr': 'metrics-scene-tab-viewer' },{ key: 'sql', label: 'SQL', 'data-attr': 'metrics-scene-tab-sql' },{ key: 'fundamentals', label: 'Fundamentals', 'data-attr': 'metrics-scene-tab-fundamentals' },@@ -59,6 +61,7 @@ const MetricsSceneContent = (): JSX.Element => {AccessControlLevel.Viewer)const tabDisabledReasons: Record<MetricsSceneActiveTab, string | null> = {+ overview: metricsViewerDisabledReason,viewer: metricsViewerDisabledReason,sql: metricsSqlDisabledReason,fundamentals: metricsViewerDisabledReason,@@ -107,6 +110,7 @@ const MetricsSceneContent = (): JSX.Element => {/><MetricsSetupPrompt><div className="flex flex-col gap-2 py-2 flex-1 min-h-0">+ {activeTab === 'overview' && <MetricsOverview />}{activeTab === 'viewer' && <MetricsViewer />}{activeTab === 'sql' && <MetricsSqlEditor />}{activeTab === 'fundamentals' && <MetricsFundamentals />}diff --git a/products/metrics/frontend/components/MetricsOverview.tsx b/products/metrics/frontend/components/MetricsOverview.tsxnew file mode 100644index 000000000000..ab8d9dc94398--- /dev/null+++ b/products/metrics/frontend/components/MetricsOverview.tsx@@ -0,0 +1,134 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonTable, LemonTag, Link, Spinner } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { dayjs } from 'lib/dayjs'+import { humanFriendlyNumber } from 'lib/utils/numbers'++import type { _MetricsOverviewServiceApi } from '../generated/api.schemas'+import { STALE_AFTER_MS, metricsOverviewLogic } from './metricsOverviewLogic'++const isStale = (lastSeen: string): boolean => dayjs().diff(dayjs(lastSeen)) > STALE_AFTER_MS++const OverviewStat = ({ label, value, caption }: { label: string; value: number; caption: string }): JSX.Element => (+ <div className="flex flex-col border rounded p-4 flex-1 min-w-40">+ <span className="text-2xl font-semibold">{humanFriendlyNumber(value)}</span>+ <span className="text-sm">{label}</span>+ <span className="text-xs text-secondary">{caption}</span>+ </div>+)++const IngestionStatus = ({ lastSeen }: { lastSeen: string | null }): JSX.Element => {+ if (lastSeen === null) {+ return (+ <LemonBanner+ type="info"+ action={{ to: 'https://posthog.com/docs/metrics', targetBlank: true, children: 'Setup guide' }}+ >+ No metrics have arrived yet. Follow the setup guide to start sending them.+ </LemonBanner>+ )+ }++ if (isStale(lastSeen)) {+ return (+ <LemonBanner+ type="warning"+ action={{+ to: 'https://posthog.com/docs/metrics',+ targetBlank: true,+ children: 'Troubleshoot setup',+ }}+ >+ No metrics received in the last 15 minutes. The last datapoint arrived <TZLabel time={lastSeen} />.+ Check that your exporters and agents are still running.+ </LemonBanner>+ )+ }++ return (+ <div className="flex items-center gap-2 px-3 py-1.5 border border-accent rounded self-start">+ <div className="relative flex items-center justify-center">+ <div className="absolute w-3 h-3 border-2 border-accent rounded-full animate-ping" />+ <div className="w-2 h-2 bg-accent rounded-full" />+ </div>+ <span className="text-sm">+ Receiving metrics. Last datapoint <TZLabel time={lastSeen} />.+ </span>+ </div>+ )+}++export const MetricsOverview = (): JSX.Element => {+ const { overview, overviewLoading } = useValues(metricsOverviewLogic)+ const { viewService } = useActions(metricsOverviewLogic)++ if (!overview) {+ return (+ <div className="flex justify-center py-8">+ <Spinner />+ </div>+ )+ }++ const windowHours = Math.round(overview.lookback_seconds / 3600)+ const windowLabel = `Last ${windowHours} hours`++ return (+ <div className="flex flex-col gap-4">+ <IngestionStatus lastSeen={overview.last_seen} />+ <div className="flex flex-wrap gap-2">+ <OverviewStat label="Services" value={overview.services.length} caption={windowLabel} />+ <OverviewStat label="Metric names" value={overview.metric_names} caption={windowLabel} />+ <OverviewStat label="Active series" value={overview.series} caption={windowLabel} />+ </div>+ <LemonTable+ dataSource={overview.services as _MetricsOverviewServiceApi[]}+ loading={overviewLoading && overview.services.length === 0}+ rowKey="service_name"+ emptyState={`No services have reported metrics in the ${windowLabel.toLowerCase()}.`}+ columns={[+ {+ title: 'Service',+ key: 'service_name',+ render: (_, service) => (+ <Link+ data-attr="metrics-overview-service-link"+ title="View this service's metrics in the viewer"+ onClick={() => viewService(service.service_name)}+ >+ {service.service_name || 'unknown'}+ </Link>+ ),+ },+ {+ title: 'Metrics',+ key: 'metric_names',+ align: 'right',+ render: (_, service) => humanFriendlyNumber(service.metric_names),+ sorter: (a, b) => a.metric_names - b.metric_names,+ },+ {+ title: 'Active series',+ key: 'series',+ align: 'right',+ render: (_, service) => humanFriendlyNumber(service.series),+ sorter: (a, b) => a.series - b.series,+ },+ {+ title: 'Last seen',+ key: 'last_seen',+ render: (_, service) => (+ <span className="flex items-center gap-2">+ <TZLabel time={service.last_seen} />+ {isStale(service.last_seen) && <LemonTag type="warning">quiet</LemonTag>}+ </span>+ ),+ sorter: (a, b) => a.last_seen.localeCompare(b.last_seen),+ },+ ]}+ />+ </div>+ )+}diff --git a/products/metrics/frontend/components/metricsOverviewLogic.test.ts b/products/metrics/frontend/components/metricsOverviewLogic.test.tsnew file mode 100644index 000000000000..8a4f95f7913b--- /dev/null+++ b/products/metrics/frontend/components/metricsOverviewLogic.test.ts@@ -0,0 +1,87 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'++import { metricsOverviewRetrieve, metricsValuesRetrieve } from '../generated/api'+import type { _MetricsOverviewResponseApi } from '../generated/api.schemas'+import { metricsSceneLogic } from '../metricsSceneLogic'+import { metricsOverviewLogic } from './metricsOverviewLogic'+import { metricsViewerLogic } from './metricsViewerLogic'++jest.mock('../generated/api', () => ({+ metricsAttributeValuesRetrieve: jest.fn(),+ metricsAttributesRetrieve: jest.fn(),+ metricsCharacterizeCreate: jest.fn(),+ metricsExplainCreate: jest.fn(),+ metricsHasMetricsRetrieve: jest.fn(),+ metricsOverviewRetrieve: jest.fn(),+ metricsQueryCreate: jest.fn(),+ metricsSamplesCreate: jest.fn(),+ metricsValuesRetrieve: jest.fn(),+}))++const OVERVIEW_FIXTURE: _MetricsOverviewResponseApi = {+ last_seen: '2026-08-21T10:00:00+00:00',+ metric_names: 3,+ series: 4,+ lookback_seconds: 86400,+ services: [+ { service_name: 'api', metric_names: 2, series: 3, last_seen: '2026-08-21T10:00:00+00:00' },+ { service_name: 'worker', metric_names: 1, series: 1, last_seen: '2026-08-21T09:00:00+00:00' },+ ],+}++describe('metricsOverviewLogic', () => {+ let logic: ReturnType<typeof metricsOverviewLogic.build>++ beforeEach(() => {+ window.POSTHOG_APP_CONTEXT = {+ ...window.POSTHOG_APP_CONTEXT,+ resource_access_control: {+ ...window.POSTHOG_APP_CONTEXT?.resource_access_control,+ [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,+ },+ } as AppContext+ initKeaTests()+ jest.mocked(metricsOverviewRetrieve).mockReset()+ jest.mocked(metricsOverviewRetrieve).mockResolvedValue(OVERVIEW_FIXTURE as any)+ // The name picker mounts alongside the viewer logic and loads on mount.+ jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: [] } as any)+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('loads the overview on mount', async () => {+ logic = metricsOverviewLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadOverviewSuccess']).toMatchValues({+ overview: OVERVIEW_FIXTURE,+ })+ })++ // The row click is the overview -> viewer handoff. Asserting the chip alone is not+ // enough: the viewer drops filter values it cannot send, so a chip can render while+ // the query goes out unfiltered. These assert `queryFilters` — what actually reaches+ // the API — including the "unknown" row, whose service_name is empty.+ it.each([+ ['a named service', 'api', { key: 'service_name', op: 'eq', value: 'api' }],+ ['the unknown service', '', { key: 'service_name', op: 'regex', value: '^$' }],+ ])('viewService sends a service filter for %s and switches tab', async (_name, serviceName, expected) => {+ logic = metricsOverviewLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.viewService(serviceName as string)+ }).toDispatchActions([+ metricsViewerLogic.actionTypes.setFilterGroup,+ metricsSceneLogic.actionTypes.setActiveTab,+ ])++ expect(metricsSceneLogic.values.activeTab).toBe('viewer')+ expect(metricsViewerLogic.values.queryFilters).toEqual([expected])+ })+})diff --git a/products/metrics/frontend/components/metricsOverviewLogic.tsx b/products/metrics/frontend/components/metricsOverviewLogic.tsxnew file mode 100644index 000000000000..dff021ed4fcc--- /dev/null+++ b/products/metrics/frontend/components/metricsOverviewLogic.tsx@@ -0,0 +1,115 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'++import { metricsOverviewRetrieve } from '../generated/api'+import type { _MetricsOverviewResponseApi } from '../generated/api.schemas'+import { canViewMetrics } from '../metricsAccess'+import { metricsSceneLogic } from '../metricsSceneLogic'+import { metricsViewerLogic } from './metricsViewerLogic'++// Long enough to keep the landing page cheap, short enough that "receiving+// metrics" flips to a warning within a minute of ingestion stopping.+export const OVERVIEW_REFRESH_MS = 30_000++// The scrape agent defaults to 15s scrapes and the SDKs flush every 10s, so a+// quarter hour of silence means a sender stopped, not a slow interval.+export const STALE_AFTER_MS = 15 * 60 * 1000++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsOverviewLogicValues {+ currentTeamId: number | null // teamLogic+ overview: _MetricsOverviewResponseApi | null+ overviewLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsOverviewLogicActions {+ setActiveTab: (activeTab: import('../metricsSceneLogic').MetricsSceneActiveTab) => {+ activeTab: import('../metricsSceneLogic').MetricsSceneActiveTab+ } // metricsSceneLogic+ setFilterGroup: (filterGroup: UniversalFiltersGroup) => {+ filterGroup: UniversalFiltersGroup+ } // metricsViewerLogic+ loadOverview: () => any+ loadOverviewFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadOverviewSuccess: (+ overview: _MetricsOverviewResponseApi | null,+ payload?: any+ ) => {+ overview: _MetricsOverviewResponseApi | null+ payload?: any+ }+ viewService: (serviceName: string) => {+ serviceName: string+ }+}++export type metricsOverviewLogicType = MakeLogicType<metricsOverviewLogicValues, metricsOverviewLogicActions>++const serviceFilterGroup = (serviceName: string): UniversalFiltersGroup => {+ // A sender that omits the `service.name` resource attribute lands with an empty+ // service_name, which the table shows as "unknown". The viewer drops empty filter+ // values so a half-typed chip cannot fire a query, so an exact match on "" would+ // leave the viewer unfiltered while still showing a service chip. Match that group+ // as an anchored regex, which survives the same pipeline.+ const matcher = serviceName+ ? { value: [serviceName], operator: PropertyOperator.Exact }+ : { value: ['^$'], operator: PropertyOperator.Regex }++ return {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [{ type: PropertyFilterType.MetricAttribute, key: 'service_name', ...matcher }],+ },+ ],+ }+}++export const metricsOverviewLogic = kea<metricsOverviewLogicType>([+ path(['products', 'metrics', 'frontend', 'components', 'metricsOverviewLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ actions: [metricsViewerLogic, ['setFilterGroup'], metricsSceneLogic, ['setActiveTab']],+ })),+ actions({+ viewService: (serviceName: string) => ({ serviceName }),+ }),+ loaders(({ values }) => ({+ overview: {+ __default: null as _MetricsOverviewResponseApi | null,+ loadOverview: async (): Promise<_MetricsOverviewResponseApi | null> => {+ if (!canViewMetrics()) {+ return values.overview+ }+ return await metricsOverviewRetrieve(String(values.currentTeamId))+ },+ },+ })),+ listeners(({ actions }) => ({+ // A service row click lands the user in the viewer already narrowed to+ // that service, so the picker only offers metrics it actually reports.+ viewService: ({ serviceName }) => {+ actions.setFilterGroup(serviceFilterGroup(serviceName))+ actions.setActiveTab('viewer')+ },+ })),+ afterMount(({ actions, cache }) => {+ actions.loadOverview()+ cache.disposables.add(() => {+ const pollTimer = window.setInterval(() => actions.loadOverview(), OVERVIEW_REFRESH_MS)+ return () => clearInterval(pollTimer)+ })+ }),+])diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex 6a3609eee707..da0eb23b3fdd 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -506,6 +506,33 @@ export interface _HasMetricsResponseApi {hasMetrics: boolean}+export interface _MetricsOverviewServiceApi {+ /** Service that reported metrics inside the window. */+ service_name: string+ /** Distinct metric names this service reported in the window. */+ metric_names: number+ /** Distinct series (metric + label-set combinations) this service reported in the window. */+ series: number+ /** When this service's newest datapoint arrived, ISO 8601. */+ last_seen: string+}++export interface _MetricsOverviewResponseApi {+ /**+ * When the newest datapoint arrived across all series, ISO 8601. Unlike the counts this ignores the window, so it still answers 'when did ingestion stop'. Null when nothing was ever ingested.+ * @nullable+ */+ last_seen: string | null+ /** Distinct metric names reported inside the window. */+ metric_names: number+ /** Distinct series (metric + label-set combinations) reported inside the window. */+ series: number+ /** Length of the rollup window in seconds, so consumers can label the counts. */+ lookback_seconds: number+ /** Per-service rollup for the window, largest series count first. Capped at the 500 largest. */+ services: _MetricsOverviewServiceApi[]+}+export interface _MetricGroupByApi {/*** Attribute name to split series by (e.g. 'k8s.pod.name', 'env').diff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.tsindex b6ff3cadd7cb..1c01893fbc50 100644--- a/products/metrics/frontend/generated/api.ts+++ b/products/metrics/frontend/generated/api.ts@@ -26,6 +26,7 @@ import type {_MetricQueryResponseApi,_MetricSamplesRequestApi,_MetricSamplesResponseApi,+ _MetricsOverviewResponseApi,} from './api.schemas'export const getEventFilterMetricsRetrieveUrl = (projectId: string) => {@@ -193,6 +194,24 @@ export const metricsHasMetricsRetrieve = async (})}+export const getMetricsOverviewRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/metrics/overview/`+}++/**+ * Ingestion rollup for the overview page: freshness of the newest+ * datapoint plus per-service metric/series counts over the last day.+ */+export const metricsOverviewRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<_MetricsOverviewResponseApi> => {+ return apiMutator<_MetricsOverviewResponseApi>(getMetricsOverviewRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}+export const getMetricsQueryCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/metrics/query/`}diff --git a/products/metrics/frontend/metricsSceneLogic.tsx b/products/metrics/frontend/metricsSceneLogic.tsxindex 59fad689c073..3d7533631d5d 100644--- a/products/metrics/frontend/metricsSceneLogic.tsx+++ b/products/metrics/frontend/metricsSceneLogic.tsx@@ -10,9 +10,9 @@ import { Params } from 'scenes/sceneTypes'export const METRICS_SQL_EDITOR_TAB_ID = 'metrics-sql-editor'-export type MetricsSceneActiveTab = 'viewer' | 'sql' | 'fundamentals'-const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['viewer', 'sql', 'fundamentals']-export const DEFAULT_ACTIVE_TAB: MetricsSceneActiveTab = 'viewer'+export type MetricsSceneActiveTab = 'overview' | 'viewer' | 'sql' | 'fundamentals'+const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['overview', 'viewer', 'sql', 'fundamentals']+export const DEFAULT_ACTIVE_TAB: MetricsSceneActiveTab = 'overview'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface metricsSceneLogicValues {diff --git a/products/metrics/mcp/tools.yaml b/products/metrics/mcp/tools.yamlindex 4fd160ab08f1..9ec372dde715 100644--- a/products/metrics/mcp/tools.yaml+++ b/products/metrics/mcp/tools.yaml@@ -50,6 +50,9 @@ tools:metrics-has-metrics-retrieve:operation: metrics_has_metrics_retrieveenabled: false+ metrics-overview-retrieve:+ operation: metrics_overview_retrieve+ enabled: falsemetrics-samples-create:operation: metrics_samples_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a40fa197735d..d8a98567d3e3 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -85396,6 +85396,33 @@ export namespace Schemas {results: _MetricEventSample[];}+ export interface _MetricsOverviewService {+ /** Service that reported metrics inside the window. */+ service_name: string;+ /** Distinct metric names this service reported in the window. */+ metric_names: number;+ /** Distinct series (metric + label-set combinations) this service reported in the window. */+ series: number;+ /** When this service's newest datapoint arrived, ISO 8601. */+ last_seen: string;+ }++ export interface _MetricsOverviewResponse {+ /**+ * When the newest datapoint arrived across all series, ISO 8601. Unlike the counts this ignores the window, so it still answers 'when did ingestion stop'. Null when nothing was ever ingested.+ * @nullable+ */+ last_seen: string | null;+ /** Distinct metric names reported inside the window. */+ metric_names: number;+ /** Distinct series (metric + label-set combinations) reported inside the window. */+ series: number;+ /** Length of the rollup window in seconds, so consumers can label the counts. */+ lookback_seconds: number;+ /** Per-service rollup for the window, largest series count first. Capped at the 500 largest. */+ services: _MetricsOverviewService[];+ }+/*** * `exact` - exact* * `is_not` - is_not