Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(logs): reload only the other facets when a facet value is selected (#81875)

Frank Hamand2562f09ace5b
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
index 5f15ba2ea7c6..7b3983a11274 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
@@ -7,20 +7,11 @@ import { Resizer } from 'lib/components/Resizer/Resizer'
import { ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'
import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
-import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
-import { Facet, FacetOption } from './Facet'
-import { facetCountsLogic } from './facetCountsLogic'
+import { facetPresenceLogic } from './facetPresenceLogic'
import { facetRailLogic } from './facetRailLogic'
-import {
- FacetConfig,
- FacetFilterKey,
- facetsByGroup,
- filterFacetsByName,
- logFilterExclusions,
- mergeSelectedIntoOptions,
- resourceAttributeSelection,
-} from './facets'
+import { facetsByGroup, filterFacetsByName } from './facets'
+import { RailFacet } from './RailFacet'
const DEFAULT_WIDTH_PX = 240
const COLLAPSE_THRESHOLD_PX = 120
@@ -33,16 +24,9 @@ export interface FacetRailProps {
export function FacetRail({ id }: FacetRailProps): JSX.Element {
const railRef = useRef<HTMLDivElement>(null)
const { setFacetRailCollapsed } = useActions(logsViewerConfigLogic)
- const { severityLevels, serviceNames, filterGroup } = useValues(logsViewerFiltersLogic)
- const { facetValues, loadingFacetKeys, facetSearch, visibleFacets } = useValues(facetCountsLogic({ id }))
- const { setFacetSearch } = useActions(facetCountsLogic({ id }))
- const { collapsedFacets, facetNameSearch } = useValues(facetRailLogic({ id }))
- const { toggleFacetValue, toggleFacetCollapsed, setFacetNameSearch } = useActions(facetRailLogic({ id }))
-
- const selectedByKey: Record<FacetFilterKey, string[]> = {
- severityLevels: severityLevels ?? [],
- serviceNames: serviceNames ?? [],
- }
+ const { visibleFacets } = useValues(facetPresenceLogic({ id }))
+ const { facetNameSearch } = useValues(facetRailLogic({ id }))
+ const { setFacetNameSearch } = useActions(facetRailLogic({ id }))
const onToggleClosed = useCallback(
(shouldBeClosed: boolean) => setFacetRailCollapsed(shouldBeClosed),
@@ -62,81 +46,10 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
)
const { desiredSize } = useValues(resizerLogic(resizerLogicProps))
- const renderFacet = (facet: FacetConfig): JSX.Element => {
- const { source } = facet
- // Selection: column facets read includes from their dedicated filter field and exclusions
- // from the is_not log filter under their exclusionKey (when they have one);
- // resource-attribute facets read their log_resource_attribute filters, both polarities.
- const { included: selected, excluded } =
- source.type === 'resourceAttribute'
- ? resourceAttributeSelection(filterGroup, source.key)
- : {
- included: selectedByKey[source.filterKey],
- excluded: source.exclusionKey ? logFilterExclusions(filterGroup, source.exclusionKey) : [],
- }
- // Values + counts come from the cross-filtered endpoint, keyed by facet.key.
- const fetched: FacetOption[] = (facetValues[facet.key] ?? []).map((r) => ({
- value: r.value,
- label: r.value,
- count: r.count,
- }))
- const loading = loadingFacetKeys.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
- />
- )
- }
-
- // Dynamic facet: values + counts come from the cross-filtered endpoint, plus any selected or
- // excluded values it didn't return (zero matches in scope, or below the top-N cutoff) so an
- // active filter — e.g. from an old saved-view URL — is always visible and removable.
- return (
- <Facet
- key={facet.key}
- title={facet.title}
- options={mergeSelectedIntoOptions(
- fetched,
- [...selected, ...excluded],
- facet.searchable ? facetSearch[facet.key] : undefined
- )}
- selected={selected}
- excluded={excluded}
- onToggle={onToggle}
- loading={loading}
- emptyLabel={facet.emptyLabel}
- searchValue={facet.searchable ? (facetSearch[facet.key] ?? '') : undefined}
- onSearchChange={facet.searchable ? (value) => setFacetSearch(facet.key, value) : undefined}
- searchPlaceholder={facet.searchPlaceholder}
- collapsed={collapsed}
- onToggleCollapsed={onToggleCollapsed}
- maxHeight={facet.maxHeight}
- />
- )
- }
-
- // 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
@@ -158,18 +71,21 @@ export function FacetRail({ id }: FacetRailProps): 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} id={id} 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/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx
new file mode 100644
index 000000000000..88ec5e48fcce
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx
@@ -0,0 +1,108 @@
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
+
+import { Facet, FacetOption } from './Facet'
+import { facetRailLogic } from './facetRailLogic'
+import {
+ FacetConfig,
+ FacetFilterKey,
+ logFilterExclusions,
+ mergeSelectedIntoOptions,
+ resourceAttributeSelection,
+} from './facets'
+import { facetValuesLogic } from './facetValuesLogic'
+
+export interface RailFacetProps {
+ id: string
+ facet: FacetConfig
+ /**
+ * 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({ id, facet, 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, facetSearch } = useValues(facetValuesLogic(logicProps))
+ const { setFacetSearch } = useActions(facetValuesLogic(logicProps))
+ const { severityLevels, serviceNames, filterGroup } = useValues(logsViewerFiltersLogic({ id }))
+ const { collapsedFacets } = useValues(facetRailLogic({ id }))
+ const { toggleFacetValue, toggleFacetCollapsed } = useActions(facetRailLogic({ id }))
+
+ if (hidden) {
+ return null
+ }
+
+ const { source } = facet
+ const selectedByKey: Record<FacetFilterKey, string[]> = {
+ severityLevels: severityLevels ?? [],
+ serviceNames: serviceNames ?? [],
+ }
+ // Selection: column facets read includes from their dedicated filter field and exclusions
+ // from the is_not log filter under their exclusionKey (when they have one);
+ // resource-attribute facets read their log_resource_attribute filters, both polarities.
+ const { included: selected, excluded } =
+ source.type === 'resourceAttribute'
+ ? resourceAttributeSelection(filterGroup, source.key)
+ : {
+ included: selectedByKey[source.filterKey],
+ excluded: source.exclusionKey ? logFilterExclusions(filterGroup, source.exclusionKey) : [],
+ }
+ // Values + counts come from the cross-filtered endpoint.
+ const fetched: FacetOption[] = facetValues.map((r) => ({ value: r.value, label: r.value, count: r.count }))
+ 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
+ title={facet.title}
+ options={options}
+ selected={selected}
+ excluded={excluded}
+ onToggle={onToggle}
+ loading={facetValuesLoading}
+ collapsed={collapsed}
+ onToggleCollapsed={onToggleCollapsed}
+ dimZeroCounts
+ />
+ )
+ }
+
+ // Dynamic facet: values + counts come from the cross-filtered endpoint, plus any selected or
+ // excluded values it didn't return (zero matches in scope, or below the top-N cutoff) so an
+ // active filter — e.g. from an old saved-view URL — is always visible and removable.
+ return (
+ <Facet
+ title={facet.title}
+ options={mergeSelectedIntoOptions(
+ fetched,
+ [...selected, ...excluded],
+ facet.searchable ? facetSearch : undefined
+ )}
+ selected={selected}
+ excluded={excluded}
+ onToggle={onToggle}
+ loading={facetValuesLoading}
+ emptyLabel={facet.emptyLabel}
+ searchValue={facet.searchable ? facetSearch : undefined}
+ onSearchChange={facet.searchable ? setFacetSearch : undefined}
+ searchPlaceholder={facet.searchPlaceholder}
+ collapsed={collapsed}
+ onToggleCollapsed={onToggleCollapsed}
+ maxHeight={facet.maxHeight}
+ />
+ )
+}
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts
deleted file mode 100644
index 993ab9b96d4c..000000000000
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts
+++ /dev/null
@@ -1,341 +0,0 @@
-import {
- BreakPointFunction,
- 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 { UniversalFiltersGroup } from '~/types'
-
-import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
-
-import { logsAttributesRetrieve, logsFacetValuesCreate } from '../../../generated/api'
-import { _LogFacetValueApi, _LogPropertyFilterApi, _LogsFacetValuesBodyApi } from '../../../generated/api.schemas'
-import type { LogsViewerFilters } from '../config/types'
-import { FACETS, FacetConfig, resolveFacets } from './facets'
-
-// Broad, filter-independent window for the "which resource attributes does this tenant emit" probe.
-// Cheap: keys-only group-by on the log_attributes aggregation table (no value scan).
-const PRESENCE_LOOKBACK = { date_from: '-90d' }
-
-export interface FacetCountsLogicProps {
- id: string
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface facetCountsLogicValues {
- filters: LogsViewerFilters // logsViewerFiltersLogic
- personId: string | undefined // logsViewerFiltersLogic
- queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
- utcDateRange: {
- date_from: string | null | undefined
- date_to: string | null | undefined
- explicitDate: boolean | null | undefined
- } // logsViewerFiltersLogic
- currentTeamId: number | null // teamLogic
- facetSearch: Record<string, string>
- facetValues: Record<string, _LogFacetValueApi[]>
- 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, _LogFacetValueApi[]>,
- payload?: string
- ) => {
- facetValues: Record<string, _LogFacetValueApi[]>
- payload?: string
- }
- loadFacetValuesSuccess: (
- facetValues: Record<string, _LogFacetValueApi[]>,
- payload?: string[] | null
- ) => {
- facetValues: Record<string, _LogFacetValueApi[]>
- payload?: string[] | null
- }
- loadPresentResourceKeys: () => any
- loadPresentResourceKeysFailure: (
- error: string,
- errorObject?: any
- ) => {
- error: string
- errorObject?: any
- }
- loadPresentResourceKeysSuccess: (
- presentResourceKeys: string[],
- payload?: any
- ) => {
- presentResourceKeys: string[]
- payload?: any
- }
- 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[]
- }
-}
-
-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 (the backend excludes the facet's own column or resource-attribute
- * filter). Values come back ordered by count descending. The rail is config-driven, so this fetches
- * one 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: 'default' } as FacetCountsLogicProps),
- key((props) => props.id),
- path((key) => ['products', 'logs', 'frontend', 'components', 'LogsViewer', 'FacetRail', 'facetCountsLogic', key]),
-
- connect((props: FacetCountsLogicProps) => ({
- values: [
- logsViewerFiltersLogic({ id: props.id }),
- ['filters', 'utcDateRange', 'queryFilterGroup', 'personId'],
- teamLogic,
- ['currentTeamId'],
- ],
- })),
-
- actions({
- setFacetSearch: (facetKey: string, search: string) => ({ facetKey, search }),
- }),
-
- reducers({
- facetSearch: [
- {} as Record<string, string>,
- {
- setFacetSearch: (state, { facetKey, search }) => ({ ...state, [facetKey]: search }),
- },
- ],
- // 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(({ values }) => {
- const fetchFacet = async (facet: FacetConfig): Promise<_LogFacetValueApi[]> => {
- if (!values.currentTeamId) {
- return []
- }
- const group = values.queryFilterGroup as UniversalFiltersGroup
- const filterGroup = ((group?.values?.[0] as UniversalFiltersGroup | undefined)?.values ??
- []) as unknown as _LogPropertyFilterApi[]
- const target: Partial<_LogsFacetValuesBodyApi> =
- facet.source.type === 'column'
- ? { facetField: facet.source.column }
- : { facetResourceAttribute: facet.source.key }
- const response = await logsFacetValuesCreate(String(values.currentTeamId), {
- query: {
- ...target,
- dateRange: values.utcDateRange,
- severityLevels: values.filters.severityLevels ?? [],
- serviceNames: values.filters.serviceNames ?? [],
- searchTerm: values.filters.searchTerm || undefined,
- facetSearch: values.facetSearch[facet.key] || undefined,
- filterGroup,
- personId: values.personId,
- },
- })
- 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.
- // Takes the caller's breakpoint so it can bail out right after the network round-trip: the
- // facet rail (and this logic) unmounts when the user collapses it, and reading `values.facetValues`
- // once unmounted throws "Can not find path ... in the store" instead of just discarding the result.
- const mergeFetched = async (
- facets: FacetConfig[],
- breakpoint: BreakPointFunction
- ): Promise<Record<string, _LogFacetValueApi[]>> => {
- const settled = await Promise.allSettled(
- facets.map(async (facet) => [facet.key, await fetchFacet(facet)] as const)
- )
- breakpoint()
- const fetched = settled
- .filter(
- (s): s is PromiseFulfilledResult<readonly [string, _LogFacetValueApi[]]> => s.status === 'fulfilled'
- )
- .map((s) => s.value)
- return { ...values.facetValues, ...Object.fromEntries(fetched) }
- }
-
- return {
- facetValues: [
- {} as Record<string, _LogFacetValueApi[]>,
- {
- // 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
- return await mergeFetched(facets, breakpoint)
- },
- // 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)
- if (!facet) {
- return values.facetValues
- }
- return await mergeFetched([facet], breakpoint)
- },
- },
- ],
- presentResourceKeys: [
- [] as string[],
- {
- // Which resource attribute keys the tenant emits — gates which curated facets render.
- loadPresentResourceKeys: async () => {
- if (!values.currentTeamId) {
- return []
- }
- const response = await logsAttributesRetrieve(String(values.currentTeamId), {
- attribute_type: 'resource',
- dateRange: PRESENCE_LOOKBACK,
- 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,
- ],
- }),
-
- 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 (Level/Service) load even if the probe errored.
- loadPresentResourceKeysSuccess: () => actions.loadFacetValues(null),
- loadPresentResourceKeysFailure: () => actions.loadFacetValues(null),
- })),
-
- events(({ actions }) => ({
- afterMount: () => actions.loadPresentResourceKeys(),
- })),
-
- subscriptions(({ actions, values }) => {
- // Fires on mount (initial load) and on any change. We watch `filters` (severity, service,
- // search, date, user filterGroup), `queryFilterGroup` (which folds in pinnedFilters) and
- // `personId` (the person-tab scope) so values re-fetch when any scope changes. `filterGroup`
- // feeds the first two, so a normal edit fires both — the 300ms debounce in the loader collapses that.
- const reloadAll = (): void => {
- // Before the presence probe settles, defer to loadPresentResourceKeys{Success,Failure}
- // so we issue one full fetch over the final visible set instead of two.
- if (values.presenceLoaded) {
- actions.loadFacetValues(null)
- }
- }
- return {
- filters: reloadAll,
- queryFilterGroup: reloadAll,
- personId: reloadAll,
- }
- }),
-])
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts
new file mode 100644
index 000000000000..f4481fbc3a3f
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetPresenceLogic.ts
@@ -0,0 +1,106 @@
+import { MakeLogicType, connect, events, kea, key, path, props, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { logsAttributesRetrieve } from '../../../generated/api'
+import { FACETS, FacetConfig, resolveFacets } from './facets'
+
+// Broad, filter-independent window for the "which resource attributes does this tenant emit" probe.
+// Cheap: keys-only group-by on the log_attributes aggregation table (no value scan).
+const PRESENCE_LOOKBACK = { date_from: '-90d' }
+
+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: 'default' } as FacetPresenceLogicProps),
+ key((props) => props.id),
+ path((key) => ['products', 'logs', 'frontend', 'components', 'LogsViewer', 'FacetRail', 'facetPresenceLogic', key]),
+
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
+
+ loaders(({ values }) => ({
+ presentResourceKeys: [
+ [] as string[],
+ {
+ // Which resource attribute keys the tenant emits — gates which curated facets render.
+ loadPresentResourceKeys: async () => {
+ if (!values.currentTeamId) {
+ return []
+ }
+ const response = await logsAttributesRetrieve(String(values.currentTeamId), {
+ attribute_type: 'resource',
+ dateRange: PRESENCE_LOOKBACK,
+ 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/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.test.ts
new file mode 100644
index 000000000000..e5d07d299ccd
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.test.ts
@@ -0,0 +1,86 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { logsAttributesRetrieve, logsFacetValuesCreate } from 'products/logs/frontend/generated/api'
+
+import { logsViewerFiltersLogic } from '../Filters/logsViewerFiltersLogic'
+import { FACETS, FacetConfig } from './facets'
+import { facetValuesLogic } from './facetValuesLogic'
+
+jest.mock('products/logs/frontend/generated/api', () => ({
+ __esModule: true,
+ logsFacetValuesCreate: jest.fn(),
+ logsAttributesRetrieve: jest.fn(),
+}))
+
+const mockFacetValues = logsFacetValuesCreate as jest.MockedFunction<typeof logsFacetValuesCreate>
+const mockAttributes = logsAttributesRetrieve as jest.MockedFunction<typeof logsAttributesRetrieve>
+
+const ID = 'test-viewer'
+
+const facetConfig = (key: string): FacetConfig => FACETS.find((f) => f.key === key)!
+const LEVEL = facetConfig('level')
+const SERVICE = facetConfig('service')
+
+describe('facetValuesLogic', () => {
+ let filtersLogic: ReturnType<typeof logsViewerFiltersLogic.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()
+ mockAttributes.mockResolvedValue({ results: [], count: 0 })
+ mockFacetValues.mockResolvedValue({ results: [{ value: 'api', count: 10 }] })
+ filtersLogic = logsViewerFiltersLogic({ id: ID })
+ filtersLogic.mount()
+ })
+
+ afterEach(() => {
+ mounted.splice(0).forEach((logic) => logic.unmount())
+ filtersLogic.unmount()
+ })
+
+ // Selecting a value re-scopes the *other* facets: the backend strips a facet's own filter from
+ // its own query, so refetching it burns a request on a response that cannot have changed.
+ it.each<[string, FacetConfig, FacetConfig, () => void]>([
+ ['a level selection', LEVEL, SERVICE, () => filtersLogic.actions.setSeverityLevels(['error'])],
+ ['a service selection', SERVICE, LEVEL, () => filtersLogic.actions.setServiceNames(['api'])],
+ ])('%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'])
+ mockFacetValues.mockClear()
+
+ select()
+ await expectLogic(otherLogic).toDispatchActions(['loadFacetValues', 'loadFacetValuesSuccess'])
+
+ expect(mockFacetValues).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'])
+ mockFacetValues.mockClear()
+
+ logic.actions.setFacetSearch('kaf')
+ await expectLogic(logic).toDispatchActions(['loadFacetValuesSuccess'])
+
+ expect(mockFacetValues).toHaveBeenCalledTimes(1)
+ expect(mockFacetValues).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ query: expect.objectContaining({ facetField: 'service_name', facetSearch: 'kaf' }),
+ })
+ )
+ })
+})
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts
new file mode 100644
index 000000000000..b3c73e471f3b
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts
@@ -0,0 +1,220 @@
+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 { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
+
+import { logsFacetValuesCreate } from '../../../generated/api'
+import { _LogFacetValueApi, _LogPropertyFilterApi, _LogsFacetValuesBodyApi } from '../../../generated/api.schemas'
+import type { LogsViewerFilters } from '../config/types'
+import { FacetConfig, facetScopeSignature, facetSourceKey } 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 {
+ filters: LogsViewerFilters // logsViewerFiltersLogic
+ personId: string | undefined // logsViewerFiltersLogic
+ queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
+ utcDateRange: {
+ date_from: string | null | undefined
+ date_to: string | null | undefined
+ explicitDate: boolean | null | undefined
+ } // logsViewerFiltersLogic
+ currentTeamId: number | null // teamLogic
+ facetSearch: string
+ facetValues: _LogFacetValueApi[]
+ facetValuesLoading: boolean
+ fetchSignature: string
+ scopeSignature: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface facetValuesLogicActions {
+ loadFacetValues: () => {
+ value: true
+ }
+ loadFacetValuesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadFacetValuesSuccess: (
+ facetValues: _LogFacetValueApi[],
+ payload?: {
+ value: true
+ }
+ ) => {
+ facetValues: _LogFacetValueApi[]
+ payload?: {
+ value: true
+ }
+ }
+ 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: {
+ scopeSignature: (
+ filters: LogsViewerFilters,
+ queryFilterGroup: UniversalFiltersGroup,
+ personId: string | undefined,
+ utcDateRange: {
+ date_from: string | null | undefined
+ date_to: string | null | undefined
+ explicitDate: boolean | null | undefined
+ },
+ currentTeamId: number | null,
+ arg: FacetConfig
+ ) => 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 the backend strips from the WHERE clause.
+ *
+ * One instance per facet, so each fetches on its own schedule and holds its own loading state. What
+ * it fetches on is `fetchSignature` — the 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.
+ */
+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 query, 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', 'logs', 'frontend', 'components', 'LogsViewer', 'FacetRail', 'facetValuesLogic', key]),
+
+ connect((props: FacetValuesLogicProps) => ({
+ values: [
+ logsViewerFiltersLogic({ id: props.id }),
+ ['filters', 'utcDateRange', 'queryFilterGroup', 'personId'],
+ teamLogic,
+ ['currentTeamId'],
+ ],
+ })),
+
+ actions({
+ setFacetSearch: (search: string) => ({ search }),
+ // Declared here rather than left to the loader so it carries no payload — the request is
+ // built from current values, and typegen would otherwise infer one from the loader's params.
+ loadFacetValues: true,
+ }),
+
+ reducers({
+ facetSearch: [
+ '',
+ {
+ setFacetSearch: (_, { search }) => search,
+ },
+ ],
+ }),
+
+ loaders(({ props, values }) => ({
+ facetValues: [
+ [] as _LogFacetValueApi[],
+ {
+ loadFacetValues: async (_, breakpoint) => {
+ await breakpoint(300)
+ if (!values.currentTeamId) {
+ return values.facetValues
+ }
+ const { source } = props.facet
+ const group = values.queryFilterGroup as UniversalFiltersGroup
+ const filterGroup = ((group?.values?.[0] as UniversalFiltersGroup | undefined)?.values ??
+ []) as unknown as _LogPropertyFilterApi[]
+ const target: Partial<_LogsFacetValuesBodyApi> =
+ source.type === 'column'
+ ? { facetField: source.column }
+ : { facetResourceAttribute: source.key }
+ const response = await logsFacetValuesCreate(String(values.currentTeamId), {
+ query: {
+ ...target,
+ dateRange: values.utcDateRange,
+ severityLevels: values.filters.severityLevels ?? [],
+ serviceNames: values.filters.serviceNames ?? [],
+ searchTerm: values.filters.searchTerm || undefined,
+ facetSearch: values.facetSearch || undefined,
+ filterGroup,
+ personId: values.personId,
+ },
+ })
+ // 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({
+ // Everything that can change this facet's values, minus its own selection.
+ scopeSignature: [
+ (s) => [
+ s.filters,
+ s.queryFilterGroup,
+ s.personId,
+ s.utcDateRange,
+ s.currentTeamId,
+ (_, p) => p.facet as FacetConfig,
+ ],
+ (
+ filters: LogsViewerFilters,
+ queryFilterGroup: UniversalFiltersGroup,
+ personId: string | undefined,
+ utcDateRange: {
+ date_from: string | null | undefined
+ date_to: string | null | undefined
+ explicitDate: boolean | null | undefined
+ },
+ currentTeamId: number | null,
+ facet: FacetConfig
+ ): string =>
+ facetScopeSignature(facet, {
+ currentTeamId,
+ utcDateRange,
+ searchTerm: filters.searchTerm,
+ severityLevels: filters.severityLevels,
+ serviceNames: filters.serviceNames,
+ queryFilterGroup,
+ personId,
+ }),
+ ],
+ // 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 }) => ({
+ // Fires with its initial value on mount, so this is also the first fetch.
+ fetchSignature: () => actions.loadFacetValues(),
+ })),
+])
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
index 9eabc174dc07..6b16b0151795 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
@@ -4,7 +4,9 @@ import { FacetOption } from './Facet'
import {
FACETS as CONFIGURED_FACETS,
FacetConfig,
+ FacetScope,
cycleResourceAttributeFilter,
+ facetScopeSignature,
filterFacetsByName,
logFilterExclusions,
mergeSelectedIntoOptions,
@@ -242,6 +244,169 @@ describe('facets', () => {
})
})
+ describe('facetScopeSignature', () => {
+ const configured = (key: string): FacetConfig => CONFIGURED_FACETS.find((f) => f.key === key)!
+ const LEVEL = configured('level')
+ const SERVICE = configured('service')
+ const NAMESPACE = configured('namespace')
+
+ const group = (...filters: Record<string, unknown>[]): UniversalFiltersGroup => ({
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: filters as UniversalFiltersGroup['values'] }],
+ })
+ const filter = (
+ type: PropertyFilterType,
+ key: string,
+ operator: PropertyOperator,
+ value: unknown
+ ): Record<string, unknown> => ({ type, key, operator, value })
+
+ const BASE: FacetScope = {
+ currentTeamId: 1,
+ utcDateRange: { date_from: '-1h', date_to: null, explicitDate: false },
+ searchTerm: undefined,
+ severityLevels: [],
+ serviceNames: [],
+ queryFilterGroup: group(),
+ personId: undefined,
+ }
+ const signature = (facet: FacetConfig, scope: Partial<FacetScope> = {}): string =>
+ facetScopeSignature(facet, { ...BASE, ...scope })
+
+ // A facet that reacts to its own selection refetches a list the backend guarantees is
+ // unchanged; one that ignores a filter it should see serves stale counts. Both are silent.
+ it.each<[string, FacetConfig, Partial<FacetScope>, boolean]>([
+ ['level ignores its own included levels', LEVEL, { severityLevels: ['error'] }, false],
+ [
+ 'level ignores its own excluded levels',
+ LEVEL,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.Log, 'severity_level', PropertyOperator.IsNot, ['info'])
+ ),
+ },
+ false,
+ ],
+ [
+ 'level ignores a severity_level chip at any operator, matching the backend strip',
+ LEVEL,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.Log, 'severity_level', PropertyOperator.IContains, 'err')
+ ),
+ },
+ false,
+ ],
+ [
+ 'level sees a log_attribute filter under the same key, which the backend keeps',
+ LEVEL,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.LogAttribute, 'severity_level', PropertyOperator.Exact, ['error'])
+ ),
+ },
+ true,
+ ],
+ ['level sees the service selection', LEVEL, { serviceNames: ['api'] }, true],
+ [
+ 'level sees a service exclusion',
+ LEVEL,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.Log, 'service_name', PropertyOperator.IsNot, ['api'])
+ ),
+ },
+ true,
+ ],
+ ['level sees the body search', LEVEL, { searchTerm: 'timeout' }, true],
+ ['level sees the date range', LEVEL, { utcDateRange: { date_from: '-7d', date_to: null } }, true],
+ ['level sees the person scope', LEVEL, { personId: 'abc' }, true],
+ ['service ignores its own included services', SERVICE, { serviceNames: ['api'] }, false],
+ [
+ 'service ignores its own excluded services',
+ SERVICE,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.Log, 'service_name', PropertyOperator.IsNot, ['api'])
+ ),
+ },
+ false,
+ ],
+ ['service sees the level selection', SERVICE, { severityLevels: ['error'] }, true],
+ [
+ 'namespace ignores its own included values',
+ NAMESPACE,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.LogResourceAttribute, 'k8s.namespace.name', PropertyOperator.Exact, [
+ 'argocd',
+ ])
+ ),
+ },
+ false,
+ ],
+ [
+ 'namespace ignores its own excluded values',
+ NAMESPACE,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.LogResourceAttribute, 'k8s.namespace.name', PropertyOperator.IsNot, [
+ 'argocd',
+ ])
+ ),
+ },
+ false,
+ ],
+ [
+ 'namespace sees another resource attribute',
+ NAMESPACE,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.LogResourceAttribute, 'host.name', PropertyOperator.Exact, ['node-1'])
+ ),
+ },
+ true,
+ ],
+ [
+ 'namespace sees a nested filter group',
+ NAMESPACE,
+ {
+ queryFilterGroup: {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.Or,
+ values: [
+ filter(PropertyFilterType.LogAttribute, 'user_id', PropertyOperator.Exact, [
+ '7',
+ ]),
+ ],
+ },
+ ] as UniversalFiltersGroup['values'],
+ },
+ ],
+ },
+ },
+ 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 = (): Record<string, unknown> =>
+ filter(PropertyFilterType.LogResourceAttribute, 'host.name', PropertyOperator.Exact, ['node-1'])
+ expect(signature(NAMESPACE, { queryFilterGroup: group(chip()) })).toEqual(
+ signature(NAMESPACE, { queryFilterGroup: group(chip()) })
+ )
+ })
+ })
+
describe('resolveFacets', () => {
const environmentKey = (presentResourceKeys: string[]): string | undefined => {
const facet = resolveFacets(CONFIGURED_FACETS, presentResourceKeys).find((f) => f.key === 'environment')
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
index 8ec133fc967f..70c1fd572ef2 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
@@ -73,10 +73,18 @@ interface RailPropertyFilter {
value?: PropertyFilterValue
}
+// The inner group holds property filters, but can also hold a nested group — one value ORed across
+// several attribute keys (e.g. the person-scope distinct-id group).
+type RailFilterEntry = RailPropertyFilter | UniversalFiltersGroup
+
// The logs filterGroup is always { AND, values: [{ AND, values: [<property filters>] }] } — the
// editable property filters live in the single inner group.
-function innerFilters(group: UniversalFiltersGroup | undefined): RailPropertyFilter[] {
- return ((group?.values?.[0] as UniversalFiltersGroup | undefined)?.values ?? []) as RailPropertyFilter[]
+function innerFilters(group: UniversalFiltersGroup | undefined): RailFilterEntry[] {
+ return ((group?.values?.[0] as UniversalFiltersGroup | undefined)?.values ?? []) as RailFilterEntry[]
+}
+
+function isPropertyLeaf(entry: RailFilterEntry): entry is RailPropertyFilter {
+ return !('values' in entry)
}
/**
@@ -94,11 +102,12 @@ export interface FacetSelection {
// untouched on write.
const RAIL_OPERATORS: PropertyOperator[] = [PropertyOperator.Exact, PropertyOperator.IsNot]
-function isRailFacetFilter(filter: RailPropertyFilter, key: string): boolean {
+function isRailFacetFilter(entry: RailFilterEntry, key: string): entry is RailPropertyFilter {
return (
- filter?.type === PropertyFilterType.LogResourceAttribute &&
- filter?.key === key &&
- RAIL_OPERATORS.includes(filter?.operator)
+ isPropertyLeaf(entry) &&
+ entry?.type === PropertyFilterType.LogResourceAttribute &&
+ entry?.key === key &&
+ RAIL_OPERATORS.includes(entry?.operator)
)
}
@@ -142,7 +151,8 @@ export function cycleResourceAttributeFilter(
nextIncluded = [...included, value]
}
- const values = innerFilters(group).filter((f) => !isRailFacetFilter(f, key))
+ // Annotated: negating the type guard would otherwise narrow the survivors to nested groups.
+ const values: RailFilterEntry[] = innerFilters(group).filter((f) => !isRailFacetFilter(f, key))
if (nextIncluded.length > 0) {
values.push({
key,
@@ -165,8 +175,13 @@ export function cycleResourceAttributeFilter(
// A column facet's exclusions are the `is_not` `log` property filter under the facet's
// exclusionKey. The rail owns only that filter — includes live in the facet's dedicated query
// field, so an `exact` chip on the same key is chips-bar state: ignored on read, preserved on write.
-function isLogExclusionFilter(filter: RailPropertyFilter, key: string): boolean {
- return filter?.type === PropertyFilterType.Log && filter?.key === key && filter?.operator === PropertyOperator.IsNot
+function isLogExclusionFilter(entry: RailFilterEntry, key: string): entry is RailPropertyFilter {
+ return (
+ isPropertyLeaf(entry) &&
+ entry?.type === PropertyFilterType.Log &&
+ entry?.key === key &&
+ entry?.operator === PropertyOperator.IsNot
+ )
}
/** A column facet's excluded values, read from the `is_not` log filter under `key`. */
@@ -182,13 +197,92 @@ export function setLogFilterExclusions(
key: string,
excluded: string[]
): UniversalFiltersGroup {
- const values = innerFilters(group).filter((f) => !isLogExclusionFilter(f, key))
+ // Annotated: negating the type guard would otherwise narrow the survivors to nested groups.
+ const values: RailFilterEntry[] = innerFilters(group).filter((f) => !isLogExclusionFilter(f, key))
if (excluded.length > 0) {
values.push({ key, type: PropertyFilterType.Log, operator: PropertyOperator.IsNot, value: excluded })
}
return { type: FilterLogicalOperator.And, values: [{ type: FilterLogicalOperator.And, values }] }
}
+// The `log` property-filter key the backend drops alongside a column facet's dedicated field, keyed
+// by column rather than by FacetConfig.exclusionKey: the backend strips by column whatever the rail
+// happens to write. Mirrors LogsFilterBuilder.where() in products/logs/backend/logs_query_runner.py,
+// pinned from the other side by products/logs/backend/test/test_log_facet_values.py.
+const COLUMN_SELF_LOG_KEY: Record<FacetField, string> = {
+ severity_text: 'severity_level',
+ service_name: 'service_name',
+}
+
+/** The data key a facet is queried on: 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; explicitDate?: boolean | null }
+ searchTerm?: string | null
+ severityLevels?: string[] | null
+ serviceNames?: string[] | null
+ /** filterGroup with pinned filters folded in — what the query actually carries. */
+ queryFilterGroup: UniversalFiltersGroup | undefined
+ personId?: string
+}
+
+/**
+ * A stable string identifying everything that can change this facet's values: the query scope minus
+ * the facet's own contributions, mirroring what the backend strips (exclude_facet_field /
+ * exclude_resource_attribute). 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: `filters` and `queryFilterGroup` get a fresh identity on every edit, so an
+ * object couldn't tell "nothing I care about changed". Errs toward refetching — a dimension the
+ * backend ignores still enters the signature — never toward serving stale counts.
+ */
+export function facetScopeSignature(facet: FacetConfig, scope: FacetScope): string {
+ const { source } = facet
+ const selfLogKey = source.type === 'column' ? COLUMN_SELF_LOG_KEY[source.column] : undefined
+ const selfResourceKey = source.type === 'resourceAttribute' ? source.key : undefined
+ const groupSignature = innerFilters(scope.queryFilterGroup)
+ .map((entry): unknown[] | null => {
+ if (!isPropertyLeaf(entry)) {
+ // Nested groups aren't leaves the backend can strip — carry them whole.
+ return ['group', JSON.stringify(entry)]
+ }
+ // Any operator: the backend skips a log filter under the facet's own column wholesale.
+ if (selfLogKey !== undefined && entry.type === PropertyFilterType.Log && entry.key === selfLogKey) {
+ return null
+ }
+ // Both polarities, any operator.
+ if (
+ selfResourceKey !== undefined &&
+ entry.type === PropertyFilterType.LogResourceAttribute &&
+ entry.key === selfResourceKey
+ ) {
+ return null
+ }
+ return [entry.type, entry.key, entry.operator, JSON.stringify(entry.value ?? null)]
+ })
+ .filter((entry) => entry !== 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 === 'column' ? ['column', source.column] : ['resource', source.key],
+ scope.utcDateRange.date_from ?? null,
+ scope.utcDateRange.date_to ?? null,
+ scope.utcDateRange.explicitDate ?? null,
+ scope.searchTerm || null,
+ source.type === 'column' && source.column === 'severity_text' ? null : (scope.severityLevels ?? []),
+ source.type === 'column' && source.column === 'service_name' ? null : (scope.serviceNames ?? []),
+ scope.personId ?? null,
+ groupSignature,
+ ])
+}
+
// Colors mirror the severity bar in the log rows (SEVERITY_BAR_COLORS) so the rail matches the viewer.
const SEVERITY_OPTIONS: FacetOption[] = (
[
@@ -266,7 +360,7 @@ const HOST_FACET = resourceAttributeFacet('host.name', 'host', 'Host', 'Infrastr
* The rail is rendered entirely from this list — append a config to add a facet (or a new group).
* Ordered by group (Standard → Kubernetes → Infrastructure) since facetsByGroup keeps first-appearance order.
* Resource-attribute facets only render when the tenant actually emits the key or one of its aliases
- * (see resolveFacets, called from facetCountsLogic).
+ * (see resolveFacets, called from facetPresenceLogic).
*/
export const FACETS: FacetConfig[] = [
LEVEL_FACET,