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.

feat(logs): config-driven per-facet counts fetch keyed by facet (#65118)

Jon McCallumb1e8ccce1ca4
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
index d164285653eb..fc234d093285 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
@@ -10,7 +10,7 @@ import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsVi
import { Facet, FacetOption } from './Facet'
import { facetCountsLogic } from './facetCountsLogic'
import { facetRailLogic } from './facetRailLogic'
-import { FacetConfig, FacetField, FacetFilterKey, facetsByGroup, resourceAttributeValues } from './facets'
+import { FacetConfig, FacetFilterKey, facetsByGroup, resourceAttributeValues } from './facets'
const DEFAULT_WIDTH_PX = 240
const COLLAPSE_THRESHOLD_PX = 120
@@ -24,9 +24,7 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
const railRef = useRef<HTMLDivElement>(null)
const { setFacetRailCollapsed } = useActions(logsViewerConfigLogic)
const { severityLevels, serviceNames, filterGroup } = useValues(logsViewerFiltersLogic)
- const { levelValues, levelValuesLoading, serviceValues, serviceValuesLoading, facetSearch } = useValues(
- facetCountsLogic({ id })
- )
+ const { facetValues, loadingFacetKeys, facetSearch } = useValues(facetCountsLogic({ id }))
const { setFacetSearch } = useActions(facetCountsLogic({ id }))
const { collapsedFacets } = useValues(facetRailLogic({ id }))
const { toggleFacetValue, toggleFacetCollapsed } = useActions(facetRailLogic({ id }))
@@ -35,14 +33,6 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
severityLevels: severityLevels ?? [],
serviceNames: serviceNames ?? [],
}
- const valuesByField: Record<FacetField, FacetOption[]> = {
- severity_text: levelValues.map((r) => ({ value: r.value, label: r.value, count: r.count })),
- service_name: serviceValues.map((r) => ({ value: r.value, label: r.value, count: r.count })),
- }
- const loadingByField: Record<FacetField, boolean> = {
- severity_text: levelValuesLoading,
- service_name: serviceValuesLoading,
- }
const onToggleClosed = useCallback(
(shouldBeClosed: boolean) => setFacetRailCollapsed(shouldBeClosed),
@@ -70,10 +60,13 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
source.type === 'resourceAttribute'
? resourceAttributeValues(filterGroup, source.key)
: selectedByKey[source.filterKey]
- // Counts/values + search are still keyed by FacetField (column facets only today); resource
- // attribute facets get their own per-facet fetch in a follow-up.
- const field: FacetField | null = source.type === 'column' ? source.column : null
- const fetched = field ? valuesByField[field] : []
+ // 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)
@@ -92,7 +85,7 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
options={options}
selected={selected}
onToggle={onToggle}
- loading={field ? loadingByField[field] : false}
+ loading={loading}
collapsed={collapsed}
onToggleCollapsed={onToggleCollapsed}
dimZeroCounts
@@ -108,10 +101,10 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
options={fetched}
selected={selected}
onToggle={onToggle}
- loading={field ? loadingByField[field] : false}
+ loading={loading}
emptyLabel={facet.emptyLabel}
- searchValue={facet.searchable && field ? (facetSearch[field] ?? '') : undefined}
- onSearchChange={facet.searchable && field ? (value) => setFacetSearch(field, value) : undefined}
+ searchValue={facet.searchable ? (facetSearch[facet.key] ?? '') : undefined}
+ onSearchChange={facet.searchable ? (value) => setFacetSearch(facet.key, value) : undefined}
searchPlaceholder={facet.searchPlaceholder}
collapsed={collapsed}
onToggleCollapsed={onToggleCollapsed}
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts
index d83e3d5cb7bb..2cf203f99cd8 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetCountsLogic.ts
@@ -1,4 +1,4 @@
-import { actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
+import { actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
@@ -9,9 +9,9 @@ import { UniversalFiltersGroup } from '~/types'
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
import { logsFacetValuesCreate } from '../../../generated/api'
-import { _LogFacetValueApi, _LogPropertyFilterApi } from '../../../generated/api.schemas'
+import { _LogFacetValueApi, _LogPropertyFilterApi, _LogsFacetValuesBodyApi } from '../../../generated/api.schemas'
import type { facetCountsLogicType } from './facetCountsLogicType'
-import { FacetField } from './facets'
+import { FACETS, FacetConfig } from './facets'
export interface FacetCountsLogicProps {
id: string
@@ -19,9 +19,10 @@ export interface FacetCountsLogicProps {
/**
* Per-facet values + counts, cross-filtered server-side: each facet's results reflect every active
- * filter except its own selection (see the backend's exclude_facet_field). Values come back ordered
- * by count descending. Dynamic facets (e.g. service) also pass a per-facet type-ahead search so they
- * can match values beyond the returned window.
+ * 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),
@@ -38,91 +39,133 @@ export const facetCountsLogic = kea<facetCountsLogicType>([
})),
actions({
- setFacetSearch: (facetField: FacetField, search: string) => ({ facetField, search }),
+ setFacetSearch: (facetKey: string, search: string) => ({ facetKey, search }),
}),
reducers({
facetSearch: [
{} as Record<string, string>,
{
- setFacetSearch: (state, { facetField, search }) => ({ ...state, [facetField]: search }),
+ 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,
},
],
}),
+ selectors({
+ // 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,
+ ],
+ }),
+
loaders(({ values }) => {
- const fetchValues = async (facetField: FacetField): Promise<_LogFacetValueApi[]> => {
+ 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: {
- facetField,
+ ...target,
dateRange: values.utcDateRange,
severityLevels: values.filters.severityLevels ?? [],
serviceNames: values.filters.serviceNames ?? [],
searchTerm: values.filters.searchTerm || undefined,
- facetSearch: values.facetSearch[facetField] || undefined,
+ 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.
+ const mergeFetched = async (facets: FacetConfig[]): Promise<Record<string, _LogFacetValueApi[]>> => {
+ const settled = await Promise.allSettled(
+ facets.map(async (facet) => [facet.key, await fetchFacet(facet)] as const)
+ )
+ 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 {
- levelValues: [
- [] as _LogFacetValueApi[],
+ facetValues: [
+ {} as Record<string, _LogFacetValueApi[]>,
{
- loadLevelValues: async (_: null, breakpoint) => {
+ // Refetch all facets (null) or a subset — used when filters change.
+ loadFacetValues: async (facetKeys: string[] | null, breakpoint) => {
await breakpoint(300)
- const results = await fetchValues('severity_text')
+ const facets = facetKeys ? FACETS.filter((f) => facetKeys.includes(f.key)) : FACETS
+ const result = await mergeFetched(facets)
breakpoint()
- return results
+ return result
},
- },
- ],
- serviceValues: [
- [] as _LogFacetValueApi[],
- {
- loadServiceValues: async (_: null, 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)
- const results = await fetchValues('service_name')
+ const facet = FACETS.find((f) => f.key === facetKey)
+ const result = facet ? await mergeFetched([facet]) : values.facetValues
breakpoint()
- return results
+ return result
},
},
],
}
}),
- listeners(({ actions }) => {
- // Re-fetch the facet whose search term changed. Typed by FacetField so adding a field is a
- // compile error until its loader is wired here (fixed facets just never receive a search).
- const reloaders: Record<FacetField, () => void> = {
- severity_text: () => actions.loadLevelValues(null),
- service_name: () => actions.loadServiceValues(null),
- }
- return {
- setFacetSearch: ({ facetField }) => reloaders[facetField](),
- }
- }),
+ 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),
+ })),
subscriptions(({ actions }) => {
- // Fires on mount (initial load) and on any change. We watch both `filters` (severity,
- // service, search, date, user filterGroup) and `queryFilterGroup` (which folds in
- // pinnedFilters, e.g. the person-tab distinct_id pin) so values re-fetch when the pinned
- // scope changes too. `filterGroup` feeds both, so a normal edit fires both — the 300ms
- // debounce in each loader collapses that into one request.
- const reload = (): void => {
- actions.loadLevelValues(null)
- actions.loadServiceValues(null)
- }
+ // Fires on mount (initial load) and on any change. We watch both `filters` (severity, service,
+ // search, date, user filterGroup) and `queryFilterGroup` (which folds in pinnedFilters, e.g. the
+ // person-tab distinct_id pin) so values re-fetch when the pinned scope changes too. `filterGroup`
+ // feeds both, so a normal edit fires both — the 300ms debounce in the loader collapses that.
+ const reloadAll = (): void => actions.loadFacetValues(null)
return {
- filters: reload,
- queryFilterGroup: reload,
+ filters: reloadAll,
+ queryFilterGroup: reloadAll,
}
}),
])