: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 a facet rail to the metrics viewer (#117380)
Daniel Visca620ec4557309
diff --git a/frontend/src/lib/components/FacetRail/FacetRail.tsx b/frontend/src/lib/components/FacetRail/FacetRail.tsxindex 927f4d1b107c..5df4ce661797 100644--- a/frontend/src/lib/components/FacetRail/FacetRail.tsx+++ b/frontend/src/lib/components/FacetRail/FacetRail.tsx@@ -1,5 +1,5 @@import { useActions, useValues } from 'kea'-import { Fragment, useMemo, useRef } from 'react'+import { Fragment, ReactNode, useMemo, useRef } from 'react'import { IconPlus } from '@posthog/icons'import { LemonInput } from '@posthog/lemon-ui'@@ -15,20 +15,28 @@ import { FacetGroupItem, facetsByGroup, filterFacetsByName } from './facetGroupsconst DEFAULT_WIDTH_PX = 240const COLLAPSE_THRESHOLD_PX = 120+interface AddFacetGroupTypes {+ attribute: TaxonomicFilterGroupType+ resourceAttribute: TaxonomicFilterGroupType+}+export interface FacetRailProps<T extends FacetGroupItem> {- product: CustomFacetsProduct+ /** Omit, with `addFacetGroupTypes`, for a product without custom facets: the rail then hides the add button. */+ product?: CustomFacetsProductfacets: T[]/** Renders one facet. A facet that the name search hides still renders, so its logic stays mounted. */renderFacet: (facet: T, hidden: boolean) => JSX.ElementfacetNameSearch: stringonFacetNameSearchChange: (value: string) => voidonCollapsedChange: (collapsed: boolean) => void- addFacetGroupTypes: { attribute: TaxonomicFilterGroupType; resourceAttribute: TaxonomicFilterGroupType }+ addFacetGroupTypes?: AddFacetGroupTypes/** Persisted width keys. Frozen: a change resets every user's saved rail width. */resizerLogicKey: stringresizerPersistPrefix: string/** Prefix for the rail's data-attrs, e.g. `logs-facet-rail`. Frozen: autocapture and tests select on them. */dataAttrPrefix: string+ /** Shown above the facets, such as an error when the facet list itself failed to load. */+ notice?: ReactNode}/** Resizable left-hand facet rail: a facet-name search, an add-custom-facet button, and the grouped facets. */@@ -43,10 +51,9 @@ export function FacetRail<T extends FacetGroupItem>({resizerLogicKey,resizerPersistPrefix,dataAttrPrefix,+ notice,}: FacetRailProps<T>): JSX.Element {const railRef = useRef<HTMLDivElement>(null)- const { addCustomFacet } = useActions(customFacetsLogic({ product }))- const { customFacetsEnabled, entriesLoading } = useValues(customFacetsLogic({ product }))const resizerLogicProps: ResizerLogicProps = useMemo(() => ({@@ -87,26 +94,16 @@ export function FacetRail<T extends FacetGroupItem>({onChange={onFacetNameSearchChange}data-attr={`${dataAttrPrefix}-search`}/>- {customFacetsEnabled && (- <TaxonomicStringPopover- groupType={addFacetGroupTypes.attribute}- groupTypes={[addFacetGroupTypes.attribute, addFacetGroupTypes.resourceAttribute]}- placeholder={null}- size="small"- icon={<IconPlus />}- tooltip="Add custom facet"- disabledReason={entriesLoading ? 'Custom facets are updating' : undefined}- data-attr={`${dataAttrPrefix}-add`}- onChange={(value, groupType) =>- addCustomFacet(- value,- groupType === addFacetGroupTypes.resourceAttribute ? 'resourceAttribute' : 'attribute'- )- }+ {product && addFacetGroupTypes && (+ <AddCustomFacetButton+ product={product}+ groupTypes={addFacetGroupTypes}+ dataAttrPrefix={dataAttrPrefix}/>)}</div><div className="flex-1 min-h-0 overflow-y-auto p-2">+ {notice}{matchingKeys.size === 0 && facetNameSearch.trim() && (<div className="px-1 text-xs text-muted">No matching facets</div>)}@@ -127,3 +124,34 @@ export function FacetRail<T extends FacetGroupItem>({</div>)}++function AddCustomFacetButton({+ product,+ groupTypes,+ dataAttrPrefix,+}: {+ product: CustomFacetsProduct+ groupTypes: AddFacetGroupTypes+ dataAttrPrefix: string+}): JSX.Element | null {+ const { addCustomFacet } = useActions(customFacetsLogic({ product }))+ const { customFacetsEnabled, entriesLoading } = useValues(customFacetsLogic({ product }))+ if (!customFacetsEnabled) {+ return null+ }+ return (+ <TaxonomicStringPopover+ groupType={groupTypes.attribute}+ groupTypes={[groupTypes.attribute, groupTypes.resourceAttribute]}+ placeholder={null}+ size="small"+ icon={<IconPlus />}+ tooltip="Add custom facet"+ disabledReason={entriesLoading ? 'Custom facets are updating' : undefined}+ data-attr={`${dataAttrPrefix}-add`}+ onChange={(value, groupType) =>+ addCustomFacet(value, groupType === groupTypes.resourceAttribute ? 'resourceAttribute' : 'attribute')+ }+ />+ )+}diff --git a/frontend/src/lib/components/FacetRail/facetGroups.test.ts b/frontend/src/lib/components/FacetRail/facetGroups.test.tsindex 88cdc5b129d0..8d56b7e6f0c0 100644--- a/frontend/src/lib/components/FacetRail/facetGroups.test.ts+++ b/frontend/src/lib/components/FacetRail/facetGroups.test.ts@@ -1,4 +1,5 @@-import { FacetGroupItem, filterFacetsByName } from './facetGroups'+import { FacetOption } from './Facet'+import { FacetGroupItem, filterFacetsByName, mergeSelectedIntoOptions } from './facetGroups'const facet = (key: string, title: string, group: string): FacetGroupItem => ({ key, title, group })@@ -25,4 +26,42 @@ describe('facetGroups', () => {expect(filterFacetsByName(FACETS, query).map((f) => f.key)).toEqual(expectedKeys)})})++ describe('mergeSelectedIntoOptions', () => {+ const fetched: FacetOption[] = [+ { value: 'api', label: 'api', count: 10 },+ { value: 'worker', label: 'worker', count: 5 },+ ]++ it.each<[string, string[], string | undefined, string[]]>([+ ['no selected values leaves fetched unchanged', [], undefined, ['api', 'worker']],+ ['selected value already fetched is not duplicated', ['api'], undefined, ['api', 'worker']],+ ['missing selected value is prepended', ['batch-exports'], undefined, ['batch-exports', 'api', 'worker']],+ ['multiple missing values keep selection order', ['b', 'a'], undefined, ['b', 'a', 'api', 'worker']],+ // A value hand-edited into both polarities reaches here twice (included ++ excluded).+ [+ 'a value repeated across polarities is not duplicated',+ ['dup', 'dup'],+ undefined,+ ['dup', 'api', 'worker'],+ ],+ ['missing selected value not matching the search is omitted', ['batch-exports'], 'api', ['api', 'worker']],+ [+ 'search match is a case-insensitive substring',+ ['Batch-Exports'],+ 'batch',+ ['Batch-Exports', 'api', 'worker'],+ ],+ ])('%s', (_, selected, search, expectedValues) => {+ expect(mergeSelectedIntoOptions(fetched, selected, search).map((o) => o.value)).toEqual(expectedValues)+ })++ it('injects missing selected values with a zero count', () => {+ expect(mergeSelectedIntoOptions(fetched, ['batch-exports'], undefined)[0]).toEqual({+ value: 'batch-exports',+ label: 'batch-exports',+ count: 0,+ })+ })+ })})diff --git a/frontend/src/lib/components/FacetRail/facetGroups.ts b/frontend/src/lib/components/FacetRail/facetGroups.tsindex d0abb6c5df34..7820e99cfeaa 100644--- a/frontend/src/lib/components/FacetRail/facetGroups.ts+++ b/frontend/src/lib/components/FacetRail/facetGroups.ts@@ -1,3 +1,5 @@+import { FacetOption } from './Facet'+/** The fields the shared rail needs from a product's facet config to search and group it. */export interface FacetGroupItem {key: string@@ -33,3 +35,23 @@ export function facetsByGroup<T extends FacetGroupItem>(facets: T[]): [string, T}return groups}++/**+ * Ensure every selected (included or excluded) value of a dynamic facet renders even when absent+ * from the fetched list —+ * a filter from a URL or saved view can reference a value with no matches in the current scope+ * (or one below the top-N cutoff), and without a visible row it can't be seen or toggled off.+ * Missing values are prepended with a zero count. An active type-ahead search still applies to+ * injected rows, matching the server-side substring semantics of the fetched ones.+ */+export function mergeSelectedIntoOptions(fetched: FacetOption[], selected: string[], search?: string): FacetOption[] {+ const needle = (search ?? '').trim().toLowerCase()+ const fetchedValues = new Set(fetched.map((option) => option.value))+ // Dedupe: callers pass included+excluded concatenated, and a value hand-edited into both+ // polarities appears in both — without this it would inject a duplicate-keyed row.+ const missing = Array.from(new Set(selected))+ .filter((value) => !fetchedValues.has(value))+ .filter((value) => !needle || value.toLowerCase().includes(needle))+ .map((value) => ({ value, label: value, count: 0 }))+ return missing.length > 0 ? [...missing, ...fetched] : fetched+}diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 24b15150e614..4898ad8a436d 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -422,6 +422,7 @@ export const FEATURE_FLAGS = {METRICS_DASHBOARD_IMPORT: 'metrics-dashboard-import', // owner: #team-apm — gates the dashboard import from a Grafana JSON model or a screenshot, which bills AI creditsMETRICS_DASHBOARD_PANELS: 'metrics-dashboard-panels', // owner: #team-apm — gates the stat/gauge/bargauge/table panel picker entriesMETRICS_ERROR_OVERLAYS: 'metrics-error-overlays', // owner: #team-apm — gates the error-spike overlay PoC on metrics charts+ METRICS_FACET_RAIL: 'metrics-facet-rail', // owner: #team-apm — gates the facet rail (faceted filter sidebar) in the metrics viewerMETRICS_INSIGHT_BUILDER: 'metrics-insight-builder', // owner: #team-apm — offers Metrics in the new insight menu and the metrics builder in insight edit modeMETRICS_QUERY_LANGUAGES: 'metrics-query-languages', // owner: #team-apm — lets a metrics insight switch between the builder, PromQL and SQLMETRICS_SUGGESTED_DASHBOARDS: 'metrics-suggested-dashboards', // owner: #team-apm — suggests bank dashboards that fit the ingested metrics, and runs the AI analysis and generation for the teamdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ef342a22be15..d5c27ca29251 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4341,6 +4341,9 @@ importers:kea-router:specifier: 'catalog:'version: 3.4.2([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ kea-subscriptions:+ specifier: 'catalog:'+ version: 3.0.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))posthog-js:specifier: 'catalog:'version: 1.438.12(@types/[email protected])([email protected])diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsxindex 38c0ee9f646d..c8d2dc005651 100644--- a/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx+++ b/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx@@ -3,12 +3,13 @@ import { useCallback, useMemo } from 'react'import { customFacetsLogic } from 'lib/components/FacetRail/customFacetsLogic'import { Facet, FacetOption } from 'lib/components/FacetRail/Facet'+import { mergeSelectedIntoOptions } from 'lib/components/FacetRail/facetGroups'import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'import { facetFilterTarget, facetSelection } from './facetFilters'import { facetRailLogic } from './facetRailLogic'-import { FacetConfig, customFacetIdentity, mergeSelectedIntoOptions } from './facets'+import { FacetConfig, customFacetIdentity } from './facets'import { facetValuesLogic } from './facetValuesLogic'export interface RailFacetProps {diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.tsindex 8015184a64c7..592a252ba55f 100644--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts@@ -1,5 +1,3 @@-import { FacetOption } from 'lib/components/FacetRail/Facet'-import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'import {@@ -9,51 +7,12 @@ import {buildCustomFacet,customFacetIdentity,facetScopeSignature,- mergeSelectedIntoOptions,presenceProbeKeys,presenceProbeWindow,resolveFacets,} from './facets'describe('facets', () => {- describe('mergeSelectedIntoOptions', () => {- const fetched: FacetOption[] = [- { value: 'api', label: 'api', count: 10 },- { value: 'worker', label: 'worker', count: 5 },- ]-- it.each<[string, string[], string | undefined, string[]]>([- ['no selected values leaves fetched unchanged', [], undefined, ['api', 'worker']],- ['selected value already fetched is not duplicated', ['api'], undefined, ['api', 'worker']],- ['missing selected value is prepended', ['batch-exports'], undefined, ['batch-exports', 'api', 'worker']],- ['multiple missing values keep selection order', ['b', 'a'], undefined, ['b', 'a', 'api', 'worker']],- // A value hand-edited into both polarities reaches here twice (included ++ excluded).- [- 'a value repeated across polarities is not duplicated',- ['dup', 'dup'],- undefined,- ['dup', 'api', 'worker'],- ],- ['missing selected value not matching the search is omitted', ['batch-exports'], 'api', ['api', 'worker']],- [- 'search match is a case-insensitive substring',- ['Batch-Exports'],- 'batch',- ['Batch-Exports', 'api', 'worker'],- ],- ])('%s', (_, selected, search, expectedValues) => {- expect(mergeSelectedIntoOptions(fetched, selected, search).map((o) => o.value)).toEqual(expectedValues)- })-- it('injects missing selected values with a zero count', () => {- expect(mergeSelectedIntoOptions(fetched, ['batch-exports'], undefined)[0]).toEqual({- value: 'batch-exports',- label: 'batch-exports',- count: 0,- })- })- })-describe('facetScopeSignature', () => {const configured = (key: string): FacetConfig => CONFIGURED_FACETS.find((f) => f.key === key)!const LEVEL = configured('level')diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.tsindex 0cb901ce6e1f..f542e11d5f07 100644--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts@@ -284,26 +284,6 @@ export function resolveFacets(facets: FacetConfig[], presentResourceKeys: stringreturn resolved}-/**- * Ensure every selected (included or excluded) value of a dynamic facet renders even when absent- * from the fetched list —- * a filter from a URL or saved view can reference a value with no matches in the current scope- * (or one below the top-N cutoff), and without a visible row it can't be seen or toggled off.- * Missing values are prepended with a zero count. An active type-ahead search still applies to- * injected rows, matching the server-side substring semantics of the fetched ones.- */-export function mergeSelectedIntoOptions(fetched: FacetOption[], selected: string[], search?: string): FacetOption[] {- const needle = (search ?? '').trim().toLowerCase()- const fetchedValues = new Set(fetched.map((option) => option.value))- // Dedupe: callers pass included+excluded concatenated, and a value hand-edited into both- // polarities appears in both — without this it would inject a duplicate-keyed row.- const missing = Array.from(new Set(selected))- .filter((value) => !fetchedValues.has(value))- .filter((value) => !needle || value.toLowerCase().includes(needle))- .map((value) => ({ value, label: value, count: 0 }))- return missing.length > 0 ? [...missing, ...fetched] : fetched-}-/** Builds a rail-renderable FacetConfig for a user-added custom facet — always dynamic, with a remove control. */export function buildCustomFacet(key: string, sourceType: CustomFacetSourceType): FacetConfig {return {diff --git a/products/metrics/frontend/components/FacetRail/MetricsFacetRail.tsx b/products/metrics/frontend/components/FacetRail/MetricsFacetRail.tsxnew file mode 100644index 000000000000..00a1ae2cf921--- /dev/null+++ b/products/metrics/frontend/components/FacetRail/MetricsFacetRail.tsx@@ -0,0 +1,83 @@+import { useActions, useValues } from 'kea'+import { ReactNode } from 'react'++import { IconChevronLeft, IconChevronRight } from '@posthog/icons'+import { LemonButton, Link } from '@posthog/lemon-ui'++import { FacetRail } from 'lib/components/FacetRail/FacetRail'++import { metricsFacetRailLogic } from './metricsFacetRailLogic'+import { RailFacet } from './RailFacet'++/** The metrics viewer's facet rail: the service and every attribute the active metric carries. */+export function MetricsFacetRail(): JSX.Element | null {+ const {+ visibleFacets,+ facetNameSearch,+ railCollapsed,+ attributeKeysFailed,+ attributeKeysLoading,+ loadedAttributeKeysScope,+ attributeKeysScope,+ } = useValues(metricsFacetRailLogic)+ const { setFacetNameSearch, setRailCollapsed, retryAttributeKeys } = useActions(metricsFacetRailLogic)++ if (railCollapsed) {+ return null+ }+ return (+ <FacetRail+ notice={+ attributeKeysFailed &&+ !attributeKeysLoading && (+ <div className="px-1 pb-2 text-xs text-secondary" data-attr="metrics-facet-rail-keys-error">+ {loadedAttributeKeysScope === attributeKeysScope+ ? "Couldn't refresh this metric's attributes."+ : "Couldn't load this metric's attributes."}{' '}+ <Link onClick={retryAttributeKeys} data-attr="metrics-facet-rail-keys-retry">+ Retry+ </Link>+ </div>+ )+ }+ facets={visibleFacets}+ renderFacet={(facet, hidden) => <RailFacet facet={facet} hidden={hidden} />}+ facetNameSearch={facetNameSearch}+ onFacetNameSearchChange={setFacetNameSearch}+ onCollapsedChange={setRailCollapsed}+ resizerLogicKey="metrics-facet-rail"+ resizerPersistPrefix="2026-10-14"+ dataAttrPrefix="metrics-facet-rail"+ />+ )+}++export function MetricsFacetRailToggle(): JSX.Element {+ const { railCollapsed } = useValues(metricsFacetRailLogic)+ const { setRailCollapsed } = useActions(metricsFacetRailLogic)++ return (+ <LemonButton+ size="small"+ type="secondary"+ icon={railCollapsed ? <IconChevronRight /> : <IconChevronLeft />}+ onClick={() => setRailCollapsed(!railCollapsed)}+ data-attr="metrics-facet-rail-toggle"+ >+ {railCollapsed ? 'Show filters' : 'Hide filters'}+ </LemonButton>+ )+}++/** Puts the rail beside the viewer, with the viewer scrolling on its own so the rail keeps its height. */+export function MetricsFacetRailLayout({ enabled, children }: { enabled: boolean; children: ReactNode }): JSX.Element {+ if (!enabled) {+ return <div className="flex flex-col gap-3">{children}</div>+ }+ return (+ <div className="flex gap-2 flex-1 min-h-0">+ <MetricsFacetRail />+ <div className="flex flex-col gap-3 flex-1 min-w-0 min-h-0 overflow-y-auto">{children}</div>+ </div>+ )+}diff --git a/products/metrics/frontend/components/FacetRail/RailFacet.tsx b/products/metrics/frontend/components/FacetRail/RailFacet.tsxnew file mode 100644index 000000000000..7f19db1b3be7--- /dev/null+++ b/products/metrics/frontend/components/FacetRail/RailFacet.tsx@@ -0,0 +1,46 @@+import { useActions, useValues } from 'kea'++import { Facet } from 'lib/components/FacetRail/Facet'+import { mergeSelectedIntoOptions } from 'lib/components/FacetRail/facetGroups'++import { metricsViewerLogic } from '../metricsViewerLogic'+import { MetricFacetConfig, metricFacetSelection } from './facets'+import { metricsFacetRailLogic } from './metricsFacetRailLogic'+import { metricsFacetValuesLogic } from './metricsFacetValuesLogic'++/** One metric attribute in the rail. A facet that the name search hides renders nothing, but its logic stays mounted. */+export function RailFacet({ facet, hidden }: { facet: MetricFacetConfig; hidden: boolean }): JSX.Element | null {+ const { facetValues, facetValuesLoading, fetchFailed, facetSearch, collapsed } = useValues(+ metricsFacetValuesLogic({ facet })+ )+ const { setFacetSearch, retryFacetValues } = useActions(metricsFacetValuesLogic({ facet }))+ const { filterGroup } = useValues(metricsViewerLogic)+ const { toggleFacetValue, toggleFacetCollapsed } = useActions(metricsFacetRailLogic)++ if (hidden) {+ return null+ }++ const { included, excluded } = metricFacetSelection(filterGroup, facet.attributeKey)+ return (+ <Facet+ title={facet.title}+ options={mergeSelectedIntoOptions(facetValues, [...included, ...excluded], facetSearch)}+ selected={included}+ excluded={excluded}+ onToggle={(value) => toggleFacetValue(facet.attributeKey, value)}+ dataAttrPrefix="metrics-facet"+ zeroCountReason="No data points of this metric have this value in this time range"+ loading={facetValuesLoading}+ emptyLabel={`No ${facet.title} values`}+ searchValue={facetSearch}+ onSearchChange={setFacetSearch}+ searchPlaceholder="Search values…"+ collapsed={collapsed}+ onToggleCollapsed={() => toggleFacetCollapsed(facet.key)}+ maxHeight={300}+ error={fetchFailed}+ onRetry={retryFacetValues}+ />+ )+}diff --git a/products/metrics/frontend/components/FacetRail/facets.test.ts b/products/metrics/frontend/components/FacetRail/facets.test.tsnew file mode 100644index 000000000000..803e6181f480--- /dev/null+++ b/products/metrics/frontend/components/FacetRail/facets.test.ts@@ -0,0 +1,114 @@+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'++import { metricFiltersForGroup } from '../metricsViewerLogic'+import { buildMetricFacets, cycleMetricFacetFilter, metricFacetSelection } from './facets'++const group = (values: Record<string, unknown>[]): UniversalFiltersGroup => ({+ type: FilterLogicalOperator.And,+ values: [{ type: FilterLogicalOperator.And, values: values as any }],+})++const EMPTY = group([])++describe('metrics facets', () => {+ describe('buildMetricFacets', () => {+ it.each([+ ['service always comes first', ['env', 'region'], ['service_name', 'env', 'region']],+ [+ 'both service spellings fold into the service facet',+ ['service.name', 'env', 'service_name'],+ ['service_name', 'env'],+ ],+ ['duplicate keys render once', ['env', 'env'], ['service_name', 'env']],+ ['no keys still offers service', [], ['service_name']],+ ])('%s', (_, keys, expected) => {+ expect(buildMetricFacets(keys).map((facet) => facet.attributeKey)).toEqual(expected)+ })+ })++ describe('cycleMetricFacetFilter / metricFacetSelection', () => {+ it('cycles a value through included, excluded and cleared', () => {+ const included = cycleMetricFacetFilter(EMPTY, 'env', 'prod')+ expect(metricFacetSelection(included, 'env')).toEqual({ included: ['prod'], excluded: [] })++ const excluded = cycleMetricFacetFilter(included, 'env', 'prod')+ expect(metricFacetSelection(excluded, 'env')).toEqual({ included: [], excluded: ['prod'] })++ const cleared = cycleMetricFacetFilter(excluded, 'env', 'prod')+ expect(metricFacetSelection(cleared, 'env')).toEqual({ included: [], excluded: [] })+ expect(cleared).toEqual(EMPTY)+ })++ it.each(['service.name', 'service_name'])(+ 'reads and replaces a %s chip from the filter bar on the service facet',+ (chipKey) => {+ const fromFilterBar = group([+ {+ key: chipKey,+ type: PropertyFilterType.MetricAttribute,+ operator: PropertyOperator.Exact,+ value: ['checkout'],+ },+ ])+ expect(metricFacetSelection(fromFilterBar, 'service_name')).toEqual({+ included: ['checkout'],+ excluded: [],+ })++ const excluded = cycleMetricFacetFilter(fromFilterBar, 'service_name', 'checkout')+ expect((excluded.values[0] as UniversalFiltersGroup).values).toEqual([+ {+ key: 'service_name',+ type: PropertyFilterType.MetricAttribute,+ operator: PropertyOperator.IsNot,+ value: ['checkout'],+ },+ ])+ }+ )++ it('adds a second value to the same include filter', () => {+ const next = cycleMetricFacetFilter(cycleMetricFacetFilter(EMPTY, 'env', 'prod'), 'env', 'dev')+ expect(metricFacetSelection(next, 'env')).toEqual({ included: ['prod', 'dev'], excluded: [] })+ })++ it('keeps chips the rail does not own', () => {+ const regexChip = {+ key: 'env',+ type: PropertyFilterType.MetricAttribute,+ operator: PropertyOperator.Regex,+ value: ['pr.*'],+ }+ const otherKey = {+ key: 'region',+ type: PropertyFilterType.MetricAttribute,+ operator: PropertyOperator.Exact,+ value: ['us'],+ }+ const next = cycleMetricFacetFilter(group([regexChip, otherKey]), 'env', 'prod')+ expect((next.values[0] as UniversalFiltersGroup).values).toEqual([+ regexChip,+ otherKey,+ {+ key: 'env',+ type: PropertyFilterType.MetricAttribute,+ operator: PropertyOperator.Exact,+ value: ['prod'],+ },+ ])+ expect(metricFacetSelection(next, 'env')).toEqual({ included: ['prod'], excluded: [] })+ })++ it('writes filters the metrics query sends as matchers', () => {+ const next = cycleMetricFacetFilter(+ cycleMetricFacetFilter(cycleMetricFacetFilter(EMPTY, 'env', 'prod'), 'region', 'us'),+ 'region',+ 'us'+ )+ expect(metricFiltersForGroup(next)).toEqual([+ { key: 'env', op: 'eq', value: 'prod' },+ { key: 'region', op: 'neq', value: 'us' },+ ])+ })+ })+})diff --git a/products/metrics/frontend/components/FacetRail/facets.ts b/products/metrics/frontend/components/FacetRail/facets.tsnew file mode 100644index 000000000000..5a2c832b62b9--- /dev/null+++ b/products/metrics/frontend/components/FacetRail/facets.ts@@ -0,0 +1,106 @@+import { FacetGroupItem } from 'lib/components/FacetRail/facetGroups'++import {+ FilterLogicalOperator,+ PropertyFilterType,+ PropertyFilterValue,+ PropertyOperator,+ UniversalFiltersGroup,+} from '~/types'++import { SERVICE_NAME_KEY } from '../../metricsAttributes'++export interface MetricFacetConfig extends FacetGroupItem {+ /** The metric attribute key the facet lists values for and filters on. */+ attributeKey: string+}++// The backend reads both spellings from the service column, so they share one facet.+const SERVICE_KEYS = new Set([SERVICE_NAME_KEY, 'service.name'])++const SERVICE_FACET: MetricFacetConfig = {+ key: 'service',+ title: 'Service',+ group: 'Standard',+ attributeKey: SERVICE_NAME_KEY,+}++/** The service facet, then one facet per other attribute key, in the order the endpoint ranks them. */+export function buildMetricFacets(attributeKeys: string[]): MetricFacetConfig[] {+ const attributeFacets = Array.from(new Set(attributeKeys))+ .filter((key) => !SERVICE_KEYS.has(key))+ .map((key) => ({ key: `attribute:${key}`, title: key, group: 'Attributes', attributeKey: key }))+ return [SERVICE_FACET, ...attributeFacets]+}++interface MetricFacetFilter {+ key: string+ type: PropertyFilterType+ operator: PropertyOperator+ value?: PropertyFilterValue+}++export interface MetricFacetSelection {+ included: string[]+ excluded: string[]+}++// A clause filterGroup is { AND, values: [{ AND, values: [<chips>] }] }, and the filter bar edits the inner group.+function innerFilters(group: UniversalFiltersGroup): MetricFacetFilter[] {+ return ((group.values[0] as UniversalFiltersGroup | undefined)?.values ?? []) as MetricFacetFilter[]+}++// The rail owns the `exact` and `is_not` chips on its key. Other chips on the same key, such as a+// regex, stay as the filter bar wrote them. The service facet owns chips on both service spellings,+// so a `service.name` chip from the filter bar does not stay beside a contradicting rail chip.+function isRailFilter(filter: MetricFacetFilter, attributeKey: string): boolean {+ const sameKey = SERVICE_KEYS.has(attributeKey) ? SERVICE_KEYS.has(filter.key) : filter.key === attributeKey+ return (+ filter.type === PropertyFilterType.MetricAttribute &&+ sameKey &&+ (filter.operator === PropertyOperator.Exact || filter.operator === PropertyOperator.IsNot)+ )+}++function filterValues(filter: MetricFacetFilter): string[] {+ const values = Array.isArray(filter.value) ? filter.value : filter.value == null ? [] : [filter.value]+ return values.map(String).filter((value) => value !== '')+}++export function metricFacetSelection(group: UniversalFiltersGroup, attributeKey: string): MetricFacetSelection {+ const railFilters = innerFilters(group).filter((filter) => isRailFilter(filter, attributeKey))+ return {+ included: railFilters.filter((f) => f.operator === PropertyOperator.Exact).flatMap(filterValues),+ excluded: railFilters.filter((f) => f.operator === PropertyOperator.IsNot).flatMap(filterValues),+ }+}++/** Moves `value` one step through unchecked → included → excluded → unchecked, and returns a new filterGroup. */+export function cycleMetricFacetFilter(+ group: UniversalFiltersGroup,+ attributeKey: string,+ value: string+): UniversalFiltersGroup {+ const { included, excluded } = metricFacetSelection(group, attributeKey)+ let nextIncluded = included+ let nextExcluded = excluded+ if (included.includes(value)) {+ nextIncluded = included.filter((v) => v !== value)+ nextExcluded = [...excluded, value]+ } else if (excluded.includes(value)) {+ nextExcluded = excluded.filter((v) => v !== value)+ } else {+ nextIncluded = [...included, value]+ }++ const values = innerFilters(group).filter((filter) => !isRailFilter(filter, attributeKey))+ for (const [operator, selection] of [+ [PropertyOperator.Exact, nextIncluded],+ [PropertyOperator.IsNot, nextExcluded],+ ] as const) {+ if (selection.length > 0) {+ values.push({ key: attributeKey, type: PropertyFilterType.MetricAttribute, operator, value: selection })+ }+ }+ return { type: FilterLogicalOperator.And, values: [{ type: FilterLogicalOperator.And, values: values as any }] }+}diff --git a/products/metrics/frontend/components/FacetRail/metricsFacetRailLogic.test.ts b/products/metrics/frontend/components/FacetRail/metricsFacetRailLogic.test.tsnew file mode 100644index 000000000000..767d2afe9cb7--- /dev/null+++ b/products/metrics/frontend/components/FacetRail/metricsFacetRailLogic.test.ts@@ -0,0 +1,244 @@+import { expectLogic } from 'kea-test-utils'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'+import { AccessControlLevel, AccessControlResourceType, AppContext } from '~/types'++import { metricsAttributesRetrieve, metricsAttributeValuesRetrieve } from '../../generated/api'+import { metricsViewerLogic } from '../metricsViewerLogic'+import { DEFAULT_EXPANDED_FACETS, metricsFacetRailLogic } from './metricsFacetRailLogic'+import { metricsFacetValuesLogic } from './metricsFacetValuesLogic'++jest.mock('../../generated/api', () => ({+ ...jest.requireActual('../../generated/api'),+ metricsAttributesRetrieve: jest.fn(),+ metricsAttributeValuesRetrieve: jest.fn(),+}))++const KEYS = Array.from({ length: DEFAULT_EXPANDED_FACETS + 2 }, (_, i) => ({ name: `key_${i}`, value_count: 10 - i }))++describe('metricsFacetRailLogic', () => {+ let viewer: ReturnType<typeof metricsViewerLogic.build>+ let logic: ReturnType<typeof metricsFacetRailLogic.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+ // The collapse state persists, so one test's toggles would leak into the next.+ localStorage.clear()+ initKeaTests()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.METRICS]: true })+ jest.mocked(metricsAttributesRetrieve).mockReset().mockResolvedValue({ results: KEYS, count: KEYS.length })+ jest.mocked(metricsAttributeValuesRetrieve)+ .mockReset()+ .mockResolvedValue({ results: [{ id: 'prod', name: 'prod', count: 3 }] })+ viewer = metricsViewerLogic()+ viewer.mount()+ logic = metricsFacetRailLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ viewer.unmount()+ })++ it('lists the active metric attribute keys as facets after the service facet', async () => {+ viewer.actions.setMetricName('http_requests')++ await expectLogic(logic).toDispatchActions(['loadAttributeKeysSuccess'])++ expect(jest.mocked(metricsAttributesRetrieve).mock.lastCall?.[1]).toMatchObject({+ metricName: 'http_requests',+ })+ expect(logic.values.visibleFacets.map((facet) => facet.attributeKey)).toEqual([+ 'service_name',+ ...KEYS.map((key) => key.name),+ ])+ })++ it('starts facets past the first few collapsed, and remembers a toggle', async () => {+ await expectLogic(logic).toDispatchActions(['loadAttributeKeysSuccess'])+ const facets = logic.values.visibleFacets+ const firstCollapsed = facets[DEFAULT_EXPANDED_FACETS]++ expect(logic.values.collapsedFacetKeys).toEqual(facets.slice(DEFAULT_EXPANDED_FACETS).map((f) => f.key))++ logic.actions.toggleFacetCollapsed(firstCollapsed.key)+ expect(logic.values.collapsedFacetKeys).not.toContain(firstCollapsed.key)++ logic.actions.toggleFacetCollapsed(facets[0].key)+ expect(logic.values.collapsedFacetKeys).toContain(facets[0].key)+ })++ it('writes a toggled value into the active clause filters', () => {+ logic.actions.toggleFacetValue('env', 'prod')++ expect(viewer.values.activeClause.filterGroup).toEqual({+ type: 'AND',+ values: [+ {+ type: 'AND',+ values: [{ key: 'env', type: 'metric_attribute', operator: 'exact', value: ['prod'] }],+ },+ ],+ })+ })++ it('loads facet values for the active metric only while the facet is expanded', async () => {+ viewer.actions.setMetricName('http_requests')+ await expectLogic(logic).toDispatchActions(['loadAttributeKeysSuccess'])+ const collapsed = logic.values.visibleFacets[DEFAULT_EXPANDED_FACETS]+ const values = metricsFacetValuesLogic({ facet: collapsed })+ values.mount()++ await expectLogic(values).toNotHaveDispatchedActions(['loadFacetValues'])++ logic.actions.toggleFacetCollapsed(collapsed.key)+ await expectLogic(values).toDispatchActions(['loadFacetValuesSuccess'])++ expect(jest.mocked(metricsAttributeValuesRetrieve).mock.lastCall?.[1]).toMatchObject({+ key: collapsed.attributeKey,+ metricName: 'http_requests',+ })+ expect(values.values.facetValues).toEqual([{ value: 'prod', label: 'prod', count: 3 }])+ values.unmount()+ })++ it('skips the values request when the facet collapses during the debounce', async () => {+ viewer.actions.setMetricName('http_requests')+ await expectLogic(logic).toDispatchActions(['loadAttributeKeysSuccess'])+ const [expanded] = logic.values.visibleFacets+ const values = metricsFacetValuesLogic({ facet: expanded })+ values.mount()++ logic.actions.toggleFacetCollapsed(expanded.key)+ await expectLogic(values).toDispatchActions(['loadFacetValuesSuccess'])++ expect(metricsAttributeValuesRetrieve).not.toHaveBeenCalled()+ values.unmount()+ })++ it('shows only the service facet until the keys for a new metric arrive', async () => {+ viewer.actions.setMetricName('http_requests')+ await expectLogic(logic).toDispatchActions(['loadAttributeKeysSuccess'])+ let releaseKeys: (response: {+ results: { name: string; value_count: number }[]+ count: number+ }) => void = () => {}+ jest.mocked(metricsAttributesRetrieve).mockReturnValueOnce(+ new Promise((resolve) => {+ releaseKeys = resolve+ })+ )++ viewer.actions.setMetricName('queue_depth')+ expect(logic.values.visibleFacets.map((facet) => facet.attributeKey)).toEqual(['service_name'])++ releaseKeys({ results: [{ name: 'queue', value_count: 1 }], count: 1 })+ await expectLogic(logic).toDispatchActions(['loadAttributeKeysSuccess'])+ expect(logic.values.visibleFacets.map((facet) => facet.attributeKey)).toEqual(['service_name', 'queue'])+ })++ it('reports a failed attribute-key load and retries it', async () => {+ jest.mocked(metricsAttributesRetrieve).mockRejectedValueOnce(new Error('timeout'))+ viewer.actions.setMetricName('http_requests')++ await expectLogic(logic).toDispatchActions(['loadAttributeKeysFailure']).toMatchValues({+ attributeKeysFailed: true,+ })+ expect(logic.values.visibleFacets.map((facet) => facet.attributeKey)).toEqual(['service_name'])++ logic.actions.retryAttributeKeys()+ await expectLogic(logic).toDispatchActions(['loadAttributeKeysSuccess']).toMatchValues({+ attributeKeysFailed: false,+ })+ expect(logic.values.visibleFacets).toHaveLength(KEYS.length + 1)+ })++ it('reloads the keys and the expanded facet values on each auto-refresh tick, but not mid-load', async () => {+ viewer.actions.setMetricName('http_requests')+ await expectLogic(logic).toDispatchActions(['loadAttributeKeysSuccess'])+ const expanded = logic.values.visibleFacets[0]+ const collapsed = logic.values.visibleFacets[DEFAULT_EXPANDED_FACETS]+ const expandedValues = metricsFacetValuesLogic({ facet: expanded })+ const collapsedValues = metricsFacetValuesLogic({ facet: collapsed })+ expandedValues.mount()+ collapsedValues.mount()+ await expectLogic(expandedValues).toDispatchActions(['loadFacetValuesSuccess'])+ jest.mocked(metricsAttributesRetrieve).mockClear()+ jest.mocked(metricsAttributeValuesRetrieve).mockClear()++ viewer.actions.liveRefreshTick()+ // The facets stay on screen while the refresh runs.+ expect(logic.values.visibleFacets).toHaveLength(KEYS.length + 1)+ await expectLogic(logic).toDispatchActions(['loadAttributeKeysSuccess'])+ await expectLogic(expandedValues).toDispatchActions(['loadFacetValuesSuccess'])++ expect(metricsAttributesRetrieve).toHaveBeenCalledTimes(1)+ expect(jest.mocked(metricsAttributeValuesRetrieve).mock.calls.map((call) => call[1].key)).toEqual([+ expanded.attributeKey,+ ])++ // A query slower than the refresh interval: the next tick must not restart it.+ jest.mocked(metricsAttributesRetrieve).mockClear()+ jest.mocked(metricsAttributeValuesRetrieve).mockClear()+ let releaseKeys: () => void = () => {}+ let releaseValues: () => void = () => {}+ let keysRequested: () => void = () => {}+ let valuesRequested: () => void = () => {}+ const bothRequested = Promise.all([+ new Promise<void>((resolve) => {+ keysRequested = resolve+ }),+ new Promise<void>((resolve) => {+ valuesRequested = resolve+ }),+ ])+ jest.mocked(metricsAttributesRetrieve).mockImplementationOnce(() => {+ keysRequested()+ return new Promise((resolve) => {+ releaseKeys = () => resolve({ results: KEYS, count: KEYS.length })+ })+ })+ jest.mocked(metricsAttributeValuesRetrieve).mockImplementationOnce(() => {+ valuesRequested()+ return new Promise((resolve) => {+ releaseValues = () => resolve({ results: [{ id: 'prod', name: 'prod', count: 3 }] })+ })+ })+ viewer.actions.liveRefreshTick()+ await bothRequested++ viewer.actions.liveRefreshTick()+ releaseKeys()+ releaseValues()+ await expectLogic(logic).toDispatchActions(['loadAttributeKeysSuccess'])+ await expectLogic(expandedValues).toDispatchActions(['loadFacetValuesSuccess'])++ expect(metricsAttributesRetrieve).toHaveBeenCalledTimes(1)+ expect(metricsAttributeValuesRetrieve).toHaveBeenCalledTimes(1)++ // Hidden rail: ticks do not poll the keys, and reopening the rail refreshes them once.+ jest.mocked(metricsAttributesRetrieve).mockClear()+ viewer.actions.setLiveRefresh(true)+ logic.actions.setRailCollapsed(true)+ viewer.actions.liveRefreshTick()+ await expectLogic(logic).toFinishAllListeners()+ expect(metricsAttributesRetrieve).not.toHaveBeenCalled()++ logic.actions.setRailCollapsed(false)+ await expectLogic(logic).toDispatchActions(['loadAttributeKeysSuccess'])+ expect(metricsAttributesRetrieve).toHaveBeenCalledTimes(1)+ viewer.actions.setLiveRefresh(false)+ expandedValues.unmount()+ collapsedValues.unmount()+ })+})diff --git a/products/metrics/frontend/components/FacetRail/metricsFacetRailLogic.ts b/products/metrics/frontend/components/FacetRail/metricsFacetRailLogic.tsnew file mode 100644index 000000000000..c5da09d6d588--- /dev/null+++ b/products/metrics/frontend/components/FacetRail/metricsFacetRailLogic.ts@@ -0,0 +1,229 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'+import posthog from 'posthog-js'++import type { UniversalFiltersGroup } from '../../../../../frontend/src/types'+import { metricsAttributesRetrieve } from '../../generated/api'+import { canViewMetrics } from '../../metricsAccess'+import { SERVICE_NAME_KEY } from '../../metricsAttributes'+import { metricsViewerLogic, resolveDate } from '../metricsViewerLogic'+import { MetricFacetConfig, buildMetricFacets, cycleMetricFacetFilter } from './facets'++// A metric can carry dozens of attributes, and each expanded facet runs its own values query,+// so only the top-ranked facets start expanded.+export const DEFAULT_EXPANDED_FACETS = 5+const ATTRIBUTE_KEYS_LIMIT = 50++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsFacetRailLogicValues {+ currentTeamId: number | null // metricsViewerLogic+ dateFrom: string | null // metricsViewerLogic+ dateTo: string | null // metricsViewerLogic+ filterGroup: UniversalFiltersGroup // metricsViewerLogic+ liveRefresh: boolean // metricsViewerLogic+ metricName: string // metricsViewerLogic+ timezone: string // metricsViewerLogic+ attributeKeys: string[]+ attributeKeysFailed: boolean+ attributeKeysLoading: boolean+ attributeKeysScope: string+ collapseOverrides: Record<string, boolean>+ collapsedFacetKeys: string[]+ facetNameSearch: string+ loadedAttributeKeysScope: string | null+ railCollapsed: boolean+ visibleFacets: MetricFacetConfig[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsFacetRailLogicActions {+ liveRefreshTick: () => {+ value: true+ } // metricsViewerLogic+ setFilterGroup: (filterGroup: UniversalFiltersGroup) => {+ filterGroup: UniversalFiltersGroup+ } // metricsViewerLogic+ loadAttributeKeys: (_scope: string) => string+ loadAttributeKeysFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAttributeKeysSuccess: (+ attributeKeys: string[],+ payload?: string+ ) => {+ attributeKeys: string[]+ payload?: string+ }+ retryAttributeKeys: () => {+ value: true+ }+ setFacetCollapsed: (+ facetKey: string,+ collapsed: boolean+ ) => {+ collapsed: boolean+ facetKey: string+ }+ setFacetNameSearch: (search: string) => {+ search: string+ }+ setRailCollapsed: (railCollapsed: boolean) => {+ railCollapsed: boolean+ }+ toggleFacetCollapsed: (facetKey: string) => {+ facetKey: string+ }+ toggleFacetValue: (+ attributeKey: string,+ value: string+ ) => {+ attributeKey: string+ value: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsFacetRailLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ visibleFacets: (+ attributeKeys: string[],+ loadedAttributeKeysScope: string | null,+ attributeKeysScope: string+ ) => MetricFacetConfig[]+ collapsedFacetKeys: (visibleFacets: MetricFacetConfig[], collapseOverrides: Record<string, boolean>) => string[]+ attributeKeysScope: (+ metricName: string,+ dateFrom: string | null,+ dateTo: string | null,+ currentTeamId: number | null+ ) => string+ }+}++export type metricsFacetRailLogicType = MakeLogicType<+ metricsFacetRailLogicValues,+ metricsFacetRailLogicActions,+ Record<string, any>,+ metricsFacetRailLogicMeta+>++/** The metrics viewer's facet rail: which facets render, which are collapsed, and value toggles. */+export const metricsFacetRailLogic = kea<metricsFacetRailLogicType>([+ path(['products', 'metrics', 'frontend', 'components', 'FacetRail', 'metricsFacetRailLogic']),+ connect(() => ({+ values: [+ metricsViewerLogic,+ ['metricName', 'dateFrom', 'dateTo', 'timezone', 'currentTeamId', 'filterGroup', 'liveRefresh'],+ ],+ actions: [metricsViewerLogic, ['setFilterGroup', 'liveRefreshTick']],+ })),+ actions({+ retryAttributeKeys: true,+ toggleFacetValue: (attributeKey: string, value: string) => ({ attributeKey, value }),+ toggleFacetCollapsed: (facetKey: string) => ({ facetKey }),+ setFacetCollapsed: (facetKey: string, collapsed: boolean) => ({ facetKey, collapsed }),+ setFacetNameSearch: (search: string) => ({ search }),+ setRailCollapsed: (railCollapsed: boolean) => ({ railCollapsed }),+ }),+ reducers({+ facetNameSearch: ['', { setFacetNameSearch: (_, { search }) => search }],+ railCollapsed: [false, { persist: true }, { setRailCollapsed: (_, { railCollapsed }) => railCollapsed }],+ // Only the user's own toggles. The default depends on the facet's rank, which changes with the metric.+ collapseOverrides: [+ {} as Record<string, boolean>,+ { persist: true },+ {+ setFacetCollapsed: (state, { facetKey, collapsed }) => ({ ...state, [facetKey]: collapsed }),+ },+ ],+ // The scope the loaded keys belong to. Until it matches the current scope, the keys are another+ // metric's, and their facets would query the new metric for nothing.+ loadedAttributeKeysScope: [+ null as string | null,+ { loadAttributeKeysSuccess: (_, { payload }) => payload ?? null },+ ],+ attributeKeysFailed: [+ false,+ {+ loadAttributeKeysSuccess: () => false,+ loadAttributeKeysFailure: () => true,+ },+ ],+ }),+ loaders(({ values }) => ({+ attributeKeys: [+ [] as string[],+ {+ // The scope is unused here, but it rides on the success action to loadedAttributeKeysScope.+ loadAttributeKeys: async (_scope: string, breakpoint) => {+ if (!canViewMetrics() || !values.currentTeamId) {+ return []+ }+ await breakpoint(300)+ const dateFrom = resolveDate(values.dateFrom, values.timezone)+ const dateTo = resolveDate(values.dateTo, values.timezone)+ const response = await metricsAttributesRetrieve(String(values.currentTeamId), {+ ...(values.metricName.trim() ? { metricName: values.metricName.trim() } : {}),+ ...(dateFrom ? { dateFrom } : {}),+ ...(dateTo ? { dateTo } : {}),+ limit: ATTRIBUTE_KEYS_LIMIT,+ })+ breakpoint()+ return response.results.map((result) => result.name)+ },+ },+ ],+ })),+ selectors({+ visibleFacets: [+ (s) => [s.attributeKeys, s.loadedAttributeKeysScope, s.attributeKeysScope],+ (attributeKeys: string[], loadedScope: string | null, scope: string): MetricFacetConfig[] =>+ buildMetricFacets(loadedScope === scope ? attributeKeys : []),+ ],+ collapsedFacetKeys: [+ (s) => [s.visibleFacets, s.collapseOverrides],+ (facets: MetricFacetConfig[], overrides: Record<string, boolean>): string[] =>+ facets+ .filter((facet, index) => overrides[facet.key] ?? index >= DEFAULT_EXPANDED_FACETS)+ .map((facet) => facet.key),+ ],+ attributeKeysScope: [+ (s) => [s.metricName, s.dateFrom, s.dateTo, s.currentTeamId],+ (metricName: string, dateFrom: string | null, dateTo: string | null, teamId: number | null): string =>+ JSON.stringify([metricName.trim(), dateFrom, dateTo, teamId]),+ ],+ }),+ listeners(({ actions, values }) => ({+ toggleFacetValue: ({ attributeKey, value }) => {+ actions.setFilterGroup(cycleMetricFacetFilter(values.filterGroup, attributeKey, value))+ // Attribute keys are the customer's own names, so the event only says whether it was the service facet.+ posthog.capture('metrics facet rail value toggled', { is_service_facet: attributeKey === SERVICE_NAME_KEY })+ },+ toggleFacetCollapsed: ({ facetKey }) => {+ actions.setFacetCollapsed(facetKey, !values.collapsedFacetKeys.includes(facetKey))+ },+ retryAttributeKeys: () => actions.loadAttributeKeys(values.attributeKeysScope),+ // A rolling range moves with each refresh, so new attributes can appear in it. A load still in+ // flight is left to finish, because a restart would discard its result. A hidden rail does not+ // poll, because the toggle keeps this logic mounted.+ liveRefreshTick: () => {+ if (!values.railCollapsed && !values.attributeKeysLoading) {+ actions.loadAttributeKeys(values.attributeKeysScope)+ }+ },+ // Reopening catches up on the ticks the hidden rail skipped.+ setRailCollapsed: ({ railCollapsed }) => {+ if (!railCollapsed && values.liveRefresh && !values.attributeKeysLoading) {+ actions.loadAttributeKeys(values.attributeKeysScope)+ }+ },+ })),+ subscriptions(({ actions }) => ({+ attributeKeysScope: (scope: string) => actions.loadAttributeKeys(scope),+ })),+])diff --git a/products/metrics/frontend/components/FacetRail/metricsFacetValuesLogic.ts b/products/metrics/frontend/components/FacetRail/metricsFacetValuesLogic.tsnew file mode 100644index 000000000000..942b032babf0--- /dev/null+++ b/products/metrics/frontend/components/FacetRail/metricsFacetValuesLogic.ts@@ -0,0 +1,194 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'++import { FacetOption } from 'lib/components/FacetRail/Facet'++import { metricsAttributeValuesRetrieve } from '../../generated/api'+import { canViewMetrics } from '../../metricsAccess'+import { metricsViewerLogic, resolveDate } from '../metricsViewerLogic'+import { MetricFacetConfig } from './facets'+import { metricsFacetRailLogic } from './metricsFacetRailLogic'++const FACET_VALUES_LIMIT = 50++export interface MetricsFacetValuesLogicProps {+ facet: MetricFacetConfig+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsFacetValuesLogicValues {+ collapsedFacetKeys: string[] // metricsFacetRailLogic+ currentTeamId: number | null // metricsViewerLogic+ dateFrom: string | null // metricsViewerLogic+ dateTo: string | null // metricsViewerLogic+ metricName: string // metricsViewerLogic+ timezone: string // metricsViewerLogic+ collapsed: boolean+ facetSearch: string+ facetValues: FacetOption[]+ facetValuesLoading: boolean+ fetchFailed: boolean+ fetchScope: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsFacetValuesLogicActions {+ liveRefreshTick: () => {+ value: true+ } // metricsViewerLogic+ loadFacetValues: (_: any) => any+ loadFacetValuesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadFacetValuesSuccess: (+ facetValues:+ | FacetOption[]+ | {+ count: number+ label: string+ value: string+ }[],+ payload?: any+ ) => {+ facetValues:+ | FacetOption[]+ | {+ count: number+ label: string+ value: string+ }[]+ payload?: any+ }+ retryFacetValues: () => {+ value: true+ }+ setFacetSearch: (search: string) => {+ search: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface metricsFacetValuesLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ collapsed: (collapsedFacetKeys: string[], facet: MetricFacetConfig) => boolean+ fetchScope: (+ collapsed: boolean,+ metricName: string,+ dateFrom: string | null,+ dateTo: string | null,+ currentTeamId: number | null,+ facetSearch: string+ ) => string | null+ }+}++export type metricsFacetValuesLogicType = MakeLogicType<+ metricsFacetValuesLogicValues,+ metricsFacetValuesLogicActions,+ MetricsFacetValuesLogicProps,+ metricsFacetValuesLogicMeta+>++/**+ * One facet's values and data point counts for the active metric. A collapsed facet does not fetch,+ * so a metric with many attributes costs one query per facet the user opens.+ */+export const metricsFacetValuesLogic = kea<metricsFacetValuesLogicType>([+ props({} as MetricsFacetValuesLogicProps),+ key((props) => props.facet.key),+ path((key) => ['products', 'metrics', 'frontend', 'components', 'FacetRail', 'metricsFacetValuesLogic', key]),+ connect(() => ({+ values: [+ metricsViewerLogic,+ ['metricName', 'dateFrom', 'dateTo', 'timezone', 'currentTeamId'],+ metricsFacetRailLogic,+ ['collapsedFacetKeys'],+ ],+ actions: [metricsViewerLogic, ['liveRefreshTick']],+ })),+ actions({+ setFacetSearch: (search: string) => ({ search }),+ retryFacetValues: true,+ }),+ reducers({+ facetSearch: ['', { setFacetSearch: (_, { search }) => search }],+ fetchFailed: [+ false,+ {+ loadFacetValues: () => false,+ loadFacetValuesSuccess: () => false,+ loadFacetValuesFailure: () => true,+ },+ ],+ }),+ loaders(({ props, values }) => ({+ facetValues: [+ [] as FacetOption[],+ {+ loadFacetValues: async (_, breakpoint) => {+ if (!canViewMetrics() || !values.currentTeamId) {+ return []+ }+ await breakpoint(300)+ // Collapsed while this was still debouncing: nobody can see the list, so skip the request.+ if (values.collapsed) {+ return values.facetValues+ }+ const dateFrom = resolveDate(values.dateFrom, values.timezone)+ const dateTo = resolveDate(values.dateTo, values.timezone)+ const response = await metricsAttributeValuesRetrieve(String(values.currentTeamId), {+ key: props.facet.attributeKey,+ ...(values.metricName.trim() ? { metricName: values.metricName.trim() } : {}),+ ...(values.facetSearch.trim() ? { value: values.facetSearch.trim() } : {}),+ ...(dateFrom ? { dateFrom } : {}),+ ...(dateTo ? { dateTo } : {}),+ limit: FACET_VALUES_LIMIT,+ })+ breakpoint()+ return response.results.map((row) => ({ value: row.name, label: row.name, count: row.count }))+ },+ },+ ],+ })),+ selectors({+ collapsed: [+ (s, p) => [s.collapsedFacetKeys, p.facet],+ (collapsedFacetKeys: string[], facet: MetricFacetConfig): boolean => collapsedFacetKeys.includes(facet.key),+ ],+ // Null while collapsed, so opening a facet fetches and closing one does not.+ fetchScope: [+ (s) => [s.collapsed, s.metricName, s.dateFrom, s.dateTo, s.currentTeamId, s.facetSearch],+ (+ collapsed: boolean,+ metricName: string,+ dateFrom: string | null,+ dateTo: string | null,+ teamId: number | null,+ facetSearch: string+ ): string | null =>+ collapsed ? null : JSON.stringify([metricName.trim(), dateFrom, dateTo, teamId, facetSearch.trim()]),+ ],+ }),+ subscriptions(({ actions }) => ({+ fetchScope: (scope: string | null) => {+ if (scope !== null) {+ actions.loadFacetValues({})+ }+ },+ })),+ listeners(({ actions, values }) => ({+ retryFacetValues: () => actions.loadFacetValues({}),+ // A load still in flight is left to finish, because a restart would discard its result.+ liveRefreshTick: () => {+ if (!values.collapsed && !values.facetValuesLoading) {+ actions.loadFacetValues({})+ }+ },+ })),+])diff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex 081d32591248..797ab31881b5 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -20,6 +20,7 @@ import { useOpenTraceDialog } from 'products/tracing/frontend/components/TraceDiimport { getMetricsInsightEditorDisabledReason } from '../metricsAccess'import { MetricsHistogramQueryNode } from '../nodes/MetricsHistogramQueryNode'import { MetricsPanel } from '../panels/MetricsPanel'+import { MetricsFacetRailLayout, MetricsFacetRailToggle } from './FacetRail/MetricsFacetRail'import { MetricsAnomalyPanel } from './MetricsAnomalyPanel'import { type MetricsExemplar } from './MetricsExemplarMarkers'import { MetricsLogsSourceTag } from './MetricsLogsSourceTag'@@ -172,9 +173,11 @@ export const MetricsViewer = (): JSX.Element => {}, [anomalyFingerprint, dateFrom, dateTo, hasMetricName, timezone]) // eslint-disable-line react-hooks/exhaustive-depsconst languagesEnabled = useFeatureFlag('METRICS_QUERY_LANGUAGES')+ // The rail writes builder filter chips, which PromQL and SQL queries do not read.+ const facetRailEnabled = useFeatureFlag('METRICS_FACET_RAIL') && language === 'builder'return (- <div className="flex flex-col gap-3">+ <MetricsFacetRailLayout enabled={facetRailEnabled}><MetricsQueryControlsdataAttrPrefix="metrics-viewer"onSwitchLanguage={@@ -185,6 +188,7 @@ export const MetricsViewer = (): JSX.Element => {heatmap={{ eligible: heatmapEligible }}toolbarExtras={<>+ {facetRailEnabled && <MetricsFacetRailToggle />}<LemonSwitchlabel="Auto-refresh"checked={liveRefresh}@@ -330,6 +334,6 @@ export const MetricsViewer = (): JSX.Element => {</div>)}</div>- </div>+ </MetricsFacetRailLayout>)}diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex b24507c4dde8..5cf409e1cd84 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -699,6 +699,9 @@ export interface metricsViewerLogicActions {queryResults: _MetricSeriesApi[]payload?: any}+ liveRefreshTick: () => {+ value: true+ }loadAttributeKeyOptions: (_: any) => anyloadAttributeKeyOptionsFailure: (error: string,@@ -962,6 +965,8 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([// Null means auto: the backend picks a step from the range.setInterval: (interval: string | null) => ({ interval }),setLiveRefresh: (liveRefresh: boolean) => ({ liveRefresh }),+ // One auto-refresh cycle. The chart and the facet rail both reload on it.+ liveRefreshTick: true,setGroupBySearch: (groupBySearch: string) => ({ groupBySearch }),// Narrows the chart to one label value, from the anomaly panel's ranked movers.addAttributeFilter: (key: string, value: string) => ({ key, value }),@@ -1462,13 +1467,14 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([}// pauseOnPageHidden (default) stops polling on a hidden tab and resumes on focus.cache.disposables.add(() => {- const intervalId = setInterval(() => {- actions.fetchQueryResults({})- actions.fetchAnomaly({})- }, LIVE_REFRESH_MS)+ const intervalId = setInterval(() => actions.liveRefreshTick(), LIVE_REFRESH_MS)return () => clearInterval(intervalId)}, LIVE_REFRESH_KEY)},+ liveRefreshTick: () => {+ actions.fetchQueryResults({})+ actions.fetchAnomaly({})+ },}}),loaders(({ values, actions }) => ({diff --git a/products/metrics/package.json b/products/metrics/package.jsonindex ea4e5b1db591..c4daff342439 100644--- a/products/metrics/package.json+++ b/products/metrics/package.json@@ -10,6 +10,7 @@"kea": "catalog:","kea-loaders": "catalog:","kea-router": "catalog:",+ "kea-subscriptions": "catalog:","posthog-js": "catalog:"},"devDependencies": {diff --git a/products/tracing/frontend/components/FacetRail/RailFacet.tsx b/products/tracing/frontend/components/FacetRail/RailFacet.tsxindex bcfb7c0c2fb5..954a792179a7 100644--- a/products/tracing/frontend/components/FacetRail/RailFacet.tsx+++ b/products/tracing/frontend/components/FacetRail/RailFacet.tsx@@ -3,11 +3,12 @@ import { useMemo } from 'react'import { customFacetsLogic } from 'lib/components/FacetRail/customFacetsLogic'import { Facet, FacetOption } from 'lib/components/FacetRail/Facet'+import { mergeSelectedIntoOptions } from 'lib/components/FacetRail/facetGroups'import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from 'products/tracing/frontend/tracingFiltersLogic'import { facetRailLogic } from './facetRailLogic'-import { FacetConfig, customFacetIdentity, facetSelection, facetValueGroup, mergeSelectedIntoOptions } from './facets'+import { FacetConfig, customFacetIdentity, facetSelection, facetValueGroup } from './facets'import { facetValuesLogic } from './facetValuesLogic'export interface RailFacetProps {diff --git a/products/tracing/frontend/components/FacetRail/facets.test.ts b/products/tracing/frontend/components/FacetRail/facets.test.tsindex 4792f080eb9f..ff46011b9951 100644--- a/products/tracing/frontend/components/FacetRail/facets.test.ts+++ b/products/tracing/frontend/components/FacetRail/facets.test.ts@@ -14,7 +14,6 @@ import {facetScopeSignature,facetSelection,facetValueGroup,- mergeSelectedIntoOptions,resolveFacets,} from './facets'@@ -193,45 +192,6 @@ describe('facets', () => {})})- describe('mergeSelectedIntoOptions', () => {- it('prepends a selected value absent from the fetched list with a zero count', () => {- const fetched = [{ value: 'api', label: 'api', count: 5 }]- expect(mergeSelectedIntoOptions(fetched, ['worker'])).toEqual([- { value: 'worker', label: 'worker', count: 0 },- { value: 'api', label: 'api', count: 5 },- ])- })-- it('collapses duplicate selected values into one row so keys never collide', () => {- // A URL or saved view can carry the same value twice; two rows sharing a value would- // collide on their React key and toggle target.- expect(mergeSelectedIntoOptions([], ['worker', 'worker'])).toEqual([- { value: 'worker', label: 'worker', count: 0 },- ])- })-- it('does not re-add a selected value already present in the fetched list', () => {- const fetched = [{ value: 'api', label: 'api', count: 5 }]- expect(mergeSelectedIntoOptions(fetched, ['api'])).toEqual(fetched)- })- })-- describe('mergeSelectedIntoOptions', () => {- const fetched = [{ value: 'api', label: 'api', count: 10 }]-- // Injected selected-but-absent rows must honor an active type-ahead search — otherwise a- // selected value the server just filtered out reappears pinned at 0, contradicting the list.- it.each<[string, string | undefined, string[]]>([- ['no search injects every missing selected value', undefined, ['worker-1']],- ['a matching search keeps the injected value (case-insensitive)', 'WORK', ['worker-1']],- ['a non-matching search drops the injected value', 'kafka', []],- ])('%s', (_, search, expectedInjected) => {- const options = mergeSelectedIntoOptions(fetched, ['api', 'worker-1'], search)- expect(options.filter((o) => o.count === 0).map((o) => o.value)).toEqual(expectedInjected)- expect(options).toEqual(expect.arrayContaining(fetched))- })- })-describe('facetScopeSignature', () => {const configured = (key: string): FacetConfig => FACETS.find((f) => f.key === key)!const SERVICE = configured('service')diff --git a/products/tracing/frontend/components/FacetRail/facets.ts b/products/tracing/frontend/components/FacetRail/facets.tsindex 0f14e948d361..7a58d9f4265b 100644--- a/products/tracing/frontend/components/FacetRail/facets.ts+++ b/products/tracing/frontend/components/FacetRail/facets.ts@@ -426,29 +426,6 @@ export function resolveFacets(facets: FacetConfig[], presentResourceKeys: stringreturn resolved}-/**- * Ensure every selected value of a dynamic facet renders even when absent from the fetched list —- * a filter from a URL or saved view can reference a value with no matches in the current scope- * (or one below the top-N cutoff), and without a visible row it can't be seen or toggled off.- * Missing values are prepended with a zero count. An active type-ahead search still applies to- * injected rows, matching the server-side substring semantics of the fetched ones.- */-export function mergeSelectedIntoOptions(fetched: FacetOption[], selected: string[], search?: string): FacetOption[] {- const needle = (search ?? '').trim().toLowerCase()- const seen = new Set(fetched.map((option) => option.value))- // Dedupe as we go: a URL or saved view can carry the same value twice, and two rows sharing a- // value would collide on their React key and toggle target.- const missing: FacetOption[] = []- for (const value of selected) {- if (seen.has(value) || (needle && !value.toLowerCase().includes(needle))) {- continue- }- seen.add(value)- missing.push({ value, label: value, count: 0 })- }- return missing.length > 0 ? [...missing, ...fetched] : fetched-}-/** Builds a rail-renderable FacetConfig for a user-added custom facet — always dynamic, with a remove control. */export function buildCustomFacet(key: string, sourceType: CustomFacetSourceType): FacetConfig {return {