: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
fix(metrics): scope and order group-by attributes (#99525)
Frank Hamand8e9fd00da35f
diff --git a/docs/internal/metrics-group-by.md b/docs/internal/metrics-group-by.mdnew file mode 100644index 000000000000..89363d5139a3--- /dev/null+++ b/docs/internal/metrics-group-by.md@@ -0,0 +1,19 @@+# Metrics group by++The Group by dropdown lists attributes by series count, from highest to lowest.+Each item shows its series count on the right.+Hover over a count to show the "Number of series with this attribute" tooltip.+Attributes with the same count appear in alphabetical order.+Search keeps this order.++The count uses distinct series whose latest metadata timestamp is at or after the selected start time, across the project.+It does not read raw metric samples or enforce the selected end time.+Counts are informational and most useful for recent series.+Metadata updates can lag samples, so this is not an exact count for the selected time window.+When a metric is selected, it only lists attributes from that metric.+When no metric is selected, it lists attributes from all metrics in the project.+The count includes both metric attributes and resource attributes.+An attribute that occurs in both scopes counts once per series.+The `service_name` item uses the same count and order as other attributes.++Users can still enter custom attribute keys. Custom keys have no count until the API returns them.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c9b26fb8f16c..5f612a692000 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5160,6 +5160,10 @@ snapshots:hash: v1.k794b7964.4cbfe20c626f0f7912dbd47b41a152c9c30f92d12a3f599476fb10043d7f7e70.9NI9FaMch59lt8xO3Xhp9ruHKLyDcvupNp20dZrR8_Ymcp-apps-workflows--list--light:hash: v1.k794b7964.477017f5e06d957b8cebbbe9105e96e82c52bdf7ff512ec84d13f4db71f7916c.-hG1WABHKvQyC5AFOmyjA9Lj2lWdnz67KScAAuRz_Ps+ metrics-group-by--default--dark:+ hash: v1.k794b7964.ee00c0f572067d18b53141dce72c182c640f399bd746abce9b2098503dbb62aa.Bkt1qCLQus_6z8XlmJ6Ax5cQjvOkEdyrQDtZKyV_KJY+ metrics-group-by--default--light:+ hash: v1.k794b7964.e5d6a1978e274f76e13a0476f07c2956302b2b84bc318e38c55c72bd2839d8e9.sZnt-HOnAKGE8421CprrJcFq9wQut5SU7DSEi_6Kqiwposthog-3000-keyboard-shortcut--default--dark:hash: v1.k794b7964.a5fc5a426df52137d3fb6377a06c7b39c36b041280de154cf2b95cbe46932b8d.f2HHu2jv6bztshqmrVtHpiuuv3PJZNskIh7SbZRgIpkposthog-3000-keyboard-shortcut--default--light:diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1d053f315e5a..9df9f70fd24f 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4051,6 +4051,9 @@ importers:'@testing-library/react':specifier: ^14.3.1+ '@testing-library/user-event':+ specifier: ^14.6.1+ version: 14.6.1(@testing-library/[email protected])kea-test-utils:specifier: 'catalog:'version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.pyindex 09245f329e24..d415e3286615 100644--- a/products/metrics/backend/facade/api.py+++ b/products/metrics/backend/facade/api.py@@ -269,21 +269,30 @@ def get_metrics_overview(*, team: Team, lookback: dt.timedelta | None = None) ->def list_metric_attribute_keys(*,team: Team,+ metric_name: str = "",search: str = "",date_from: dt.datetime | None = None,date_to: dt.datetime | None = None,limit: int = 100,) -> list[dict[str, Any]]:- """List distinct attribute keys seen on the team's metrics, most frequent- first, for the filter bar's key autocomplete.-- Datapoint and resource attributes are merged into one list (filters run- with scope 'auto', so the split doesn't matter to callers); `service_name`- is always surfaced when it matches the search. The window defaults to the- last 7 days. Returns `{"name": str}` dicts. Raises `ValueError` for an- out-of-range limit or an inverted window.+ """List attribute keys by distinct series count, from highest to lowest.++ When a metric name is provided, only series that emitted that metric in the+ recent window supply choices. Datapoint and resource attributes are merged+ into one list (filters run with scope 'auto', so the split doesn't matter+ to callers); `service_name` is always surfaced when it matches the search.+ The window defaults to the last 7 days. Returns `{"name": str,+ "series_count": int}` dicts. Raises `ValueError` for an out-of-range limit+ or an inverted window."""- runner = MetricAttributeKeysQueryRunner(team=team, search=search, date_from=date_from, date_to=date_to, limit=limit)+ runner = MetricAttributeKeysQueryRunner(+ team=team,+ metric_name=metric_name,+ search=search,+ date_from=date_from,+ date_to=date_to,+ limit=limit,+ )return runner.run()diff --git a/products/metrics/backend/metric_attributes_query_runner.py b/products/metrics/backend/metric_attributes_query_runner.pyindex 33f303dd126b..770270817dc2 100644--- a/products/metrics/backend/metric_attributes_query_runner.py+++ b/products/metrics/backend/metric_attributes_query_runner.py@@ -1,10 +1,8 @@"""Attribute key/value autocomplete for the metrics filter bar.-Queries the `metric_attributes` aggregate table (fed by MVs on the metrics-ingest stream) rather than the raw data point table, mirroring the logs product's-`LogAttributesQueryRunner`/`LogValuesQueryRunner` pair. Keys are searched-across both datapoint ('metric') and resource attributes in one pass — the-viewer filters with scope 'auto', so the split is invisible to users.+Keys count distinct series from recent metadata, without reading raw samples.+Values use the `metric_attributes` aggregate table.+Both queries merge metric attributes and resource attributes."""import datetime as dt@@ -58,45 +56,54 @@ def _validate_limit(limit: int) -> int:class MetricAttributeKeysQueryRunner:- """Distinct attribute keys seen on the team's metrics in a window, most- frequent first, exact search matches floated to the top."""+ """Attribute keys ordered by distinct recent series count."""def __init__(self,team: Team,*,+ metric_name: str = "",search: str = "",date_from: dt.datetime | None = None,date_to: dt.datetime | None = None,limit: int = 100,) -> None:self.team = team+ self.metric_name = metric_name.strip()self.search = search.strip()self.date_from, self.date_to = _resolve_window(date_from, date_to)+ self.date_from += _TIME_BUCKET_INTERVALself.limit = _validate_limit(limit)def run(self) -> list[dict[str, Any]]:query = parse_select("""SELECT- attribute_key AS name,- sum(attribute_count) AS total_count- FROM posthog.metric_attributes- WHERE time_bucket >= {date_from}- AND time_bucket < {date_to}- AND attribute_key ILIKE {search_pattern}+ arrayJoin(arrayDistinct(arrayConcat(+ mapKeys(attributes), mapKeys(resource_attributes), ['service_name']+ ))) AS attribute_key,+ uniqExact(series_fingerprint) AS series_count+ FROM posthog.metric_series+ WHERE last_seen >= {date_from}+ AND {metric_name_filter}+ AND (attribute_key ILIKE {search_pattern}+ OR (attribute_key = 'service_name' AND 'service.name' ILIKE {search_pattern}))GROUP BY attribute_key- ORDER BY- lower(attribute_key) = lower({exact}) DESC,- sum(attribute_count) DESC,- attribute_key ASC+ ORDER BY series_count DESC, attribute_key ASCLIMIT {limit}""",placeholders={"date_from": ast.Constant(value=self.date_from),- "date_to": ast.Constant(value=self.date_to),+ "metric_name_filter": (+ ast.Constant(value=True)+ if not self.metric_name+ else ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["metric_name"]),+ right=ast.Constant(value=self.metric_name),+ )+ ),"search_pattern": ast.Constant(value=ilike_pattern(self.search)),- "exact": ast.Constant(value=self.search),"limit": ast.Constant(value=self.limit),},)@@ -110,13 +117,11 @@ class MetricAttributeKeysQueryRunner:settings=_QUERY_SETTINGS,)- keys = [row[0] for row in response.results]- # service_name lives in its own column, so it never appears as an attribute- # row; surface it whenever it matches the search (mirrors anomaly key discovery).+ results = [{"name": row[0], "series_count": int(row[1])} for row in response.results]search_lower = self.search.lower()- if (search_lower in "service_name" or search_lower in "service.name") and "service_name" not in keys:- keys.insert(0, "service_name")- return [{"name": key} for key in keys[: self.limit]]+ if not results and (search_lower in "service_name" or search_lower in "service.name"):+ results.append({"name": "service_name", "series_count": 0})+ return resultsclass MetricAttributeValuesQueryRunner:diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.pyindex 8f8132610429..65d272f453ae 100644--- a/products/metrics/backend/presentation/api.py+++ b/products/metrics/backend/presentation/api.py@@ -498,6 +498,13 @@ class _MetricPickerNamesResponseSerializer(serializers.Serializer):class _MetricAttributeKeysParamsSerializer(serializers.Serializer):+ metricName = serializers.CharField(+ required=False,+ allow_blank=True,+ default="",+ max_length=255,+ help_text="Exact metric name to limit attribute keys to. Omit to list keys across all metrics.",+ )search = serializers.CharField(required=False,allow_blank=True,@@ -563,12 +570,15 @@ class _MetricAttributeKeySerializer(serializers.Serializer):name = serializers.CharField(help_text="Attribute key as it appears on the team's metrics (e.g. 'env', 'k8s.pod.name').")+ series_count = serializers.IntegerField(+ help_text="Number of distinct recent series with this attribute, based on series metadata."+ )class _MetricAttributeKeysResponseSerializer(serializers.Serializer):results = _MetricAttributeKeySerializer(many=True,- help_text="Distinct attribute keys (datapoint and resource attributes merged), most frequent first.",+ help_text="Distinct attribute keys (datapoint and resource attributes merged), ordered by series count descending.",)count = serializers.IntegerField(help_text="Number of keys returned.")@@ -961,9 +971,8 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):throttle_classes=[ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle],)def attributes(self, request: Request, *args, **kwargs) -> Response:- """Distinct attribute keys seen on the team's metrics (datapoint and- resource attributes merged), most frequent first. Backs the filter- bar's key autocomplete."""+ """Attribute keys ordered by distinct series count, from highest to+ lowest. `metricName` limits choices to one metric."""tag_queries(product=Product.METRICS, feature=Feature.QUERY)params = _MetricAttributeKeysParamsSerializer(data=request.query_params)@@ -972,6 +981,7 @@ class MetricsViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):try:results = list_metric_attribute_keys(team=self.team,+ metric_name=params.validated_data["metricName"],search=params.validated_data["search"],date_from=params.validated_data["dateFrom"],date_to=params.validated_data["dateTo"],diff --git a/products/metrics/backend/tests/test_metric_attributes.py b/products/metrics/backend/tests/test_metric_attributes.pyindex 5ffba4ac9d32..6fef94918ceb 100644--- a/products/metrics/backend/tests/test_metric_attributes.py+++ b/products/metrics/backend/tests/test_metric_attributes.py@@ -27,7 +27,7 @@ class TestMetricAttributesAPI(ClickhouseTestMixin, APIBaseTest):service_name="checkout",points=recent,labels={"env": "prod", "region": "us"},- resource_labels={"k8s.pod.name": "pod-1"},+ resource_labels={"k8s.pod.name": "pod-1", "region": "us"},)seed_metric(team_id=cls.team.id,@@ -52,14 +52,12 @@ class TestMetricAttributesAPI(ClickhouseTestMixin, APIBaseTest):response = self._get("attributes")assert response.status_code == status.HTTP_200_OK, response.json()body = response.json()- # service_name is synthesized (it lives in its own column, never as an- # attribute row); the rest order by total count desc, then name asc.- assert [r["name"] for r in body["results"]] == [- "service_name",- "env",- "k8s.pod.name",- "region",- "stale_key",+ assert body["results"] == [+ {"name": "service_name", "series_count": 3},+ {"name": "env", "series_count": 2},+ {"name": "k8s.pod.name", "series_count": 1},+ {"name": "region", "series_count": 1},+ {"name": "stale_key", "series_count": 1},]assert body["count"] == 5@@ -67,6 +65,8 @@ class TestMetricAttributesAPI(ClickhouseTestMixin, APIBaseTest):[("substring_of_attribute_key", "env", ["env"]),("substring_of_synthetic_service_name", "serv", ["service_name"]),+ ("dotted_service_name", "service.name", ["service_name"]),+ ("series_count_order", "e", ["service_name", "env", "k8s.pod.name", "region", "stale_key"]),])def test_attributes_search_filters_keys(self, _name: str, search: str, expected: list[str]) -> None:@@ -74,12 +74,32 @@ class TestMetricAttributesAPI(ClickhouseTestMixin, APIBaseTest):assert response.status_code == status.HTTP_200_OKassert [r["name"] for r in response.json()["results"]] == expected- def test_attributes_window_excludes_out_of_range_buckets(self):- response = self._get("attributes", {"dateFrom": (self.now - dt.timedelta(hours=1)).isoformat()})+ @parameterized.expand([("recent", 0), ("historical", 10)])+ def test_attributes_use_recent_metadata_without_enforcing_end_time(self, _name: str, end_minutes_ago: int):+ response = self._get(+ "attributes",+ {+ "dateFrom": (self.now - dt.timedelta(hours=1)).isoformat(),+ "dateTo": (self.now - dt.timedelta(minutes=end_minutes_ago)).isoformat(),+ },+ )assert response.status_code == status.HTTP_200_OK- names = [r["name"] for r in response.json()["results"]]- assert "stale_key" not in names- assert "env" in names+ assert response.json()["results"] == [+ {"name": "env", "series_count": 2},+ {"name": "service_name", "series_count": 2},+ {"name": "k8s.pod.name", "series_count": 1},+ {"name": "region", "series_count": 1},+ ]++ def test_attributes_metric_name_limits_keys_to_that_metric(self):+ response = self._get("attributes", {"metricName": "http_requests"})+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["results"] == [+ {"name": "env", "series_count": 2},+ {"name": "service_name", "series_count": 2},+ {"name": "k8s.pod.name", "series_count": 1},+ {"name": "region", "series_count": 1},+ ]def test_attribute_values_returns_values_with_aggregated_counts(self):response = self._get("attribute_values", {"key": "env"})diff --git a/products/metrics/frontend/components/MetricsGroupByButton.stories.tsx b/products/metrics/frontend/components/MetricsGroupByButton.stories.tsxnew file mode 100644index 000000000000..06b058399a46--- /dev/null+++ b/products/metrics/frontend/components/MetricsGroupByButton.stories.tsx@@ -0,0 +1,56 @@+import { Meta, StoryObj } from '@storybook/react'+import { waitFor } from '@testing-library/react'+import { useState } from 'react'++import { mswDecorator } from '~/mocks/browser'++import { MetricsGroupByButton } from './MetricsGroupByButton'++const meta: Meta<typeof MetricsGroupByButton> = {+ title: 'Metrics/Group by',+ component: MetricsGroupByButton,+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/metrics/values/': { results: [] },+ '/api/projects/:team_id/metrics/attributes/': {+ results: [+ { name: 'service_name', series_count: 12000 },+ { name: 'environment', series_count: 8000 },+ { name: 'k8s.pod.name', series_count: 350 },+ { name: 'resource.attribute.with.a.long.name', series_count: 25 },+ ],+ count: 4,+ },+ },+ }),+ ],+ parameters: { layout: 'padded' },+ render: function Render() {+ const [groupByKeys, setGroupByKeys] = useState<string[]>([])+ return <MetricsGroupByButton groupByKeys={groupByKeys} onChange={setGroupByKeys} disabledReason={null} />+ },+}++export default meta+type Story = StoryObj<typeof MetricsGroupByButton>+export const Default: Story = {+ play: async () => {+ // The trigger is not in the DOM yet when the play function starts, and a bare+ // `querySelector(...)?.click()` silently does nothing when it misses — the dropdown+ // then never opens and the attribute fetch never fires.+ const trigger = await waitFor(() => {+ const element = document.querySelector<HTMLElement>('[data-attr="metrics-viewer-group-by-button"]')+ if (!element) {+ throw new Error('Group by button is not rendered')+ }+ return element+ })+ trigger.click()+ await waitFor(() => {+ if (!document.querySelector('.tabular-nums')) {+ throw new Error('Series counts are not visible')+ }+ })+ },+}diff --git a/products/metrics/frontend/components/MetricsGroupByButton.tsx b/products/metrics/frontend/components/MetricsGroupByButton.tsxindex 0dfb01549cbd..35499344edc9 100644--- a/products/metrics/frontend/components/MetricsGroupByButton.tsx+++ b/products/metrics/frontend/components/MetricsGroupByButton.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { useState } from 'react'import { IconChevronDown } from '@posthog/icons'-import { LemonButton, LemonDropdown, LemonInputSelect } from '@posthog/lemon-ui'+import { LemonButton, LemonDropdown, LemonInputSelect, Tooltip } from '@posthog/lemon-ui'import { metricsViewerLogic } from './metricsViewerLogic'@@ -39,9 +39,21 @@ export function MetricsGroupByButton({mode="multiple"size="small"allowCustomValues+ disableFiltering+ popoverClassName="[&_.whitespace-nowrap]:w-full"value={groupByKeys}onChange={onChange}- options={attributeKeyOptions}+ options={attributeKeyOptions.map((option) => ({+ ...option,+ labelComponent: (+ <span className="flex items-center justify-between gap-2">+ <span className="truncate">{option.label}</span>+ <Tooltip title="Number of series with this attribute">+ <span className="text-muted tabular-nums shrink-0">{option.seriesCount}</span>+ </Tooltip>+ </span>+ ),+ }))}loading={attributeKeyOptionsLoading}onInputChange={setGroupBySearch}onFocus={() => loadAttributeKeyOptions({})}diff --git a/products/metrics/frontend/components/MetricsViewer.test.tsx b/products/metrics/frontend/components/MetricsViewer.test.tsxindex 147b62befec4..be889179ec22 100644--- a/products/metrics/frontend/components/MetricsViewer.test.tsx+++ b/products/metrics/frontend/components/MetricsViewer.test.tsx@@ -1,6 +1,7 @@import '@testing-library/jest-dom'import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'import { Provider } from 'kea'import { insightsApi } from 'scenes/insights/utils/api'@@ -21,6 +22,7 @@ import {metricsNamesRetrieve,} from 'products/metrics/frontend/generated/api'+import { MetricsGroupByButton } from './MetricsGroupByButton'import { MetricsViewer } from './MetricsViewer'import { metricsViewerLogic } from './metricsViewerLogic'@@ -69,6 +71,28 @@ describe('MetricsViewer', () => {logic?.unmount()})+ it('shows series counts in the group-by dropdown and selects the attribute key', async () => {+ jest.mocked(metricsAttributesRetrieve).mockResolvedValue({+ results: [+ { name: 'service_name', series_count: 20 },+ { name: 'env', series_count: 2 },+ ],+ count: 2,+ })+ const onChange = jest.fn()+ render(<MetricsGroupByButton groupByKeys={[]} onChange={onChange} disabledReason={null} />)+ fireEvent.click(screen.getByText('Group by'))+ const serviceOption = await screen.findByText('service_name')+ const envOption = screen.getByText('env')+ expect(serviceOption.compareDocumentPosition(envOption) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ await userEvent.hover(screen.getByText('20'))+ expect(await screen.findByText('Number of series with this attribute')).toBeInTheDocument()+ fireEvent.change(screen.getByPlaceholderText('Group by attribute…'), { target: { value: 'e' } })+ expect(serviceOption.compareDocumentPosition(envOption) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ fireEvent.click(envOption)+ expect(onChange).toHaveBeenCalledWith(['env'])+ })+// The formula input only means something once a second series can feed it; showing it// is what makes the multi-series feature discoverable at all.it('reveals a second clause row and the formula input when a series is added', async () => {diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex 4b9b533872ff..f4b9ece33396 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -643,24 +643,25 @@ describe('metricsViewerLogic', () => {expect(logic.values.queryFilters).toEqual([{ key: 'env', op: 'eq', value: 'prod' }])})- // The group-by picker shipped with `options={[]}` and never fetched, so it offered no- // attribute keys. Typing must query the attributes endpoint (scoped by search) and map- // `{ name }` rows into `{ key, label }` options.- it('group-by search fetches attribute keys and maps them into options', async () => {+ it('group-by search keeps the series counts and order from the selected metric API response', async () => {jest.mocked(metricsAttributesRetrieve).mockResolvedValue({- results: [{ name: 'env' }, { name: 'service_name' }],+ results: [+ { name: 'service_name', series_count: 20 },+ { name: 'env', series_count: 2 },+ ],count: 2,})+ logic.actions.setMetricName('requests_total')await expectLogic(logic, () => {logic.actions.setGroupBySearch('e')}).toDispatchActions(['loadAttributeKeyOptions', 'loadAttributeKeyOptionsSuccess'])expect(metricsAttributesRetrieve).toHaveBeenCalledWith(expect.any(String),- expect.objectContaining({ search: 'e' })+ expect.objectContaining({ search: 'e', metricName: 'requests_total' }))expect(logic.values.attributeKeyOptions).toEqual([- { key: 'env', label: 'env' },- { key: 'service_name', label: 'service_name' },+ { key: 'service_name', label: 'service_name', seriesCount: 20 },+ { key: 'env', label: 'env', seriesCount: 2 },])})diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex 0a312fc64557..f9a9fd203b7e 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -351,6 +351,7 @@ export interface metricsViewerLogicValues {attributeKeyOptions: {key: stringlabel: string+ seriesCount: number}[]attributeKeyOptionsLoading: booleanchartSeries: MetricsChartSeries[]@@ -500,12 +501,14 @@ export interface metricsViewerLogicActions {attributeKeyOptions: {key: stringlabel: string+ seriesCount: number}[],payload?: any) => {attributeKeyOptions: {key: stringlabel: string+ seriesCount: number}[]payload?: any}@@ -1090,10 +1093,11 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([}}),loaders(({ values, actions }) => ({- // Backs the group-by attribute-key autocomplete. Scoped to the viewer's window so- // suggestions match the data on screen; debounced to match the chart fetch cadence.+ // Backs the group-by attribute-key autocomplete. Scope it to the active metric and+ // viewer window so choices match the data the clause can actually group; debounce to+ // match the chart fetch cadence.attributeKeyOptions: [- [] as { key: string; label: string }[],+ [] as { key: string; label: string; seriesCount: number }[],{loadAttributeKeyOptions: async (_, breakpoint) => {if (!canViewMetrics()) {@@ -1104,12 +1108,17 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([const dateTo = resolveDate(values.dateTo) ?? undefinedconst response = await metricsAttributesRetrieve(String(values.currentTeamId), {search: values.groupBySearch,+ ...(values.metricName.trim() ? { metricName: values.metricName.trim() } : {}),...(dateFrom ? { dateFrom } : {}),...(dateTo ? { dateTo } : {}),limit: 100,})breakpoint()- return response.results.map((result) => ({ key: result.name, label: result.name }))+ return response.results.map((result) => ({+ key: result.name,+ label: result.name,+ seriesCount: result.series_count,+ }))},},],diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.tsindex 728266cf8b9d..644dfb3c95a4 100644--- a/products/metrics/frontend/generated/api.schemas.ts+++ b/products/metrics/frontend/generated/api.schemas.ts@@ -40,10 +40,12 @@ export interface _MetricAttributeValuesResponseApi {export interface _MetricAttributeKeyApi {/** Attribute key as it appears on the team's metrics (e.g. 'env', 'k8s.pod.name'). */name: string+ /** Number of distinct recent series with this attribute, based on series metadata. */+ series_count: number}export interface _MetricAttributeKeysResponseApi {- /** Distinct attribute keys (datapoint and resource attributes merged), most frequent first. */+ /** Distinct attribute keys (datapoint and resource attributes merged), ordered by series count descending. */results: _MetricAttributeKeyApi[]/** Number of keys returned. */count: number@@ -855,6 +857,11 @@ export type MetricsAttributesRetrieveParams = {* @maximum 1000*/limit?: number+ /**+ * Exact metric name to limit attribute keys to. Omit to list keys across all metrics.+ * @maxLength 255+ */+ metricName?: string/*** Substring filter (case-insensitive) applied to attribute keys.* @maxLength 255diff --git a/products/metrics/frontend/generated/api.ts b/products/metrics/frontend/generated/api.tsindex 7272ef3385f7..fde7ebc42760 100644--- a/products/metrics/frontend/generated/api.ts+++ b/products/metrics/frontend/generated/api.ts@@ -126,9 +126,8 @@ export const getMetricsAttributesRetrieveUrl = (projectId: string, params?: Metr}/**- * Distinct attribute keys seen on the team's metrics (datapoint and- * resource attributes merged), most frequent first. Backs the filter- * bar's key autocomplete.+ * Attribute keys ordered by distinct series count, from highest to+ * lowest. `metricName` limits choices to one metric.*/export const metricsAttributesRetrieve = async (projectId: string,diff --git a/products/metrics/package.json b/products/metrics/package.jsonindex c163a4c4db73..e26515a96bfc 100644--- a/products/metrics/package.json+++ b/products/metrics/package.json@@ -15,6 +15,7 @@"@storybook/react": "catalog:","@testing-library/jest-dom": "^5.17.0","@testing-library/react": "^14.3.1",+ "@testing-library/user-event": "^14.6.1","kea-test-utils": "catalog:"},"peerDependencies": {@@ -24,6 +25,7 @@"@storybook/react": "*","@testing-library/jest-dom": "*","@testing-library/react": "*",+ "@testing-library/user-event": "*","@types/react": "*","clsx": "*","react": "*",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9b4fe35f39e4..04bf4fe7c793 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -92761,10 +92761,12 @@ export namespace Schemas {export interface _MetricAttributeKey {/** Attribute key as it appears on the team's metrics (e.g. 'env', 'k8s.pod.name'). */name: string;+ /** Number of distinct recent series with this attribute, based on series metadata. */+ series_count: number;}export interface _MetricAttributeKeysResponse {- /** Distinct attribute keys (datapoint and resource attributes merged), most frequent first. */+ /** Distinct attribute keys (datapoint and resource attributes merged), ordered by series count descending. */results: _MetricAttributeKey[];/** Number of keys returned. */count: number;@@ -102177,6 +102179,11 @@ export namespace Schemas {* @maximum 1000*/limit?: number;+ /**+ * Exact metric name to limit attribute keys to. Omit to list keys across all metrics.+ * @maxLength 255+ */+ metricName?: string;/*** Substring filter (case-insensitive) applied to attribute keys.* @maxLength 255