: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 an Explore catalog to make metrics browsable (#94626)
Daniel Visca0611a8d52d95
diff --git a/products/metrics/backend/anomaly.py b/products/metrics/backend/anomaly.pyindex 150383f539f1..f40bdc68185e 100644--- a/products/metrics/backend/anomaly.py+++ b/products/metrics/backend/anomaly.py@@ -59,7 +59,7 @@ _AGGREGATION_BY_TYPE = {def _default_aggregation(team: Team, metric_name: str) -> tuple[str, float | None]:"""Pick an aggregation from the metric's OTel type: counters get `rate`,gauges `avg`, histograms `histogram_quantile(0.95)`."""- for row in MetricNamesQueryRunner(team=team, search=metric_name, limit=5).run():+ for row in MetricNamesQueryRunner(team=team, search=metric_name, limit=5, include_sparklines=False).run():if row["name"] == metric_name:aggregation = _AGGREGATION_BY_TYPE.get(row["metric_type"], "avg")return aggregation, 0.95 if aggregation == "histogram_quantile" else Nonediff --git a/products/metrics/backend/metric_names_query_runner.py b/products/metrics/backend/metric_names_query_runner.pyindex a78c25c2370b..bc9b429678b2 100644--- a/products/metrics/backend/metric_names_query_runner.py+++ b/products/metrics/backend/metric_names_query_runner.py@@ -56,6 +56,20 @@ METRIC_NAMES_CACHE_TTL = 60# and the bound keeps one request from building an unbounded IN list.MAX_PICKER_SERVICES = 50+# Sparklines summarize this window, downsampled to at most this many points. A+# card only needs the recent shape, so the window is far shorter than the name+# lookback and the point count is bounded to keep one row small.+SPARKLINE_WINDOW = dt.timedelta(hours=6)+SPARKLINE_MAX_POINTS = 24+++def _isoformat(value: Any) -> str | None:+ """ClickHouse hands back datetimes, but a driver or JSON round-trip can leave a+ string. The API serializer accepts ISO either way, so normalize without assuming."""+ if value is None:+ return None+ return value.isoformat() if hasattr(value, "isoformat") else str(value)+class MetricNamesQueryRunner:def __init__(@@ -66,6 +80,7 @@ class MetricNamesQueryRunner:limit: int = 100,lookback: dt.timedelta = dt.timedelta(days=7),services: Sequence[str] = (),+ include_sparklines: bool = True,) -> None:if limit <= 0 or limit > 1000:raise ValueError("limit must be in [1, 1000]")@@ -83,6 +98,10 @@ class MetricNamesQueryRunner:# selection: a sender that omits the `service.name` resource attribute# lands in the group the overview labels "unknown".self.services = tuple(sorted(set(services)))+ # Sparklines read `metric_samples`, whose ordering puts `timestamp`+ # behind `series_fingerprint`, so the scan is the expensive part of a+ # name lookup. Callers that only need the type (anomaly defaults) skip it.+ self.include_sparklines = include_sparklinesdef _build_query(self) -> ast.SelectQuery:# The alias is `last_seen_at`, not `last_seen`: HogQL registers select@@ -100,6 +119,7 @@ class MetricNamesQueryRunner:SELECTmetric_name AS name,any(metric_type) AS metric_type,+ any(unit) AS unit,max(last_seen) AS last_seen_atFROM posthog.metric_seriesWHERE last_seen > now() - {lookback}@@ -115,6 +135,7 @@ class MetricNamesQueryRunner:SELECTmetric_name AS name,any(metric_type) AS metric_type,+ any(unit) AS unit,max(last_seen) AS last_seen_atFROM posthog.metric_seriesWHERE last_seen > now() - {lookback}@@ -165,7 +186,113 @@ class MetricNamesQueryRunner:settings=_QUERY_SETTINGS,)- return [{"name": row[0], "metric_type": row[1]} for row in response.results]+ names = [row[0] for row in response.results]+ sparklines = self._sparklines(names) if self.include_sparklines else {}++ return [+ {+ "name": row[0],+ "metric_type": row[1],+ "unit": row[2],+ "last_seen": _isoformat(row[3]),+ "sparkline": sparklines.get(row[0], []),+ }+ for row in response.results+ ]++ def _sparklines(self, names: Sequence[str]) -> dict[str, list[float]]:+ """A small recent shape per metric, for the catalog cards.++ Reads `metric_samples` (raw emissions) rather than the pre-aggregated+ `metrics` table, so a series written without a metrics row still draws —+ the same reason the name list reads `metric_series`. Each metric is+ bucketed onto a fixed grid and averaged per bucket across its series; a+ card only shows direction and spikes, so per-series fidelity is not worth+ the rows it would cost. Only the names this page returned are read, so a+ scoped picker never scans the whole samples table.+ """+ if not names:+ return {}++ # The grid anchors to the query's `now()`: bucket edges land on the+ # window endpoints, so the window always holds exactly MAX_POINTS buckets+ # (a bare toStartOfInterval aligns to wall-clock boundaries and a window+ # starting mid-bucket intersects one extra).+ bucket_seconds = max(int(SPARKLINE_WINDOW.total_seconds()) // SPARKLINE_MAX_POINTS, 1)+ window_seconds = int(SPARKLINE_WINDOW.total_seconds())+ query = parse_select(+ """+ SELECT+ metric_name AS name,+ toDateTime(intDiv(toUnixTimestamp(timestamp) - toUnixTimestamp(now() - {window_interval}), {bucket_seconds}) * {bucket_seconds} + toUnixTimestamp(now() - {window_interval})) AS bucket_start,+ avg(value) AS bucket_value+ FROM posthog.metric_samples+ WHERE timestamp > now() - {window_interval}+ AND metric_name IN {names}+ AND series_fingerprint IN {series_scope}+ GROUP BY name, bucket_start+ ORDER BY name, bucket_start+ """,+ placeholders={+ "bucket_seconds": ast.Constant(value=bucket_seconds),+ "window_interval": ast.Call(name="toIntervalSecond", args=[ast.Constant(value=window_seconds)]),+ "names": ast.Tuple(exprs=[ast.Constant(value=name) for name in names]),+ # A sample carries no service column; its series_fingerprint is+ # the link back to the series row that does. Without this scope,+ # two services emitting one metric name share a card and a scoped+ # catalog draws a shape blended across services.+ "series_scope": self._series_scope_subquery(names),+ },+ )+ assert isinstance(query, ast.SelectQuery)++ response = execute_hogql_query(+ query_type="MetricNamesSparklineQuery",+ query=query,+ team=self.team,+ workload=Workload.LOGS,+ settings=_QUERY_SETTINGS,+ )++ sparklines: dict[str, list[float]] = {}+ for name, _bucket_start, bucket_value in response.results:+ sparklines.setdefault(name, []).append(float(bucket_value))+ return sparklines++ def _series_scope_subquery(self, names: Sequence[str]) -> ast.SelectQuery:+ """The series fingerprints, for these names, owned by the scoped services.++ Built as its own parsed query so the service predicate is attached with an+ explicit And the way `_build_query` does, not spliced into the SQL text.+ """+ lookback = ast.Call(name="toIntervalSecond", args=[ast.Constant(value=int(self.lookback.total_seconds()))])+ subquery = parse_select(+ """+ SELECT series_fingerprint+ FROM posthog.metric_series+ WHERE last_seen > now() - {lookback}+ AND metric_name IN {names}+ GROUP BY series_fingerprint+ """,+ placeholders={+ "lookback": lookback,+ "names": ast.Tuple(exprs=[ast.Constant(value=name) for name in names]),+ },+ )+ assert isinstance(subquery, ast.SelectQuery)+ assert subquery.where is not None+ if self.services:+ subquery.where = ast.And(+ exprs=[+ subquery.where,+ ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["service_name"]),+ right=ast.Tuple(exprs=[ast.Constant(value=service) for service in self.services]),+ ),+ ]+ )+ return subquerydef cached_metric_names(diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex 2e9b3fab58ab..58dae004ed1a 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -468,6 +468,17 @@ class _MetricNameSerializer(serializers.Serializer):metric_type = serializers.CharField(help_text="OTel metric type (gauge, sum, histogram, summary, exponential_histogram).")+ unit = serializers.CharField(+ required=False, allow_blank=True, help_text="Unit of the metric value, if any (e.g. 'ms', 'By')."+ )+ last_seen = serializers.DateTimeField(+ required=False, allow_null=True, help_text="When the newest datapoint for this metric arrived, ISO 8601."+ )+ sparkline = serializers.ListField(+ child=serializers.FloatField(),+ required=False,+ help_text="A small downsampled series of the metric's recent shape, for a sparkline.",+ )class _MetricNamesResponseSerializer(serializers.Serializer):diff --git a/products/metrics/backend/tests/test_metric_names_query_runner.py b/products/metrics/backend/tests/test_metric_names_query_runner.pyindex bd6a3084fd73..4f834e2aaf6c 100644--- a/products/metrics/backend/tests/test_metric_names_query_runner.py+++ b/products/metrics/backend/tests/test_metric_names_query_runner.py@@ -119,8 +119,21 @@ class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):metric_type="gauge",)- runner = MetricNamesQueryRunner(team=self.team)- self.assertEqual(runner.run(), [{"name": "queue.depth", "metric_type": "gauge"}])+ # Sparklines are off so the row shape stays about the series collapse,+ # not the bucket grid.+ runner = MetricNamesQueryRunner(team=self.team, include_sparklines=False)+ self.assertEqual(+ runner.run(),+ [+ {+ "name": "queue.depth",+ "metric_type": "gauge",+ "unit": "",+ "last_seen": (anchor - dt.timedelta(minutes=1)).isoformat(),+ "sparkline": [],+ }+ ],+ )def test_cache_covers_the_unsearched_list_only(self):with patch.object(MetricNamesQueryRunner, "run") as run:@@ -282,3 +295,151 @@ class TestMetricsValuesAPI(ClickhouseTestMixin, APIBaseTest):response = self.client.get(f"/api/projects/{self.team.id}/metrics/values?limit=0")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+++class TestMetricCatalogQueryRunner(ClickhouseTestMixin, APIBaseTest):+ """The catalog is the picker row plus what makes a card scannable: the unit,+ when the metric was last heard from, and a small sparkline of its recent+ shape. Sparkline points come from `metric_samples`, so a series written+ without a pre-aggregated `metrics` row still draws."""++ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ truncate_metrics_tables()+ cache.clear()++ def test_catalog_row_carries_unit_and_last_seen(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ seed_metric(+ team_id=self.team.id,+ metric_name="http.server.duration",+ points=[(anchor, 1.0)],+ metric_type="histogram",+ unit="ms",+ )++ runner = MetricNamesQueryRunner(team=self.team)+ row = next(r for r in runner.run() if r["name"] == "http.server.duration")++ self.assertEqual(row["unit"], "ms")+ # last_seen is an ISO string so the API layer can pass it straight through.+ self.assertIn("T", row["last_seen"])++ def test_sparkline_reflects_the_metric_shape(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=30)+ # A clear rise across the window: any faithful downsampling keeps the+ # last value above the first.+ points = [(anchor + dt.timedelta(minutes=i), float(i)) for i in range(30)]+ # Sparklines read metric_samples, so seed through the raw-sample path+ # (seed_metric writes only the pre-aggregated metrics row).+ seed_metric_event(team_id=self.team.id, metric_name="queue.depth", points=points, metric_type="gauge")++ runner = MetricNamesQueryRunner(team=self.team)+ row = next(r for r in runner.run() if r["name"] == "queue.depth")++ sparkline = row["sparkline"]+ self.assertGreater(len(sparkline), 1)+ self.assertLess(sparkline[0], sparkline[-1])++ def test_sparkline_is_bounded(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=120)+ points = [(anchor + dt.timedelta(minutes=i), float(i % 7)) for i in range(120)]+ # Sparklines read metric_samples, so seed through the raw-sample path.+ seed_metric_event(team_id=self.team.id, metric_name="busy.metric", points=points, metric_type="gauge")++ runner = MetricNamesQueryRunner(team=self.team)+ row = next(r for r in runner.run() if r["name"] == "busy.metric")++ # The bound is only meaningful against a card that has data to draw.+ self.assertGreater(len(row["sparkline"]), 1)+ self.assertLessEqual(len(row["sparkline"]), 24)++ def test_sparkline_reads_samples_without_a_preaggregated_row(self):+ # seed_metric_event writes metric_series + metric_samples and no metrics+ # row, so this fails if the sparkline goes back to aggregating posthog.metrics.+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=20)+ points = [(anchor + dt.timedelta(minutes=i), float(i)) for i in range(10)]+ seed_metric_event(team_id=self.team.id, metric_name="samples.only", points=points, metric_type="gauge")++ runner = MetricNamesQueryRunner(team=self.team)+ row = next(r for r in runner.run() if r["name"] == "samples.only")++ self.assertGreater(len(row["sparkline"]), 1)+ self.assertLess(row["sparkline"][0], row["sparkline"][-1])++ def test_metric_with_no_samples_has_empty_sparkline(self):+ # Samples older than the sparkline window leave the series row (and so+ # the card) in place but give it nothing to draw.+ old_anchor = timezone.now().replace(microsecond=0) - dt.timedelta(hours=10)+ seed_metric(+ team_id=self.team.id,+ metric_name="old.metric",+ points=[(old_anchor, 1.0)],+ metric_type="gauge",+ )++ runner = MetricNamesQueryRunner(team=self.team)+ row = next(r for r in runner.run() if r["name"] == "old.metric")++ self.assertEqual(row["sparkline"], [])++ def test_sparkline_scoped_to_services(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=20)+ for service, metric_name in (("web", "http.duration"), ("worker", "jobs.processed")):+ # Sparklines read metric_samples, so seed through the raw-sample path.+ seed_metric_event(+ team_id=self.team.id,+ metric_name=metric_name,+ points=[(anchor + dt.timedelta(minutes=i), float(i)) for i in range(10)],+ service_name=service,+ )++ runner = MetricNamesQueryRunner(team=self.team, services=["web"])+ rows = runner.run()++ self.assertEqual([r["name"] for r in rows], ["http.duration"])+ self.assertGreater(len(rows[0]["sparkline"]), 1)++ def test_sparkline_excludes_other_services_series(self):+ # web and worker emit the same metric name. A card scoped to web must+ # draw only web's series; an unscoped card averages both.+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=20)+ # Sparklines read metric_samples, so seed through the raw-sample path.+ seed_metric_event(+ team_id=self.team.id,+ metric_name="shared.metric",+ points=[(anchor + dt.timedelta(minutes=i), 100.0) for i in range(10)],+ metric_type="gauge",+ service_name="web",+ )+ seed_metric_event(+ team_id=self.team.id,+ metric_name="shared.metric",+ points=[(anchor + dt.timedelta(minutes=i), 1.0) for i in range(10)],+ metric_type="gauge",+ service_name="worker",+ )++ web_row = next(r for r in MetricNamesQueryRunner(team=self.team, services=["web"]).run())+ all_row = next(r for r in MetricNamesQueryRunner(team=self.team).run())++ # Non-empty first: `all()` on an empty sparkline passes vacuously, which+ # is how the unscoped-averaging bug slipped through before.+ self.assertGreater(len(web_row["sparkline"]), 1)+ self.assertGreater(len(all_row["sparkline"]), 1)+ self.assertTrue(all(v == 100.0 for v in web_row["sparkline"]))+ self.assertTrue(all(v < 100.0 for v in all_row["sparkline"]))++ def test_runner_can_skip_the_sparkline_scan(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ _seed_point(team_id=self.team.id, metric_name="m1", value=1.0, timestamp=anchor)++ with patch("products.metrics.backend.metric_names_query_runner.execute_hogql_query") as execute:+ execute.return_value.results = [("m1", "gauge", "", timezone.now())]+ rows = MetricNamesQueryRunner(team=self.team, include_sparklines=False).run()++ # One query for the names, none for the samples.+ self.assertEqual(execute.call_count, 1)+ self.assertEqual(rows[0]["sparkline"], [])diff --git a/products/metrics/frontend/MetricsScene.tsx b/products/metrics/frontend/MetricsScene.tsxindex 901ce9eaa2c0..970aee6728c6 100644--- a/products/metrics/frontend/MetricsScene.tsx+++ b/products/metrics/frontend/MetricsScene.tsx@@ -16,7 +16,10 @@ import { ProductKey } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType } from '~/types'import { metricNamePickerLogic } from './components/metricNamePickerLogic'+import { MetricsCatalog } from './components/MetricsCatalog'+import { metricsCatalogLogic } from './components/metricsCatalogLogic'import { MetricsFundamentals } from './components/MetricsFundamentals'+import { metricsFundamentalsLogic } from './components/metricsFundamentalsLogic'import { MetricsOverview } from './components/MetricsOverview'import { MetricsSqlEditor } from './components/MetricsSqlEditor'import { metricsUsageTrackingLogic } from './components/metricsUsageTrackingLogic'@@ -31,6 +34,7 @@ const METRICS_FEEDBACK_SURVEY_ID = '01a07c35-6be3-0000-16b3-4cd66a6873f3'const TABS: { key: MetricsSceneActiveTab; label: string; 'data-attr': string }[] = [{ key: 'overview', label: 'Overview', 'data-attr': 'metrics-scene-tab-overview' },+ { key: 'explore', label: 'Explore', 'data-attr': 'metrics-scene-tab-explore' },{ 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' },@@ -73,6 +77,7 @@ const MetricsSceneContent = (): JSX.Element => {)const tabDisabledReasons: Record<MetricsSceneActiveTab, string | null> = {overview: metricsViewerDisabledReason,+ explore: metricsViewerDisabledReason,viewer: metricsViewerDisabledReason,sql: metricsSqlDisabledReason,fundamentals: metricsViewerDisabledReason,@@ -83,6 +88,11 @@ const MetricsSceneContent = (): JSX.Element => {// Prime the metric-name list here rather than inside MetricsViewer, so the fetch// races the has_metrics check instead of waiting on the setup prompt to resolve.useMountedLogic(metricNamePickerLogic)+ // These two hold cross-tab state: a catalog card click preloads the viewer, and+ // the viewer's explain button preloads fundamentals. Mounted here, a tab flip+ // cannot unmount the logic and reset the handoff before the destination reads it.+ useMountedLogic(metricsCatalogLogic)+ useMountedLogic(metricsFundamentalsLogic)const onFeedbackClick = (): void => {posthog.displaySurvey(METRICS_FEEDBACK_SURVEY_ID)@@ -128,6 +138,7 @@ const MetricsSceneContent = (): JSX.Element => {/><div className="flex flex-col gap-2 py-2 flex-1 min-h-0">{effectiveTab === 'overview' && <MetricsOverview />}+ {effectiveTab === 'explore' && <MetricsCatalog />}{effectiveTab === 'viewer' && <MetricsViewer />}{effectiveTab === 'sql' && <MetricsSqlEditor />}{effectiveTab === 'fundamentals' && <MetricsFundamentals />}diff --git a/products/metrics/frontend/components/MetricsCatalog.tsx b/products/metrics/frontend/components/MetricsCatalog.tsxnew file mode 100644index 000000000000..488bab9fb903--- /dev/null+++ b/products/metrics/frontend/components/MetricsCatalog.tsx@@ -0,0 +1,112 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import { IconSearch } from '@posthog/icons'+import { LemonInput, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'++import { Sparkline } from 'lib/components/Sparkline'+import { TZLabel } from 'lib/components/TZLabel'++import { metricNamePickerLogic } from './metricNamePickerLogic'+import { MetricCatalogItem, metricsCatalogLogic } from './metricsCatalogLogic'++// A metric's OTel type says how to read it before it is opened. The one-liner is+// the catalog's main teaching surface: it turns a bare name into a sentence the+// reader can scan, and it matches the recommended aggregation the viewer applies.+const describeMetric = (item: MetricCatalogItem): string => {+ const unit = item.unit ? ` (${item.unit})` : ''+ switch (item.metric_type) {+ case 'gauge':+ return `A current level, read at each scrape${unit}.`+ case 'sum':+ return `A running total that grows over time${unit}.`+ case 'histogram':+ case 'exponential_histogram':+ return `A distribution of values; chart a percentile${unit}.`+ case 'summary':+ return `A distribution with precomputed percentiles${unit}.`+ default:+ return `A metric${unit}.`+ }+}++const typeTagLabel = (metricType: string): string =>+ metricType === 'sum' ? 'counter' : metricType === 'exponential_histogram' ? 'histogram' : metricType || 'unknown'++const CatalogCard = ({ item }: { item: MetricCatalogItem }): JSX.Element => {+ const { openMetric } = useActions(metricsCatalogLogic)+ return (+ <button+ type="button"+ onClick={() => openMetric(item)}+ data-attr={`metrics-catalog-card-${item.name}`}+ className="flex flex-col gap-2 border rounded p-3 text-left hover:border-accent-primary focus:border-accent-primary transition-colors bg-bg-3000"+ >+ <div className="flex items-start justify-between gap-2 min-w-0">+ <span className="font-mono text-sm truncate" title={item.name}>+ {item.name}+ </span>+ <LemonTag type="muted" size="small">+ {typeTagLabel(item.metric_type)}+ </LemonTag>+ </div>+ <div className="h-10 w-full">+ {item.sparkline && item.sparkline.length > 1 ? (+ <Sparkline data={item.sparkline} type="line" />+ ) : (+ <div className="h-full flex items-center text-xs text-muted">No recent data to draw</div>+ )}+ </div>+ <p className="text-xs text-secondary mb-0">{describeMetric(item)}</p>+ {item.last_seen && (+ <span className="text-xs text-muted">+ Last seen <TZLabel time={item.last_seen} />+ </span>+ )}+ </button>+ )+}++export const MetricsCatalog = (): JSX.Element => {+ // The catalog reads the picker's service scope, so mounting the picker keeps the+ // scope the overview/viewer set live and the cards consistent with the viewer.+ useMountedLogic(metricNamePickerLogic)+ const logic = useMountedLogic(metricsCatalogLogic)+ const { visibleItems, catalogItemsLoading, search } = useValues(logic)+ const { setSearch } = useActions(logic)++ return (+ <div className="flex flex-col gap-3 overflow-y-auto">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <p className="text-secondary mb-0">+ Every metric you are collecting, as a card. Click one to open its chart.+ </p>+ <LemonInput+ size="small"+ prefix={<IconSearch />}+ value={search}+ onChange={setSearch}+ placeholder="Filter metrics"+ data-attr="metrics-catalog-search"+ className="w-64"+ />+ </div>+ {catalogItemsLoading && visibleItems.length === 0 ? (+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">+ {Array.from({ length: 8 }).map((_, i) => (+ <LemonSkeleton key={i} className="h-32" />+ ))}+ </div>+ ) : visibleItems.length === 0 ? (+ <div className="border rounded p-6 text-center text-secondary">+ {search ? `No metrics match "${search}".` : 'No metrics reported in the current scope yet.'}+ </div>+ ) : (+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">+ {visibleItems.map((item) => (+ <CatalogCard key={item.name} item={item} />+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/products/metrics/frontend/components/MetricsClauseRow.tsx b/products/metrics/frontend/components/MetricsClauseRow.tsxindex 3073dc807aee..bc108382ddce 100644--- a/products/metrics/frontend/components/MetricsClauseRow.tsx+++ b/products/metrics/frontend/components/MetricsClauseRow.tsx@@ -1,15 +1,17 @@import { useActions, useValues } from 'kea'-import { IconEllipsis } from '@posthog/icons'-import { LemonButton, LemonMenu, LemonSelect, Tooltip } from '@posthog/lemon-ui'+import { IconEllipsis, IconInfo } from '@posthog/icons'+import { LemonButton, LemonMenu, LemonSelect, LemonTag, Tooltip } from '@posthog/lemon-ui'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import UniversalFilters from 'lib/components/UniversalFilters/UniversalFilters'import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'+import { metricsSceneLogic } from '../metricsSceneLogic'import { MetricNameFilter } from './MetricNameFilter'import { MetricsClauseFilterBar } from './MetricsClauseFilterBar'+import { metricsFundamentalsLogic } from './metricsFundamentalsLogic'import { MetricsGroupByButton } from './MetricsGroupByButton'import {MAX_CLAUSES,@@ -75,6 +77,8 @@ export function MetricsClauseRow({const recommendedAggregation = clause.selectedMetricType? RECOMMENDED_AGGREGATION_BY_TYPE[clause.selectedMetricType]: undefined+ const { setActiveTab } = useActions(metricsSceneLogic)+ const { explainMetric } = useActions(metricsFundamentalsLogic)return (<div className="flex flex-wrap items-start gap-2" data-attr="metrics-clause-row">@@ -98,19 +102,42 @@ export function MetricsClauseRow({</Tooltip>)}<div className="flex flex-col gap-1">- <MetricNameFilter- value={clause.metricName}- onChange={withSelect(setMetricName)}- disabled={!!disabledReason}- disabledReason={disabledReason}- />+ <div className="flex items-center gap-1">+ <MetricNameFilter+ value={clause.metricName}+ onChange={withSelect(setMetricName)}+ disabled={!!disabledReason}+ disabledReason={disabledReason}+ />+ {clause.metricName && clause.selectedMetricType && (+ <Tooltip title="Take this metric apart: see how its chart value is recomputed from raw samples.">+ <LemonButton+ size="small"+ type="tertiary"+ icon={<IconInfo />}+ onClick={() => {+ explainMetric({+ metricName: clause.metricName,+ aggregation: clause.aggregation,+ })+ setActiveTab('fundamentals')+ }}+ data-attr="metrics-clause-explain"+ />+ </Tooltip>+ )}+ </div>{clause.selectedMetricType &&recommendedAggregation &&- clause.aggregation !== recommendedAggregation && (+ (clause.aggregation !== recommendedAggregation ? (<span className="text-xs text-secondary">{clause.selectedMetricType}: {recommendedAggregation} recommended</span>- )}+ ) : (+ <LemonTag type="muted" size="small" className="self-start">+ {clause.selectedMetricType} · {recommendedAggregation}+ </LemonTag>+ ))}</div><LemonSelectsize="small"diff --git a/products/metrics/frontend/components/metricsCatalogLogic.test.ts b/products/metrics/frontend/components/metricsCatalogLogic.test.tsnew file mode 100644index 000000000000..54f4684755f5--- /dev/null+++ b/products/metrics/frontend/components/metricsCatalogLogic.test.ts@@ -0,0 +1,129 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'++import { metricsValuesRetrieve } from '../generated/api'+import { metricsSceneLogic } from '../metricsSceneLogic'+import { metricNamePickerLogic } from './metricNamePickerLogic'+import { metricsCatalogLogic } from './metricsCatalogLogic'+import { metricsViewerLogic } from './metricsViewerLogic'++jest.mock('../generated/api', () => ({+ ...jest.requireActual('../generated/api'),+ metricsValuesRetrieve: jest.fn(),+ metricsQueryCreate: jest.fn(),+}))++const CATALOG_ITEMS = [+ {+ name: 'http.server.duration',+ metric_type: 'histogram',+ unit: 'ms',+ last_seen: '2026-09-03T10:00:00+00:00',+ sparkline: [1, 2, 3],+ },+ {+ name: 'queue.depth',+ metric_type: 'gauge',+ unit: '',+ last_seen: '2026-09-03T10:00:00+00:00',+ sparkline: [3, 2, 1],+ },+ { name: 'jobs.processed', metric_type: 'sum', unit: '', last_seen: '2026-09-03T09:00:00+00:00', sparkline: [0, 1] },+]++describe('metricsCatalogLogic', () => {+ let logic: ReturnType<typeof metricsCatalogLogic.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(metricsValuesRetrieve).mockReset()+ jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: CATALOG_ITEMS } as any)+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('loads catalog items from the metric names endpoint', async () => {+ logic = metricsCatalogLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadCatalogSuccess']).toMatchValues({+ catalogItems: CATALOG_ITEMS,+ })+ })++ it('narrows the visible cards by a search substring', async () => {+ logic = metricsCatalogLogic()+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])++ await expectLogic(logic, () => {+ logic.actions.setSearch('queue')+ }).toMatchValues({+ visibleItems: [CATALOG_ITEMS[1]],+ })+ })++ it('fetches the catalog scoped to the services the picker is pinned to', async () => {+ // The catalog follows the same picker scoping the overview drives, so a+ // service clicked on the overview only draws that service's cards.+ metricNamePickerLogic.mount()+ metricNamePickerLogic.actions.setServices(['api'])+ logic = metricsCatalogLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])++ expect(jest.mocked(metricsValuesRetrieve)).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ service: 'api' })+ )+ })++ it('fetches the whole catalog when no service scope is set', async () => {+ logic = metricsCatalogLogic()+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadCatalogSuccess'])++ const call = jest.mocked(metricsValuesRetrieve).mock.calls[0][1]+ expect(call).not.toHaveProperty('service')+ })++ it('openMetric lands the metric in the viewer and switches tab', async () => {+ metricNamePickerLogic.mount()+ await expectLogic(metricNamePickerLogic).toDispatchActions(['loadItemsSuccess'])+ logic = metricsCatalogLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.openMetric(CATALOG_ITEMS[2]) // jobs.processed, a sum+ }).toDispatchActions([metricsViewerLogic.actionTypes.setMetricName, metricsSceneLogic.actionTypes.setActiveTab])++ expect(metricsSceneLogic.values.activeTab).toBe('viewer')+ expect(metricsViewerLogic.values.metricName).toBe('jobs.processed')+ })++ it('openMetric pins the picked metric type so a reused name charts only that type', async () => {+ metricNamePickerLogic.mount()+ await expectLogic(metricNamePickerLogic).toDispatchActions(['loadItemsSuccess'])+ logic = metricsCatalogLogic()+ logic.mount()++ logic.actions.openMetric(CATALOG_ITEMS[0]) // a histogram++ expect(metricsViewerLogic.values.activeClause.selectedMetricType).toBe('histogram')+ // The type drives the default aggregation: a histogram charts as a percentile.+ expect(metricsViewerLogic.values.activeClause.aggregation).toBe('p95')+ })+})diff --git a/products/metrics/frontend/components/metricsCatalogLogic.tsx b/products/metrics/frontend/components/metricsCatalogLogic.tsxnew file mode 100644index 000000000000..84130f42ecd8--- /dev/null+++ b/products/metrics/frontend/components/metricsCatalogLogic.tsx@@ -0,0 +1,151 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { metricsValuesRetrieve } from '../generated/api'+import type { _MetricNameApi } from '../generated/api.schemas'+import { canViewMetrics } from '../metricsAccess'+import { metricsSceneLogic } from '../metricsSceneLogic'+import { metricNamePickerLogic } from './metricNamePickerLogic'+import { metricsViewerLogic, toKnownMetricType } from './metricsViewerLogic'++/** One catalog card: a metric name plus what makes it scannable before opening it. */+export type MetricCatalogItem = _MetricNameApi++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsCatalogLogicValues {+ pickerServices: string[] // metricNamePickerLogic+ currentTeamId: number | null // teamLogic+ catalogItems: MetricCatalogItem[]+ catalogItemsLoading: boolean+ search: string+ visibleItems: MetricCatalogItem[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsCatalogLogicActions {+ setServices: (services: string[]) => {+ services: string[]+ } // metricNamePickerLogic+ setActiveTab: (activeTab: import('../metricsSceneLogic').MetricsSceneActiveTab) => {+ activeTab: import('../metricsSceneLogic').MetricsSceneActiveTab+ } // metricsSceneLogic+ setMetricName: (metricName: string) => {+ metricName: string+ } // metricsViewerLogic+ setSelectedMetricType: (metricType: null | import('../generated/api.schemas').OtelMetricTypeEnumApi) => {+ metricType: null | import('../generated/api.schemas').OtelMetricTypeEnumApi+ } // metricsViewerLogic+ loadCatalog: () => any+ loadCatalogFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadCatalogSuccess: (+ catalogItems: _MetricNameApi[],+ payload?: any+ ) => {+ catalogItems: _MetricNameApi[]+ payload?: any+ }+ openMetric: (item: MetricCatalogItem) => {+ item: _MetricNameApi+ }+ setSearch: (search: string) => {+ search: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsCatalogLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ visibleItems: (catalogItems: _MetricNameApi[], search: string) => MetricCatalogItem[]+ }+}++export type metricsCatalogLogicType = MakeLogicType<+ metricsCatalogLogicValues,+ metricsCatalogLogicActions,+ Record<string, any>,+ metricsCatalogLogicMeta+>++export const metricsCatalogLogic = kea<metricsCatalogLogicType>([+ path(['products', 'metrics', 'frontend', 'components', 'metricsCatalogLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeamId'], metricNamePickerLogic, ['services as pickerServices']],+ actions: [+ metricsViewerLogic,+ ['setMetricName', 'setSelectedMetricType'],+ metricsSceneLogic,+ ['setActiveTab'],+ metricNamePickerLogic,+ ['setServices'],+ ],+ })),+ actions({+ setSearch: (search: string) => ({ search }),+ // A card click hands the metric to the viewer and switches to it.+ openMetric: (item: MetricCatalogItem) => ({ item }),+ }),+ reducers({+ search: ['' as string, { setSearch: (_, { search }) => search }],+ }),+ loaders(({ values }) => ({+ catalogItems: [+ [] as MetricCatalogItem[],+ {+ loadCatalog: async (): Promise<MetricCatalogItem[]> => {+ if (!canViewMetrics()) {+ return []+ }+ // The catalog is scoped to whatever services the picker is+ // currently pinned to (a service entered from the overview, or+ // the viewer's own scope), so the cards match what the user+ // clicked into. The endpoint returns the sparkline and unit.+ const response = await metricsValuesRetrieve(String(values.currentTeamId), {+ limit: 500,+ ...(values.pickerServices.length ? { service: values.pickerServices.join(',') } : {}),+ })+ return response.results+ },+ },+ ],+ })),+ selectors({+ visibleItems: [+ (s) => [s.catalogItems, s.search],+ (catalogItems: MetricCatalogItem[], search: string): MetricCatalogItem[] => {+ const needle = search.trim().toLowerCase()+ if (!needle) {+ return catalogItems+ }+ return catalogItems.filter((item) => item.name.toLowerCase().includes(needle))+ },+ ],+ }),+ listeners(({ actions }) => ({+ // Re-scope: entering a service from the overview or a viewer filter change+ // re-reads the cards for that scope.+ setServices: () => {+ actions.loadCatalog()+ },+ openMetric: ({ item }) => {+ // Set the type first so it latches: a metric name reused across OTel+ // types (a counter and a gauge) charts only the picked type, and the+ // viewer's recommended-aggregation backfill keys off the latched type.+ actions.setSelectedMetricType(toKnownMetricType(item.metric_type))+ actions.setMetricName(item.name)+ actions.setActiveTab('viewer')+ },+ })),+ afterMount(({ actions }) => {+ if (canViewMetrics()) {+ actions.loadCatalog()+ }+ }),+])diff --git a/products/metrics/frontend/components/metricsFundamentalsLogic.test.ts b/products/metrics/frontend/components/metricsFundamentalsLogic.test.tsindex 30e01504b329..af32645d3d39 100644--- a/products/metrics/frontend/components/metricsFundamentalsLogic.test.ts+++ b/products/metrics/frontend/components/metricsFundamentalsLogic.test.ts@@ -96,4 +96,18 @@ describe('metricsFundamentalsLogic', () => {expect(metricsExplainCreate).not.toHaveBeenCalled()expect(logic.values.checkResult).toBeNull()})++ it('explainMetric prefills the name and aggregation, then runs the check', async () => {+ // The viewer's "explain this number" hands over a metric the user is already+ // looking at, so the check must not make them retype it.+ jest.mocked(metricsQueryCreate).mockResolvedValue(queryResponse([{ time: '2026-01-01T00:05:00Z', value: 2 }]))++ await expectLogic(logic, () =>+ logic.actions.explainMetric({ metricName: 'cache_size', aggregation: 'avg' })+ ).toFinishAllListeners()++ expect(logic.values.metricName).toBe('cache_size')+ expect(logic.values.aggregation).toBe('avg')+ expect(metricsExplainCreate).toHaveBeenCalled()+ })})diff --git a/products/metrics/frontend/components/metricsFundamentalsLogic.tsx b/products/metrics/frontend/components/metricsFundamentalsLogic.tsxindex de46263d8584..cfa3fba23f12 100644--- a/products/metrics/frontend/components/metricsFundamentalsLogic.tsx+++ b/products/metrics/frontend/components/metricsFundamentalsLogic.tsx@@ -1,4 +1,4 @@-import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { lemonToast } from '@posthog/lemon-ui'@@ -34,6 +34,10 @@ export interface metricsFundamentalsLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface metricsFundamentalsLogicActions {+ explainMetric: (payload: { aggregation: MetricAggregation; metricName: string }) => {+ aggregation: MetricAggregation+ metricName: string+ }runCheck: () => {value: true}@@ -81,11 +85,26 @@ export const metricsFundamentalsLogic = kea<metricsFundamentalsLogicType>([setMetricName: (metricName: string) => ({ metricName }),setAggregation: (aggregation: MetricAggregation) => ({ aggregation }),runCheck: true,+ // The viewer's "explain this number" entry: prefill the metric the user is+ // already looking at and run the check, so the handoff needs no retyping.+ explainMetric: (payload: { metricName: string; aggregation: MetricAggregation }) => payload,}),reducers({- metricName: ['', { setMetricName: (_, { metricName }) => metricName }],- aggregation: ['sum' as MetricAggregation, { setAggregation: (_, { aggregation }) => aggregation }],+ metricName: [+ '',+ {+ setMetricName: (_, { metricName }) => metricName,+ explainMetric: (_, { metricName }) => metricName,+ },+ ],+ aggregation: [+ 'sum' as MetricAggregation,+ {+ setAggregation: (_, { aggregation }) => aggregation,+ explainMetric: (_, { aggregation }) => aggregation,+ },+ ],// Drop the previous decomposition the moment a new check starts. The// loading flag alone leaves a frame where the old answer is still on// screen under the new metric name, which reads as the new answer.@@ -145,4 +164,11 @@ export const metricsFundamentalsLogic = kea<metricsFundamentalsLogicType>([selectors({projectId: [() => [], () => window.POSTHOG_APP_CONTEXT?.current_project?.id?.toString() ?? ''],}),++ listeners(({ actions }) => ({+ explainMetric: () => {+ // Reducers have already prefilled the name and aggregation; run the check.+ actions.runCheck()+ },+ })),])diff --git a/products/metrics/frontend/components/metricsHandoff.test.ts b/products/metrics/frontend/components/metricsHandoff.test.tsnew file mode 100644index 000000000000..ee1057ba2e12--- /dev/null+++ b/products/metrics/frontend/components/metricsHandoff.test.ts@@ -0,0 +1,71 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'++import { metricsValuesRetrieve } from '../generated/api'+import { metricsCatalogLogic } from './metricsCatalogLogic'+import { metricsFundamentalsLogic } from './metricsFundamentalsLogic'++jest.mock('../generated/api', () => ({+ ...jest.requireActual('../generated/api'),+ metricsValuesRetrieve: jest.fn(),+ metricsQueryCreate: jest.fn(),+ metricsExplainCreate: jest.fn(),+}))++// The catalog and fundamentals logics are keyed (global) logics whose state must+// survive a tab flip: a card click preloads the viewer, and the viewer's explain+// button preloads fundamentals. The scene mounts both, so unmounting the tab+// component that also subscribes must not reset the preloaded state.+describe('metrics cross-tab handoffs', () => {+ beforeEach(() => {+ window.POSTHOG_APP_CONTEXT = {+ current_project: { id: 997 },+ resource_access_control: {+ [AccessControlResourceType.Metrics]: AccessControlLevel.Viewer,+ },+ } as unknown as AppContext+ initKeaTests()+ jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: [] } as any)+ })++ it('explainMetric state survives the viewer tab unmounting', async () => {+ // Stand-in for the scene-level mount that keeps the logic alive across tabs.+ const sceneHold = metricsFundamentalsLogic()+ sceneHold.mount()+ // Stand-in for the MetricsClauseRow subscription inside the viewer tab.+ const viewerHold = metricsFundamentalsLogic()+ viewerHold.mount()++ await expectLogic(sceneHold, () =>+ sceneHold.actions.explainMetric({ metricName: 'cache_size', aggregation: 'avg' })+ ).toFinishAllListeners()+ expect(sceneHold.values.metricName).toBe('cache_size')++ // The viewer tab unmounts while fundamentals renders. With only the tab+ // holding a subscription, kea would unmount the logic and drop the+ // prefill; the scene hold must keep it alive.+ viewerHold.unmount()++ expect(sceneHold.values.metricName).toBe('cache_size')+ expect(sceneHold.values.aggregation).toBe('avg')+ sceneHold.unmount()+ })++ it('a loaded catalog survives the explore tab unmounting', async () => {+ const items = [{ name: 'jobs.processed', metric_type: 'sum', unit: '', last_seen: null, sparkline: [1] }]+ jest.mocked(metricsValuesRetrieve).mockResolvedValue({ results: items } as any)++ const sceneHold = metricsCatalogLogic()+ sceneHold.mount()+ await expectLogic(sceneHold).toDispatchActions(['loadCatalogSuccess'])+ const tabHold = metricsCatalogLogic()+ tabHold.mount()++ tabHold.unmount()++ expect(sceneHold.values.catalogItems).toEqual(items)+ sceneHold.unmount()+ })+})diff --git a/products/metrics/frontend/components/metricsOverviewLogic.test.ts b/products/metrics/frontend/components/metricsOverviewLogic.test.tsindex 40db3cc26b01..033b6b408e7c 100644--- a/products/metrics/frontend/components/metricsOverviewLogic.test.ts+++ b/products/metrics/frontend/components/metricsOverviewLogic.test.ts@@ -72,7 +72,7 @@ describe('metricsOverviewLogic', () => {['a named service', 'api', { key: 'service_name', op: 'eq', value: 'api' }, ['api']],['the unknown service', '', { key: 'service_name', op: 'regex', value: '^$' }, ['']],])(- 'viewService sends a service filter for %s, scopes the picker, and switches tab',+ 'viewService sends a service filter for %s, scopes the picker, and opens the catalog',async (_name, serviceName, expected, pickerServices) => {logic = metricsOverviewLogic()logic.mount()@@ -84,9 +84,11 @@ describe('metricsOverviewLogic', () => {metricsSceneLogic.actionTypes.setActiveTab,])- expect(metricsSceneLogic.values.activeTab).toBe('viewer')+ // Clicking into a service lands on its catalog of metric cards, not an+ // empty viewer, so there is something to look at before picking a name.+ expect(metricsSceneLogic.values.activeTab).toBe('explore')expect(metricsViewerLogic.values.queryFilters).toEqual([expected])- // The landing promise: the viewer the user arrives at offers only the+ // The landing promise: the catalog the user arrives at offers only the// metrics that service reports, not every metric in the project.expect(metricNamePickerLogic.values.services).toEqual(pickerServices)}diff --git a/products/metrics/frontend/components/metricsOverviewLogic.tsx b/products/metrics/frontend/components/metricsOverviewLogic.tsxindex f865e8107dc1..7d5ac20057d3 100644--- a/products/metrics/frontend/components/metricsOverviewLogic.tsx+++ b/products/metrics/frontend/components/metricsOverviewLogic.tsx@@ -98,11 +98,13 @@ export const metricsOverviewLogic = kea<metricsOverviewLogicType>([},})),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.+ // A service row click lands the user on that service's catalog of metric+ // cards, already narrowed to the service, so there is something to scan+ // before picking a name. The catalog reuses the viewer's filter + picker+ // scope, and a card click from there opens the viewer with the metric set.viewService: ({ serviceName }) => {actions.setFilterGroup(serviceFilterGroup(serviceName))- actions.setActiveTab('viewer')+ actions.setActiveTab('explore')},})),afterMount(({ actions, cache }) => {diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex e09a6dc01cd6..ee5a73e4e0dd 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -780,6 +780,15 @@ export interface _MetricNameApi {name: string/** OTel metric type (gauge, sum, histogram, summary, exponential_histogram). */metric_type: string+ /** Unit of the metric value, if any (e.g. 'ms', 'By'). */+ unit?: string+ /**+ * When the newest datapoint for this metric arrived, ISO 8601.+ * @nullable+ */+ last_seen?: string | null+ /** A small downsampled series of the metric's recent shape, for a sparkline. */+ sparkline?: number[]}export interface _MetricNamesResponseApi {diff --git a/products/metrics/frontend/metricsSceneLogic.tsx b/products/metrics/frontend/metricsSceneLogic.tsxindex 4a9f3c04df00..bb6b562974c2 100644--- a/products/metrics/frontend/metricsSceneLogic.tsx+++ b/products/metrics/frontend/metricsSceneLogic.tsx@@ -34,8 +34,8 @@ import {export const METRICS_SQL_EDITOR_TAB_ID = 'metrics-sql-editor'-export type MetricsSceneActiveTab = 'overview' | 'viewer' | 'sql' | 'fundamentals'-const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['overview', 'viewer', 'sql', 'fundamentals']+export type MetricsSceneActiveTab = 'overview' | 'explore' | 'viewer' | 'sql' | 'fundamentals'+const VALID_ACTIVE_TABS: MetricsSceneActiveTab[] = ['overview', 'explore', 'viewer', 'sql', 'fundamentals']export const DEFAULT_ACTIVE_TAB: MetricsSceneActiveTab = 'overview'// kea-router pre-parses JSON-looking params, so anything a user types into the URL can reachdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 13f3ca26c9de..c8d02d19450e 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -91856,6 +91856,15 @@ export namespace Schemas {name: string;/** OTel metric type (gauge, sum, histogram, summary, exponential_histogram). */metric_type: string;+ /** Unit of the metric value, if any (e.g. 'ms', 'By'). */+ unit?: string;+ /**+ * When the newest datapoint for this metric arrived, ISO 8601.+ * @nullable+ */+ last_seen?: string | null;+ /** A small downsampled series of the metric's recent shape, for a sparkline. */+ sparkline?: number[];}export interface _MetricNamesResponse {