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: Streamline source of truth for logs search filters (#84368)

Jimmy Zhu1c13a1f057b2
diff --git a/products/logs/frontend/LogsScene.stories.tsx b/products/logs/frontend/LogsScene.stories.tsx
index 7f972adf3a86..bb6c6dd18b27 100644
--- a/products/logs/frontend/LogsScene.stories.tsx
+++ b/products/logs/frontend/LogsScene.stories.tsx
@@ -15,6 +15,15 @@ import { MockSignature } from '~/mocks/utils'
import { LogMessage, LogSeverityLevel } from '~/queries/schema/schema-general'
import { PropertyFilterType } from '~/types'
+import {
+ FacetFilterTarget,
+ FacetSelection,
+ SERVICE_NAME_FILTER,
+ SEVERITY_LEVEL_FILTER,
+ facetSelection,
+ setFacetSelection,
+} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'
+
function createSeededRandom(seed: number): () => number {
// LCG constants from Numerical Recipes
let m = 0x80000000 // 2^31
@@ -31,6 +40,8 @@ function createSeededRandom(seed: number): () => number {
const deterministicRandom = createSeededRandom(1234)
+const EMPTY_SELECTION: FacetSelection = { included: [], excluded: [] }
+
const delayIfNotTestRunner = async (): Promise<void> => {
await new Promise((resolve) => setTimeout(resolve, inStorybookTestRunner() ? 0 : 200 + Math.random() * 1000))
}
@@ -193,7 +204,8 @@ const getLogs = async (
_cachedLogs = generateLogs()
}
const ALL_LOGS_GENERATED = _cachedLogs
- const severityLevels = body.query?.severityLevels ?? []
+ const levels = facetSelection(body.query?.filterGroup, SEVERITY_LEVEL_FILTER)
+ const services = facetSelection(body.query?.filterGroup, SERVICE_NAME_FILTER)
const startDate = dateStringToDayJs(body.query?.dateRange?.date_from ?? null) ?? dayjs().subtract(30, 'minutes')
const endDate = dateStringToDayJs(body.query?.dateRange?.date_to ?? null) ?? dayjs()
@@ -205,13 +217,18 @@ const getLogs = async (
if (endDate && endDate.isBefore(dayjs(log.timestamp))) {
return false
}
- if (
- body.query?.serviceNames?.length &&
- !body.query?.serviceNames.includes(log.resource_attributes['service.name'])
- ) {
+ const service = log.resource_attributes['service.name']
+ if (services.included.length && !services.included.includes(service)) {
+ return false
+ }
+ if (services.excluded.includes(service)) {
return false
}
- if (severityLevels.length && !severityLevels.includes(log.severity_text.toLowerCase())) {
+ const level = log.severity_text.toLowerCase()
+ if (levels.included.length && !levels.included.includes(level)) {
+ return false
+ }
+ if (levels.excluded.includes(level)) {
return false
}
return true
@@ -311,6 +328,51 @@ const sparklineMock: MockSignature = async ({ request }) => {
return [200, results]
}
+/**
+ * Facet values + counts for the rail, computed over the same generated logs the viewer is showing so
+ * the counts and the rows agree. Cross-filtering is the backend's job: it strips the faceted field's
+ * own filter, which here means faceting on a field ignores that field's selection but honors the rest.
+ */
+const facetValuesMock: MockSignature = async ({ request }) => {
+ await delayIfNotTestRunner()
+ const body = (await request.json()) as Record<string, any>
+ const facetField = body.query?.facetField
+ const resourceAttribute = body.query?.facetResourceAttribute
+ // Strip the filter belonging to the facet being queried, whichever facet that is. Picking the
+ // wrong one inverts the contract: the facet would zero out its own selected value and keep
+ // counting rows another facet has filtered away.
+ const own: FacetFilterTarget | null =
+ facetField === 'service_name'
+ ? SERVICE_NAME_FILTER
+ : facetField === 'severity_text'
+ ? SEVERITY_LEVEL_FILTER
+ : resourceAttribute
+ ? { key: resourceAttribute, type: PropertyFilterType.LogResourceAttribute }
+ : null
+ const scopedGroup = own ? setFacetSelection(body.query?.filterGroup, own, EMPTY_SELECTION) : body.query?.filterGroup
+ const { logs } = await getLogs({ query: { ...body.query, filterGroup: scopedGroup } })
+
+ const counts = new Map<string, number>()
+ for (const log of logs) {
+ const value =
+ facetField === 'service_name'
+ ? log.resource_attributes['service.name']
+ : facetField === 'severity_text'
+ ? log.severity_text.toLowerCase()
+ : log.resource_attributes[resourceAttribute]
+ if (value) {
+ counts.set(String(value), (counts.get(String(value)) ?? 0) + 1)
+ }
+ }
+
+ const search = String(body.query?.facetSearch ?? '').toLowerCase()
+ const results = Array.from(counts.entries())
+ .filter(([value]) => !search || value.toLowerCase().includes(search))
+ .sort(([, a], [, b]) => b - a)
+ .map(([value, count]) => ({ value, count }))
+ return [200, { results }]
+}
+
const attributesMock: MockSignature = async ({ request }) => {
await delayIfNotTestRunner()
const type = (new URL(request.url).searchParams.get('attribute_type') ?? 'log_attribute') as
@@ -431,6 +493,7 @@ export default {
},
post: {
'/api/environments/:team_id/logs/query': queryMock,
+ '/api/projects/:team_id/logs/facet_values': facetValuesMock,
'/api/environments/:team_id/logs/sparkline': sparklineMock,
'/api/projects/:team_id/logs/services': servicesMock,
},
diff --git a/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts b/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts
index a9d6e0fd3865..386822b5d7ac 100644
--- a/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts
+++ b/products/logs/frontend/components/LogsGroupBy/logsGroupByLogic.ts
@@ -13,7 +13,7 @@ import type {
OrderGroupsByEnumApi,
} from 'products/logs/frontend/generated/api.schemas'
-import type { DateRange, LogSeverityLevel } from '../../../../../frontend/src/queries/schema/schema-general'
+import type { DateRange } from '../../../../../frontend/src/queries/schema/schema-general'
import type { UniversalFiltersGroup } from '../../../../../frontend/src/types'
import type { LogsViewerGroupBy } from '../LogsViewer/config/logsViewerConfigLogic'
import type { LogsViewerFilters } from '../LogsViewer/config/types'
@@ -88,12 +88,6 @@ export interface logsGroupByLogicActions {
setSearchTerm: (searchTerm: string | undefined) => {
searchTerm: string | undefined
} // logsViewerFiltersLogic
- setServiceNames: (serviceNames: string[]) => {
- serviceNames: string[]
- } // logsViewerFiltersLogic
- setSeverityLevels: (severityLevels: LogSeverityLevel[]) => {
- severityLevels: LogSeverityLevel[]
- } // logsViewerFiltersLogic
zoomDateRange: (multiplier: number) => {
multiplier: number
} // logsViewerFiltersLogic
@@ -151,16 +145,7 @@ export const logsGroupByLogic = kea<logsGroupByLogicType>([
],
actions: [
logsViewerFiltersLogic({ id: props.id }),
- [
- 'setDateRange',
- 'zoomDateRange',
- 'setSeverityLevels',
- 'setServiceNames',
- 'setSearchTerm',
- 'setFilters',
- 'setFilterGroup',
- 'setPinnedFilters',
- ],
+ ['setDateRange', 'zoomDateRange', 'setSearchTerm', 'setFilters', 'setFilterGroup', 'setPinnedFilters'],
logsViewerConfigLogic({ id: props.id }),
['setGroupBys', 'addGroupBy', 'removeGroupByAt', 'replaceGroupByAt'],
],
@@ -182,8 +167,6 @@ export const logsGroupByLogic = kea<logsGroupByLogicType>([
return await logsGroupByCreate(String(values.currentTeamId), {
query: {
dateRange: values.utcDateRange,
- severityLevels: values.filters.severityLevels,
- serviceNames: values.filters.serviceNames,
searchTerm: values.filters.searchTerm || undefined,
// Same scoping as Logs/Patterns: `queryFilterGroup` folds in any pinned
// filters from an embedded viewer, so a scoped viewer can't aggregate
@@ -234,8 +217,6 @@ export const logsGroupByLogic = kea<logsGroupByLogicType>([
return {
setDateRange: reload,
zoomDateRange: reload,
- setSeverityLevels: reload,
- setServiceNames: reload,
setSearchTerm: reload,
setFilters: reload,
setFilterGroup: reload,
diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts
index eb3b7d58818f..6899ef936b51 100644
--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts
+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts
@@ -5,6 +5,11 @@ import { initKeaTests } from '~/test/init'
import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
+import {
+ SERVICE_NAME_FILTER,
+ SEVERITY_LEVEL_FILTER,
+ facetSelection,
+} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
import { logsPatternsCreate, logsPatternsDiffCreate } from 'products/logs/frontend/generated/api'
import type {
@@ -89,6 +94,11 @@ describe('logsPatternsLogic', () => {
let logic: ReturnType<typeof logsPatternsLogic.build>
let filtersLogic: ReturnType<typeof logsViewerFiltersLogic.build>
+ const selectedLevels = (): string[] =>
+ facetSelection(filtersLogic.values.filters.filterGroup, SEVERITY_LEVEL_FILTER).included
+ const selectedServices = (): string[] =>
+ facetSelection(filtersLogic.values.filters.filterGroup, SERVICE_NAME_FILTER).included
+
beforeEach(() => {
initKeaTests()
jest.clearAllMocks()
@@ -107,9 +117,7 @@ describe('logsPatternsLogic', () => {
expect(mockCreate).toHaveBeenCalledWith(
expect.any(String),
- expect.objectContaining({
- query: expect.objectContaining({ severityLevels: [], serviceNames: [] }),
- })
+ expect.objectContaining({ query: expect.objectContaining({ filterGroup: expect.anything() }) })
)
})
@@ -135,8 +143,8 @@ describe('logsPatternsLogic', () => {
)
// The pivot also scopes by everything the sample saw — service_name and severity
// prune the scan the body regex can't, and multi-value IN filters narrow just as well.
- expect(filtersLogic.values.filters.serviceNames).toEqual(['auth', 'api'])
- expect(filtersLogic.values.filters.severityLevels).toEqual(['error', 'warn'])
+ expect(selectedServices()).toEqual(['auth', 'api'])
+ expect(selectedLevels()).toEqual(['error', 'warn'])
expect(configLogic.values.viewMode).toBe('logs')
// A filter that could silently exclude matching lines must be withheld: a services
@@ -147,8 +155,8 @@ describe('logsPatternsLogic', () => {
services: ['auth', 'api', 'db', 'kafka'],
severity_counts: { error: 2, notice: 1 },
})
- expect(filtersLogic.values.filters.serviceNames).toEqual(['auth', 'api'])
- expect(filtersLogic.values.filters.severityLevels).toEqual(['error', 'warn'])
+ expect(selectedServices()).toEqual(['auth', 'api'])
+ expect(selectedLevels()).toEqual(['error', 'warn'])
})
it('viewMatchingLogs falls back to an icontains literal filter when the regex was withheld', async () => {
@@ -195,7 +203,7 @@ describe('logsPatternsLogic', () => {
mockDiffCreate.mockClear()
await expectLogic(logic, () => {
- filtersLogic.actions.setServiceNames(['auth'])
+ filtersLogic.actions.setFilters({ serviceNames: ['auth'] })
}).toDispatchActions(['loadDiffSuccess'])
expect(mockDiffCreate).toHaveBeenCalledTimes(1)
expect(mockCreate).toHaveBeenCalledTimes(1) // only the original mount load
@@ -294,12 +302,22 @@ describe('logsPatternsLogic', () => {
mockCreate.mockClear()
await expectLogic(logic, () => {
- filtersLogic.actions.setSeverityLevels(['error'])
- }).toDispatchActions(['setSeverityLevels', 'loadPatterns', 'loadPatternsSuccess'])
+ filtersLogic.actions.setFilters({ severityLevels: ['error'] })
+ }).toDispatchActions(['setFilters', 'loadPatterns', 'loadPatternsSuccess'])
expect(mockCreate).toHaveBeenLastCalledWith(
expect.any(String),
- expect.objectContaining({ query: expect.objectContaining({ severityLevels: ['error'] }) })
+ expect.objectContaining({
+ query: expect.objectContaining({
+ filterGroup: expect.objectContaining({
+ values: [
+ expect.objectContaining({
+ values: [expect.objectContaining({ key: 'severity_level', value: ['error'] })],
+ }),
+ ],
+ }),
+ }),
+ })
)
})
diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts
index 0b70dc4cf474..4a8b28f3089e 100644
--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts
+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts
@@ -5,7 +5,6 @@ import { dayjs } from 'lib/dayjs'
import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { teamLogic } from 'scenes/teamLogic'
-import type { LogsQuery } from '~/queries/schema/schema-general'
import {
FilterLogicalOperator,
LogPropertyFilter,
@@ -15,6 +14,11 @@ import {
} from '~/types'
import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
+import {
+ SERVICE_NAME_FILTER,
+ SEVERITY_LEVEL_FILTER,
+ setFacetIncluded,
+} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
import { logsPatternsCreate, logsPatternsDiffCreate } from 'products/logs/frontend/generated/api'
import type {
@@ -24,7 +28,7 @@ import type {
_LogsPatternsResponseApi,
} from 'products/logs/frontend/generated/api.schemas'
-import type { DateRange, LogSeverityLevel } from '../../../../../frontend/src/queries/schema/schema-general'
+import type { DateRange } from '../../../../../frontend/src/queries/schema/schema-general'
import type { LogsViewerViewMode, PatternsBaselineMode } from '../LogsViewer/config/logsViewerConfigLogic'
import type { LogsViewerFilters } from '../LogsViewer/config/types'
@@ -95,8 +99,6 @@ export interface logsPatternsLogicValues {
}
filterGroup: _LogPropertyFilterApi[]
searchTerm: string | undefined
- serviceNames: string[]
- severityLevels: LogSeverityLevel[]
}
patternsResponse: _LogsPatternsResponseApi
patternsResponseLoading: boolean
@@ -137,12 +139,6 @@ export interface logsPatternsLogicActions {
setSearchTerm: (searchTerm: string | undefined) => {
searchTerm: string | undefined
} // logsViewerFiltersLogic
- setServiceNames: (serviceNames: string[]) => {
- serviceNames: string[]
- } // logsViewerFiltersLogic
- setSeverityLevels: (severityLevels: LogSeverityLevel[]) => {
- severityLevels: LogSeverityLevel[]
- } // logsViewerFiltersLogic
zoomDateRange: (multiplier: number) => {
multiplier: number
} // logsViewerFiltersLogic
@@ -202,8 +198,6 @@ export interface logsPatternsLogicMeta {
}
filterGroup: _LogPropertyFilterApi[]
searchTerm: string | undefined
- serviceNames: string[]
- severityLevels: LogSeverityLevel[]
}
patterns: (patternsResponse: _LogsPatternsResponseApi) => _LogPatternApi[]
sparklineLabels: (patternsResponse: _LogsPatternsResponseApi) => string[]
@@ -236,16 +230,7 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([
],
actions: [
logsViewerFiltersLogic({ id: props.id }),
- [
- 'setDateRange',
- 'zoomDateRange',
- 'setSeverityLevels',
- 'setServiceNames',
- 'setSearchTerm',
- 'setFilters',
- 'setFilterGroup',
- 'setPinnedFilters',
- ],
+ ['setDateRange', 'zoomDateRange', 'setSearchTerm', 'setFilters', 'setFilterGroup', 'setPinnedFilters'],
logsViewerConfigLogic({ id: props.id }),
['setViewMode', 'setCompareEnabled', 'setBaselineMode'],
],
@@ -335,8 +320,6 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([
queryFilterGroup: UniversalFiltersGroup
) => ({
dateRange: utcDateRange,
- severityLevels: filters.severityLevels,
- serviceNames: filters.serviceNames,
searchTerm: filters.searchTerm || undefined,
// Scope mining to the same filters the Logs/sparkline queries use —
// `queryFilterGroup` folds in any pinned filters from an embedded viewer
@@ -383,8 +366,6 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([
return {
setDateRange: reload,
zoomDateRange: reload,
- setSeverityLevels: reload,
- setServiceNames: reload,
setSearchTerm: reload,
setFilters: reload,
setFilterGroup: reload,
@@ -445,23 +426,25 @@ export const logsPatternsLogic = kea<logsPatternsLogicType>([
{ type: FilterLogicalOperator.And, values: [predicate] } as UniversalFiltersGroup,
],
}
- // Leave Patterns mode first so the filter writes below don't re-trigger a mine:
+ // Leave Patterns mode first so the filter write below doesn't re-trigger a mine:
// the `reload` guard sees Logs mode and bails on our own `setFilterGroup`.
actions.setViewMode('logs')
- actions.setFilterGroup(newGroup, false)
// Scope by every service and severity the sample saw: service_name is in the
// table's sort key and severity is indexed, so these prune the scan the body regex
// alone can't. Both are IN filters, so N values narrow just as validly as one, and
// both land as visible chips the user can remove if the pattern exists beyond the
// sample. Skipped only when the filter could silently exclude matching lines: a
- // cap-truncated services list, or a severity outside the canonical buckets.
+ // cap-truncated services list, or a severity outside the canonical buckets. Written
+ // into the same group as the pattern predicate so the drill-down is one filter change.
+ let scopedGroup = newGroup
if (pattern.services.length > 0 && pattern.services.length < SERVICES_LIST_CAP) {
- actions.setServiceNames(pattern.services)
+ scopedGroup = setFacetIncluded(scopedGroup, SERVICE_NAME_FILTER, pattern.services)
}
const severities = Object.keys(pattern.severity_counts)
if (severities.length > 0 && severities.every((s) => CANONICAL_SEVERITIES.includes(s))) {
- actions.setSeverityLevels(severities as LogsQuery['severityLevels'])
+ scopedGroup = setFacetIncluded(scopedGroup, SEVERITY_LEVEL_FILTER, severities)
}
+ actions.setFilterGroup(scopedGroup, false)
},
}
}),
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx
index cd4d3fb126d9..94034d78adb5 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/RailFacet.tsx
@@ -1,17 +1,12 @@
import { useActions, useValues } from 'kea'
-import { useMemo } from 'react'
+import { useCallback, useMemo } from 'react'
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
import { Facet, FacetOption } from './Facet'
+import { facetFilterTarget, facetSelection } from './facetFilters'
import { facetRailLogic } from './facetRailLogic'
-import {
- FacetConfig,
- FacetFilterKey,
- logFilterExclusions,
- mergeSelectedIntoOptions,
- resourceAttributeSelection,
-} from './facets'
+import { FacetConfig, mergeSelectedIntoOptions } from './facets'
import { facetValuesLogic } from './facetValuesLogic'
export interface RailFacetProps {
@@ -30,44 +25,54 @@ export function RailFacet({ id, facet, hidden }: RailFacetProps): JSX.Element |
const logicProps = useMemo(() => ({ id, facet }), [id, facet])
const { facetValues, facetValuesLoading, facetSearch, collapsed } = useValues(facetValuesLogic(logicProps))
const { setFacetSearch } = useActions(facetValuesLogic(logicProps))
- const { severityLevels, serviceNames, filterGroup } = useValues(logsViewerFiltersLogic({ id }))
+ const { filterGroup } = useValues(logsViewerFiltersLogic({ 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) : [],
- }
+ // Everything the value rows are built from is memoized: Facet feeds them to a virtualized list
+ // through one useMemo, so a fresh array or callback identity here re-renders every visible row in
+ // every mounted facet on any filter or count change.
+ // Both polarities come from the facet's own filters in the group, which is also what the chips
+ // bar renders, so a checkbox can't show a state the filter bar contradicts.
+ const { included: selected, excluded } = useMemo(
+ () => facetSelection(filterGroup, facetFilterTarget(source)),
+ [filterGroup, source]
+ )
// 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)
-
- if (facet.kind === 'fixed') {
- // Fixed value set from config, counts overlaid. Missing values render as a dimmed 0.
+ const fetched: FacetOption[] = useMemo(
+ () => facetValues.map((r) => ({ value: r.value, label: r.value, count: r.count })),
+ [facetValues]
+ )
+ // Fixed value set from config, counts overlaid. Missing values render as a dimmed 0.
+ const fixedOptions: FacetOption[] = useMemo(() => {
const countByValue = new Map(fetched.map((option) => [option.value, option.count]))
- const options: FacetOption[] = (facet.fixedOptions ?? []).map((option) => ({
+ return (facet.fixedOptions ?? []).map((option) => ({
...option,
count: countByValue.get(option.value) ?? 0,
}))
+ }, [fetched, facet.fixedOptions])
+ // Dynamic facet: the fetched values, plus any selected or excluded value the endpoint 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.
+ const dynamicOptions: FacetOption[] = useMemo(
+ () => mergeSelectedIntoOptions(fetched, [...selected, ...excluded], facet.searchable ? facetSearch : undefined),
+ [fetched, selected, excluded, facet.searchable, facetSearch]
+ )
+ const onToggle = useCallback((value: string): void => toggleFacetValue(source, value), [toggleFacetValue, source])
+ const onToggleCollapsed = useCallback(
+ (): void => toggleFacetCollapsed(facet.key),
+ [toggleFacetCollapsed, facet.key]
+ )
+
+ if (hidden) {
+ return null
+ }
+
+ if (facet.kind === 'fixed') {
return (
<Facet
title={facet.title}
- options={options}
+ options={fixedOptions}
selected={selected}
excluded={excluded}
onToggle={onToggle}
@@ -79,17 +84,10 @@ export function RailFacet({ id, facet, hidden }: RailFacetProps): JSX.Element |
)
}
- // 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
- )}
+ options={dynamicOptions}
selected={selected}
excluded={excluded}
onToggle={onToggle}
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.test.ts
new file mode 100644
index 000000000000..f313cb0b7437
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.test.ts
@@ -0,0 +1,229 @@
+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
+
+import {
+ FacetFilterTarget,
+ SERVICE_NAME_FILTER,
+ SEVERITY_LEVEL_FILTER,
+ cycleFacetValue,
+ facetFilterTarget,
+ facetSelection,
+ setFacetIncluded,
+ setFacetSelection,
+} from './facetFilters'
+
+const NAMESPACE: FacetFilterTarget = {
+ key: 'k8s.namespace.name',
+ type: PropertyFilterType.LogResourceAttribute,
+}
+
+const groupOf = (filters: Record<string, unknown>[]): UniversalFiltersGroup => ({
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: filters as UniversalFiltersGroup['values'] }],
+})
+
+const filterOf = (target: FacetFilterTarget, operator: PropertyOperator, value: unknown): Record<string, unknown> => ({
+ key: target.key,
+ type: target.type,
+ operator,
+ value,
+})
+
+const innerValues = (group: UniversalFiltersGroup): unknown[] => (group.values[0] as UniversalFiltersGroup).values
+
+describe('facetFilters', () => {
+ describe('facetFilterTarget', () => {
+ it.each<[string, string, FacetFilterTarget]>([
+ [
+ 'a column facet stores its selection as a log filter under its logKey',
+ 'severity_text',
+ {
+ key: 'severity_level',
+ type: PropertyFilterType.Log,
+ },
+ ],
+ [
+ 'a resource-attribute facet stores its selection under its attribute key',
+ 'k8s.namespace.name',
+ NAMESPACE,
+ ],
+ ])('%s', (_, key, expected) => {
+ const source =
+ key === 'severity_text'
+ ? ({ type: 'column', column: 'severity_text', logKey: 'severity_level' } as const)
+ : ({ type: 'resourceAttribute', key } as const)
+ expect(facetFilterTarget(source)).toEqual(expected)
+ })
+ })
+
+ describe('facetSelection', () => {
+ it.each<[string, FacetFilterTarget, Record<string, unknown>[], string[], string[]]>([
+ ['empty group reads as empty selection', NAMESPACE, [], [], []],
+ [
+ 'exact array filter reads as included',
+ NAMESPACE,
+ [filterOf(NAMESPACE, PropertyOperator.Exact, ['a', 'b'])],
+ ['a', 'b'],
+ [],
+ ],
+ [
+ 'is_not array filter reads as excluded',
+ NAMESPACE,
+ [filterOf(NAMESPACE, PropertyOperator.IsNot, ['c'])],
+ [],
+ ['c'],
+ ],
+ [
+ 'both polarities read into their own sets',
+ NAMESPACE,
+ [
+ filterOf(NAMESPACE, PropertyOperator.Exact, ['a']),
+ filterOf(NAMESPACE, PropertyOperator.IsNot, ['c']),
+ ],
+ ['a'],
+ ['c'],
+ ],
+ [
+ 'scalar chip value reads as a single-element set',
+ NAMESPACE,
+ [filterOf(NAMESPACE, PropertyOperator.Exact, 'a')],
+ ['a'],
+ [],
+ ],
+ [
+ 'other operators are not facet state',
+ NAMESPACE,
+ [filterOf(NAMESPACE, PropertyOperator.IContains, 'a')],
+ [],
+ [],
+ ],
+ [
+ 'other keys are not this facet',
+ NAMESPACE,
+ [filterOf({ key: 'host.name', type: NAMESPACE.type }, PropertyOperator.Exact, ['a'])],
+ [],
+ [],
+ ],
+ // The chips bar can hold any property type under a key, so the type has to discriminate:
+ // a resource-attribute filter named severity_level filters an attribute, not the column.
+ [
+ 'a resource-attribute filter under a column facet key is not that column selection',
+ SEVERITY_LEVEL_FILTER,
+ [
+ filterOf(
+ { key: 'severity_level', type: PropertyFilterType.LogResourceAttribute },
+ PropertyOperator.Exact,
+ ['error']
+ ),
+ ],
+ [],
+ [],
+ ],
+ [
+ 'an exact log filter under a column facet key reads as that column selection',
+ SEVERITY_LEVEL_FILTER,
+ [filterOf(SEVERITY_LEVEL_FILTER, PropertyOperator.Exact, ['error'])],
+ ['error'],
+ [],
+ ],
+ ])('%s', (_, target, filters, included, excluded) => {
+ expect(facetSelection(groupOf(filters), target)).toEqual({ included, excluded })
+ })
+ })
+
+ describe('cycleFacetValue', () => {
+ it.each<[string, FacetFilterTarget]>([
+ ['a resource attribute', NAMESPACE],
+ ['a column facet', SERVICE_NAME_FILTER],
+ ])('cycles %s unchecked → included → excluded → unchecked', (_, target) => {
+ const afterFirst = cycleFacetValue(groupOf([]), target, 'argocd')
+ expect(facetSelection(afterFirst, target)).toEqual({ included: ['argocd'], excluded: [] })
+
+ const afterSecond = cycleFacetValue(afterFirst, target, 'argocd')
+ expect(facetSelection(afterSecond, target)).toEqual({ included: [], excluded: ['argocd'] })
+
+ const afterThird = cycleFacetValue(afterSecond, target, 'argocd')
+ expect(facetSelection(afterThird, target)).toEqual({ included: [], excluded: [] })
+ // both filters are dropped once their side of the selection empties
+ expect(innerValues(afterThird)).toEqual([])
+ })
+
+ it('writes includes as an exact filter and excludes as an is_not filter, both array-valued', () => {
+ let group = cycleFacetValue(groupOf([]), NAMESPACE, 'a')
+ group = cycleFacetValue(group, NAMESPACE, 'b')
+ group = cycleFacetValue(group, NAMESPACE, 'a') // a → excluded
+
+ expect(innerValues(group)).toEqual([
+ filterOf(NAMESPACE, PropertyOperator.Exact, ['b']),
+ filterOf(NAMESPACE, PropertyOperator.IsNot, ['a']),
+ ])
+ })
+
+ it('preserves other keys and same-key non-facet chips when writing', () => {
+ const otherKey = filterOf(
+ { key: 'deployment.environment.name', type: NAMESPACE.type },
+ PropertyOperator.Exact,
+ ['prod']
+ )
+ const sameKeyContains = filterOf(NAMESPACE, PropertyOperator.IContains, 'kube')
+ const group = cycleFacetValue(groupOf([otherKey, sameKeyContains]), NAMESPACE, 'argocd')
+
+ expect(innerValues(group)).toEqual([
+ otherKey,
+ sameKeyContains,
+ filterOf(NAMESPACE, PropertyOperator.Exact, ['argocd']),
+ ])
+ })
+
+ // A user can edit an exclusion chip's operator to `=` in the filter bar, which leaves the same
+ // value on both sides. Cycling out of that must land on one polarity, not AND the two together.
+ it('a value in both polarities (hand-edited chips) cycles to excluded only, without duplication', () => {
+ const corrupt = groupOf([
+ filterOf(NAMESPACE, PropertyOperator.Exact, ['a']),
+ filterOf(NAMESPACE, PropertyOperator.IsNot, ['a']),
+ ])
+ const cycled = cycleFacetValue(corrupt, NAMESPACE, 'a')
+ expect(facetSelection(cycled, NAMESPACE)).toEqual({ included: [], excluded: ['a'] })
+ expect(innerValues(cycled)).toEqual([filterOf(NAMESPACE, PropertyOperator.IsNot, ['a'])])
+ })
+ })
+
+ // A log with no service_name facets as '', which the services table shows as "(no service)".
+ it("reads back a '' service selection so its row can cycle", () => {
+ const cycled = cycleFacetValue(groupOf([]), SERVICE_NAME_FILTER, '')
+
+ expect(facetSelection(cycled, SERVICE_NAME_FILTER).included).toEqual([''])
+ })
+
+ describe('setFacetSelection', () => {
+ it('keeps a sibling group the facet does not own', () => {
+ const sibling = { type: FilterLogicalOperator.Or, values: [] } as UniversalFiltersGroup
+ const group: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: [] }, sibling],
+ }
+
+ const written = setFacetSelection(group, SERVICE_NAME_FILTER, { included: ['api'], excluded: [] })
+
+ expect(written.values).toHaveLength(2)
+ expect(written.values[1]).toEqual(sibling)
+ expect(facetSelection(written, SERVICE_NAME_FILTER)).toEqual({ included: ['api'], excluded: [] })
+ })
+ })
+
+ describe('setFacetIncluded', () => {
+ it('replaces the included values and leaves the exclusions alone', () => {
+ const group = groupOf([
+ filterOf(SERVICE_NAME_FILTER, PropertyOperator.Exact, ['api']),
+ filterOf(SERVICE_NAME_FILTER, PropertyOperator.IsNot, ['worker']),
+ ])
+ expect(
+ facetSelection(setFacetIncluded(group, SERVICE_NAME_FILTER, ['batch']), SERVICE_NAME_FILTER)
+ ).toEqual({ included: ['batch'], excluded: ['worker'] })
+ })
+
+ it('drops the exact filter when the included set empties', () => {
+ const group = setFacetIncluded(groupOf([]), SERVICE_NAME_FILTER, ['api'])
+ expect(innerValues(setFacetIncluded(group, SERVICE_NAME_FILTER, []))).toEqual([])
+ })
+ })
+})
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.ts
new file mode 100644
index 000000000000..caced86d8142
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetFilters.ts
@@ -0,0 +1,182 @@
+/**
+ * How a facet's tri-state selection is stored in the logs filterGroup: one property filter per
+ * polarity under the facet's own key, `exact` for included values and `is_not` for excluded ones.
+ *
+ * This is the only store for a facet selection, which is what keeps the rail's checkboxes and the
+ * chips bar in agreement: both read these filters, and every rail click rewrites them.
+ */
+
+import {
+ FilterLogicalOperator,
+ PropertyFilterType,
+ PropertyFilterValue,
+ PropertyOperator,
+ UniversalFiltersGroup,
+} from '~/types'
+
+import type { FacetSource } from './facets'
+
+/**
+ * The property filter a selection is stored under: one type + key pair, holding both polarities. The
+ * rail only ever names a `log` column or a `log_resource_attribute`, but the search bar reconciles
+ * whatever type the picker produced, so the type stays open.
+ */
+export interface FacetFilterTarget {
+ key: string
+ type: PropertyFilterType
+}
+
+interface RailPropertyFilter {
+ key: string
+ type: PropertyFilterType
+ operator: PropertyOperator
+ 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. Exported for facetScopeSignature, which
+// walks the same entries to decide what a facet's values depend on.
+export function innerFilters(group: UniversalFiltersGroup | undefined): RailFilterEntry[] {
+ return ((group?.values?.[0] as UniversalFiltersGroup | undefined)?.values ?? []) as RailFilterEntry[]
+}
+
+export function isPropertyLeaf(entry: RailFilterEntry): entry is RailPropertyFilter {
+ return !('values' in entry)
+}
+
+/**
+ * Tri-state selection for a facet: a value is included, excluded, or in neither set. The query
+ * effect is `IN (included)` AND `NOT IN (excluded)` — attribute exclusions keep rows missing the
+ * attribute entirely.
+ */
+export interface FacetSelection {
+ included: string[]
+ excluded: string[]
+}
+
+// A selection is held by a key's `exact` (include) and `is_not` (exclude) filters. A chip on the same
+// key with any other operator (e.g. icontains) is not part of one: it's ignored on read and preserved
+// untouched on write. Exported because the search bar reconciles against the same pair.
+export const EQUALITY_OPERATORS: PropertyOperator[] = [PropertyOperator.Exact, PropertyOperator.IsNot]
+
+/** Whether two targets name the same attribute. */
+export function isSameFilterTarget(a: FacetFilterTarget | null, b: FacetFilterTarget | null): boolean {
+ return a !== null && b !== null && a.type === b.type && a.key === b.key
+}
+
+function isRailFacetFilter(entry: RailFilterEntry, target: FacetFilterTarget): entry is RailPropertyFilter {
+ return (
+ isPropertyLeaf(entry) &&
+ entry?.type === target.type &&
+ entry?.key === target.key &&
+ EQUALITY_OPERATORS.includes(entry?.operator)
+ )
+}
+
+/**
+ * A filter's values as a list. Values keep their own type, so merging into a numeric filter does not
+ * rewrite it to strings; callers that compare stringify at the point of comparison.
+ *
+ * An empty string inside the list is kept, unlike in the tracing rail: a log with no service_name
+ * facets as `''` (the services table shows it as "(no service)" and filters on `''`), so dropping it
+ * would leave that row's checkbox unable to read its own selection.
+ */
+export function filterValues(filter: { value?: PropertyFilterValue }): unknown[] {
+ const value = filter.value
+ if (Array.isArray(value)) {
+ return value
+ }
+ return value != null && value !== '' ? [value] : []
+}
+
+/** The filterGroup property filter a facet's selection is stored in, derived from its source. */
+export function facetFilterTarget(source: FacetSource): FacetFilterTarget {
+ return source.type === 'column'
+ ? { key: source.logKey, type: PropertyFilterType.Log }
+ : { key: source.key, type: PropertyFilterType.LogResourceAttribute }
+}
+
+/** A facet's selection, read from the exact (include) and is_not (exclude) filters it owns. */
+export function facetSelection(group: UniversalFiltersGroup | undefined, target: FacetFilterTarget): FacetSelection {
+ const railFilters = innerFilters(group).filter((f) => isRailFacetFilter(f, target))
+ const valuesOf = (operator: PropertyOperator): string[] =>
+ railFilters
+ .filter((f) => f.operator === operator)
+ .flatMap(filterValues)
+ .map((v) => String(v))
+ return { included: valuesOf(PropertyOperator.Exact), excluded: valuesOf(PropertyOperator.IsNot) }
+}
+
+/**
+ * Replace a facet's selection, returning a new filterGroup. Both polarities are stored as one filter
+ * each with an array value, `exact` and `is_not` (logs have no `in` operator); a filter is dropped
+ * when its side of the selection empties. Filters the facet doesn't own carry through untouched, and
+ * so does the rest of the group's shape: the outer operator, and any sibling group past the first,
+ * which the patterns pivot relies on to keep its message predicate.
+ */
+export function setFacetSelection(
+ group: UniversalFiltersGroup | undefined,
+ target: FacetFilterTarget,
+ selection: FacetSelection
+): UniversalFiltersGroup {
+ // Annotated: negating the type guard would otherwise narrow the survivors to nested groups.
+ const values: RailFilterEntry[] = innerFilters(group).filter((f) => !isRailFacetFilter(f, target))
+ if (selection.included.length > 0) {
+ values.push({ ...target, operator: PropertyOperator.Exact, value: selection.included })
+ }
+ if (selection.excluded.length > 0) {
+ values.push({ ...target, operator: PropertyOperator.IsNot, value: selection.excluded })
+ }
+ const inner = group?.values?.[0] as UniversalFiltersGroup | undefined
+ return {
+ type: group?.type ?? FilterLogicalOperator.And,
+ values: [
+ { type: inner?.type ?? FilterLogicalOperator.And, values } as UniversalFiltersGroup,
+ ...(group?.values?.slice(1) ?? []),
+ ],
+ }
+}
+
+/** Replace a facet's included values, leaving its exclusions in place. */
+export function setFacetIncluded(
+ group: UniversalFiltersGroup | undefined,
+ target: FacetFilterTarget,
+ included: string[]
+): UniversalFiltersGroup {
+ return setFacetSelection(group, target, { ...facetSelection(group, target), included })
+}
+
+/**
+ * Advance `value` one step through the facet cycle — unchecked → included → excluded → unchecked —
+ * returning a new filterGroup.
+ */
+export function cycleFacetValue(
+ group: UniversalFiltersGroup | undefined,
+ target: FacetFilterTarget,
+ value: string
+): UniversalFiltersGroup {
+ const { included, excluded } = facetSelection(group, target)
+ if (included.includes(value)) {
+ return setFacetSelection(group, target, {
+ included: included.filter((v) => v !== value),
+ // A value hand-edited into both polarities is already excluded; don't add it twice.
+ excluded: excluded.includes(value) ? excluded : [...excluded, value],
+ })
+ }
+ if (excluded.includes(value)) {
+ return setFacetSelection(group, target, { included, excluded: excluded.filter((v) => v !== value) })
+ }
+ return setFacetSelection(group, target, { included: [...included, value], excluded })
+}
+
+/**
+ * The two `log` filter targets the legacy dedicated query fields fold into. The facet configs and
+ * logsViewerFiltersLogic both name their key from here, so the storage key for a column facet's
+ * selection is defined once.
+ */
+export const SEVERITY_LEVEL_FILTER: FacetFilterTarget = { key: 'severity_level', type: PropertyFilterType.Log }
+export const SERVICE_NAME_FILTER: FacetFilterTarget = { key: 'service_name', type: PropertyFilterType.Log }
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.test.ts
index 8c692a58f7b3..95cf01e3c8a5 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.test.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.test.ts
@@ -1,30 +1,29 @@
import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
-import { UniversalFiltersGroup } from '~/types'
+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
import { logsViewerFiltersLogic } from '../Filters/logsViewerFiltersLogic'
+import { FacetSelection, facetFilterTarget, facetSelection } from './facetFilters'
import { facetRailLogic } from './facetRailLogic'
-import { FacetSelection, FacetSource, logFilterExclusions, resourceAttributeSelection } from './facets'
-
-const LEVEL_SOURCE: FacetSource = {
- type: 'column',
- column: 'severity_text',
- filterKey: 'severityLevels',
- exclusionKey: 'severity_level',
-}
-const SERVICE_SOURCE: FacetSource = {
- type: 'column',
- column: 'service_name',
- filterKey: 'serviceNames',
- exclusionKey: 'service_name',
-}
+import { FacetSource } from './facets'
+
+const LEVEL_SOURCE: FacetSource = { type: 'column', column: 'severity_text', logKey: 'severity_level' }
+const SERVICE_SOURCE: FacetSource = { type: 'column', column: 'service_name', logKey: 'service_name' }
const NAMESPACE_SOURCE: FacetSource = { type: 'resourceAttribute', key: 'k8s.namespace.name' }
describe('facetRailLogic', () => {
let filtersLogic: ReturnType<typeof logsViewerFiltersLogic.build>
let logic: ReturnType<typeof facetRailLogic.build>
+ const selectionOf = (source: FacetSource): FacetSelection =>
+ facetSelection(filtersLogic.values.filterGroup, facetFilterTarget(source))
+ const innerFilterValues = (): unknown[] =>
+ (filtersLogic.values.filterGroup.values[0] as UniversalFiltersGroup).values
+ const click = async (source: FacetSource, value: string): Promise<void> => {
+ await expectLogic(logic, () => logic.actions.toggleFacetValue(source, value)).toFinishAllListeners()
+ }
+
beforeEach(() => {
initKeaTests()
filtersLogic = logsViewerFiltersLogic({ id: 'test' })
@@ -38,39 +37,6 @@ describe('facetRailLogic', () => {
filtersLogic.unmount()
})
- describe('severity level cycling', () => {
- const readExcluded = (): string[] => logFilterExclusions(filtersLogic.values.filterGroup, 'severity_level')
- const click = async (value: string): Promise<void> => {
- await expectLogic(logic, () => logic.actions.toggleFacetValue(LEVEL_SOURCE, value)).toFinishAllListeners()
- }
-
- it('cycles a level across the two stores: dedicated field, then is_not log filter, then cleared', async () => {
- await click('error')
- expect(filtersLogic.values.severityLevels).toEqual(['error'])
- expect(readExcluded()).toEqual([])
-
- await click('error')
- expect(filtersLogic.values.severityLevels).toEqual([])
- expect(readExcluded()).toEqual(['error'])
-
- await click('error')
- expect(filtersLogic.values.severityLevels).toEqual([])
- expect(readExcluded()).toEqual([])
- // the is_not filter is dropped from the group entirely, not left empty
- expect((filtersLogic.values.filterGroup.values[0] as UniversalFiltersGroup).values).toEqual([])
- })
-
- it('holds one level included while another is excluded', async () => {
- await click('error')
- await click('warn')
- expect(filtersLogic.values.severityLevels).toEqual(['error', 'warn'])
-
- await click('error')
- expect(filtersLogic.values.severityLevels).toEqual(['warn'])
- expect(readExcluded()).toEqual(['error'])
- })
- })
-
describe('facet collapse', () => {
it('adds a facet to the collapsed set, then removes it on the second toggle', async () => {
await expectLogic(logic, () => logic.actions.toggleFacetCollapsed('level')).toFinishAllListeners()
@@ -85,84 +51,78 @@ describe('facetRailLogic', () => {
})
})
- describe('service name cycling', () => {
- it('cycles a service across the two stores: dedicated field, then is_not log filter, then cleared', async () => {
- await expectLogic(logic, () => logic.actions.toggleFacetValue(SERVICE_SOURCE, 'api')).toFinishAllListeners()
- expect(filtersLogic.values.serviceNames).toEqual(['api'])
- expect(logFilterExclusions(filtersLogic.values.filterGroup, 'service_name')).toEqual([])
-
- await expectLogic(logic, () => logic.actions.toggleFacetValue(SERVICE_SOURCE, 'api')).toFinishAllListeners()
- expect(filtersLogic.values.serviceNames).toEqual([])
- expect(logFilterExclusions(filtersLogic.values.filterGroup, 'service_name')).toEqual(['api'])
-
- await expectLogic(logic, () => logic.actions.toggleFacetValue(SERVICE_SOURCE, 'api')).toFinishAllListeners()
- expect(logFilterExclusions(filtersLogic.values.filterGroup, 'service_name')).toEqual([])
- expect((filtersLogic.values.filterGroup.values[0] as UniversalFiltersGroup).values).toEqual([])
+ // Every facet keeps both polarities in the filterGroup, so one suite covers all three kinds.
+ describe.each<[string, FacetSource]>([
+ ['level', LEVEL_SOURCE],
+ ['service', SERVICE_SOURCE],
+ ['namespace', NAMESPACE_SOURCE],
+ ])('%s facet cycling', (_, source) => {
+ it('cycles a value unchecked → included → excluded → cleared in the filterGroup', async () => {
+ await click(source, 'a')
+ expect(selectionOf(source)).toEqual({ included: ['a'], excluded: [] })
+
+ await click(source, 'a')
+ expect(selectionOf(source)).toEqual({ included: [], excluded: ['a'] })
+
+ await click(source, 'a')
+ expect(selectionOf(source)).toEqual({ included: [], excluded: [] })
+ // both filters are dropped from the group entirely, not left empty
+ expect(innerFilterValues()).toEqual([])
})
- it('holds one service included while another is excluded', async () => {
- await expectLogic(logic, () => logic.actions.toggleFacetValue(SERVICE_SOURCE, 'api')).toFinishAllListeners()
- await expectLogic(logic, () =>
- logic.actions.toggleFacetValue(SERVICE_SOURCE, 'worker')
- ).toFinishAllListeners()
- await expectLogic(logic, () => logic.actions.toggleFacetValue(SERVICE_SOURCE, 'api')).toFinishAllListeners()
+ it('holds one value included while another is excluded', async () => {
+ await click(source, 'a')
+ await click(source, 'b')
+ expect(selectionOf(source)).toEqual({ included: ['a', 'b'], excluded: [] })
- expect(filtersLogic.values.serviceNames).toEqual(['worker'])
- expect(logFilterExclusions(filtersLogic.values.filterGroup, 'service_name')).toEqual(['api'])
- })
-
- it('keeps service and severity exclusions under their own keys', async () => {
- // Both column facets store exclusions as is_not log filters — a service exclusion must
- // not clobber a severity exclusion already in the group, or vice versa.
- await expectLogic(logic, () => logic.actions.toggleFacetValue(LEVEL_SOURCE, 'error')).toFinishAllListeners()
- await expectLogic(logic, () => logic.actions.toggleFacetValue(LEVEL_SOURCE, 'error')).toFinishAllListeners()
- await expectLogic(logic, () => logic.actions.toggleFacetValue(SERVICE_SOURCE, 'api')).toFinishAllListeners()
- await expectLogic(logic, () => logic.actions.toggleFacetValue(SERVICE_SOURCE, 'api')).toFinishAllListeners()
-
- expect(logFilterExclusions(filtersLogic.values.filterGroup, 'severity_level')).toEqual(['error'])
- expect(logFilterExclusions(filtersLogic.values.filterGroup, 'service_name')).toEqual(['api'])
+ await click(source, 'a')
+ expect(selectionOf(source)).toEqual({ included: ['b'], excluded: ['a'] })
})
})
- describe('shared state', () => {
- it('toggles relative to selections already on the filters logic', async () => {
- filtersLogic.actions.setSeverityLevels(['info'])
- await expectLogic(filtersLogic).toFinishAllListeners()
+ describe('shared filter state', () => {
+ it('keeps each facet under its own key', async () => {
+ await click(LEVEL_SOURCE, 'error')
+ await click(LEVEL_SOURCE, 'error')
+ await click(SERVICE_SOURCE, 'api')
+ await click(NAMESPACE_SOURCE, 'argocd')
- await expectLogic(logic, () => logic.actions.toggleFacetValue(LEVEL_SOURCE, 'error')).toFinishAllListeners()
- expect(filtersLogic.values.severityLevels).toEqual(['info', 'error'])
- })
- })
-
- describe('resource attribute cycling', () => {
- const read = (): FacetSelection =>
- resourceAttributeSelection(filtersLogic.values.filterGroup, 'k8s.namespace.name')
- const click = async (value: string): Promise<void> => {
- await expectLogic(logic, () =>
- logic.actions.toggleFacetValue(NAMESPACE_SOURCE, value)
- ).toFinishAllListeners()
- }
-
- it('cycles a value included → excluded → cleared through the shared filters logic', async () => {
- await click('argocd')
- expect(read()).toEqual({ included: ['argocd'], excluded: [] })
-
- await click('argocd')
- expect(read()).toEqual({ included: [], excluded: ['argocd'] })
-
- await click('argocd')
- expect(read()).toEqual({ included: [], excluded: [] })
- // the single inner group holds no filters once the cycle completes
- expect((filtersLogic.values.filterGroup.values[0] as UniversalFiltersGroup).values).toEqual([])
+ expect(selectionOf(LEVEL_SOURCE)).toEqual({ included: [], excluded: ['error'] })
+ expect(selectionOf(SERVICE_SOURCE)).toEqual({ included: ['api'], excluded: [] })
+ expect(selectionOf(NAMESPACE_SOURCE)).toEqual({ included: ['argocd'], excluded: [] })
})
- it('holds one value included while another is excluded (OR within includes, AND with excludes)', async () => {
- await click('argocd')
- await click('kube-system')
- expect(read()).toEqual({ included: ['argocd', 'kube-system'], excluded: [] })
+ it('toggles relative to a selection the filter bar already holds', async () => {
+ // A filter the user typed into the chips bar (or an `=` they edited an exclusion chip into)
+ // is the same state the rail reads, so the next click cycles it on rather than ANDing a
+ // second, contradictory filter under the same key onto the query.
+ filtersLogic.actions.setFilterGroup(
+ {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ key: 'service_name',
+ type: PropertyFilterType.Log,
+ operator: PropertyOperator.Exact,
+ value: ['api'],
+ },
+ ],
+ } as UniversalFiltersGroup,
+ ],
+ },
+ false
+ )
+ await expectLogic(filtersLogic).toFinishAllListeners()
+ expect(selectionOf(SERVICE_SOURCE)).toEqual({ included: ['api'], excluded: [] })
- await click('argocd')
- expect(read()).toEqual({ included: ['kube-system'], excluded: ['argocd'] })
+ await click(SERVICE_SOURCE, 'api')
+ expect(selectionOf(SERVICE_SOURCE)).toEqual({ included: [], excluded: ['api'] })
+ expect(innerFilterValues()).toEqual([
+ { key: 'service_name', type: PropertyFilterType.Log, operator: PropertyOperator.IsNot, value: ['api'] },
+ ])
})
})
})
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.ts
index cf5fce331c23..f108764cf4ed 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.ts
@@ -1,22 +1,15 @@
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'
-import { LogSeverityLevel } from '~/queries/schema/schema-general'
-
-import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
import type { UniversalFiltersGroup } from '../../../../../../frontend/src/types'
-import { FacetSource, cycleResourceAttributeFilter, logFilterExclusions, setLogFilterExclusions } from './facets'
+import { cycleFacetValue, facetFilterTarget } from './facetFilters'
+import { FacetSource } from './facets'
export interface FacetRailLogicProps {
id: string
}
-function toggleMembership<T>(values: readonly T[] | undefined | null, value: T): T[] {
- const current = values ?? []
- return current.includes(value) ? current.filter((v) => v !== value) : [...current, value]
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface facetRailLogicValues {
collapsedFacets: string[]
@@ -32,19 +25,6 @@ export interface facetRailLogicActions {
filterGroup: UniversalFiltersGroup
openFilterOnInsert: boolean
} // logsViewerFiltersLogic
- setFilters: (
- filters: Partial<LogsViewerFilters>,
- pushToHistory?: boolean | undefined
- ) => {
- filters: Partial<LogsViewerFilters>
- pushToHistory: boolean
- } // logsViewerFiltersLogic
- setServiceNames: (serviceNames: string[]) => {
- serviceNames: string[]
- } // logsViewerFiltersLogic
- setSeverityLevels: (severityLevels: LogSeverityLevel[]) => {
- severityLevels: LogSeverityLevel[]
- } // logsViewerFiltersLogic
setFacetNameSearch: (search: string) => {
search: string
}
@@ -80,15 +60,12 @@ export const facetRailLogic = kea<facetRailLogicType>([
key((props) => props.id),
connect((props: FacetRailLogicProps) => ({
- actions: [
- logsViewerFiltersLogic({ id: props.id }),
- ['setSeverityLevels', 'setServiceNames', 'setFilterGroup', 'setFilters'],
- ],
+ actions: [logsViewerFiltersLogic({ id: props.id }), ['setFilterGroup']],
})),
actions({
- // Generic toggle: the rail is config-driven, so a single action writes a value into whichever
- // filter field/group the facet's source maps to (see FacetConfig.source).
+ // Generic toggle: the rail is config-driven, so a single action cycles a value through
+ // whichever filterGroup property filter the facet's source maps to (see FacetConfig.source).
toggleFacetValue: (source: FacetSource, value: string) => ({ source, value }),
toggleFacetCollapsed: (facetKey: string) => ({ facetKey }),
// Free-text filter over the facet *fields* shown in the rail (not their values). URL-synced by
@@ -115,78 +92,12 @@ export const facetRailLogic = kea<facetRailLogicType>([
listeners(({ props, actions }) => ({
toggleFacetValue: ({ source, value }) => {
- const { severityLevels, serviceNames, filterGroup } = logsViewerFiltersLogic({ id: props.id }).values
- if (source.type === 'resourceAttribute') {
- // Selection lives as log_resource_attribute filters inside the group; a click
- // cycles the value included → excluded → cleared.
- actions.setFilterGroup(cycleResourceAttributeFilter(filterGroup, source.key, value), false)
- return
- }
-
- // Column facets have a split representation: includes live in the facet's dedicated
- // field, exclusions in an is_not log filter inside the group (under exclusionKey).
- // A click cycles included → excluded → cleared across the two stores; without an
- // exclusionKey the facet stays two-state. setIncluded writes the dedicated field on
- // its own (keeping its filter-change analytics); includedFilters produces the same
- // field update as a filters patch for the one transition that must move both stores
- // atomically.
- const cycleColumnValue = (
- included: string[],
- setIncluded: (next: string[]) => void,
- includedFilters: (next: string[]) => Partial<LogsViewerFilters>
- ): void => {
- const { exclusionKey } = source
- if (!exclusionKey) {
- setIncluded(toggleMembership(included, value))
- return
- }
- const excluded = logFilterExclusions(filterGroup, exclusionKey)
- if (included.includes(value)) {
- // included → excluded moves the value across both stores at once (out of the
- // dedicated includes field, into an is_not log filter). Write them in a single
- // setFilters so the query, URL sync, and filter history all see the final
- // state, instead of two setters each firing against a half-applied cycle.
- actions.setFilters(
- {
- ...includedFilters(included.filter((v) => v !== value)),
- filterGroup: setLogFilterExclusions(
- filterGroup,
- exclusionKey,
- excluded.includes(value) ? excluded : [...excluded, value]
- ),
- },
- false
- )
- } else if (excluded.includes(value)) {
- actions.setFilterGroup(
- setLogFilterExclusions(
- filterGroup,
- exclusionKey,
- excluded.filter((v) => v !== value)
- ),
- false
- )
- } else {
- setIncluded([...included, value])
- }
- }
-
- if (source.filterKey === 'severityLevels') {
- cycleColumnValue(
- severityLevels ?? [],
- (next) => actions.setSeverityLevels(next as LogSeverityLevel[]),
- (next) => ({ severityLevels: next as LogSeverityLevel[] })
- )
- } else if (source.filterKey === 'serviceNames') {
- cycleColumnValue(
- serviceNames ?? [],
- (next) => actions.setServiceNames(next),
- (next) => ({ serviceNames: next })
- )
- } else {
- // Adding a new column filterKey without wiring its setter here is a compile error.
- source.filterKey satisfies never
- }
+ // Both polarities live in the filterGroup under the facet's own key, so a click is one
+ // write: the value cycles included → excluded → cleared, and the chips bar shows each
+ // step. Filters on the same key the facet doesn't own (any operator other than exact or
+ // is_not) are left alone.
+ const { filterGroup } = logsViewerFiltersLogic({ id: props.id }).values
+ actions.setFilterGroup(cycleFacetValue(filterGroup, facetFilterTarget(source), value), false)
},
})),
])
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.test.ts
index e269a525fc0a..2103611fd49e 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.test.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.test.ts
@@ -56,8 +56,8 @@ describe('facetValuesLogic', () => {
// 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'])],
+ ['a level selection', LEVEL, SERVICE, () => filtersLogic.actions.setFilters({ severityLevels: ['error'] })],
+ ['a service selection', SERVICE, LEVEL, () => filtersLogic.actions.setFilters({ serviceNames: ['api'] })],
])('%s reloads the other facets but not itself', async (_, selected, other, select) => {
const selectedLogic = mountFacet(selected)
const otherLogic = mountFacet(other)
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts
index eaadedef6fc7..4a630df4f0e7 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetValuesLogic.ts
@@ -6,7 +6,10 @@ import { teamLogic } from 'scenes/teamLogic'
import { UniversalFiltersGroup } from '~/types'
-import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
+import {
+ ColumnQueryFields,
+ logsViewerFiltersLogic,
+} from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
import { logsFacetValuesCreate } from '../../../generated/api'
import { _LogFacetValueApi, _LogPropertyFilterApi, _LogsFacetValuesBodyApi } from '../../../generated/api.schemas'
@@ -23,6 +26,7 @@ export interface FacetValuesLogicProps {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface facetValuesLogicValues {
collapsedFacets: string[] // facetRailLogic
+ columnQueryFields: ColumnQueryFields // logsViewerFiltersLogic
filters: LogsViewerFilters // logsViewerFiltersLogic
personId: string | undefined // logsViewerFiltersLogic
queryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic
@@ -120,7 +124,7 @@ export const facetValuesLogic = kea<facetValuesLogicType>([
connect((props: FacetValuesLogicProps) => ({
values: [
logsViewerFiltersLogic({ id: props.id }),
- ['filters', 'utcDateRange', 'queryFilterGroup', 'personId'],
+ ['filters', 'utcDateRange', 'queryFilterGroup', 'personId', 'columnQueryFields'],
teamLogic,
['currentTeamId'],
facetRailLogic({ id: props.id }),
@@ -180,8 +184,9 @@ export const facetValuesLogic = kea<facetValuesLogicType>([
query: {
...target,
dateRange: values.utcDateRange,
- severityLevels: values.filters.severityLevels ?? [],
- serviceNames: values.filters.serviceNames ?? [],
+ // The attribute facets read their level and service scope off these
+ // fields, not the group (see columnQueryFieldsOf).
+ ...values.columnQueryFields,
searchTerm: values.filters.searchTerm || undefined,
facetSearch: values.facetSearch || undefined,
filterGroup,
@@ -229,8 +234,6 @@ export const facetValuesLogic = kea<facetValuesLogicType>([
currentTeamId,
utcDateRange,
searchTerm: filters.searchTerm,
- severityLevels: filters.severityLevels,
- serviceNames: filters.serviceNames,
queryFilterGroup,
personId,
}),
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
index 6b16b0151795..cb27fc07a6d8 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
@@ -5,14 +5,10 @@ import {
FACETS as CONFIGURED_FACETS,
FacetConfig,
FacetScope,
- cycleResourceAttributeFilter,
facetScopeSignature,
filterFacetsByName,
- logFilterExclusions,
mergeSelectedIntoOptions,
resolveFacets,
- resourceAttributeSelection,
- setLogFilterExclusions,
} from './facets'
const facet = (key: string, title: string, group: string): FacetConfig => ({
@@ -85,165 +81,6 @@ describe('facets', () => {
})
})
- describe('tri-state resource attribute selection', () => {
- const KEY = 'k8s.namespace.name'
-
- const groupOf = (filters: Record<string, unknown>[]): UniversalFiltersGroup => ({
- type: FilterLogicalOperator.And,
- values: [{ type: FilterLogicalOperator.And, values: filters as UniversalFiltersGroup['values'] }],
- })
- const railFilter = (
- operator: PropertyOperator,
- value: unknown,
- key: string = KEY
- ): Record<string, unknown> => ({
- key,
- type: PropertyFilterType.LogResourceAttribute,
- operator,
- value,
- })
- const read = (group: UniversalFiltersGroup | undefined): { included: string[]; excluded: string[] } =>
- resourceAttributeSelection(group, KEY)
-
- describe('resourceAttributeSelection', () => {
- it.each<[string, Record<string, unknown>[], string[], string[]]>([
- ['empty group reads as empty selection', [], [], []],
- [
- 'exact array filter reads as included',
- [railFilter(PropertyOperator.Exact, ['a', 'b'])],
- ['a', 'b'],
- [],
- ],
- ['is_not array filter reads as excluded', [railFilter(PropertyOperator.IsNot, ['c'])], [], ['c']],
- [
- 'both polarities read into their own sets',
- [railFilter(PropertyOperator.Exact, ['a']), railFilter(PropertyOperator.IsNot, ['c'])],
- ['a'],
- ['c'],
- ],
- [
- 'scalar chip value reads as a single-element set',
- [railFilter(PropertyOperator.Exact, 'a')],
- ['a'],
- [],
- ],
- ['scalar is_not chip reads as excluded', [railFilter(PropertyOperator.IsNot, 'c')], [], ['c']],
- ['other operators are not rail state', [railFilter(PropertyOperator.IContains, 'a')], [], []],
- ['other keys are not this facet', [railFilter(PropertyOperator.Exact, ['a'], 'host.name')], [], []],
- ])('%s', (_, filters, included, excluded) => {
- expect(read(groupOf(filters))).toEqual({ included, excluded })
- })
- })
-
- describe('cycleResourceAttributeFilter', () => {
- it('cycles a value unchecked → included → excluded → unchecked', () => {
- const afterFirst = cycleResourceAttributeFilter(groupOf([]), KEY, 'argocd')
- expect(read(afterFirst)).toEqual({ included: ['argocd'], excluded: [] })
-
- const afterSecond = cycleResourceAttributeFilter(afterFirst, KEY, 'argocd')
- expect(read(afterSecond)).toEqual({ included: [], excluded: ['argocd'] })
-
- const afterThird = cycleResourceAttributeFilter(afterSecond, KEY, 'argocd')
- expect(read(afterThird)).toEqual({ included: [], excluded: [] })
- // both rail filters are dropped once their side of the selection empties
- expect((afterThird.values[0] as UniversalFiltersGroup).values).toEqual([])
- })
-
- it('writes includes as an exact filter and excludes as an is_not filter, both array-valued', () => {
- let group = cycleResourceAttributeFilter(groupOf([]), KEY, 'a')
- group = cycleResourceAttributeFilter(group, KEY, 'b')
- group = cycleResourceAttributeFilter(group, KEY, 'a') // a → excluded
-
- expect((group.values[0] as UniversalFiltersGroup).values).toEqual([
- railFilter(PropertyOperator.Exact, ['b']),
- railFilter(PropertyOperator.IsNot, ['a']),
- ])
- })
-
- it('preserves other keys and same-key non-rail chips when writing', () => {
- const otherKey = railFilter(PropertyOperator.Exact, ['prod'], 'deployment.environment.name')
- const sameKeyContains = railFilter(PropertyOperator.IContains, 'kube')
- const group = cycleResourceAttributeFilter(groupOf([otherKey, sameKeyContains]), KEY, 'argocd')
-
- expect((group.values[0] as UniversalFiltersGroup).values).toEqual([
- otherKey,
- sameKeyContains,
- railFilter(PropertyOperator.Exact, ['argocd']),
- ])
- })
-
- it('a value in both polarities (hand-edited chips) cycles to excluded only, without duplication', () => {
- const corrupt = groupOf([
- railFilter(PropertyOperator.Exact, ['a']),
- railFilter(PropertyOperator.IsNot, ['a']),
- ])
- expect(read(cycleResourceAttributeFilter(corrupt, KEY, 'a'))).toEqual({
- included: [],
- excluded: ['a'],
- })
- })
- })
-
- describe('column facet exclusions (log filters)', () => {
- const LEVEL_KEY = 'severity_level'
- const logFilter = (
- operator: PropertyOperator,
- value: unknown,
- key: string = LEVEL_KEY
- ): Record<string, unknown> => ({ key, type: PropertyFilterType.Log, operator, value })
-
- it.each<[string, Record<string, unknown>[], string[]]>([
- [
- 'is_not log filter reads as exclusions',
- [logFilter(PropertyOperator.IsNot, ['info', 'debug'])],
- ['info', 'debug'],
- ],
- [
- 'scalar is_not chip reads as a single exclusion',
- [logFilter(PropertyOperator.IsNot, 'info')],
- ['info'],
- ],
- [
- 'an exact log chip on the same key is not rail state',
- [logFilter(PropertyOperator.Exact, ['error'])],
- [],
- ],
- [
- 'a resource-attribute filter under the same key is not a log exclusion',
- [railFilter(PropertyOperator.IsNot, ['info'], LEVEL_KEY)],
- [],
- ],
- ])('%s', (_, filters, excluded) => {
- expect(logFilterExclusions(groupOf(filters), LEVEL_KEY)).toEqual(excluded)
- })
-
- it('writes, replaces, and drops the is_not filter as the exclusion set changes', () => {
- const withOne = setLogFilterExclusions(groupOf([]), LEVEL_KEY, ['info'])
- expect(logFilterExclusions(withOne, LEVEL_KEY)).toEqual(['info'])
-
- const withTwo = setLogFilterExclusions(withOne, LEVEL_KEY, ['info', 'debug'])
- expect((withTwo.values[0] as UniversalFiltersGroup).values).toEqual([
- logFilter(PropertyOperator.IsNot, ['info', 'debug']),
- ])
-
- const cleared = setLogFilterExclusions(withTwo, LEVEL_KEY, [])
- expect((cleared.values[0] as UniversalFiltersGroup).values).toEqual([])
- })
-
- it('preserves resource rail filters and same-key exact chips when writing', () => {
- const resource = railFilter(PropertyOperator.Exact, ['argocd'])
- const exactChip = logFilter(PropertyOperator.Exact, ['fatal'])
- const group = setLogFilterExclusions(groupOf([resource, exactChip]), LEVEL_KEY, ['info'])
-
- expect((group.values[0] as UniversalFiltersGroup).values).toEqual([
- resource,
- exactChip,
- logFilter(PropertyOperator.IsNot, ['info']),
- ])
- })
- })
- })
-
describe('facetScopeSignature', () => {
const configured = (key: string): FacetConfig => CONFIGURED_FACETS.find((f) => f.key === key)!
const LEVEL = configured('level')
@@ -265,8 +102,6 @@ describe('facets', () => {
currentTeamId: 1,
utcDateRange: { date_from: '-1h', date_to: null, explicitDate: false },
searchTerm: undefined,
- severityLevels: [],
- serviceNames: [],
queryFilterGroup: group(),
personId: undefined,
}
@@ -276,7 +111,16 @@ describe('facets', () => {
// 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 included levels',
+ LEVEL,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.Log, 'severity_level', PropertyOperator.Exact, ['error'])
+ ),
+ },
+ false,
+ ],
[
'level ignores its own excluded levels',
LEVEL,
@@ -307,7 +151,16 @@ describe('facets', () => {
},
true,
],
- ['level sees the service selection', LEVEL, { serviceNames: ['api'] }, true],
+ [
+ 'level sees the service selection',
+ LEVEL,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.Log, 'service_name', PropertyOperator.Exact, ['api'])
+ ),
+ },
+ true,
+ ],
[
'level sees a service exclusion',
LEVEL,
@@ -321,7 +174,16 @@ describe('facets', () => {
['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 included services',
+ SERVICE,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.Log, 'service_name', PropertyOperator.Exact, ['api'])
+ ),
+ },
+ false,
+ ],
[
'service ignores its own excluded services',
SERVICE,
@@ -332,7 +194,16 @@ describe('facets', () => {
},
false,
],
- ['service sees the level selection', SERVICE, { severityLevels: ['error'] }, true],
+ [
+ 'service sees the level selection',
+ SERVICE,
+ {
+ queryFilterGroup: group(
+ filter(PropertyFilterType.Log, 'severity_level', PropertyOperator.Exact, ['error'])
+ ),
+ },
+ true,
+ ],
[
'namespace ignores its own included values',
NAMESPACE,
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
index 70c1fd572ef2..64693586fc2f 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
@@ -1,14 +1,9 @@
-import {
- FilterLogicalOperator,
- PropertyFilterType,
- PropertyFilterValue,
- PropertyOperator,
- UniversalFiltersGroup,
-} from '~/types'
+import { PropertyFilterType, UniversalFiltersGroup } from '~/types'
import { SEVERITY_BAR_COLORS } from 'products/logs/frontend/components/VirtualizedLogsList/columnDefinitions'
import { FacetOption } from './Facet'
+import { SERVICE_NAME_FILTER, SEVERITY_LEVEL_FILTER, innerFilters, isPropertyLeaf } from './facetFilters'
/**
* Whether a facet's value set is known ahead of time or discovered from the data.
@@ -20,30 +15,30 @@ import { FacetOption } from './Facet'
*/
export type FacetKind = 'fixed' | 'dynamic'
-/** The `logsViewerFiltersLogic` field a column facet's selection is written to. */
-export type FacetFilterKey = 'severityLevels' | 'serviceNames'
-
/** The ClickHouse column a column facet's values + counts are computed over (matches backend FACET_FIELDS). */
export type FacetField = 'severity_text' | 'service_name'
/**
- * Where a facet's field lives, which determines both how it's queried and how its selection is stored.
+ * Where a facet's field lives, which determines how its values are queried. Selection itself always
+ * lives in the filterGroup, whatever the source, so the rail and the chips bar read and write one
+ * store and can never disagree about what is filtered.
*
- * - `column`: a top-level logs column. Selection lives in a dedicated filter field (severityLevels/serviceNames).
- * - `resourceAttribute`: a `resource_attributes` map key (e.g. k8s.namespace.name). No dedicated field —
- * selection is stored as up to two `log_resource_attribute` property filters inside the filterGroup:
- * `exact` for included values and `is_not` for excluded ones.
+ * - `column`: a top-level logs column, filtered through a `log` property filter under `logKey`.
+ * - `resourceAttribute`: a `resource_attributes` map key (e.g. k8s.namespace.name), filtered through
+ * a `log_resource_attribute` property filter under `key`.
*/
export type FacetSource =
| {
type: 'column'
column: FacetField
- filterKey: FacetFilterKey
/**
- * The `log` property-filter key the facet's exclusions are stored under (e.g. severity_level).
- * Includes stay in the dedicated field; without this, the facet is two-state (no exclusions).
+ * The `log` property-filter key this facet's selection is stored under (severity_level for
+ * the severity_text column). Must match the key LogsFilterBuilder.where() strips when
+ * faceting on this column (products/logs/backend/logs_query_runner.py, pinned from the
+ * other side by products/logs/backend/test/test_log_facet_values.py), or a selected value
+ * would zero out its own count.
*/
- exclusionKey?: string
+ logKey: string
}
| { type: 'resourceAttribute'; key: string; aliasKeys?: string[] }
@@ -66,154 +61,6 @@ export interface FacetConfig {
maxHeight?: number
}
-interface RailPropertyFilter {
- key: string
- type: PropertyFilterType.Log | PropertyFilterType.LogResourceAttribute
- operator: PropertyOperator
- 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): RailFilterEntry[] {
- return ((group?.values?.[0] as UniversalFiltersGroup | undefined)?.values ?? []) as RailFilterEntry[]
-}
-
-function isPropertyLeaf(entry: RailFilterEntry): entry is RailPropertyFilter {
- return !('values' in entry)
-}
-
-/**
- * Tri-state selection for a facet: a value is included, excluded, or in neither set. The query
- * effect is `IN (included)` AND `NOT IN (excluded)` — attribute exclusions keep rows missing the
- * attribute entirely.
- */
-export interface FacetSelection {
- included: string[]
- excluded: string[]
-}
-
-// The rail owns a key's `exact` (include) and `is_not` (exclude) filters. A chip on the same key
-// with any other operator (e.g. icontains) is not rail state: it's ignored on read and preserved
-// untouched on write.
-const RAIL_OPERATORS: PropertyOperator[] = [PropertyOperator.Exact, PropertyOperator.IsNot]
-
-function isRailFacetFilter(entry: RailFilterEntry, key: string): entry is RailPropertyFilter {
- return (
- isPropertyLeaf(entry) &&
- entry?.type === PropertyFilterType.LogResourceAttribute &&
- entry?.key === key &&
- RAIL_OPERATORS.includes(entry?.operator)
- )
-}
-
-function filterValues(filter: RailPropertyFilter): string[] {
- const value = filter.value
- if (Array.isArray(value)) {
- return value as string[]
- }
- return value != null && value !== '' ? [String(value)] : []
-}
-
-/** A resource-attribute facet's selection, read from its exact (include) and is_not (exclude) filters. */
-export function resourceAttributeSelection(group: UniversalFiltersGroup | undefined, key: string): FacetSelection {
- const railFilters = innerFilters(group).filter((f) => isRailFacetFilter(f, key))
- return {
- included: railFilters.filter((f) => f.operator === PropertyOperator.Exact).flatMap(filterValues),
- excluded: railFilters.filter((f) => f.operator === PropertyOperator.IsNot).flatMap(filterValues),
- }
-}
-
-/**
- * Advance `value` one step through the facet cycle — unchecked → included → excluded → unchecked —
- * returning a new filterGroup. Selection is stored as up to two log_resource_attribute filters per
- * key with array values, `exact` and `is_not` (logs have no `in` operator); a filter is dropped
- * when its side of the selection empties.
- */
-export function cycleResourceAttributeFilter(
- group: UniversalFiltersGroup | undefined,
- key: string,
- value: string
-): UniversalFiltersGroup {
- const { included, excluded } = resourceAttributeSelection(group, key)
- let nextIncluded = included
- let nextExcluded = excluded
- if (included.includes(value)) {
- nextIncluded = included.filter((v) => v !== value)
- nextExcluded = excluded.includes(value) ? excluded : [...excluded, value]
- } else if (excluded.includes(value)) {
- nextExcluded = excluded.filter((v) => v !== value)
- } else {
- nextIncluded = [...included, value]
- }
-
- // 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,
- type: PropertyFilterType.LogResourceAttribute,
- operator: PropertyOperator.Exact,
- value: nextIncluded,
- })
- }
- if (nextExcluded.length > 0) {
- values.push({
- key,
- type: PropertyFilterType.LogResourceAttribute,
- operator: PropertyOperator.IsNot,
- value: nextExcluded,
- })
- }
- return { type: FilterLogicalOperator.And, values: [{ type: FilterLogicalOperator.And, values }] }
-}
-
-// 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(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`. */
-export function logFilterExclusions(group: UniversalFiltersGroup | undefined, key: string): string[] {
- return innerFilters(group)
- .filter((f) => isLogExclusionFilter(f, key))
- .flatMap(filterValues)
-}
-
-/** Replace the `is_not` log filter under `key` with `excluded`, dropping the filter when empty. */
-export function setLogFilterExclusions(
- group: UniversalFiltersGroup | undefined,
- key: string,
- excluded: string[]
-): UniversalFiltersGroup {
- // 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
@@ -224,8 +71,6 @@ 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
@@ -243,7 +88,7 @@ export interface FacetScope {
*/
export function facetScopeSignature(facet: FacetConfig, scope: FacetScope): string {
const { source } = facet
- const selfLogKey = source.type === 'column' ? COLUMN_SELF_LOG_KEY[source.column] : undefined
+ const selfLogKey = source.type === 'column' ? source.logKey : undefined
const selfResourceKey = source.type === 'resourceAttribute' ? source.key : undefined
const groupSignature = innerFilters(scope.queryFilterGroup)
.map((entry): unknown[] | null => {
@@ -276,8 +121,6 @@ export function facetScopeSignature(facet: FacetConfig, scope: FacetScope): stri
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,
])
@@ -300,7 +143,7 @@ const LEVEL_FACET: FacetConfig = {
title: 'Level',
group: 'Standard',
kind: 'fixed',
- source: { type: 'column', column: 'severity_text', filterKey: 'severityLevels', exclusionKey: 'severity_level' },
+ source: { type: 'column', column: 'severity_text', logKey: SEVERITY_LEVEL_FILTER.key },
fixedOptions: SEVERITY_OPTIONS,
}
@@ -309,7 +152,7 @@ const SERVICE_FACET: FacetConfig = {
title: 'Service',
group: 'Standard',
kind: 'dynamic',
- source: { type: 'column', column: 'service_name', filterKey: 'serviceNames', exclusionKey: 'service_name' },
+ source: { type: 'column', column: 'service_name', logKey: SERVICE_NAME_FILTER.key },
searchable: true,
searchPlaceholder: 'Search services…',
emptyLabel: 'No services',
diff --git a/products/logs/frontend/components/LogsViewer/Filters/FilterHistoryDropdown.tsx b/products/logs/frontend/components/LogsViewer/Filters/FilterHistoryDropdown.tsx
index db3a07101c6c..2b50408c1aaa 100644
--- a/products/logs/frontend/components/LogsViewer/Filters/FilterHistoryDropdown.tsx
+++ b/products/logs/frontend/components/LogsViewer/Filters/FilterHistoryDropdown.tsx
@@ -5,7 +5,8 @@ import { LemonButton, LemonMenu, LemonMenuSection } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
-import { getFiltersSummaryLines } from 'products/logs/frontend/utils'
+import { SERVICE_NAME_FILTER } from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'
+import { getFiltersSummaryLines, summaryColumnSelection } from 'products/logs/frontend/utils'
import { LogsFiltersHistoryEntry } from '../../../types'
import { logsFilterHistoryLogic } from './logsFilterHistoryLogic'
@@ -18,10 +19,9 @@ const formatHistoryEntryDetails = (entry: LogsFiltersHistoryEntry): string => {
}
const formatServiceNames = (entry: LogsFiltersHistoryEntry): string => {
- const { filters } = entry
- const serviceNames = filters.serviceNames
+ const serviceNames = summaryColumnSelection(entry.filters, 'serviceNames', SERVICE_NAME_FILTER)
- if (serviceNames && serviceNames.length > 0) {
+ if (serviceNames.length > 0) {
const maxDisplayed = 3
const displayedNames = serviceNames.slice(0, maxDisplayed)
const remainingCount = serviceNames.length - displayedNames.length
diff --git a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsx b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsx
index e462658bd17e..146ed31ed40e 100644
--- a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsx
+++ b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsx
@@ -71,8 +71,8 @@ export const LogsQueryControls = (): JSX.Element => {
}
export const LogsFilterGroup = ({ children }: { children: React.ReactNode }): JSX.Element => {
- const { filters, id, utcDateRange, queryFilterGroup } = useValues(logsViewerFiltersLogic)
- const { filterGroup, serviceNames } = filters
+ const { filters, id, utcDateRange, queryFilterGroup, columnQueryFields } = useValues(logsViewerFiltersLogic)
+ const { filterGroup } = filters
const { setFilterGroup } = useActions(logsViewerFiltersLogic)
// Taxonomic value suggestions should respect any active scope (e.g. the person-tab
@@ -82,7 +82,8 @@ export const LogsFilterGroup = ({ children }: { children: React.ReactNode }): JS
const endpointFilters = {
dateRange: { ...utcDateRange, date_to: utcDateRange.date_to ?? dayjs().toISOString() },
filterGroup: queryFilterGroup,
- serviceNames,
+ // The suggestion lookups read their service scope off this field, not the group.
+ ...columnQueryFields,
}
return (
@@ -148,7 +149,7 @@ export function addLogsValueFilter(
export const LogsFilterSearch = (): JSX.Element => {
const [visible, setVisible] = useState<boolean>(false)
- const { utcDateRange, filters: logsFilters, queryFilterGroup } = useValues(logsViewerFiltersLogic)
+ const { utcDateRange, queryFilterGroup, columnQueryFields } = useValues(logsViewerFiltersLogic)
const { addGroupFilter, setGroupValues } = useActions(universalFiltersLogic)
const { filterGroup } = useValues(universalFiltersLogic)
@@ -166,7 +167,7 @@ export const LogsFilterSearch = (): JSX.Element => {
endpointFilters: {
dateRange: { ...utcDateRange, date_to: utcDateRange.date_to ?? dayjs().toISOString() },
filterGroup: queryFilterGroup,
- serviceNames: logsFilters.serviceNames,
+ ...columnQueryFields,
},
onChange: (taxonomicGroup, value, item) => {
if (item.value === undefined) {
diff --git a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.test.ts b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.test.ts
index ef1a42c60ea8..262915ff1a80 100644
--- a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.test.ts
+++ b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.test.ts
@@ -1,15 +1,25 @@
import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
-import { FilterLogicalOperator } from '~/types'
+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'
+import {
+ SERVICE_NAME_FILTER,
+ SEVERITY_LEVEL_FILTER,
+ facetSelection,
+} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'
import { logsViewerFiltersLogic } from './logsViewerFiltersLogic'
describe('logsViewerFiltersLogic', () => {
let logic: ReturnType<typeof logsViewerFiltersLogic.build>
+ const selectedLevels = (built = logic): string[] =>
+ facetSelection(built.values.filters.filterGroup, SEVERITY_LEVEL_FILTER).included
+ const selectedServices = (built = logic): string[] =>
+ facetSelection(built.values.filters.filterGroup, SERVICE_NAME_FILTER).included
+
beforeEach(() => {
initKeaTests()
logic = logsViewerFiltersLogic({ id: 'test-tab' })
@@ -24,8 +34,6 @@ describe('logsViewerFiltersLogic', () => {
it.each([
['setDateRange', 'dateRange', { date_from: '-24h', date_to: null }],
['setSearchTerm', 'searchTerm', 'error message'],
- ['setSeverityLevels', 'severityLevels', ['error', 'warn']],
- ['setServiceNames', 'serviceNames', ['api', 'worker']],
[
'setFilterGroup',
'filterGroup',
@@ -38,15 +46,6 @@ describe('logsViewerFiltersLogic', () => {
expect((logic.values.filters as any)[key]).toEqual(value)
})
-
- it('preserves other filters when setting a single filter', async () => {
- logic.actions.setSearchTerm('first')
- logic.actions.setSeverityLevels(['error'])
- await expectLogic(logic).toFinishAllListeners()
-
- expect(logic.values.filters.searchTerm).toBe('first')
- expect(logic.values.filters.severityLevels).toEqual(['error'])
- })
})
describe('setFilters (bulk)', () => {
@@ -58,7 +57,7 @@ describe('logsViewerFiltersLogic', () => {
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.filters.searchTerm).toBe('existing search')
- expect(logic.values.filters.severityLevels).toEqual(['error', 'warn'])
+ expect(selectedLevels()).toEqual(['error', 'warn'])
})
it('applies all filters when fully specified', async () => {
@@ -75,9 +74,70 @@ describe('logsViewerFiltersLogic', () => {
await expectLogic(logic, () => {
logic.actions.setFilters(newFilters)
- }).toMatchValues({
- filters: newFilters,
- })
+ }).toFinishAllListeners()
+
+ expect(logic.values.filters.dateRange).toEqual(newFilters.dateRange)
+ expect(logic.values.filters.searchTerm).toBe('test query')
+ expect(selectedLevels()).toEqual(['info', 'debug'])
+ expect(selectedServices()).toEqual(['frontend'])
+ })
+
+ // The level/service fields are an input channel; a caller that hands them over gets a chip in
+ // the filter bar, which is the same state the facet rail reads.
+ it('folds a level and service selection into the filterGroup', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ severityLevels: ['error'], serviceNames: ['api'] })
+ }).toFinishAllListeners()
+
+ expect((logic.values.filters.filterGroup.values[0] as UniversalFiltersGroup).values).toEqual([
+ {
+ key: 'severity_level',
+ type: PropertyFilterType.Log,
+ operator: PropertyOperator.Exact,
+ value: ['error'],
+ },
+ { key: 'service_name', type: PropertyFilterType.Log, operator: PropertyOperator.Exact, value: ['api'] },
+ ])
+ })
+
+ it('clears a folded selection when handed the field empty', async () => {
+ logic.actions.setFilters({ serviceNames: ['api'] })
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ serviceNames: [] })
+ }).toFinishAllListeners()
+
+ expect(selectedServices()).toEqual([])
+ })
+
+ // A filter-history entry or a saved view can hand over both, and the group is then the whole
+ // selection.
+ it('keeps a chip when an empty field arrives alongside a group', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({
+ serviceNames: [],
+ severityLevels: [],
+ filterGroup: {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ key: 'service_name',
+ type: PropertyFilterType.Log,
+ operator: PropertyOperator.Exact,
+ value: ['api'],
+ },
+ ],
+ },
+ ],
+ },
+ })
+ }).toFinishAllListeners()
+
+ expect(selectedServices()).toEqual(['api'])
})
})
@@ -139,7 +199,7 @@ describe('logsViewerFiltersLogic', () => {
await expectLogic(initialLogic).toFinishAllListeners()
expect(initialLogic.values.filters.searchTerm).toBe('session_id:abc')
- expect(initialLogic.values.filters.severityLevels).toEqual(['error'])
+ expect(selectedLevels(initialLogic)).toEqual(['error'])
// other filters remain at defaults
expect(initialLogic.values.filters.dateRange).toEqual({ date_from: '-1h', date_to: null })
@@ -152,7 +212,7 @@ describe('logsViewerFiltersLogic', () => {
await expectLogic(plainLogic).toFinishAllListeners()
expect(plainLogic.values.filters.searchTerm).toBe('')
- expect(plainLogic.values.filters.severityLevels).toEqual([])
+ expect(selectedLevels(plainLogic)).toEqual([])
plainLogic.unmount()
})
@@ -176,7 +236,7 @@ describe('logsViewerFiltersLogic', () => {
await expectLogic(builtLogic).toFinishAllListeners()
expect(builtLogic.values.filters.searchTerm).toBe('second')
- expect(builtLogic.values.filters.severityLevels).toEqual(['warn'])
+ expect(selectedLevels(builtLogic)).toEqual(['warn'])
builtLogic.unmount()
})
@@ -195,8 +255,8 @@ describe('logsViewerFiltersLogic', () => {
await expectLogic(builtLogic).toFinishAllListeners()
expect(builtLogic.values.filters.searchTerm).toBe('')
- expect(builtLogic.values.filters.severityLevels).toEqual([])
- expect(builtLogic.values.filters.serviceNames).toEqual([])
+ expect(selectedLevels(builtLogic)).toEqual([])
+ expect(selectedServices(builtLogic)).toEqual([])
builtLogic.unmount()
})
diff --git a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
index 6e5a54eaa7b5..ae7c0252d63f 100644
--- a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
@@ -28,6 +28,13 @@ import {
} from '~/types'
import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'
+import {
+ FacetFilterTarget,
+ SERVICE_NAME_FILTER,
+ SEVERITY_LEVEL_FILTER,
+ facetSelection,
+ setFacetIncluded,
+} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'
export const DEFAULT_DATE_RANGE = { date_from: '-1h', date_to: null }
const VALID_SEVERITY_LEVELS: readonly LogSeverityLevel[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal']
@@ -78,8 +85,71 @@ export function combineWithPinnedFilters(
}
}
+/**
+ * Folds the legacy `severityLevels` / `serviceNames` fields into the filterGroup as `exact` log
+ * filters. Those fields predate the facet rail and are still how URL params, saved views, alerts and
+ * embedding scenes hand the viewer a level or service selection, but the viewer keeps that selection
+ * in the filterGroup alone, so the rail's checkboxes and the chips bar cannot disagree about what is
+ * filtered. Exclusions have never had a dedicated field, so they are left as they are.
+ *
+ * A field that is present but empty clears that facet's includes, which is how an embedding scene
+ * drops the scope it applied; a field that is absent leaves the group untouched. An empty field
+ * handed over *alongside* a group is ignored, because the group is then the whole selection: a saved
+ * view or a persisted filter-history entry can carry `severityLevels: []` next to a group that holds
+ * a `severity_level =` chip the user added by hand, and clearing on that would drop the chip on
+ * restore.
+ */
+export function foldLegacyColumnFilters(
+ filterGroup: UniversalFiltersGroup,
+ filters: Partial<LogsViewerFilters>
+): UniversalFiltersGroup {
+ const groupIsAuthoritative = !!filters.filterGroup?.values
+ let folded = filterGroup
+ const fold = (field: string[] | undefined, target: FacetFilterTarget): void => {
+ if (field === undefined || (groupIsAuthoritative && field.length === 0)) {
+ return
+ }
+ folded = setFacetIncluded(folded, target, field)
+ }
+ fold(filters.severityLevels, SEVERITY_LEVEL_FILTER)
+ fold(filters.serviceNames, SERVICE_NAME_FILTER)
+ return folded
+}
+
+/**
+ * The level and service selections, as the dedicated query fields.
+ *
+ * Three lookups behind the viewer read level and service from these fields alone: the facet value
+ * counts (LogFacetValuesQueryRunner._attribute_query) and the taxonomic key and value suggestions
+ * (LogAttributesQueryRunner, LogValuesQueryRunner). None of them parses `filterGroup`, so a request
+ * that omits these fields loses its level and service scope, and counts or suggestions widen without
+ * saying so. Only inclusions survive the trip, which is all those lookups have ever honored:
+ * exclusions have no field of their own. Delete this once those three runners read the group.
+ */
+export interface ColumnQueryFields {
+ severityLevels: LogsQuery['severityLevels']
+ serviceNames: LogsQuery['serviceNames']
+}
+
+export function columnQueryFieldsOf(filterGroup: UniversalFiltersGroup): ColumnQueryFields {
+ return {
+ severityLevels: facetSelection(filterGroup, SEVERITY_LEVEL_FILTER).included as LogsQuery['severityLevels'],
+ serviceNames: facetSelection(filterGroup, SERVICE_NAME_FILTER).included,
+ }
+}
+
+/**
+ * The dedicated LogsQuery fields, empty. Level and service selections travel inside `filterGroup`
+ * (see foldLegacyColumnFilters), but LogsQuery requires both keys, so viewer query payloads spread
+ * this in rather than each restating that they filter on neither.
+ */
+export function unsetColumnQueryFields(): Pick<LogsQuery, 'severityLevels' | 'serviceNames'> {
+ return { severityLevels: [], serviceNames: [] }
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsViewerFiltersLogicValues {
+ columnQueryFields: ColumnQueryFields
dateRange: DateRange
filterGroup: UniversalFiltersGroup
filters: LogsViewerFilters
@@ -89,8 +159,6 @@ export interface logsViewerFiltersLogicValues {
pinnedFilters: UniversalFiltersGroup | undefined
queryFilterGroup: UniversalFiltersGroup
searchTerm: LogsQuery['searchTerm']
- serviceNames: LogsQuery['serviceNames']
- severityLevels: LogsQuery['severityLevels']
utcDateRange: {
date_from: string | null | undefined
date_to: string | null | undefined
@@ -137,12 +205,6 @@ export interface logsViewerFiltersLogicActions {
setSearchTerm: (searchTerm: LogsQuery['searchTerm']) => {
searchTerm: string | undefined
}
- setServiceNames: (serviceNames: LogsQuery['serviceNames']) => {
- serviceNames: string[]
- }
- setSeverityLevels: (severityLevels: LogsQuery['severityLevels']) => {
- severityLevels: LogSeverityLevel[]
- }
zoomDateRange: (multiplier: number) => {
multiplier: number
}
@@ -156,10 +218,9 @@ export interface logsViewerFiltersLogicMeta {
filters: (
dateRange: DateRange,
searchTerm: string | undefined,
- severityLevels: LogSeverityLevel[],
- serviceNames: string[],
filterGroup: UniversalFiltersGroup
) => LogsViewerFilters
+ columnQueryFields: (filterGroup: UniversalFiltersGroup) => ColumnQueryFields
queryFilterGroup: (
filterGroup: UniversalFiltersGroup,
pinnedFilters: UniversalFiltersGroup | undefined
@@ -188,8 +249,6 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
// setting individual filters
setDateRange: (dateRange: DateRange) => ({ dateRange }),
setSearchTerm: (searchTerm: LogsQuery['searchTerm']) => ({ searchTerm }),
- setSeverityLevels: (severityLevels: LogsQuery['severityLevels']) => ({ severityLevels }),
- setServiceNames: (serviceNames: LogsQuery['serviceNames']) => ({ serviceNames }),
setFilterGroup: (filterGroup: UniversalFiltersGroup, openFilterOnInsert: boolean = true) => ({
filterGroup,
openFilterOnInsert,
@@ -239,27 +298,16 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
setFilters: (state, { filters }) => filters.searchTerm ?? state,
},
],
- severityLevels: [
- DEFAULT_SEVERITY_LEVELS as LogsQuery['severityLevels'],
- {
- setSeverityLevels: (_, { severityLevels }) => severityLevels,
- setFilters: (state, { filters }) => filters.severityLevels ?? state,
- },
- ],
- serviceNames: [
- DEFAULT_SERVICE_NAMES as LogsQuery['serviceNames'],
- {
- setServiceNames: (_, { serviceNames }) => serviceNames,
- setFilters: (state, { filters }) => filters.serviceNames ?? state,
- },
- ],
filterGroup: [
DEFAULT_UNIVERSAL_GROUP_FILTER as UniversalFiltersGroup,
{
setFilterGroup: (_, { filterGroup }) =>
filterGroup && filterGroup.values ? filterGroup : DEFAULT_UNIVERSAL_GROUP_FILTER,
setFilters: (state, { filters }) =>
- filters.filterGroup && filters.filterGroup.values ? filters.filterGroup : state,
+ foldLegacyColumnFilters(
+ filters.filterGroup && filters.filterGroup.values ? filters.filterGroup : state,
+ filters
+ ),
},
],
openFilterOnInsert: [
@@ -285,19 +333,22 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
selectors({
id: [(_, p) => [p.id], (id: string) => id],
filters: [
- (s) => [s.dateRange, s.searchTerm, s.severityLevels, s.serviceNames, s.filterGroup],
+ (s) => [s.dateRange, s.searchTerm, s.filterGroup],
(
dateRange: DateRange,
searchTerm: LogsQuery['searchTerm'],
- severityLevels: LogsQuery['severityLevels'],
- serviceNames: LogsQuery['serviceNames'],
filterGroup: UniversalFiltersGroup
- ): LogsViewerFilters => ({ dateRange, searchTerm, severityLevels, serviceNames, filterGroup }),
+ ): LogsViewerFilters => ({ dateRange, searchTerm, filterGroup }),
],
// Combined view used for query payloads and taxonomic value suggestions —
// user-editable `filterGroup` with pinned filters prepended. Pinned filters
// intentionally never enter `filterGroup` itself so chips and saved views
// can't pick them up.
+ // Scope for the three lookups that still read the dedicated fields (see columnQueryFieldsOf).
+ columnQueryFields: [
+ (s) => [s.filterGroup],
+ (filterGroup: UniversalFiltersGroup) => columnQueryFieldsOf(filterGroup),
+ ],
queryFilterGroup: [
(s) => [s.filterGroup, s.pinnedFilters],
(filterGroup: UniversalFiltersGroup, pinnedFilters: UniversalFiltersGroup | undefined) =>
diff --git a/products/logs/frontend/components/LogsViewer/config/types.ts b/products/logs/frontend/components/LogsViewer/config/types.ts
index 0c2fb22219a2..74cfbda54400 100644
--- a/products/logs/frontend/components/LogsViewer/config/types.ts
+++ b/products/logs/frontend/components/LogsViewer/config/types.ts
@@ -4,8 +4,14 @@ import { UniversalFiltersGroup } from '~/types'
export interface LogsViewerFilters {
dateRange: DateRange
searchTerm: LogsQuery['searchTerm']
- severityLevels: LogsQuery['severityLevels']
- serviceNames: LogsQuery['serviceNames']
+ /**
+ * Level and service selections reach the viewer through these fields (URL params, saved views,
+ * alerts, embedding scenes), but it doesn't keep them: logsViewerFiltersLogic folds them into
+ * `filterGroup` as `exact` log filters, which is where the facet rail and the chips bar both read
+ * the selection from. Anything reading a viewer selection back out reads the filterGroup.
+ */
+ severityLevels?: LogsQuery['severityLevels']
+ serviceNames?: LogsQuery['serviceNames']
filterGroup: UniversalFiltersGroup
}
diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts
index 843064268ddd..f889ec0fd1ca 100644
--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts
+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts
@@ -379,8 +379,6 @@ describe('logsViewerDataLogic', () => {
it.each([
['setSearchTerm', 'error message'],
['setDateRange', { date_from: '-24h', date_to: null }],
- ['setSeverityLevels', ['error', 'warn']],
- ['setServiceNames', ['api-server']],
])('%s triggers runQuery', async (action, value) => {
await expectLogic(logic, () => {
;(filtersLogic.actions as any)[action](value)
diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
index 00c110e3d472..d14a9c7c8e87 100644
--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
@@ -38,11 +38,14 @@ import { JsonType, PropertyGroupFilter, UniversalFiltersGroup, UniversalFiltersG
import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'
-import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
+import {
+ logsViewerFiltersLogic,
+ unsetColumnQueryFields,
+} from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
import { OTHER_BREAKDOWN_LABEL, OTHER_BREAKDOWN_VALUE } from 'products/logs/frontend/sparklineOtherBreakdown'
import type { ProductIntentProperties } from '../../../../../../frontend/src/lib/utils/product-intents'
-import type { DateRange, LogSeverityLevel } from '../../../../../../frontend/src/queries/schema/schema-general'
+import type { DateRange } from '../../../../../../frontend/src/queries/schema/schema-general'
// TODO: Move to ./types.ts
import { ParsedLogMessage } from '../../../types'
import type { LogsOrderBy } from '../../../types'
@@ -230,12 +233,6 @@ export interface logsViewerDataLogicActions {
setSearchTerm: (searchTerm: string | undefined) => {
searchTerm: string | undefined
} // logsViewerFiltersLogic
- setServiceNames: (serviceNames: string[]) => {
- serviceNames: string[]
- } // logsViewerFiltersLogic
- setSeverityLevels: (severityLevels: LogSeverityLevel[]) => {
- severityLevels: LogSeverityLevel[]
- } // logsViewerFiltersLogic
addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
addLogsToSparkline: (logs: LogMessage[]) => LogMessage[]
cancelInProgressLiveTail: (liveTailAbortController: AbortController | null) => {
@@ -492,7 +489,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
teamLogic,
['addProductIntent'],
logsViewerFiltersLogic({ id }),
- ['setDateRange', 'setFilterGroup', 'setFilters', 'setSearchTerm', 'setSeverityLevels', 'setServiceNames'],
+ ['setDateRange', 'setFilterGroup', 'setFilters', 'setSearchTerm'],
logsViewerConfigLogic({ id }),
['setSparklineBreakdownBy', 'setOrderBy', 'setColumns', 'addColumn', 'removeColumn'],
],
@@ -688,8 +685,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
dateRange: values.utcDateRange,
searchTerm: values.filters.searchTerm,
filterGroup: values.queryFilterGroup as PropertyGroupFilter,
- severityLevels: values.filters.severityLevels,
- serviceNames: values.filters.serviceNames,
+ ...unsetColumnQueryFields(),
personId: values.personId,
customColumns: sentCustomColumns,
},
@@ -740,8 +736,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
dateRange: values.utcDateRange,
searchTerm: values.filters.searchTerm,
filterGroup: values.queryFilterGroup as PropertyGroupFilter,
- severityLevels: values.filters.severityLevels,
- serviceNames: values.filters.serviceNames,
+ ...unsetColumnQueryFields(),
personId: values.personId,
customColumns: values.customColumns,
after: values.nextCursor,
@@ -774,8 +769,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
dateRange: values.utcDateRange,
searchTerm: values.filters.searchTerm,
filterGroup: values.queryFilterGroup as PropertyGroupFilter,
- severityLevels: values.filters.severityLevels,
- serviceNames: values.filters.serviceNames,
+ ...unsetColumnQueryFields(),
sparklineBreakdownBy: values.sparklineBreakdownBy,
personId: values.personId,
},
@@ -1021,12 +1015,6 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
setDateRange: () => {
actions.handleQueryChange('date_range')
},
- setSeverityLevels: ({ severityLevels }) => {
- actions.handleQueryChange('severity', { severity_levels: severityLevels ?? [] })
- },
- setServiceNames: ({ serviceNames }) => {
- actions.handleQueryChange('service', { service_count: serviceNames?.length ?? 0 })
- },
setFilters: ({ pushToHistory }) => {
if (pushToHistory) {
actions.handleQueryChange('bulk')
@@ -1170,8 +1158,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
dateRange: values.utcDateRange,
searchTerm: values.filters.searchTerm,
filterGroup: values.queryFilterGroup as PropertyGroupFilter,
- severityLevels: values.filters.severityLevels,
- serviceNames: values.filters.serviceNames,
+ ...unsetColumnQueryFields(),
personId: values.personId,
customColumns: values.customColumns,
liveLogsCheckpoint: values.liveLogsCheckpoint ?? undefined,
diff --git a/products/logs/frontend/components/LogsViewer/logsExportLogic.ts b/products/logs/frontend/components/LogsViewer/logsExportLogic.ts
index 9851fcef8c19..766ee279c00c 100644
--- a/products/logs/frontend/components/LogsViewer/logsExportLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/logsExportLogic.ts
@@ -15,7 +15,7 @@ import { ParsedLogMessage } from '../../types'
import type { LogsOrderBy } from '../../types'
import type { LogsViewerFilters } from './config/types'
import { logsViewerDataLogic } from './data/logsViewerDataLogic'
-import { logsViewerFiltersLogic } from './Filters/logsViewerFiltersLogic'
+import { logsViewerFiltersLogic, unsetColumnQueryFields } from './Filters/logsViewerFiltersLogic'
import { logsViewerLogic } from './logsViewerLogic'
function triggerBlobDownload(blob: Blob, filename: string): void {
@@ -150,8 +150,7 @@ export const logsExportLogic = kea<logsExportLogicType>([
dateRange: values.utcDateRange,
searchTerm: values.filters.searchTerm,
filterGroup: values.filters.filterGroup as PropertyGroupFilter,
- severityLevels: values.filters.severityLevels,
- serviceNames: values.filters.serviceNames,
+ ...unsetColumnQueryFields(),
orderBy: values.orderBy,
personId: values.personId,
}
diff --git a/products/logs/frontend/logsSceneLogic.test.ts b/products/logs/frontend/logsSceneLogic.test.ts
index 0ac17d85bb0d..981b7779f4b9 100644
--- a/products/logs/frontend/logsSceneLogic.test.ts
+++ b/products/logs/frontend/logsSceneLogic.test.ts
@@ -3,12 +3,25 @@ import { expectLogic } from 'kea-test-utils'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { FilterLogicalOperator } from '~/types'
+
+import {
+ SERVICE_NAME_FILTER,
+ SEVERITY_LEVEL_FILTER,
+ facetSelection,
+} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'
import { logsSceneLogic } from './logsSceneLogic'
describe('logsSceneLogic', () => {
let logic: ReturnType<typeof logsSceneLogic.build>
+ // The two legacy params fold into filterGroup, which is where the selection lives.
+ const selectedLevels = (): string[] =>
+ facetSelection(logic.values.filters.filterGroup, SEVERITY_LEVEL_FILTER).included
+ const selectedServices = (): string[] =>
+ facetSelection(logic.values.filters.filterGroup, SERVICE_NAME_FILTER).included
+
beforeEach(async () => {
useMocks({
post: {
@@ -37,7 +50,7 @@ describe('logsSceneLogic', () => {
router.actions.push('/logs', { severityLevels: urlValue })
}).toFinishAllListeners()
- expect(logic.values.filters.severityLevels).toEqual(expected)
+ expect(selectedLevels()).toEqual(expected)
})
it.each([
@@ -48,7 +61,46 @@ describe('logsSceneLogic', () => {
router.actions.push('/logs', { serviceNames: urlValue })
}).toFinishAllListeners()
- expect(logic.values.filters.serviceNames).toEqual(expected)
+ expect(selectedServices()).toEqual(expected)
+ })
+
+ it.each<[string, string]>([
+ ['severityLevels', '["error"]'],
+ ['serviceNames', '["api"]'],
+ ])('drops the %s param once it has been applied', async (param, urlValue) => {
+ await expectLogic(logic, () => {
+ router.actions.push('/logs', { [param]: urlValue })
+ }).toFinishAllListeners()
+
+ // Left in place, the param is read again on every later URL change and folds its
+ // selection back in, contradicting whatever the rail did to it since.
+ expect(router.values.searchParams[param]).toBeUndefined()
+ expect(router.values.searchParams.filterGroup).not.toBeUndefined()
+ })
+
+ it.each<[string, string, string[], string[]]>([
+ [
+ 'a group that already selects the facet wins over the param',
+ '["error"]',
+ ['error', 'warn'],
+ ['error', 'warn'],
+ ],
+ ['a group silent about the facet lets the param through', '["error"]', [], ['error']],
+ ])('%s', async (_, param, groupLevels, expected) => {
+ const values = groupLevels.length
+ ? [{ key: 'severity_level', type: 'log', operator: 'exact', value: groupLevels }]
+ : []
+ await expectLogic(logic, () => {
+ router.actions.push('/logs', {
+ severityLevels: param,
+ filterGroup: JSON.stringify({
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values }],
+ }),
+ })
+ }).toFinishAllListeners()
+
+ expect(selectedLevels()).toEqual(expected)
})
it('filters out malformed JSON as invalid severity level', async () => {
@@ -57,7 +109,7 @@ describe('logsSceneLogic', () => {
}).toFinishAllListeners()
// parseTagsFilter falls back to comma-separated parsing, then validation filters invalid levels
- expect(logic.values.filters.severityLevels).toEqual([])
+ expect(selectedLevels()).toEqual([])
})
it('filters out non-array JSON as invalid severity level', async () => {
@@ -66,7 +118,7 @@ describe('logsSceneLogic', () => {
}).toFinishAllListeners()
// parseTagsFilter falls back to comma-separated parsing, then validation filters invalid levels
- expect(logic.values.filters.severityLevels).toEqual([])
+ expect(selectedLevels()).toEqual([])
})
it('handles comma-separated values via parseTagsFilter', async () => {
@@ -74,7 +126,7 @@ describe('logsSceneLogic', () => {
router.actions.push('/logs', { severityLevels: 'error,warn,info' })
}).toFinishAllListeners()
- expect(logic.values.filters.severityLevels).toEqual(['error', 'warn', 'info'])
+ expect(selectedLevels()).toEqual(['error', 'warn', 'info'])
})
it.each([
@@ -113,7 +165,7 @@ describe('logsSceneLogic', () => {
router.actions.push('/logs', { severityLevels: urlValue })
}).toFinishAllListeners()
- expect(logic.values.filters.severityLevels).toEqual(expected)
+ expect(selectedLevels()).toEqual(expected)
})
it('parses a stringified filterGroup from the URL (e.g. a cross-product session link)', async () => {
diff --git a/products/logs/frontend/logsSceneLogic.tsx b/products/logs/frontend/logsSceneLogic.tsx
index 826bc5e7d2ec..bc83e9e110f3 100644
--- a/products/logs/frontend/logsSceneLogic.tsx
+++ b/products/logs/frontend/logsSceneLogic.tsx
@@ -22,12 +22,16 @@ import {
DEFAULT_INITIAL_LOGS_LIMIT,
logsViewerDataLogic,
} from 'products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic'
+import {
+ FacetFilterTarget,
+ SERVICE_NAME_FILTER,
+ SEVERITY_LEVEL_FILTER,
+ facetSelection,
+} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'
import { facetRailLogic } from 'products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic'
import { logsFilterHistoryLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsFilterHistoryLogic'
import {
DEFAULT_DATE_RANGE,
- DEFAULT_SERVICE_NAMES,
- DEFAULT_SEVERITY_LEVELS,
isValidSeverityLevel,
logsViewerFiltersLogic,
} from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
@@ -242,28 +246,47 @@ export const logsSceneLogic = kea<logsSceneLogicType>([
filtersFromUrl.searchTerm = ''
hasFilterChanges = true
}
+ // `filterGroup` holds the level and service selections, so these two params are read but
+ // never written: reading them keeps legacy links working, along with hand-written ones
+ // like the services table's deep link, and `setFilters` folds a param into the group.
+ // Their absent-param case needs no reset branch: clearing `filterGroup` already clears
+ // these selections with it.
+ //
+ // A `filterGroup` in the same URL is the whole selection, so a param naming a facet that
+ // group already selects is residue from a link minted in the dedicated-field shape, and
+ // folding it would narrow the group's selection to the param's values. Without a group in
+ // the URL there is nothing to defer to, so the param is compared against the live
+ // selection, which also stops it re-applying on every URL change.
+ const legacyFacetParam = <T extends string>(
+ raw: T[] | null | undefined,
+ target: FacetFilterTarget
+ ): T[] | undefined => {
+ if (!raw?.length) {
+ return undefined
+ }
+ const selected = facetSelection(
+ filtersFromUrl.filterGroup ?? values.filters.filterGroup,
+ target
+ ).included
+ if (filtersFromUrl.filterGroup !== undefined && selected.length > 0) {
+ return undefined
+ }
+ return equal(raw, selected) ? undefined : raw
+ }
if (params.severityLevels) {
const parsed = parseTagsFilter(params.severityLevels)
- if (parsed) {
- const levels = parsed.filter(isValidSeverityLevel)
- if (levels.length > 0 && !equal(levels, values.filters.severityLevels)) {
- filtersFromUrl.severityLevels = levels
- hasFilterChanges = true
- }
+ const levels = parsed && legacyFacetParam(parsed.filter(isValidSeverityLevel), SEVERITY_LEVEL_FILTER)
+ if (levels) {
+ filtersFromUrl.severityLevels = levels
+ hasFilterChanges = true
}
- } else if (!equal(DEFAULT_SEVERITY_LEVELS, values.filters.severityLevels)) {
- filtersFromUrl.severityLevels = DEFAULT_SEVERITY_LEVELS
- hasFilterChanges = true
}
if (params.serviceNames) {
- const names = parseTagsFilter(params.serviceNames)
- if (names && !equal(names, values.filters.serviceNames)) {
+ const names = legacyFacetParam(parseTagsFilter(params.serviceNames), SERVICE_NAME_FILTER)
+ if (names) {
filtersFromUrl.serviceNames = names
hasFilterChanges = true
}
- } else if (!equal(DEFAULT_SERVICE_NAMES, values.filters.serviceNames)) {
- filtersFromUrl.serviceNames = DEFAULT_SERVICE_NAMES
- hasFilterChanges = true
}
if (hasFilterChanges) {
@@ -335,8 +358,12 @@ export const logsSceneLogic = kea<logsSceneLogicType>([
DEFAULT_UNIVERSAL_GROUP_FILTER
)
updateSearchParams(params, 'dateRange', values.filters.dateRange, DEFAULT_DATE_RANGE)
- updateSearchParams(params, 'severityLevels', values.filters.severityLevels, DEFAULT_SEVERITY_LEVELS)
- updateSearchParams(params, 'serviceNames', values.filters.serviceNames, DEFAULT_SERVICE_NAMES)
+ // No writer sets these two, so they have to be deleted rather than left alone:
+ // syncSearchParams only removes keys it is told about, and a param still in the
+ // URL is read again on the next URL change, folding a selection back in on top of
+ // whatever the rail did to it since.
+ delete params.severityLevels
+ delete params.serviceNames
updateSearchParams(params, 'orderBy', values.orderBy, DEFAULT_ORDER_BY)
updateSearchParams(params, 'facetNameSearch', values.facetNameSearch, '')
return params
diff --git a/products/logs/frontend/utils.test.ts b/products/logs/frontend/utils.test.ts
index f9b22909311f..079d9163e815 100644
--- a/products/logs/frontend/utils.test.ts
+++ b/products/logs/frontend/utils.test.ts
@@ -293,6 +293,33 @@ describe('logs utils', () => {
[{ label: 'Severity', value: 'Error, Fatal' }],
],
['singular service', { serviceNames: ['api'] }, [{ label: 'Service', value: 'api' }]],
+ // A viewer-written selection lives in the group, so an entry holding it has to summarize the
+ // same way one holding a dedicated field does.
+ [
+ 'group-stored level and service selections',
+ {
+ filterGroup: filterGroup(
+ { key: 'severity_level', value: ['error'], type: 'log' },
+ { key: 'service_name', value: ['api'], type: 'log' }
+ ),
+ },
+ [
+ { label: 'Severity', value: 'Error' },
+ { label: 'Service', value: 'api' },
+ ],
+ ],
+ [
+ 'a group-stored exclusion still shows as a filter',
+ {
+ filterGroup: filterGroup({
+ key: 'service_name',
+ value: ['api'],
+ type: 'log',
+ operator: 'is_not',
+ }),
+ },
+ [{ label: 'Filter', value: 'service_name=api' }],
+ ],
[
'plural services with truncation',
{ serviceNames: ['api', 'worker', 'scheduler', 'cron'] },
diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsx
index 1df20909582f..d394a5d3f789 100644
--- a/products/logs/frontend/utils.tsx
+++ b/products/logs/frontend/utils.tsx
@@ -6,19 +6,58 @@ import { capitalizeFirstLetter } from 'lib/utils/strings'
import { AnyPropertyFilter, FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'
import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'
+import {
+ FacetFilterTarget,
+ SERVICE_NAME_FILTER,
+ SEVERITY_LEVEL_FILTER,
+ facetSelection,
+} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'
-export function formatFilterGroupValues(filterGroup: Record<string, any> | undefined): string[] {
+/**
+ * A level or service selection reaches a summary in one of two shapes: the dedicated
+ * `severityLevels`/`serviceNames` field, which saved views, alerts and persisted filter history can
+ * carry, or the `exact` log filter in `filterGroup`, which is what the viewer writes. Read both, so
+ * an entry in either shape summarizes identically.
+ */
+export function summaryColumnSelection(
+ filters: Record<string, any>,
+ legacyField: 'severityLevels' | 'serviceNames',
+ target: FacetFilterTarget
+): string[] {
+ const legacy = filters[legacyField]
+ if (Array.isArray(legacy) && legacy.length > 0) {
+ return legacy as string[]
+ }
+ return facetSelection(filters.filterGroup, target).included
+}
+
+/**
+ * One `key=value` string per property filter in the group. `skipIncludes` drops the `exact` filters
+ * under the given targets, for callers that summarize those selections under their own label.
+ */
+export function formatFilterGroupValues(
+ filterGroup: Record<string, any> | undefined,
+ skipIncludes: FacetFilterTarget[] = []
+): string[] {
const group = filterGroup?.values?.[0]
if (!group || !('values' in group)) {
return []
}
- return group.values.filter(isValidPropertyFilter).map((filter: AnyPropertyFilter) => {
- const key = filter.key || '?'
- const value = Array.isArray(filter.value) ? filter.value.join(', ') : String(filter.value ?? '')
- const truncatedValue = value.length > 15 ? `${value.slice(0, 15)}...` : value
- return `${key}=${truncatedValue}`
- })
+ const isSkipped = (filter: AnyPropertyFilter): boolean =>
+ 'operator' in filter &&
+ filter.operator === PropertyOperator.Exact &&
+ skipIncludes.some((target) => filter.type === target.type && filter.key === target.key)
+
+ return group.values
+ .filter(isValidPropertyFilter)
+ .filter((filter: AnyPropertyFilter) => !isSkipped(filter))
+ .map((filter: AnyPropertyFilter) => {
+ const key = filter.key || '?'
+ const value = Array.isArray(filter.value) ? filter.value.join(', ') : String(filter.value ?? '')
+ const truncatedValue = value.length > 15 ? `${value.slice(0, 15)}...` : value
+ return `${key}=${truncatedValue}`
+ })
}
export interface FiltersSummaryLine {
@@ -34,20 +73,22 @@ export function getFiltersSummaryLines(filters: Record<string, any>): FiltersSum
lines.push({ label: 'Date range', value: label })
}
- if (filters.severityLevels?.length) {
+ const severityLevels = summaryColumnSelection(filters, 'severityLevels', SEVERITY_LEVEL_FILTER)
+ if (severityLevels.length > 0) {
lines.push({
label: 'Severity',
- value: filters.severityLevels.map((l: string) => capitalizeFirstLetter(l)).join(', '),
+ value: severityLevels.map((l: string) => capitalizeFirstLetter(l)).join(', '),
})
}
- if (filters.serviceNames?.length) {
+ const serviceNames = summaryColumnSelection(filters, 'serviceNames', SERVICE_NAME_FILTER)
+ if (serviceNames.length > 0) {
const maxDisplayed = 3
- const displayed = filters.serviceNames.slice(0, maxDisplayed)
- const remaining = filters.serviceNames.length - displayed.length
+ const displayed = serviceNames.slice(0, maxDisplayed)
+ const remaining = serviceNames.length - displayed.length
const serviceText = displayed.join(', ')
lines.push({
- label: filters.serviceNames.length === 1 ? 'Service' : 'Services',
+ label: serviceNames.length === 1 ? 'Service' : 'Services',
value: remaining > 0 ? `${serviceText} +${remaining} more` : serviceText,
})
}
@@ -57,7 +98,16 @@ export function getFiltersSummaryLines(filters: Record<string, any>): FiltersSum
lines.push({ label: 'Search', value: `"${truncated}"` })
}
- const attributeFilters = formatFilterGroupValues(filters.filterGroup)
+ // Skips the `exact` log filters the Severity and Service lines above already cover, so a
+ // group-stored selection isn't reported twice. Only where the line came from the group: a line
+ // read off the legacy field says nothing about the group, so skipping there would drop a
+ // `severity_level =` chip from the summary entirely. Exclusions always show here.
+ const usedLegacyField = (legacyField: 'severityLevels' | 'serviceNames'): boolean =>
+ Array.isArray(filters[legacyField]) && filters[legacyField].length > 0
+ const attributeFilters = formatFilterGroupValues(filters.filterGroup, [
+ ...(usedLegacyField('severityLevels') ? [] : [SEVERITY_LEVEL_FILTER]),
+ ...(usedLegacyField('serviceNames') ? [] : [SERVICE_NAME_FILTER]),
+ ])
if (attributeFilters.length > 0) {
lines.push({
label: attributeFilters.length === 1 ? 'Filter' : 'Filters',