: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(tracing): reload only the other facets when a facet value is selected (#81907)
Frank Hamandaef831ddf597
diff --git a/products/tracing/frontend/components/FacetRail/FacetRail.tsx b/products/tracing/frontend/components/FacetRail/FacetRail.tsxindex 6c3b46ce85d2..f75850ef63d2 100644--- a/products/tracing/frontend/components/FacetRail/FacetRail.tsx+++ b/products/tracing/frontend/components/FacetRail/FacetRail.tsx@@ -7,18 +7,10 @@ import { Resizer } from 'lib/components/Resizer/Resizer'import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'import { tracingConfigLogic } from '../../tracingConfigLogic'-import { tracingFiltersLogic } from '../../tracingFiltersLogic'-import { Facet } from './Facet'-import { facetCountsLogic } from './facetCountsLogic'+import { facetPresenceLogic } from './facetPresenceLogic'import { facetRailLogic } from './facetRailLogic'-import {- FacetConfig,- FacetOption,- facetSelection,- facetsByGroup,- filterFacetsByName,- mergeSelectedIntoOptions,-} from './facets'+import { facetsByGroup, filterFacetsByName } from './facets'+import { RailFacet } from './RailFacet'const DEFAULT_WIDTH_PX = 240const COLLAPSE_THRESHOLD_PX = 120@@ -27,11 +19,9 @@ const COLLAPSE_THRESHOLD_PX = 120export function FacetRail(): JSX.Element {const railRef = useRef<HTMLDivElement>(null)const { setFacetRailCollapsed } = useActions(tracingConfigLogic)- const { serviceNames, filters } = useValues(tracingFiltersLogic)- const { facetValues, loadingFacetKeys, erroredFacetKeys, facetSearch, visibleFacets } = useValues(facetCountsLogic)- const { setFacetSearch } = useActions(facetCountsLogic)- const { collapsedFacets, facetNameSearch } = useValues(facetRailLogic)- const { toggleFacetValue, toggleFacetCollapsed, setFacetNameSearch } = useActions(facetRailLogic)+ const { visibleFacets } = useValues(facetPresenceLogic)+ const { facetNameSearch } = useValues(facetRailLogic)+ const { setFacetNameSearch } = useActions(facetRailLogic)const onToggleClosed = useCallback((shouldBeClosed: boolean) => setFacetRailCollapsed(shouldBeClosed),@@ -51,77 +41,10 @@ export function FacetRail(): JSX.Element {)const { desiredSize } = useValues(resizerLogic(resizerLogicProps))- const renderFacet = (facet: FacetConfig): JSX.Element => {- const { source } = facet- // Selection: the service facet reads the dedicated serviceNames field (include-only);- // everything else reads its property filters out of the group, both polarities.- const { included: selected, excluded } = facetSelection(filters.filterGroup, serviceNames, source)- // Values + counts come from the cross-filtered endpoint, keyed by facet.key. Drop the- // empty-value bucket (spans missing the attribute): it renders as a blank, label-less row- // that the selection reader can't track, so it would become a stuck, un-toggleable filter.- const fetched: FacetOption[] = (facetValues[facet.key] ?? [])- .filter((row) => row.value !== '')- .map((row) => ({- value: row.value,- label: row.value,- count: row.count,- }))- const loading = loadingFacetKeys.includes(facet.key)- const error = erroredFacetKeys.includes(facet.key)- const onToggle = (value: string): void => toggleFacetValue(source, value)- const onToggleCollapsed = (): void => toggleFacetCollapsed(facet.key)- const collapsed = collapsedFacets.includes(facet.key)-- if (facet.kind === 'fixed') {- // Fixed value set from config, counts overlaid. Missing values render as a dimmed 0.- const countByValue = new Map(fetched.map((option) => [option.value, option.count]))- const options: FacetOption[] = (facet.fixedOptions ?? []).map((option) => ({- ...option,- count: countByValue.get(option.value) ?? 0,- }))- return (- <Facet- key={facet.key}- title={facet.title}- options={options}- selected={selected}- excluded={excluded}- onToggle={onToggle}- loading={loading}- collapsed={collapsed}- onToggleCollapsed={onToggleCollapsed}- dimZeroCounts- error={error}- />- )- }-- // Dynamic facet: values + counts come straight from the cross-filtered endpoint (zeros never- // appear), with any selected-but-absent values injected so they stay visible and toggleable.- const search = facet.searchable ? facetSearch[facet.key] : undefined- return (- <Facet- key={facet.key}- title={facet.title}- options={mergeSelectedIntoOptions(fetched, [...selected, ...excluded], search)}- selected={selected}- excluded={excluded}- onToggle={onToggle}- loading={loading}- emptyLabel={facet.emptyLabel}- searchValue={facet.searchable ? (search ?? '') : undefined}- onSearchChange={facet.searchable ? (value) => setFacetSearch(facet.key, value) : undefined}- searchPlaceholder={facet.searchPlaceholder}- collapsed={collapsed}- onToggleCollapsed={onToggleCollapsed}- maxHeight={facet.maxHeight}- error={error}- />- )- }-- // Filter the rail by the field-name search, then group — empty groups fall away in facetsByGroup.- const displayedGroups = facetsByGroup(filterFacetsByName(visibleFacets, facetNameSearch))+ // Every visible facet renders a container, whether or not the field-name search matches it: a+ // non-matching one renders nothing but stays mounted, so clearing the search doesn't refetch.+ const matchingKeys = new Set(filterFacetsByName(visibleFacets, facetNameSearch).map((f) => f.key))+ const groups = facetsByGroup(visibleFacets)return (<div@@ -145,18 +68,21 @@ export function FacetRail(): JSX.Element {/></div><div className="flex-1 min-h-0 overflow-y-auto p-2">- {displayedGroups.length === 0 && facetNameSearch.trim() ? (+ {matchingKeys.size === 0 && facetNameSearch.trim() && (<div className="px-1 text-xs text-muted">No matching facets</div>- ) : (- displayedGroups.map(([group, facets]) => (- <div key={group}>+ )}+ {groups.map(([group, facets]) => (+ <div key={group}>+ {facets.some((facet) => matchingKeys.has(facet.key)) && (<div className="px-1 pb-1 mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted border-b border-primary">{group}</div>- {facets.map(renderFacet)}- </div>- ))- )}+ )}+ {facets.map((facet) => (+ <RailFacet key={facet.key} facet={facet} hidden={!matchingKeys.has(facet.key)} />+ ))}+ </div>+ ))}</div><Resizer {...resizerLogicProps} visible={false} offset="0.25rem" handleClassName="rounded my-1" /></div>diff --git a/products/tracing/frontend/components/FacetRail/RailFacet.tsx b/products/tracing/frontend/components/FacetRail/RailFacet.tsxnew file mode 100644index 000000000000..22344e0830ad--- /dev/null+++ b/products/tracing/frontend/components/FacetRail/RailFacet.tsx@@ -0,0 +1,92 @@+import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { TRACING_SCENE_VIEWER_ID, tracingFiltersLogic } from 'products/tracing/frontend/tracingFiltersLogic'++import { Facet } from './Facet'+import { facetRailLogic } from './facetRailLogic'+import { FacetConfig, FacetOption, facetSelection, mergeSelectedIntoOptions } from './facets'+import { facetValuesLogic } from './facetValuesLogic'++export interface RailFacetProps {+ facet: FacetConfig+ id?: string+ /**+ * Filtered out by the rail's facet-name search. Renders nothing, but keeps this facet's logic+ * mounted — clearing the search box shouldn't cost a round trip to redraw values we already had.+ */+ hidden?: boolean+}++/** One facet in the rail, with its own independently-loaded values (see facetValuesLogic). */+export function RailFacet({ facet, id = TRACING_SCENE_VIEWER_ID, hidden }: RailFacetProps): JSX.Element | null {+ // `facet` comes from the memoized visibleFacets selector, so this identity is stable.+ const logicProps = useMemo(() => ({ id, facet }), [id, facet])+ const { facetValues, facetValuesLoading, fetchFailed, facetSearch, collapsed } = useValues(+ facetValuesLogic(logicProps)+ )+ const { setFacetSearch } = useActions(facetValuesLogic(logicProps))+ const { serviceNames, filters } = useValues(tracingFiltersLogic({ id }))+ const { toggleFacetValue, toggleFacetCollapsed } = useActions(facetRailLogic({ id }))++ if (hidden) {+ return null+ }++ const { source } = facet+ // Selection: the service facet reads the dedicated serviceNames field (include-only);+ // everything else reads its property filters out of the group, both polarities.+ const { included: selected, excluded } = facetSelection(filters.filterGroup, serviceNames, source)+ // Drop the empty-value bucket (spans missing the attribute): it renders as a blank, label-less row+ // that the selection reader can't track, so it would become a stuck, un-toggleable filter.+ const fetched: FacetOption[] = facetValues+ .filter((row) => row.value !== '')+ .map((row) => ({ value: row.value, label: row.value, count: row.count }))+ const onToggle = (value: string): void => toggleFacetValue(source, value)+ const onToggleCollapsed = (): void => toggleFacetCollapsed(facet.key)++ if (facet.kind === 'fixed') {+ // Fixed value set from config, counts overlaid. Missing values render as a dimmed 0.+ const countByValue = new Map(fetched.map((option) => [option.value, option.count]))+ const options: FacetOption[] = (facet.fixedOptions ?? []).map((option) => ({+ ...option,+ count: countByValue.get(option.value) ?? 0,+ }))+ return (+ <Facet+ title={facet.title}+ options={options}+ selected={selected}+ excluded={excluded}+ onToggle={onToggle}+ loading={facetValuesLoading}+ collapsed={collapsed}+ onToggleCollapsed={onToggleCollapsed}+ dimZeroCounts+ error={fetchFailed}+ />+ )+ }++ // Dynamic facet: values + counts come straight from the cross-filtered endpoint (zeros never+ // appear), with any selected-but-absent values injected so they stay visible and toggleable.+ const search = facet.searchable ? facetSearch : undefined+ return (+ <Facet+ title={facet.title}+ options={mergeSelectedIntoOptions(fetched, [...selected, ...excluded], search)}+ selected={selected}+ excluded={excluded}+ onToggle={onToggle}+ loading={facetValuesLoading}+ emptyLabel={facet.emptyLabel}+ searchValue={search}+ onSearchChange={facet.searchable ? setFacetSearch : undefined}+ searchPlaceholder={facet.searchPlaceholder}+ collapsed={collapsed}+ onToggleCollapsed={onToggleCollapsed}+ maxHeight={facet.maxHeight}+ error={fetchFailed}+ />+ )+}diff --git a/products/tracing/frontend/components/FacetRail/facetCountsLogic.test.ts b/products/tracing/frontend/components/FacetRail/facetCountsLogic.test.tsdeleted file mode 100644index 40a63ecc5aff..000000000000--- a/products/tracing/frontend/components/FacetRail/facetCountsLogic.test.ts+++ /dev/null@@ -1,120 +0,0 @@-import { expectLogic } from 'kea-test-utils'--import { initKeaTests } from '~/test/init'--import {- tracingSpansAttributeBreakdownCreate,- tracingSpansAttributesRetrieve,-} from 'products/tracing/frontend/generated/api'-import type { _TracingAttributeBreakdownRowApi } from 'products/tracing/frontend/generated/api.schemas'--import { facetCountsLogic } from './facetCountsLogic'--jest.mock('products/tracing/frontend/generated/api', () => ({- __esModule: true,- tracingSpansAttributeBreakdownCreate: jest.fn(),- tracingSpansAttributesRetrieve: jest.fn(),-}))--const mockBreakdown = tracingSpansAttributeBreakdownCreate as jest.MockedFunction<- typeof tracingSpansAttributeBreakdownCreate->-const mockAttributes = tracingSpansAttributesRetrieve as jest.MockedFunction<typeof tracingSpansAttributesRetrieve>--const ID = 'test-viewer'--function row(value: string, count: number): _TracingAttributeBreakdownRowApi {- return { value, count, error_count: 0, p50_duration_nano: 0, p95_duration_nano: 0 }-}--describe('facetCountsLogic', () => {- let logic: ReturnType<typeof facetCountsLogic.build>-- beforeEach(() => {- initKeaTests()- jest.clearAllMocks()- // No resource-attribute keys present, so only the column facets (service, status) are visible.- mockAttributes.mockResolvedValue({ results: [], count: 0 })- mockBreakdown.mockResolvedValue({ results: [row('api', 10)], compare: null })- logic = facetCountsLogic({ id: ID })- })-- afterEach(() => {- logic.unmount()- })-- it('a facet search refetches only that facet, passing facetSearch to the endpoint', async () => {- logic.mount()- await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])- mockBreakdown.mockClear()-- logic.actions.setFacetSearch('service', 'kaf')- await expectLogic(logic).toDispatchActions(['loadFacetValuesForKey', 'loadFacetValuesForKeySuccess'])-- expect(mockBreakdown).toHaveBeenCalledTimes(1)- expect(mockBreakdown).toHaveBeenCalledWith(- expect.any(String),- expect.objectContaining({- query: expect.objectContaining({ breakdownKey: 'service_name', facetSearch: 'kaf' }),- })- )- })-- it('a failed facet is marked errored without wiping the others, and recovers on the next fetch', async () => {- // One broken breakdown must show per-facet (erroredFacetKeys), not blank the whole rail.- mockBreakdown.mockImplementation((_, request) =>- request.query.breakdownKey === 'status_code'- ? Promise.reject(new Error('breakdown failed'))- : Promise.resolve({ results: [row('api', 10)], compare: null })- )- logic.mount()- await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])-- expect(logic.values.erroredFacetKeys).toEqual(['status'])- expect(logic.values.facetValues['service']).toEqual([row('api', 10)])- expect(logic.values.facetValues['status']).toBeUndefined()-- mockBreakdown.mockResolvedValue({ results: [row('2', 3)], compare: null })- logic.actions.loadFacetValues(null)- await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])-- expect(logic.values.erroredFacetKeys).toEqual([])- expect(logic.values.facetValues['status']).toEqual([row('2', 3)])- })-- it('a full reload that raced a facet search does not overwrite the narrowed results', async () => {- logic.mount()- await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])-- // The reload's service request (no facetSearch) hangs until released; the search request- // (facetSearch set) and every other facet resolve immediately.- let releaseStaleReload: (rows: _TracingAttributeBreakdownRowApi[]) => void = () => {}- let staleReloadRequested: () => void = () => {}- const staleReloadIssued = new Promise<void>((resolve) => (staleReloadRequested = resolve))- mockBreakdown.mockImplementation((_, request) => {- if (request.query.breakdownKey === 'service_name' && !request.query.facetSearch) {- staleReloadRequested()- return new Promise((resolve) => {- releaseStaleReload = (rows) => resolve({ results: rows, compare: null })- })- }- if (request.query.facetSearch === 'kaf') {- return Promise.resolve({ results: [row('kafka-consumer', 2)], compare: null })- }- return Promise.resolve({ results: [row('api', 10)], compare: null })- })-- logic.actions.loadFacetValues(null)- await staleReloadIssued-- logic.actions.setFacetSearch('service', 'kaf')- await expectLogic(logic).toDispatchActions(['loadFacetValuesForKeySuccess'])- expect(logic.values.facetValues['service']).toEqual([row('kafka-consumer', 2)])-- releaseStaleReload([row('api', 10), row('worker', 5)])- await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])-- expect(logic.values.facetValues['service']).toEqual([row('kafka-consumer', 2)])- expect(logic.values.erroredFacetKeys).toEqual([])- })-})diff --git a/products/tracing/frontend/components/FacetRail/facetCountsLogic.ts b/products/tracing/frontend/components/FacetRail/facetCountsLogic.tsdeleted file mode 100644index 8339767eca8c..000000000000--- a/products/tracing/frontend/components/FacetRail/facetCountsLogic.ts+++ /dev/null@@ -1,402 +0,0 @@-import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'-import { loaders } from 'kea-loaders'-import { subscriptions } from 'kea-subscriptions'--import { teamLogic } from 'scenes/teamLogic'--import { DateRange } from '~/queries/schema/schema-general'-import { UniversalFiltersGroup } from '~/types'--import {- TRACING_SCENE_VIEWER_ID,- tracingFiltersLogic,- TracingFiltersLogicProps,-} from 'products/tracing/frontend/tracingFiltersLogic'--import { tracingSpansAttributeBreakdownCreate, tracingSpansAttributesRetrieve } from '../../generated/api'-import {- _SpanPropertyFilterApi,- _SpanPropertyFilterOperatorEnumApi,- _TracingAttributeBreakdownRowApi,- SpanPropertyTypeEnumApi,- TracingSpansAttributesRetrieveAttributeType,-} from '../../generated/api.schemas'-import { FACETS, FacetConfig, innerFilters, resolveFacets } from './facets'--export interface FacetCountsLogicProps {- id: string-}--/** The query-relevant slice of filter state — the breakdown requests read exactly these three. */-export interface BreakdownScope {- utcDateRange: DateRange- serviceNames: string[]- queryFilterGroup: UniversalFiltersGroup-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface facetCountsLogicValues {- currentTeamId: number | null // teamLogic- queryFilterGroup: UniversalFiltersGroup // tracingFiltersLogic- serviceNames: string[] // tracingFiltersLogic- utcDateRange: {- date_from: string | null | undefined- date_to: string | null | undefined- } // tracingFiltersLogic- breakdownScope: BreakdownScope- erroredFacetKeys: string[]- facetSearch: Record<string, string>- facetValues: Record<string, _TracingAttributeBreakdownRowApi[]>- facetValuesLoading: boolean- loadingFacetKeys: string[]- loadingReloadKeys: string[]- loadingSearchKey: string | null- presenceLoaded: boolean- presentResourceKeys: string[]- presentResourceKeysLoading: boolean- visibleFacets: FacetConfig[]-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface facetCountsLogicActions {- loadFacetValues: (facetKeys: string[] | null) => string[] | null- loadFacetValuesFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadFacetValuesForKey: (facetKey: string) => string- loadFacetValuesForKeyFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadFacetValuesForKeySuccess: (- facetValues: Record<string, _TracingAttributeBreakdownRowApi[]>,- payload?: string- ) => {- facetValues: Record<string, _TracingAttributeBreakdownRowApi[]>- payload?: string- }- loadFacetValuesSuccess: (- facetValues: Record<string, _TracingAttributeBreakdownRowApi[]>,- payload?: string[] | null- ) => {- facetValues: Record<string, _TracingAttributeBreakdownRowApi[]>- payload?: string[] | null- }- loadPresentResourceKeys: () => any- loadPresentResourceKeysFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadPresentResourceKeysSuccess: (- presentResourceKeys: string[],- payload?: any- ) => {- presentResourceKeys: string[]- payload?: any- }- setFacetFetchErrors: (- attempted: string[],- failed: string[]- ) => {- attempted: string[]- failed: string[]- }- setFacetSearch: (- facetKey: string,- search: string- ) => {- facetKey: string- search: string- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface facetCountsLogicMeta {- key: string- __keaTypeGenInternalSelectorTypes: {- visibleFacets: (presentResourceKeys: string[]) => FacetConfig[]- loadingFacetKeys: (loadingReloadKeys: string[], loadingSearchKey: string | null) => string[]- breakdownScope: (- utcDateRange: {- date_from: string | null | undefined- date_to: string | null | undefined- },- serviceNames: string[],- queryFilterGroup: UniversalFiltersGroup- ) => BreakdownScope- }-}--export type facetCountsLogicType = MakeLogicType<- facetCountsLogicValues,- facetCountsLogicActions,- FacetCountsLogicProps,- facetCountsLogicMeta->--/**- * Per-facet values + counts, cross-filtered server-side: each facet's results reflect every active- * filter except its own selection (excludeBreakdownFilter drops the facet's own column, serviceNames,- * or attribute filter). Values come back ordered by count descending. The rail is config-driven, so- * this fetches one attribute-breakdown request per facet in FACETS, keyed by facet.key. A per-facet- * type-ahead search re-fetches only that facet (its CH group-by is a full scan, so we don't refetch- * the others on every keystroke).- */-export const facetCountsLogic = kea<facetCountsLogicType>([- props({ id: TRACING_SCENE_VIEWER_ID } as FacetCountsLogicProps),- key((props) => props.id),- path((key) => ['products', 'tracing', 'frontend', 'components', 'FacetRail', 'facetCountsLogic', key]),-- connect((props: FacetCountsLogicProps) => ({- values: [- tracingFiltersLogic({ id: props.id } as TracingFiltersLogicProps),- ['serviceNames', 'utcDateRange', 'queryFilterGroup'],- teamLogic,- ['currentTeamId'],- ],- })),-- actions({- setFacetSearch: (facetKey: string, search: string) => ({ facetKey, search }),- // Dispatched by the loaders after each allSettled batch: `attempted` facets leave the error- // set (they got a fresh verdict), `failed` ones (re-)enter it.- setFacetFetchErrors: (attempted: string[], failed: string[]) => ({ attempted, failed }),- }),-- reducers({- facetSearch: [- {} as Record<string, string>,- {- setFacetSearch: (state, { facetKey, search }) => ({ ...state, [facetKey]: search }),- },- ],- // Facets whose latest fetch failed — drives the per-facet inline error state, so one broken- // breakdown shows in place instead of blanking the rail.- erroredFacetKeys: [- [] as string[],- {- setFacetFetchErrors: (state, { attempted, failed }) => [- ...state.filter((key) => !attempted.includes(key)),- ...failed,- ],- },- ],- // Facets being refreshed by a filter-change reload. Single-flight (its own breakpoint), so the- // whole set clears together on settle. null arg = all facets.- loadingReloadKeys: [- [] as string[],- {- loadFacetValues: (_, facetKeys: string[] | null) => facetKeys ?? FACETS.map((f) => f.key),- loadFacetValuesSuccess: () => [],- loadFacetValuesFailure: () => [],- },- ],- // The single facet whose type-ahead search is in flight. Single-flight across facets (the per-key- // loader shares one breakpoint), so a new search supersedes the previous one rather than stacking.- loadingSearchKey: [- null as string | null,- {- loadFacetValuesForKey: (_, facetKey: string) => facetKey,- loadFacetValuesForKeySuccess: () => null,- loadFacetValuesForKeyFailure: () => null,- },- ],- // Latches true once the presence probe settles (success or failure). Until then the value- // fetch is deferred, so column facets aren't fetched on mount and then re-fetched once- // presence resolves and the resource-attribute facets become visible.- presenceLoaded: [- false,- {- loadPresentResourceKeysSuccess: () => true,- loadPresentResourceKeysFailure: () => true,- },- ],- }),-- loaders(({ actions, values }) => {- const fetchFacet = async (facet: FacetConfig): Promise<_TracingAttributeBreakdownRowApi[]> => {- if (!values.currentTeamId) {- return []- }- // The endpoint takes the flat inner filter list. The stored filters carry the app-side- // enums (PropertyFilterType/PropertyOperator) which are nominally distinct from the- // generated string-union enums despite identical runtime values, so mapping onto the- // generated shape type-checks the field structure (key/value) while casting only the two- // enum fields.- const filterGroup: _SpanPropertyFilterApi[] = innerFilters(values.queryFilterGroup).map((f) => ({- key: f.key,- type: f.type as unknown as SpanPropertyTypeEnumApi,- operator: f.operator as unknown as _SpanPropertyFilterOperatorEnumApi,- value: f.value,- }))- const target =- facet.source.type === 'column'- ? { breakdownKey: facet.source.column, breakdownType: SpanPropertyTypeEnumApi.Span }- : { breakdownKey: facet.source.key, breakdownType: SpanPropertyTypeEnumApi.SpanResourceAttribute }- const response = await tracingSpansAttributeBreakdownCreate(String(values.currentTeamId), {- query: {- ...target,- excludeBreakdownFilter: true,- dateRange: values.utcDateRange,- serviceNames: values.serviceNames ?? [],- facetSearch: values.facetSearch[facet.key] || undefined,- filterGroup,- },- })- return response.results- }-- // Fetch each facet independently and merge into the existing record. allSettled (not all) so- // one facet's failed request leaves the others' counts intact instead of wiping the batch.- // Failures are recorded per facet for the inline error state.- const mergeFetched = async (- facets: FacetConfig[]- ): Promise<Record<string, _TracingAttributeBreakdownRowApi[]>> => {- // The search term each request is about to carry. A full reload and a per-facet search- // have independent breakpoints, so a reload issued before the user typed can settle- // after the narrowed search response — merging it would put unsearched rows under a- // still-filled search box. Dropping stale-term rows leaves the fresher response's in place.- const searchAtRequest = Object.fromEntries(facets.map((f) => [f.key, values.facetSearch[f.key] ?? '']))- const settled = await Promise.allSettled(- facets.map(async (facet) => [facet.key, await fetchFacet(facet)] as const)- )- const fulfilled = settled- .filter(- (s): s is PromiseFulfilledResult<readonly [string, _TracingAttributeBreakdownRowApi[]]> =>- s.status === 'fulfilled'- )- .map((s) => s.value)- // Error state keys off fulfillment: a stale-term fetch still succeeded, it just doesn't merge.- const fulfilledKeys = new Set(fulfilled.map(([key]) => key))- const attemptedKeys = facets.map((f) => f.key)- // Fires before the final breakpoint, so a superseded batch can record error state — the- // winning batch immediately overwrites it, since every batch reports all attempted keys.- actions.setFacetFetchErrors(- attemptedKeys,- attemptedKeys.filter((key) => !fulfilledKeys.has(key))- )- const fetched = fulfilled.filter(([key]) => (values.facetSearch[key] ?? '') === searchAtRequest[key])- return { ...values.facetValues, ...Object.fromEntries(fetched) }- }-- return {- facetValues: [- {} as Record<string, _TracingAttributeBreakdownRowApi[]>,- {- // Refetch all facets (null) or a subset — used when filters change.- loadFacetValues: async (facetKeys: string[] | null, breakpoint) => {- await breakpoint(300)- const facets = facetKeys- ? values.visibleFacets.filter((f) => facetKeys.includes(f.key))- : values.visibleFacets- const result = await mergeFetched(facets)- breakpoint()- return result- },- // A single facet's type-ahead search. Separate action so its breakpoint is independent:- // typing in one facet's search must not cancel a still-debouncing full reload.- loadFacetValuesForKey: async (facetKey: string, breakpoint) => {- await breakpoint(300)- // Resolved, not raw: an aliased facet must search the key the tenant emits.- const facet = values.visibleFacets.find((f) => f.key === facetKey)- const result = facet ? await mergeFetched([facet]) : values.facetValues- breakpoint()- return result- },- },- ],- presentResourceKeys: [- [] as string[],- {- // Which resource attribute keys the tenant emits — gates which curated facets render.- // Reads the trace_attributes rollup keys-only; no date range parameter (server default window).- loadPresentResourceKeys: async () => {- if (!values.currentTeamId) {- return []- }- const response = await tracingSpansAttributesRetrieve(String(values.currentTeamId), {- attribute_type: TracingSpansAttributesRetrieveAttributeType.SpanResourceAttribute,- limit: 100,- })- return response.results.map((r) => r.name)- },- },- ],- }- }),-- selectors({- // Column facets always render; resource-attribute facets only when the tenant emits the key (or one- // of its aliases, which resolution rewrites the facet onto).- visibleFacets: [- (s) => [s.presentResourceKeys],- (presentResourceKeys: string[]): FacetConfig[] => resolveFacets(FACETS, presentResourceKeys),- ],- // Per-facet loading state. A filter-change reload and a per-facet search have independent- // breakpoints and can overlap, so union both sources — otherwise whichever settles first would- // clear the other's spinners. Keeping them as separate single-flight reducers means neither can- // leak a stuck spinner: each clears wholesale on its own settle.- loadingFacetKeys: [- (s) => [s.loadingReloadKeys, s.loadingSearchKey],- (loadingReloadKeys: string[], loadingSearchKey: string | null): string[] =>- loadingSearchKey && !loadingReloadKeys.includes(loadingSearchKey)- ? [...loadingReloadKeys, loadingSearchKey]- : loadingReloadKeys,- ],- // The subset of filter state the breakdown queries actually depend on, built from the stable- // leaf values — not the `filters` roll-up, which also carries presentation state (viewMode,- // orderBy, compareMode, overlay windows) and gets a new identity whenever any of it changes.- // Subscribing to this keeps a view-mode or sort toggle from refetching every facet.- breakdownScope: [- (s) => [s.utcDateRange, s.serviceNames, s.queryFilterGroup],- (- utcDateRange: {- date_from: string | null | undefined- date_to: string | null | undefined- },- serviceNames: string[],- queryFilterGroup: UniversalFiltersGroup- ): BreakdownScope => ({- utcDateRange,- serviceNames,- queryFilterGroup,- }),- ],- }),-- listeners(({ actions }) => ({- // A facet's search changed — refetch only that facet, via its own action so it doesn't- // cancel a still-debouncing full reload (independent breakpoint).- setFacetSearch: ({ facetKey }) => actions.loadFacetValuesForKey(facetKey),- // Presence settled — drive the first full fetch now that visibleFacets is known. On failure- // we still fetch so the column facets (Service/Status) load even if the probe errored.- loadPresentResourceKeysSuccess: () => actions.loadFacetValues(null),- loadPresentResourceKeysFailure: () => actions.loadFacetValues(null),- })),-- events(({ actions }) => ({- afterMount: () => actions.loadPresentResourceKeys(),- })),-- subscriptions(({ actions, values }) => ({- // Fires on any change to the query-relevant filter state (date range, services, filter group- // including an embedder's pinned scope). Before the presence probe settles, defer to- // loadPresentResourceKeys{Success,Failure} so we issue one full fetch over the final visible- // set instead of two.- breakdownScope: () => {- if (values.presenceLoaded) {- actions.loadFacetValues(null)- }- },- })),-])diff --git a/products/tracing/frontend/components/FacetRail/facetPresenceLogic.ts b/products/tracing/frontend/components/FacetRail/facetPresenceLogic.tsnew file mode 100644index 000000000000..5af7e604ecc5--- /dev/null+++ b/products/tracing/frontend/components/FacetRail/facetPresenceLogic.ts@@ -0,0 +1,105 @@+import { MakeLogicType, connect, events, kea, key, path, props, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { TRACING_SCENE_VIEWER_ID } from 'products/tracing/frontend/tracingFiltersLogic'++import { tracingSpansAttributesRetrieve } from '../../generated/api'+import { TracingSpansAttributesRetrieveAttributeType } from '../../generated/api.schemas'+import { FACETS, FacetConfig, resolveFacets } from './facets'++export interface FacetPresenceLogicProps {+ id: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface facetPresenceLogicValues {+ currentTeamId: number | null // teamLogic+ presentResourceKeys: string[]+ presentResourceKeysLoading: boolean+ visibleFacets: FacetConfig[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface facetPresenceLogicActions {+ loadPresentResourceKeys: () => any+ loadPresentResourceKeysFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadPresentResourceKeysSuccess: (+ presentResourceKeys: string[],+ payload?: any+ ) => {+ presentResourceKeys: string[]+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface facetPresenceLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ visibleFacets: (presentResourceKeys: string[]) => FacetConfig[]+ }+}++export type facetPresenceLogicType = MakeLogicType<+ facetPresenceLogicValues,+ facetPresenceLogicActions,+ FacetPresenceLogicProps,+ facetPresenceLogicMeta+>++/**+ * Which facets the rail renders. The curated list in FACETS is config, not data: a resource-attribute+ * facet only earns a slot if the tenant emits its key (or an older spelling of it), so this probes the+ * emitted keys once on mount and resolves the list against them. Values and counts are fetched per+ * facet, by facetValuesLogic.+ */+export const facetPresenceLogic = kea<facetPresenceLogicType>([+ props({ id: TRACING_SCENE_VIEWER_ID } as FacetPresenceLogicProps),+ key((props) => props.id),+ path((key) => ['products', 'tracing', 'frontend', 'components', 'FacetRail', 'facetPresenceLogic', key]),++ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ })),++ loaders(({ values }) => ({+ presentResourceKeys: [+ [] as string[],+ {+ // Which resource attribute keys the tenant emits — gates which curated facets render.+ // Reads the trace_attributes rollup keys-only; no date range parameter (server default window).+ loadPresentResourceKeys: async () => {+ if (!values.currentTeamId) {+ return []+ }+ const response = await tracingSpansAttributesRetrieve(String(values.currentTeamId), {+ attribute_type: TracingSpansAttributesRetrieveAttributeType.SpanResourceAttribute,+ limit: 100,+ })+ return response.results.map((r) => r.name)+ },+ },+ ],+ })),++ selectors({+ // Column facets always render; resource-attribute facets only when the tenant emits the key (or one+ // of its aliases, which resolution rewrites the facet onto).+ visibleFacets: [+ (s) => [s.presentResourceKeys],+ (presentResourceKeys: string[]): FacetConfig[] => resolveFacets(FACETS, presentResourceKeys),+ ],+ }),++ events(({ actions }) => ({+ afterMount: () => actions.loadPresentResourceKeys(),+ })),+])diff --git a/products/tracing/frontend/components/FacetRail/facetValuesLogic.test.ts b/products/tracing/frontend/components/FacetRail/facetValuesLogic.test.tsnew file mode 100644index 000000000000..b2335328eab3--- /dev/null+++ b/products/tracing/frontend/components/FacetRail/facetValuesLogic.test.ts@@ -0,0 +1,170 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'++import { tracingSpansAttributeBreakdownCreate } from 'products/tracing/frontend/generated/api'+import type { _TracingAttributeBreakdownRowApi } from 'products/tracing/frontend/generated/api.schemas'+import { tracingFiltersLogic } from 'products/tracing/frontend/tracingFiltersLogic'++import { facetRailLogic } from './facetRailLogic'+import { FACETS, FacetConfig } from './facets'+import { facetValuesLogic } from './facetValuesLogic'++jest.mock('products/tracing/frontend/generated/api', () => ({+ __esModule: true,+ tracingSpansAttributeBreakdownCreate: jest.fn(),+ tracingSpansAttributesRetrieve: jest.fn(),+}))++const mockBreakdown = tracingSpansAttributeBreakdownCreate as jest.MockedFunction<+ typeof tracingSpansAttributeBreakdownCreate+>++const ID = 'test-viewer'++const facetConfig = (key: string): FacetConfig => FACETS.find((f) => f.key === key)!+const SERVICE = facetConfig('service')+const STATUS = facetConfig('status')++function row(value: string, count: number): _TracingAttributeBreakdownRowApi {+ return { value, count, error_count: 0, p50_duration_nano: 0, p95_duration_nano: 0 }+}++const statusFilterGroup: UniversalFiltersGroup = {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: PropertyFilterType.Span,+ key: 'status_code',+ operator: PropertyOperator.Exact,+ value: ['2'],+ },+ ] as UniversalFiltersGroup['values'],+ },+ ],+}++describe('facetValuesLogic', () => {+ let filtersLogic: ReturnType<typeof tracingFiltersLogic.build>+ let railLogic: ReturnType<typeof facetRailLogic.build>+ const mounted: ReturnType<typeof facetValuesLogic.build>[] = []++ const mountFacet = (facet: FacetConfig): ReturnType<typeof facetValuesLogic.build> => {+ const logic = facetValuesLogic({ id: ID, facet })+ logic.mount()+ mounted.push(logic)+ return logic+ }++ beforeEach(() => {+ initKeaTests()+ jest.clearAllMocks()+ mockBreakdown.mockResolvedValue({ results: [row('api', 10)], compare: null })+ filtersLogic = tracingFiltersLogic({ id: ID })+ filtersLogic.mount()+ railLogic = facetRailLogic({ id: ID })+ railLogic.mount()+ })++ afterEach(() => {+ mounted.splice(0).forEach((logic) => logic.unmount())+ railLogic.unmount()+ filtersLogic.unmount()+ })++ // Selecting a value re-scopes the *other* facets: excludeBreakdownFilter strips a facet's own+ // filter from its own breakdown, so refetching it burns a request on an unchanged response.+ it.each<[string, FacetConfig, FacetConfig, () => void]>([+ ['a service selection', SERVICE, STATUS, () => filtersLogic.actions.setServiceNames(['api'])],+ ['a status selection', STATUS, SERVICE, () => filtersLogic.actions.setFilterGroup(statusFilterGroup)],+ ])('%s reloads the other facets but not itself', async (_, selected, other, select) => {+ const selectedLogic = mountFacet(selected)+ const otherLogic = mountFacet(other)+ await expectLogic(selectedLogic).toDispatchActions(['loadFacetValuesSuccess'])+ await expectLogic(otherLogic).toDispatchActions(['loadFacetValuesSuccess'])+ mockBreakdown.mockClear()++ select()+ await expectLogic(otherLogic).toDispatchActions(['loadFacetValues', 'loadFacetValuesSuccess'])++ expect(mockBreakdown).toHaveBeenCalledTimes(1)+ expect(selectedLogic.values.facetValuesLoading).toBe(false)+ })++ it('a type-ahead search refetches this facet with the search term', async () => {+ const logic = mountFacet(SERVICE)+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])+ mockBreakdown.mockClear()++ logic.actions.setFacetSearch('kaf')+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])++ expect(mockBreakdown).toHaveBeenCalledTimes(1)+ expect(mockBreakdown).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ query: expect.objectContaining({ breakdownKey: 'service_name', facetSearch: 'kaf' }),+ })+ )+ })++ it('a failed breakdown shows in place and clears on the next fetch', async () => {+ // One broken breakdown must show on its own facet, not blank the rail.+ mockBreakdown.mockRejectedValueOnce(new Error('breakdown failed'))+ const logic = mountFacet(SERVICE)+ await expectLogic(logic).toDispatchActions(['loadFacetValuesFailure'])+ expect(logic.values.fetchFailed).toBe(true)++ logic.actions.setFacetSearch('api')+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])+ expect(logic.values.fetchFailed).toBe(false)+ expect(logic.values.facetValues).toEqual([row('api', 10)])+ })++ it('a collapsed facet defers its fetch until it is expanded, then only if the scope moved', async () => {+ railLogic.actions.toggleFacetCollapsed(SERVICE.key)+ const logic = mountFacet(SERVICE)+ const other = mountFacet(STATUS)+ await expectLogic(other).toDispatchActions(['loadFacetValuesSuccess'])+ expect(mockBreakdown).toHaveBeenCalledTimes(1)++ filtersLogic.actions.setDateRange({ date_from: '-7d' })+ await expectLogic(other).toDispatchActions(['loadFacetValuesSuccess'])+ expect(logic.values.facetValues).toEqual([])++ mockBreakdown.mockClear()+ railLogic.actions.toggleFacetCollapsed(SERVICE.key)+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])+ expect(mockBreakdown).toHaveBeenCalledTimes(1)++ // Collapsing and expanding again with nothing else changed has nothing to fetch.+ mockBreakdown.mockClear()+ railLogic.actions.toggleFacetCollapsed(SERVICE.key)+ railLogic.actions.toggleFacetCollapsed(SERVICE.key)+ await expectLogic(logic).toNotHaveDispatchedActions(['loadFacetValues'])+ expect(mockBreakdown).not.toHaveBeenCalled()+ })++ it('collapsing while a fetch is still debouncing drops it, and expanding fetches again', async () => {+ // The request is debounced, so a facet collapsed within that window would otherwise still+ // hit the endpoint — and, having recorded the signature, look fresh enough to skip the+ // refetch on expand, leaving the stale list it was showing before.+ const logic = mountFacet(SERVICE)+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])+ mockBreakdown.mockClear()++ filtersLogic.actions.setDateRange({ date_from: '-7d' })+ await expectLogic(logic).toDispatchActions(['loadFacetValues'])+ railLogic.actions.toggleFacetCollapsed(SERVICE.key)+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])+ expect(mockBreakdown).not.toHaveBeenCalled()++ railLogic.actions.toggleFacetCollapsed(SERVICE.key)+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])+ expect(mockBreakdown).toHaveBeenCalledTimes(1)+ })+})diff --git a/products/tracing/frontend/components/FacetRail/facetValuesLogic.ts b/products/tracing/frontend/components/FacetRail/facetValuesLogic.tsnew file mode 100644index 000000000000..bf7a46c79da8--- /dev/null+++ b/products/tracing/frontend/components/FacetRail/facetValuesLogic.ts@@ -0,0 +1,273 @@+import { MakeLogicType, actions, connect, kea, key, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'++import { teamLogic } from 'scenes/teamLogic'++import { UniversalFiltersGroup } from '~/types'++import { tracingFiltersLogic, TracingFiltersLogicProps } from 'products/tracing/frontend/tracingFiltersLogic'++import { tracingSpansAttributeBreakdownCreate } from '../../generated/api'+import {+ _SpanPropertyFilterApi,+ _SpanPropertyFilterOperatorEnumApi,+ _TracingAttributeBreakdownRowApi,+ SpanPropertyTypeEnumApi,+} from '../../generated/api.schemas'+import { facetRailLogic } from './facetRailLogic'+import { FacetConfig, facetScopeSignature, facetSourceKey, innerFilters } from './facets'++export interface FacetValuesLogicProps {+ id: string+ /** Already resolved by resolveFacets, so `source` points at the key the tenant emits. */+ facet: FacetConfig+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface facetValuesLogicValues {+ collapsedFacets: string[] // facetRailLogic+ currentTeamId: number | null // teamLogic+ queryFilterGroup: UniversalFiltersGroup // tracingFiltersLogic+ serviceNames: string[] // tracingFiltersLogic+ utcDateRange: {+ date_from: string | null | undefined+ date_to: string | null | undefined+ } // tracingFiltersLogic+ collapsed: boolean+ facetSearch: string+ facetValues: _TracingAttributeBreakdownRowApi[]+ facetValuesLoading: boolean+ fetchFailed: boolean+ fetchSignature: string+ fetchedSignature: string | null+ scopeSignature: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface facetValuesLogicActions {+ clearFetchedSignature: () => {+ value: true+ }+ loadFacetValues: (signature: string) => {+ signature: string+ }+ loadFacetValuesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadFacetValuesSuccess: (+ facetValues: _TracingAttributeBreakdownRowApi[],+ payload?: {+ signature: string+ }+ ) => {+ facetValues: _TracingAttributeBreakdownRowApi[]+ payload?: {+ signature: string+ }+ }+ setFacetSearch: (search: string) => {+ search: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface facetValuesLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ collapsed: (collapsedFacets: string[], arg: any) => boolean+ scopeSignature: (+ utcDateRange: {+ date_from: string | null | undefined+ date_to: string | null | undefined+ },+ serviceNames: string[],+ queryFilterGroup: UniversalFiltersGroup,+ currentTeamId: number | null,+ arg: any+ ) => string+ fetchSignature: (scopeSignature: string, facetSearch: string) => string+ }+}++export type facetValuesLogicType = MakeLogicType<+ facetValuesLogicValues,+ facetValuesLogicActions,+ FacetValuesLogicProps,+ facetValuesLogicMeta+>++/**+ * One facet's values + counts, cross-filtered server-side: the results reflect every active filter+ * except this facet's own selection, which excludeBreakdownFilter strips from the query.+ *+ * One instance per facet, so each fetches on its own schedule and holds its own loading and error+ * state. What it fetches on is `fetchSignature` — the breakdown scope with this facet's own filters+ * removed, plus its type-ahead — so clicking a value here re-scopes the *other* facets and leaves+ * this list alone, and a facet whose section is collapsed doesn't fetch until it's expanded.+ */+export const facetValuesLogic = kea<facetValuesLogicType>([+ props({} as FacetValuesLogicProps),+ // The resolved source key is part of the key: when alias resolution moves a facet onto another+ // attribute spelling, that's a different breakdown, so it gets a fresh instance rather than the+ // old key's values.+ key((props) => `${props.id}-${props.facet.key}-${facetSourceKey(props.facet)}`),+ path((key) => ['products', 'tracing', 'frontend', 'components', 'FacetRail', 'facetValuesLogic', key]),++ connect((props: FacetValuesLogicProps) => ({+ values: [+ tracingFiltersLogic({ id: props.id } as TracingFiltersLogicProps),+ ['serviceNames', 'utcDateRange', 'queryFilterGroup'],+ teamLogic,+ ['currentTeamId'],+ facetRailLogic({ id: props.id }),+ ['collapsedFacets'],+ ],+ })),++ actions({+ setFacetSearch: (search: string) => ({ search }),+ // Declared here rather than left to the loader: the request is built from current values,+ // and the signature payload is only there for the reducer below to record.+ loadFacetValues: (signature: string) => ({ signature }),+ clearFetchedSignature: true,+ }),++ reducers({+ facetSearch: [+ '',+ {+ setFacetSearch: (_, { search }) => search,+ },+ ],+ // The signature the values in the store were fetched for. Set when the request goes out, not+ // when it lands, so an overlapping trigger (e.g. expanding the facet mid-flight) doesn't+ // restart the same request. Cleared on failure, and when collapsing abandons an in-flight+ // load, so the next trigger retries rather than trusting values that never arrived.+ fetchedSignature: [+ null as string | null,+ {+ loadFacetValues: (_, { signature }) => signature,+ loadFacetValuesFailure: () => null,+ clearFetchedSignature: () => null,+ },+ ],+ // Drives this facet's inline error state, so one broken breakdown shows in place rather than+ // blanking the rail.+ fetchFailed: [+ false,+ {+ loadFacetValuesSuccess: () => false,+ loadFacetValuesFailure: () => true,+ },+ ],+ }),++ loaders(({ props, values }) => ({+ facetValues: [+ [] as _TracingAttributeBreakdownRowApi[],+ {+ loadFacetValues: async (_, breakpoint) => {+ await breakpoint(300)+ // Collapsed while this was still debouncing: nobody can see the list, so drop the+ // request. clearFetchedSignature has already run, so expanding refetches.+ if (values.collapsed || !values.currentTeamId) {+ return values.facetValues+ }+ // The endpoint takes the flat inner filter list. The stored filters carry the+ // app-side enums (PropertyFilterType/PropertyOperator) which are nominally+ // distinct from the generated string-union enums despite identical runtime+ // values, so mapping onto the generated shape type-checks the field structure+ // (key/value) while casting only the two enum fields.+ const filterGroup: _SpanPropertyFilterApi[] = innerFilters(values.queryFilterGroup).map((f) => ({+ key: f.key,+ type: f.type as unknown as SpanPropertyTypeEnumApi,+ operator: f.operator as unknown as _SpanPropertyFilterOperatorEnumApi,+ value: f.value,+ }))+ const { source } = props.facet+ const target =+ source.type === 'column'+ ? { breakdownKey: source.column, breakdownType: SpanPropertyTypeEnumApi.Span }+ : {+ breakdownKey: source.key,+ breakdownType: SpanPropertyTypeEnumApi.SpanResourceAttribute,+ }+ const response = await tracingSpansAttributeBreakdownCreate(String(values.currentTeamId), {+ query: {+ ...target,+ excludeBreakdownFilter: true,+ dateRange: values.utcDateRange,+ serviceNames: values.serviceNames ?? [],+ facetSearch: values.facetSearch || undefined,+ filterGroup,+ },+ })+ // Bail out right after the round-trip: the rail (and this logic) unmounts when+ // the user collapses it, and returning into a dead store throws rather than+ // being discarded.+ breakpoint()+ return response.results+ },+ },+ ],+ })),++ selectors({+ collapsed: [+ (s) => [s.collapsedFacets, (_, p) => p.facet],+ (collapsedFacets: string[], facet: FacetConfig): boolean => collapsedFacets.includes(facet.key),+ ],+ // Everything that can change this facet's values, minus its own selection.+ scopeSignature: [+ (s) => [s.utcDateRange, s.serviceNames, s.queryFilterGroup, s.currentTeamId, (_, p) => p.facet],+ (+ utcDateRange: {+ date_from: string | null | undefined+ date_to: string | null | undefined+ },+ serviceNames: string[],+ queryFilterGroup: UniversalFiltersGroup,+ currentTeamId: number | null,+ facet: FacetConfig+ ): string => facetScopeSignature(facet, { currentTeamId, utcDateRange, serviceNames, queryFilterGroup }),+ ],+ // One trigger for the one in-flight request: a scope change and a keystroke in this facet's+ // search box supersede each other rather than racing.+ fetchSignature: [+ (s) => [s.scopeSignature, s.facetSearch],+ (scopeSignature: string, facetSearch: string): string => `${scopeSignature}|${facetSearch}`,+ ],+ }),++ subscriptions(({ actions, values }) => {+ // Subscriptions fire with their initial value, so this is also the mount fetch.+ const loadIfStale = (): void => {+ if (values.collapsed || values.fetchSignature === values.fetchedSignature) {+ return+ }+ actions.loadFacetValues(values.fetchSignature)+ }+ return {+ fetchSignature: loadIfStale,+ collapsed: (collapsed: boolean) => {+ if (collapsed) {+ // The loader drops a still-debouncing load on collapse, so forget the signature it+ // recorded — otherwise expanding would trust values that never arrived. Only when+ // one is in flight: settled values stay valid for their signature.+ if (values.facetValuesLoading) {+ actions.clearFetchedSignature()+ }+ return+ }+ // Expanding fetches what it missed while collapsed — and nothing if the scope hasn't+ // moved since.+ loadIfStale()+ },+ }+ }),+])diff --git a/products/tracing/frontend/components/FacetRail/facets.test.ts b/products/tracing/frontend/components/FacetRail/facets.test.tsindex e39d33e2db74..8f6a53a5754c 100644--- a/products/tracing/frontend/components/FacetRail/facets.test.ts+++ b/products/tracing/frontend/components/FacetRail/facets.test.ts@@ -2,11 +2,14 @@ import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFimport {FACETS,+ FacetConfig,+ FacetScope,FacetSelection,FacetSource,FilterGroupFacetSource,cycleFacetFilter,facetFilterSelection,+ facetScopeSignature,facetSelection,mergeSelectedIntoOptions,resolveFacets,@@ -163,6 +166,115 @@ describe('facets', () => {})})+ describe('facetScopeSignature', () => {+ const configured = (key: string): FacetConfig => FACETS.find((f) => f.key === key)!+ const SERVICE = configured('service')+ const STATUS = configured('status')+ const NAMESPACE = configured('namespace')++ const filter = (type: PropertyFilterType, key: string, operator: PropertyOperator, value: unknown): object => ({+ type,+ key,+ operator,+ value,+ })++ const BASE: FacetScope = {+ currentTeamId: 1,+ utcDateRange: { date_from: '-1h', date_to: null },+ serviceNames: [],+ queryFilterGroup: groupWith([]),+ }+ const signature = (facet: FacetConfig, scope: Partial<FacetScope> = {}): string =>+ facetScopeSignature(facet, { ...BASE, ...scope })++ // A facet that reacts to its own selection refetches a list excludeBreakdownFilter guarantees+ // is unchanged; one that ignores a filter it should see serves stale counts. Both are silent.+ it.each<[string, FacetConfig, Partial<FacetScope>, boolean]>([+ ['service ignores its own selection', SERVICE, { serviceNames: ['api'] }, false],+ [+ 'service ignores a span filter on its own column, at any operator',+ SERVICE,+ {+ queryFilterGroup: groupWith([+ filter(PropertyFilterType.Span, 'service_name', PropertyOperator.IContains, 'ap'),+ ]),+ },+ false,+ ],+ [+ 'service sees the status selection',+ SERVICE,+ {+ queryFilterGroup: groupWith([+ filter(PropertyFilterType.Span, 'status_code', PropertyOperator.Exact, ['2']),+ ]),+ },+ true,+ ],+ ['service sees the date range', SERVICE, { utcDateRange: { date_from: '-7d', date_to: null } }, true],+ [+ 'status ignores its own selection',+ STATUS,+ {+ queryFilterGroup: groupWith([+ filter(PropertyFilterType.Span, 'status_code', PropertyOperator.Exact, ['2']),+ ]),+ },+ false,+ ],+ ['status sees the service selection', STATUS, { serviceNames: ['api'] }, true],+ [+ 'namespace ignores its own values, either polarity',+ NAMESPACE,+ {+ queryFilterGroup: groupWith([+ filter(PropertyFilterType.SpanResourceAttribute, 'k8s.namespace.name', PropertyOperator.IsNot, [+ 'argocd',+ ]),+ ]),+ },+ false,+ ],+ [+ 'namespace sees a span_attribute filter under the same key, which the backend keeps',+ NAMESPACE,+ {+ queryFilterGroup: groupWith([+ filter(PropertyFilterType.SpanAttribute, 'k8s.namespace.name', PropertyOperator.Exact, [+ 'argocd',+ ]),+ ]),+ },+ true,+ ],+ [+ 'namespace sees another resource attribute',+ NAMESPACE,+ {+ queryFilterGroup: groupWith([+ filter(PropertyFilterType.SpanResourceAttribute, 'host.name', PropertyOperator.Exact, [+ 'node-1',+ ]),+ ]),+ },+ true,+ ],+ ])('%s', (_, facet, scope, expectedToChange) => {+ expect(signature(facet, scope) !== signature(facet)).toBe(expectedToChange)+ })++ it('is identical for structurally equal filter groups', () => {+ // The signature is what the rail subscribes on: if it carried object identity rather than+ // content, every unrelated filter edit would refetch every facet again.+ const chip = (): object =>+ filter(PropertyFilterType.SpanResourceAttribute, 'host.name', PropertyOperator.Exact, ['node-1'])+ expect(signature(NAMESPACE, { queryFilterGroup: groupWith([chip()]) })).toEqual(+ signature(NAMESPACE, { queryFilterGroup: groupWith([chip()]) })+ )+ })+ })+describe('resolveFacets', () => {const environmentKey = (presentResourceKeys: string[]): string | undefined => {const facet = resolveFacets(FACETS, presentResourceKeys).find((f) => f.key === 'environment')diff --git a/products/tracing/frontend/components/FacetRail/facets.ts b/products/tracing/frontend/components/FacetRail/facets.tsindex fcb2fbc4d627..5651d8aa188f 100644--- a/products/tracing/frontend/components/FacetRail/facets.ts+++ b/products/tracing/frontend/components/FacetRail/facets.ts@@ -201,6 +201,54 @@ export function cycleFacetFilter(return { type: FilterLogicalOperator.And, values: [{ type: FilterLogicalOperator.And, values }] }}+/** The data key a facet is broken down by: its column, or the resource-attribute key resolution picked. */+export function facetSourceKey(facet: FacetConfig): string {+ return facet.source.type === 'column' ? facet.source.column : facet.source.key+}++/** Everything a facet's own values can depend on, before its own selection is stripped out. */+export interface FacetScope {+ currentTeamId: number | null+ utcDateRange: { date_from?: string | null; date_to?: string | null }+ serviceNames: string[] | undefined+ /** filterGroup with any pinned scope folded in — what the breakdown request actually carries. */+ queryFilterGroup: UniversalFiltersGroup | undefined+}++/**+ * A stable string identifying everything that can change this facet's values: the breakdown scope+ * minus the facet's own contributions, mirroring what the backend strips when excludeBreakdownFilter+ * is set (see _extract_filters in products/tracing/backend/attribute_breakdown_query_runner.py,+ * pinned from the other side by test_attribute_breakdown.py::test_exclude_breakdown_filter_*).+ * Selecting a value in this facet leaves the signature untouched, so the facet doesn't refetch+ * itself; selecting in any other facet changes it.+ *+ * A string, not an object: `queryFilterGroup` gets a fresh identity on every edit, so an object+ * couldn't tell "nothing I care about changed". Presentation state (view mode, sort, compare) is+ * deliberately absent — the breakdown request doesn't read it.+ */+export function facetScopeSignature(facet: FacetConfig, scope: FacetScope): string {+ const { source } = facet+ const selfKey = facetSourceKey(facet)+ const selfType = source.type === 'column' ? PropertyFilterType.Span : PropertyFilterType.SpanResourceAttribute+ // Any operator: the backend drops every filter under the breakdown key, not just the rail's own.+ const groupSignature = innerFilters(scope.queryFilterGroup)+ .filter((filter) => !(filter.type === selfType && filter.key === selfKey))+ .map((filter) => [filter.type, filter.key, filter.operator, JSON.stringify(filter.value ?? null)])++ return JSON.stringify([+ // A facet mounted before the team resolved fetches nothing; keeping the id in the signature+ // makes it fetch once the team arrives.+ scope.currentTeamId ?? null,+ [source.type, selfKey],+ scope.utcDateRange.date_from ?? null,+ scope.utcDateRange.date_to ?? null,+ // The service facet breaks down the same column the dedicated field filters.+ source.type === 'column' && source.column === 'service_name' ? null : (scope.serviceNames ?? []),+ groupSignature,+ ])+}+// OTel span status. Values must stay the digit strings "0"/"1"/"2": breakdown rows arrive// stringified (the backend toString()s the Int16 column), so these are what counts key on.// Don't switch to the label strings — the server-side filter normaliser treats "OK" as