Skip to content

: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.

fix(metrics): fetch attribute keys for the group-by picker (#69641)

Frank Hamand1b12d6fea638
diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsx
index 095355565a2f..bd64900690e2 100644
--- a/products/metrics/frontend/components/MetricsViewer.tsx
+++ b/products/metrics/frontend/components/MetricsViewer.tsx
@@ -112,6 +112,8 @@ export const MetricsViewer = (): JSX.Element => {
viewMode,
statSummary,
groupByKeys,
+ attributeKeyOptions,
+ attributeKeyOptionsLoading,
filterGroup,
attributeEndpointFilters,
chartSeries,
@@ -133,6 +135,8 @@ export const MetricsViewer = (): JSX.Element => {
setViewMode,
setStatSummary,
setGroupByKeys,
+ setGroupBySearch,
+ loadAttributeKeyOptions,
setFilterGroup,
setLiveRefresh,
fetchQueryResults,
@@ -230,7 +234,10 @@ export const MetricsViewer = (): JSX.Element => {
allowCustomValues
value={groupByKeys}
onChange={setGroupByKeys}
- options={[]}
+ options={attributeKeyOptions}
+ loading={attributeKeyOptionsLoading}
+ onInputChange={setGroupBySearch}
+ onFocus={() => loadAttributeKeyOptions({})}
placeholder="Group by attribute…"
className="min-w-[12rem]"
data-attr="metrics-viewer-group-by"
diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.ts
index 55ad0bc7f4a7..606f72f58d56 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts
+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts
@@ -1,3 +1,5 @@
+import { expectLogic } from 'kea-test-utils'
+
import { NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import {
@@ -8,7 +10,7 @@ import {
UniversalFiltersGroupValue,
} from '~/types'
-import { metricsValuesRetrieve } from 'products/metrics/frontend/generated/api'
+import { metricsAttributesRetrieve, metricsValuesRetrieve } from 'products/metrics/frontend/generated/api'
import { metricNamePickerLogic } from './metricNamePickerLogic'
import { metricsViewerLogic, NEW_QUERY_STARTED_ERROR_MESSAGE } from './metricsViewerLogic'
@@ -16,6 +18,7 @@ import { metricsViewerLogic, NEW_QUERY_STARTED_ERROR_MESSAGE } from './metricsVi
jest.mock('products/metrics/frontend/generated/api', () => ({
...jest.requireActual('products/metrics/frontend/generated/api'),
metricsValuesRetrieve: jest.fn(),
+ metricsAttributesRetrieve: jest.fn(),
}))
const filterGroupWith = (filters: Record<string, any>[]): UniversalFiltersGroup => ({
@@ -177,4 +180,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 () => {
+ jest.mocked(metricsAttributesRetrieve).mockResolvedValue({
+ results: [{ name: 'env' }, { name: 'service_name' }],
+ count: 2,
+ })
+ await expectLogic(logic, () => {
+ logic.actions.setGroupBySearch('e')
+ }).toDispatchActions(['loadAttributeKeyOptions', 'loadAttributeKeyOptionsSuccess'])
+ expect(metricsAttributesRetrieve).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ search: 'e' })
+ )
+ expect(logic.values.attributeKeyOptions).toEqual([
+ { key: 'env', label: 'env' },
+ { key: 'service_name', label: 'service_name' },
+ ])
+ })
})
diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsx
index 1ed537040a33..fea08479f2b7 100644
--- a/products/metrics/frontend/components/metricsViewerLogic.tsx
+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx
@@ -19,7 +19,11 @@ import { MetricsQuery, MetricsQueryClause, MetricsQueryFilter, NodeKind } from '
import { QueryBasedInsightModel } from '~/types'
import { PropertyOperator, UniversalFilterValue, UniversalFiltersGroup } from '~/types'
-import { metricsCharacterizeCreate, metricsQueryCreate } from 'products/metrics/frontend/generated/api'
+import {
+ metricsAttributesRetrieve,
+ metricsCharacterizeCreate,
+ metricsQueryCreate,
+} from 'products/metrics/frontend/generated/api'
import { OtelMetricTypeEnumApi } from 'products/metrics/frontend/generated/api.schemas'
import type {
_MetricAnomalyReportApi,
@@ -155,6 +159,7 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
setStatSummary: (statSummary: MetricSummary) => ({ statSummary }),
setLiveRefresh: (liveRefresh: boolean) => ({ liveRefresh }),
setGroupByKeys: (groupByKeys: string[]) => ({ groupByKeys }),
+ setGroupBySearch: (groupBySearch: string) => ({ groupBySearch }),
setFilterGroup: (filterGroup: UniversalFiltersGroup) => ({ filterGroup }),
// AbortController plumbing mirrors logsViewerDataLogic: a `cancelInProgress`
// action aborts the previous controller before storing the new one.
@@ -178,6 +183,8 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
liveRefresh: [false, { setLiveRefresh: (_, { liveRefresh }) => liveRefresh }],
// Attribute keys to split the metric into one series each (e.g. ['service.name', 'env']).
groupByKeys: [[] as string[], { setGroupByKeys: (_, { groupByKeys }) => groupByKeys }],
+ // Free-text search backing the group-by attribute-key autocomplete.
+ groupBySearch: ['' as string, { setGroupBySearch: (_, { groupBySearch }) => groupBySearch }],
// The filter bar's UniversalFilters group; converted into backend matchers by `queryFilters`.
filterGroup: [DEFAULT_UNIVERSAL_GROUP_FILTER, { setFilterGroup: (_, { filterGroup }) => filterGroup }],
queryAbortController: [
@@ -210,6 +217,9 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([
saveAsInsightFailure: ({ error }) => {
lemonToast.error(`Failed to save insight: ${error}`)
},
+ setGroupBySearch: () => {
+ actions.loadAttributeKeyOptions({})
+ },
cancelInProgressQuery: ({ controller }) => {
if (values.queryAbortController !== null) {
// An AbortError-named DOMException (not a bare string) is what api.ts and the global
@@ -237,6 +247,26 @@ 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.
+ attributeKeyOptions: [
+ [] as { key: string; label: string }[],
+ {
+ loadAttributeKeyOptions: async (_, breakpoint) => {
+ await breakpoint(300)
+ const dateFrom = resolveDate(values.dateFrom) ?? undefined
+ const dateTo = resolveDate(values.dateTo) ?? undefined
+ const response = await metricsAttributesRetrieve(String(values.currentTeamId), {
+ search: values.groupBySearch,
+ ...(dateFrom ? { dateFrom } : {}),
+ ...(dateTo ? { dateTo } : {}),
+ limit: 100,
+ })
+ breakpoint()
+ return response.results.map((result) => ({ key: result.name, label: result.name }))
+ },
+ },
+ ],
queryResults: [
[] as MetricsViewerSeries[],
{