: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): metric-name picker with metric_type hint (#60377)
Daniel Visca9e7681caf5e1
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex ddc2fbf149b9..68804d0321d7 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -743,6 +743,10 @@ export class ApiRequest {return this.metrics(projectId).addPathComponent('query')}+ public metricsValues(projectId?: ProjectType['id']): ApiRequest {+ return this.metrics(projectId).addPathComponent('values')+ }+// # Tracingpublic tracingSpans(): ApiRequest {return this.environmentsDetail().addPathComponent('tracing').addPathComponent('spans')@@ -2819,6 +2823,20 @@ const api = {}): Promise<{ results: { time: string; value: number }[] }> {return new ApiRequest().metricsQuery().create({ signal, data: { query } })},+ async values({+ search,+ limit,+ signal,+ }: {+ search?: string+ limit?: number+ signal?: AbortSignal+ } = {}): Promise<{ results: { name: string; metric_type: string }[] }> {+ return new ApiRequest()+ .metricsValues()+ .withQueryString({ value: search ?? '', limit: limit ?? 100 })+ .get({ signal })+ },},tracing: {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0bee1158371b..e3a5c6c5b3f5 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3087,6 +3087,9 @@ importers:react:specifier: 18.3.1version: 18.3.1+ react-window:+ specifier: '*'products/notebooks:dependencies:diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex c2d99b4caf90..9066453ef91f 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -11,6 +11,7 @@ from typing import Anyfrom posthog.models import Teamfrom products.metrics.backend.has_metrics_query_runner import team_has_metrics as _team_has_metrics+from products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunnerfrom products.metrics.backend.metric_query_runner import MetricQueryRunner@@ -41,3 +42,19 @@ def query_metric(date_to=date_to,)return runner.run()+++def list_metric_names(+ *,+ team: Team,+ search: str = "",+ limit: int = 100,+) -> list[dict[str, Any]]:+ """List distinct metric names for the team's picker.++ Returns a list of `{"name": str, "metric_type": str}` dicts ordered by+ most-recently-seen, with exact-name matches floated to the top.+ Raises `ValueError` for an out-of-range limit.+ """+ runner = MetricNamesQueryRunner(team=team, search=search, limit=limit)+ return runner.run()diff --git a/products/metrics/backend/metric_names_query_runner.py b/products/metrics/backend/metric_names_query_runner.pynew file mode 100644index 000000000000..f3f10ce5e093--- /dev/null+++ b/products/metrics/backend/metric_names_query_runner.py@@ -0,0 +1,82 @@+"""Distinct metric names for a team's picker UI.++Queries `posthog.metrics` directly rather than `metric_attributes`: `metric_name`+is a top-level column on the source table with a `set(100)` skip index+(`idx_metric_name_set`) purpose-built for this lookup. Materialising it into+the attributes table would require a new MV with negligible upside given the+cardinality (10s — low 100s of distinct names per team).++Surfaces `metric_type` alongside the name so the viewer can hint at the+type-appropriate default aggregation (gauge -> avg, counter/sum -> sum, etc.)+without a second round-trip.+"""++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+++class MetricNamesQueryRunner:+ def __init__(+ self,+ team: Team,+ *,+ search: str = "",+ limit: int = 100,+ lookback: dt.timedelta = dt.timedelta(days=7),+ ) -> None:+ if limit <= 0 or limit > 1000:+ raise ValueError("limit must be in [1, 1000]")+ if lookback <= dt.timedelta(0):+ raise ValueError("lookback must be positive")++ self.team = team+ self.search = search.strip()+ self.limit = limit+ self.lookback = lookback++ def run(self) -> list[dict[str, Any]]:+ # ILIKE on metric_name uses the bloom filter side of the skip index;+ # any() on metric_type collapses to the single canonical type per+ # name (a metric name shouldn't change type — if it does, we get the+ # most-recent answer ClickHouse picks, which is fine for a picker).+ query = parse_select(+ """+ SELECT+ metric_name AS name,+ any(metric_type) AS metric_type,+ max(timestamp) AS last_seen+ FROM posthog.metrics+ WHERE timestamp > now() - {lookback}+ AND metric_name ILIKE {search_pattern}+ GROUP BY metric_name+ ORDER BY+ lower(metric_name) = lower({exact}) DESC,+ last_seen DESC+ LIMIT {limit}+ """,+ placeholders={+ "lookback": ast.Call(+ name="toIntervalSecond", args=[ast.Constant(value=int(self.lookback.total_seconds()))]+ ),+ "search_pattern": ast.Constant(value=f"%{self.search}%"),+ "exact": ast.Constant(value=self.search),+ "limit": ast.Constant(value=self.limit),+ },+ )+ assert isinstance(query, ast.SelectQuery)++ response = execute_hogql_query(+ query_type="MetricNamesQuery",+ query=query,+ team=self.team,+ workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now+ )++ return [{"name": row[0], "metric_type": row[1]} for row in response.results]diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex 293a60a6a7a5..3990cd8eda7e 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -9,7 +9,7 @@ import datetime as dtfrom django.utils import timezonefrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import extend_schema+from drf_spectacular.utils import OpenApiParameter, extend_schemafrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import ParseError@@ -21,7 +21,7 @@ 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 query_metric, team_has_metrics+from products.metrics.backend.facade.api import list_metric_names, query_metric, team_has_metrics__all__ = ["MetricsViewSet"]@@ -58,6 +58,17 @@ class _MetricQueryResponseSerializer(serializers.Serializer):results = _MetricQueryPointSerializer(many=True, help_text="Time-bucketed points, ordered by time ascending.")+class _MetricNameSerializer(serializers.Serializer):+ name = serializers.CharField(help_text="Metric name as it appears in the team's data.")+ metric_type = serializers.CharField(+ help_text="OTel metric type (gauge, sum, histogram, summary, exponential_histogram)."+ )+++class _MetricNamesResponseSerializer(serializers.Serializer):+ results = _MetricNameSerializer(many=True, help_text="Distinct metric names ordered by recent activity.")++@extend_schema(tags=["metrics"])class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "metrics"@@ -79,6 +90,42 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):return Response({"hasMetrics": has_metrics}, status=status.HTTP_200_OK)+ @extend_schema(+ parameters=[+ OpenApiParameter(+ "value",+ OpenApiTypes.STR,+ OpenApiParameter.QUERY,+ description="Substring filter (case-insensitive) applied to metric names.",+ ),+ OpenApiParameter(+ "limit",+ OpenApiTypes.INT,+ OpenApiParameter.QUERY,+ description="Max number of names to return. Defaults to 100, capped at 1000.",+ ),+ ],+ responses={200: _MetricNamesResponseSerializer},+ )+ @action(detail=False, methods=["GET"], required_scopes=["metrics:read"])+ def values(self, request: Request, *args, **kwargs) -> Response:+ """Distinct metric names for the team. Backs the picker UI."""+ tag_queries(product=Product.METRICS, feature=Feature.QUERY)++ search = request.query_params.get("value") or ""+ limit_raw = request.query_params.get("limit") or "100"+ try:+ limit = int(limit_raw)+ except ValueError:+ raise ParseError("limit must be an integer")++ try:+ results = list_metric_names(team=self.team, search=search, limit=limit)+ except ValueError as exc:+ raise ParseError(str(exc))++ return Response({"results": results}, 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:diff --git a/products/metrics/backend/tests/test_metric_names_query_runner.py b/products/metrics/backend/tests/test_metric_names_query_runner.pynew file mode 100644index 000000000000..d5e7814a8da1--- /dev/null+++ b/products/metrics/backend/tests/test_metric_names_query_runner.py@@ -0,0 +1,160 @@+import datetime as dt++from posthog.test.base import APIBaseTest, ClickhouseTestMixin++from django.utils import timezone++from rest_framework import status++from posthog.clickhouse.client import sync_execute++from products.metrics.backend.metric_names_query_runner import MetricNamesQueryRunner+from products.metrics.backend.tests.test_metric_query_runner import _insert_metric_row+++class TestMetricNamesQueryRunner(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")++ def test_rejects_out_of_range_limit(self):+ with self.assertRaises(ValueError):+ MetricNamesQueryRunner(team=self.team, limit=0)+ with self.assertRaises(ValueError):+ MetricNamesQueryRunner(team=self.team, limit=10_000)++ def test_rejects_non_positive_lookback(self):+ with self.assertRaises(ValueError):+ MetricNamesQueryRunner(team=self.team, lookback=dt.timedelta(0))++ def test_returns_empty_for_no_data(self):+ runner = MetricNamesQueryRunner(team=self.team)+ self.assertEqual(runner.run(), [])++ def test_returns_distinct_names_with_metric_type(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ _insert_metric_row(+ team_id=self.team.id,+ metric_name="http.server.duration",+ value=1.0,+ timestamp=anchor,+ metric_type="histogram",+ )+ _insert_metric_row(+ team_id=self.team.id,+ metric_name="http.server.duration",+ value=2.0,+ timestamp=anchor,+ metric_type="histogram",+ )+ _insert_metric_row(+ team_id=self.team.id,+ metric_name="queue.depth",+ value=12.0,+ timestamp=anchor,+ metric_type="gauge",+ )++ runner = MetricNamesQueryRunner(team=self.team)+ results = runner.run()++ names = {row["name"] for row in results}+ self.assertEqual(names, {"http.server.duration", "queue.depth"})++ by_name = {row["name"]: row["metric_type"] for row in results}+ self.assertEqual(by_name["http.server.duration"], "histogram")+ self.assertEqual(by_name["queue.depth"], "gauge")++ def test_search_filters_by_substring(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ _insert_metric_row(team_id=self.team.id, metric_name="http.server.duration", value=1.0, timestamp=anchor)+ _insert_metric_row(team_id=self.team.id, metric_name="queue.depth", value=12.0, timestamp=anchor)++ runner = MetricNamesQueryRunner(team=self.team, search="server")+ results = runner.run()+ self.assertEqual([row["name"] for row in results], ["http.server.duration"])++ def test_exact_match_floats_to_top(self):+ anchor = timezone.now().replace(microsecond=0)+ _insert_metric_row(+ team_id=self.team.id,+ metric_name="foo.bar",+ value=1.0,+ timestamp=anchor - dt.timedelta(minutes=10),+ )+ _insert_metric_row(+ team_id=self.team.id,+ metric_name="bar",+ value=2.0,+ timestamp=anchor - dt.timedelta(minutes=1),+ )++ runner = MetricNamesQueryRunner(team=self.team, search="bar")+ results = runner.run()+ self.assertEqual(results[0]["name"], "bar")++ def test_respects_team_isolation(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ _insert_metric_row(team_id=99999, metric_name="other.team.metric", value=1.0, timestamp=anchor)++ runner = MetricNamesQueryRunner(team=self.team)+ self.assertEqual(runner.run(), [])++ def test_lookback_excludes_old_data(self):+ old = timezone.now().replace(microsecond=0) - dt.timedelta(days=14)+ recent = timezone.now().replace(microsecond=0) - dt.timedelta(hours=1)+ _insert_metric_row(team_id=self.team.id, metric_name="old.metric", value=1.0, timestamp=old)+ _insert_metric_row(team_id=self.team.id, metric_name="recent.metric", value=2.0, timestamp=recent)++ runner = MetricNamesQueryRunner(team=self.team, lookback=dt.timedelta(days=7))+ names = [row["name"] for row in runner.run()]+ self.assertIn("recent.metric", names)+ self.assertNotIn("old.metric", names)+++class TestMetricsValuesAPI(ClickhouseTestMixin, APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = True++ def setUp(self):+ super().setUp()+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")++ def test_values_requires_authentication(self):+ self.client.logout()+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/values")+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_values_returns_empty_for_no_data(self):+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/values")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"results": []})++ def test_values_returns_metric_names(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ _insert_metric_row(team_id=self.team.id, metric_name="m1", value=1.0, timestamp=anchor)+ _insert_metric_row(team_id=self.team.id, metric_name="m2", value=2.0, timestamp=anchor, metric_type="gauge")++ response = self.client.get(f"/api/projects/{self.team.id}/metrics/values")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ body = response.json()+ names = {row["name"] for row in body["results"]}+ self.assertEqual(names, {"m1", "m2"})++ def test_values_search_param(self):+ anchor = timezone.now().replace(microsecond=0) - dt.timedelta(minutes=5)+ _insert_metric_row(team_id=self.team.id, metric_name="http.duration", value=1.0, timestamp=anchor)+ _insert_metric_row(team_id=self.team.id, metric_name="queue.depth", value=2.0, timestamp=anchor)++ response = self.client.get(f"/api/projects/{self.team.id}/metrics/values?value=http")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ names = [row["name"] for row in response.json()["results"]]+ self.assertEqual(names, ["http.duration"])++ def test_values_rejects_invalid_limit(self):+ response = self.client.get(f"/api/projects/{self.team.id}/metrics/values?limit=not-a-number")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ response = self.client.get(f"/api/projects/{self.team.id}/metrics/values?limit=0")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)diff --git a/products/metrics/frontend/components/MetricNameFilter.tsx b/products/metrics/frontend/components/MetricNameFilter.tsxnew file mode 100644index 000000000000..6840e5df33ad--- /dev/null+++ b/products/metrics/frontend/components/MetricNameFilter.tsx@@ -0,0 +1,154 @@+import { BindLogic, useActions, useValues } from 'kea'+import { CSSProperties, useCallback, useMemo } from 'react'+import { List } from 'react-window'++import { IconChevronDown } from '@posthog/icons'+import { LemonButton, LemonDropdown, LemonInput } from '@posthog/lemon-ui'++import { metricNamePickerLogic, MetricNamePickerLogicProps } from './metricNamePickerLogic'++const ROW_HEIGHT = 44+const MAX_DROPDOWN_HEIGHT = 320+const DROPDOWN_WIDTH = 320++interface OptionRowData {+ items: { name: string; metric_type: string }[]+ selected: string+ onPick: (name: string) => void+}++function MetricOptionRow({+ index,+ style,+ items,+ selected,+ onPick,+}: {+ ariaAttributes: Record<string, unknown>+ index: number+ style: CSSProperties+} & OptionRowData): JSX.Element {+ const item = items[index]+ const isSelected = selected === item.name+ return (+ <div style={style}>+ <LemonButton+ type={isSelected ? 'primary' : 'tertiary'}+ size="small"+ fullWidth+ onClick={() => onPick(item.name)}+ data-attr={`metrics-name-option-${item.name}`}+ >+ <div className="min-w-0 flex flex-col items-start gap-0.5 py-0.5">+ <span className="truncate">{item.name}</span>+ {item.metric_type && <span className="text-xs text-muted">{item.metric_type}</span>}+ </div>+ </LemonButton>+ </div>+ )+}++export interface MetricNameFilterProps {+ /** Currently selected metric name (empty string when nothing is picked). */+ value: string+ onChange: (name: string) => void+ /** Per-tab keying so picker state doesn't leak across tabs. */+ tabId: string+ /** Placeholder shown on the trigger when no metric is picked. */+ placeholder?: string+}++export const MetricNameFilter = ({+ value,+ onChange,+ tabId,+ placeholder = 'Pick a metric',+}: MetricNameFilterProps): JSX.Element => {+ const logicProps: MetricNamePickerLogicProps = { tabId }++ return (+ <BindLogic logic={metricNamePickerLogic} props={logicProps}>+ <MetricNameFilterInner value={value} onChange={onChange} placeholder={placeholder} />+ </BindLogic>+ )+}++function MetricNameFilterInner({+ value,+ onChange,+ placeholder,+}: {+ value: string+ onChange: (name: string) => void+ placeholder: string+}): JSX.Element {+ const { items, itemsLoading, search } = useValues(metricNamePickerLogic)+ const { setSearch } = useActions(metricNamePickerLogic)++ const onPick = useCallback(+ (name: string) => {+ // Single-select: replace on pick. Multi-mode can be added later when+ // metrics-alerts arrives, mirroring ServiceFilter's selectionMode prop.+ onChange(value === name ? '' : name)+ },+ [value, onChange]+ )++ const rowProps = useMemo<OptionRowData>(() => ({ items, selected: value, onPick }), [items, value, onPick])++ const listHeight = useMemo(() => {+ const height = items.length * ROW_HEIGHT+ return Math.min(height, MAX_DROPDOWN_HEIGHT)+ }, [items.length])++ const selectedType = useMemo(() => items.find((item) => item.name === value)?.metric_type, [items, value])++ const triggerLabel = !value ? placeholder : selectedType ? `${value} (${selectedType})` : value++ return (+ <LemonDropdown+ closeOnClickInside+ overlay={+ <div className="space-y-px p-1">+ <div className="px-1 pb-1">+ <LemonInput+ type="search"+ placeholder="Search metrics..."+ size="small"+ fullWidth+ value={search}+ onChange={(val) => setSearch(val)}+ autoFocus+ />+ </div>+ {itemsLoading && items.length === 0 ? (+ <div className="p-2 text-muted text-center text-xs">Loading metrics…</div>+ ) : items.length === 0 ? (+ <div className="p-2 text-muted text-center text-xs">+ {search ? 'No metrics match this search.' : 'No metrics ingested in the last 7 days.'}+ </div>+ ) : (+ <List<OptionRowData>+ style={{ width: DROPDOWN_WIDTH, height: listHeight }}+ rowCount={items.length}+ rowHeight={ROW_HEIGHT}+ overscanCount={5}+ rowComponent={MetricOptionRow}+ rowProps={rowProps}+ />+ )}+ </div>+ }+ >+ <LemonButton+ data-attr="metrics-name-filter"+ type="secondary"+ size="small"+ sideIcon={<IconChevronDown />}+ loading={itemsLoading && !value}+ >+ {triggerLabel}+ </LemonButton>+ </LemonDropdown>+ )+}diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex 27dcd08838c7..aef22b0e1f34 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -1,7 +1,7 @@-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'import { useCallback, useEffect, useMemo } from 'react'-import { LemonInput, LemonSelect, SpinnerOverlay } from '@posthog/lemon-ui'+import { LemonSelect, SpinnerOverlay } from '@posthog/lemon-ui'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'@@ -11,6 +11,8 @@ import { DATE_TIME_FORMAT, formatDateRange } from 'lib/utils'import { DateMappingOption } from '~/types'+import { MetricNameFilter } from './MetricNameFilter'+import { metricNamePickerLogic } from './metricNamePickerLogic'import { MetricAggregation, metricsViewerLogic } from './metricsViewerLogic'const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [@@ -20,6 +22,17 @@ const AGGREGATION_OPTIONS: { value: MetricAggregation; label: string }[] = [{ value: 'p95', label: 'p95' },]+// Recommended aggregation per OTel metric type. Used for an inline hint —+// we don't auto-switch the user's choice (hint, don't overwrite).+const RECOMMENDED_AGGREGATION_BY_TYPE: Record<string, MetricAggregation> = {+ gauge: 'avg',+ sum: 'sum',+ counter: 'sum',+ histogram: 'p95',+ summary: 'p95',+ exponential_histogram: 'p95',+}+// Mirrors the curated set used by `LogsViewer/Filters/DateRangeFilter`.const DATE_OPTIONS: DateMappingOption[] = [{ key: CUSTOM_OPTION_KEY, values: [] },@@ -61,6 +74,9 @@ export interface MetricsViewerProps {export const MetricsViewer = ({ id }: MetricsViewerProps): JSX.Element => {const logic = metricsViewerLogic({ tabId: id })+ // Keep the picker logic mounted alongside the viewer so the chosen metric's+ // metric_type stays available for the aggregation hint after the dropdown closes.+ const pickerLogic = useMountedLogic(metricNamePickerLogic({ tabId: id }))const {metricName,aggregation,@@ -72,12 +88,19 @@ export const MetricsViewer = ({ id }: MetricsViewerProps): JSX.Element => {hasMetricName,} = useValues(logic)const { setMetricName, setAggregation, setDateFrom, setDateTo, fetchQueryResults } = useActions(logic)+ const { items: pickerItems } = useValues(pickerLogic)- // Refetch whenever any filter changes — the loader breakpoint debounces input.+ // Refetch the chart whenever any filter changes — the loader breakpoint debounces input.useEffect(() => {fetchQueryResults({})}, [metricName, aggregation, dateFrom, dateTo]) // eslint-disable-line react-hooks/exhaustive-deps+ const selectedMetricType = useMemo(+ () => pickerItems.find((item) => item.name === metricName)?.metric_type,+ [pickerItems, metricName]+ )+ const recommendedAggregation = selectedMetricType ? RECOMMENDED_AGGREGATION_BY_TYPE[selectedMetricType] : undefined+// Mirrors the format/timeUnit ladder LogsSparkline uses so the X-axis density// matches the selected range.const { timeUnit, tickFormat } = useMemo(() => {@@ -124,14 +147,15 @@ export const MetricsViewer = ({ id }: MetricsViewerProps): JSX.Element => {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]"- />+ <div className="flex flex-wrap items-end gap-2">+ <div className="flex flex-col gap-1">+ <MetricNameFilter tabId={id} value={metricName} onChange={setMetricName} />+ {selectedMetricType && recommendedAggregation && aggregation !== recommendedAggregation && (+ <span className="text-xs text-secondary">+ {selectedMetricType} — {recommendedAggregation} recommended+ </span>+ )}+ </div><LemonSelectsize="small"value={aggregation}@@ -156,7 +180,7 @@ export const MetricsViewer = ({ id }: MetricsViewerProps): JSX.Element => {<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.+ Pick a metric to see its time series.</div>) : hasResults ? (<Sparklinediff --git a/products/metrics/frontend/components/metricNamePickerLogic.ts b/products/metrics/frontend/components/metricNamePickerLogic.tsnew file mode 100644index 000000000000..3a18460de528--- /dev/null+++ b/products/metrics/frontend/components/metricNamePickerLogic.ts@@ -0,0 +1,52 @@+import { actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'++import type { metricNamePickerLogicType } from './metricNamePickerLogicType'++export interface MetricNameItem {+ name: string+ metric_type: string+}++export interface MetricNamePickerLogicProps {+ tabId: string+}++export const metricNamePickerLogic = kea<metricNamePickerLogicType>([+ path(['products', 'metrics', 'frontend', 'components', 'metricNamePickerLogic']),+ props({} as MetricNamePickerLogicProps),+ key((p) => p.tabId),+ actions({+ setSearch: (search: string) => ({ search }),+ }),+ reducers({+ search: ['' as string, { setSearch: (_, { search }) => search }],+ }),+ loaders(({ values }) => ({+ items: [+ [] as MetricNameItem[],+ {+ loadItems: async (_, breakpoint) => {+ // Debounce — match the 300ms cadence used in the viewer logic so+ // both fetches feel cohesive.+ await breakpoint(300)+ const response = await api.metrics.values({ search: values.search, limit: 100 })+ breakpoint()+ return response.results+ },+ },+ ],+ })),+ listeners(({ actions }) => ({+ setSearch: () => {+ actions.loadItems({})+ },+ })),+ afterMount(({ actions }) => {+ // Prime the list so the dropdown isn't empty on first open. Mirrors+ // serviceFilterLogic's afterMount in logs.+ actions.loadItems({})+ }),+])diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex dfe7f93c001d..30f8fda58385 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -74,4 +74,27 @@ export interface _MetricQueryResponseApi {results: _MetricQueryPointApi[]}+export interface _MetricNameApi {+ /** Metric name as it appears in the team's data. */+ name: string+ /** OTel metric type (gauge, sum, histogram, summary, exponential_histogram). */+ metric_type: string+}++export interface _MetricNamesResponseApi {+ /** Distinct metric names ordered by recent activity. */+ results: _MetricNameApi[]+}+export type MetricsHasMetricsRetrieve200 = { [key: string]: unknown }++export type MetricsValuesRetrieveParams = {+ /**+ * Max number of names to return. Defaults to 100, capped at 1000.+ */+ limit?: number+ /**+ * Substring filter (case-insensitive) applied to metric names.+ */+ value?: string+}diff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.tsindex 4d411a62918b..f6fd8cf37449 100644--- a/products/metrics/frontend/generated/api.ts+++ b/products/metrics/frontend/generated/api.ts@@ -12,6 +12,8 @@ import type {AppMetricsResponseApi,AppMetricsTotalsResponseApi,MetricsHasMetricsRetrieve200,+ MetricsValuesRetrieveParams,+ _MetricNamesResponseApi,_MetricQueryRequestApi,_MetricQueryResponseApi,} from './api.schemas'@@ -88,3 +90,33 @@ export const metricsQueryCreate = async (body: JSON.stringify(_metricQueryRequestApi),})}++export const getMetricsValuesRetrieveUrl = (projectId: string, params?: MetricsValuesRetrieveParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : value.toString())+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/metrics/values/?${stringifiedParams}`+ : `/api/projects/${projectId}/metrics/values/`+}++/**+ * Distinct metric names for the team. Backs the picker UI.+ */+export const metricsValuesRetrieve = async (+ projectId: string,+ params?: MetricsValuesRetrieveParams,+ options?: RequestInit+): Promise<_MetricNamesResponseApi> => {+ return apiMutator<_MetricNamesResponseApi>(getMetricsValuesRetrieveUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}diff --git a/products/metrics/package.json b/products/metrics/package.jsonindex de444b9545da..d553ace6ffb2 100644--- a/products/metrics/package.json+++ b/products/metrics/package.json@@ -15,6 +15,7 @@"@posthog/products-error-tracking": "workspace:*","@types/react": "*","clsx": "*",- "react": "*"+ "react": "*",+ "react-window": "*"}}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fff929bacd76..ec366d057fe8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -38625,6 +38625,18 @@ export namespace Schemas {refreshing: boolean;}+ export interface _MetricName {+ /** Metric name as it appears in the team's data. */+ name: string;+ /** OTel metric type (gauge, sum, histogram, summary, exponential_histogram). */+ metric_type: string;+ }++ export interface _MetricNamesResponse {+ /** Distinct metric names ordered by recent activity. */+ results: _MetricName[];+ }+export interface _MetricQueryBody {/*** Exact metric name to query (e.g. 'http.server.duration').@@ -40854,6 +40866,17 @@ export namespace Schemas {export type EnvironmentsMetricsHasMetricsRetrieve200 = { [key: string]: unknown };+ export type EnvironmentsMetricsValuesRetrieveParams = {+ /**+ * Max number of names to return. Defaults to 100, capped at 1000.+ */+ limit?: number;+ /**+ * Substring filter (case-insensitive) applied to metric names.+ */+ value?: string;+ };+export type EnvironmentsPersistedFolderListParams = {/*** Number of results to return per page.@@ -46327,6 +46350,17 @@ export namespace Schemas {export type MetricsHasMetricsRetrieve200 = { [key: string]: unknown };+ export type MetricsValuesRetrieveParams = {+ /**+ * Max number of names to return. Defaults to 100, capped at 1000.+ */+ limit?: number;+ /**+ * Substring filter (case-insensitive) applied to metric names.+ */+ value?: string;+ };+export type NotebooksListParams = {/*** Filter for notebooks that match a provided filter.