Skip to content

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

feat(logs): tri-state facet checkboxes on resource-attribute facets (#73546)

Jon McCallumeac14c7d97a2
diff --git a/products/logs/backend/test/test_log_facet_values.py b/products/logs/backend/test/test_log_facet_values.py
index b6cf10f8a006..87633143b7bc 100644
--- a/products/logs/backend/test/test_log_facet_values.py
+++ b/products/logs/backend/test/test_log_facet_values.py
@@ -119,12 +119,13 @@ class TestLogFacetValues(ClickhouseTestMixin, APIBaseTest):
self.assertGreater(len(result), 0)
self.assertNotIn("", result)
- def test_resource_facet_ignores_its_own_filter(self):
- """Selecting a value via a log_resource_attribute filter must not change that facet's own counts."""
+ @parameterized.expand([("exact",), ("is_not",)])
+ def test_resource_facet_ignores_its_own_filter(self, operator):
+ """Selecting or excluding a value via a log_resource_attribute filter must not change that facet's own counts."""
base = self._facet_attr("k8s.namespace.name")
own_value = next(iter(base))
filter_group = [
- {"key": "k8s.namespace.name", "type": "log_resource_attribute", "operator": "exact", "value": own_value}
+ {"key": "k8s.namespace.name", "type": "log_resource_attribute", "operator": operator, "value": own_value}
]
self.assertEqual(self._facet_attr("k8s.namespace.name", filterGroup=filter_group), base)
@@ -139,13 +140,19 @@ class TestLogFacetValues(ClickhouseTestMixin, APIBaseTest):
self.assertTrue(set(scoped).issubset(set(base)))
self.assertLess(sum(scoped.values()), sum(base.values()))
- def test_resource_facet_honors_other_resource_attribute_filter(self):
- # A different resource-attribute filter re-scopes the counts via the rollup's
- # resource_fingerprint subquery — proves cross-filtering still works on log_attributes.
+ @parameterized.expand([("exact",), ("is_not",)])
+ def test_resource_facet_honors_other_resource_attribute_filter(self, operator):
+ # A different resource-attribute filter — include or exclude — re-scopes the counts via the
+ # rollup's resource_fingerprint subquery — proves cross-filtering still works on log_attributes.
base = self._facet_attr("k8s.pod.name")
one_namespace = next(iter(self._facet_attr("k8s.namespace.name")))
filter_group = [
- {"key": "k8s.namespace.name", "type": "log_resource_attribute", "operator": "exact", "value": one_namespace}
+ {
+ "key": "k8s.namespace.name",
+ "type": "log_resource_attribute",
+ "operator": operator,
+ "value": one_namespace,
+ }
]
scoped = self._facet_attr("k8s.pod.name", filterGroup=filter_group)
self.assertGreater(len(scoped), 0)
diff --git a/products/logs/backend/test/test_logs_query_runner.py b/products/logs/backend/test/test_logs_query_runner.py
index 8fde15c49825..0fad861b7c26 100644
--- a/products/logs/backend/test/test_logs_query_runner.py
+++ b/products/logs/backend/test/test_logs_query_runner.py
@@ -379,6 +379,46 @@ class TestAttributeFilters(APIBaseTest):
self.assertNotIn("message__str", query_str)
self.assertIn("in(resource_fingerprint", query_str)
+ def test_same_key_positive_and_negative_resource_attribute_filters(self):
+ # The facet rail emits an exact + is_not filter pair on the same key (include some values,
+ # exclude others) — both polarities must survive into their own fingerprint subquery.
+ query = LogsQuery(
+ dateRange=DateRange(date_from="2024-01-10T00:00:00Z", date_to="2024-01-15T23:59:59Z"),
+ serviceNames=[],
+ severityLevels=[],
+ filterGroup=PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ LogPropertyFilter(
+ key="k8s.namespace.name",
+ operator=PropertyOperator.EXACT,
+ type=LogPropertyFilterType.LOG_RESOURCE_ATTRIBUTE,
+ value=["argocd", "default"],
+ ),
+ LogPropertyFilter(
+ key="k8s.namespace.name",
+ operator=PropertyOperator.IS_NOT,
+ type=LogPropertyFilterType.LOG_RESOURCE_ATTRIBUTE,
+ value=["kube-system"],
+ ),
+ ],
+ )
+ ],
+ ),
+ kind="LogsQuery",
+ )
+
+ query_str = self._to_clickhouse_sql(query)
+
+ self.assertIn("notIn(resource_fingerprint", query_str)
+ # the include subquery must survive alongside the exclude one
+ self.assertIn("in(resource_fingerprint", query_str.replace("notIn(resource_fingerprint", ""))
+ for value in ("argocd", "default", "kube-system"):
+ self.assertIn(value, query_str)
+
def test_positive_and_negative_resource_attribute_filters(self):
"""Test combinations of log attributes and resource attributes"""
query = LogsQuery(
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/Facet.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/Facet.tsx
index a423619b8b4d..e9362f621ea1 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/Facet.tsx
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/Facet.tsx
@@ -1,7 +1,7 @@
import { CSSProperties, useMemo } from 'react'
import { List } from 'react-window'
-import { IconChevronDown, IconChevronRight } from '@posthog/icons'
+import { IconChevronDown, IconChevronRight, IconMinusSmall } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonInput } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
@@ -22,6 +22,8 @@ interface FacetProps {
title: string
options: FacetOption[]
selected: string[]
+ /** Values in the excluded state — matching records are filtered out. Disjoint from `selected`. */
+ excluded?: string[]
onToggle: (value: string) => void
loading?: boolean
emptyLabel?: string
@@ -42,6 +44,7 @@ export function Facet({
title,
options,
selected,
+ excluded = [],
onToggle,
loading = false,
emptyLabel = 'No values',
@@ -56,8 +59,8 @@ export function Facet({
const slug = title.toLowerCase().replace(/\s+/g, '-')
const rowProps = useMemo<FacetValueRowProps>(
- () => ({ options, selected, slug, onToggle, dimZeroCounts }),
- [options, selected, slug, onToggle, dimZeroCounts]
+ () => ({ options, selected, excluded, slug, onToggle, dimZeroCounts }),
+ [options, selected, excluded, slug, onToggle, dimZeroCounts]
)
return (
@@ -110,6 +113,7 @@ export function Facet({
key={option.value}
option={option}
selected={selected.includes(option.value)}
+ excluded={excluded.includes(option.value)}
slug={slug}
onToggle={onToggle}
dimZeroCounts={dimZeroCounts}
@@ -126,6 +130,7 @@ export function Facet({
interface FacetValueRowProps {
options: FacetOption[]
selected: string[]
+ excluded: string[]
slug: string
onToggle: (value: string) => void
dimZeroCounts: boolean
@@ -136,6 +141,7 @@ function FacetValueRow({
style,
options,
selected,
+ excluded,
slug,
onToggle,
dimZeroCounts,
@@ -151,6 +157,7 @@ function FacetValueRow({
<FacetValueButton
option={option}
selected={selected.includes(option.value)}
+ excluded={excluded.includes(option.value)}
slug={slug}
onToggle={onToggle}
dimZeroCounts={dimZeroCounts}
@@ -162,33 +169,55 @@ function FacetValueRow({
function FacetValueButton({
option,
selected,
+ excluded,
slug,
onToggle,
dimZeroCounts,
}: {
option: FacetOption
selected: boolean
+ excluded: boolean
slug: string
onToggle: (value: string) => void
dimZeroCounts: boolean
}): JSX.Element {
// A fixed facet value with no matches in the current scope: dim it, and disable it unless it's
- // already selected (so a selected-but-now-empty value can still be toggled off).
+ // already active (selected or excluded), so an active-but-now-empty value can still be cycled off.
+ const isActive = selected || excluded
const isZero = dimZeroCounts && option.count === 0
+ // The tri-state is otherwise only visual (checkbox / red minus / line-through), so spell the
+ // current state out for screen readers — the button cycles included → excluded → not filtered.
+ const stateLabel = excluded ? 'excluded' : selected ? 'included' : 'not filtered'
return (
<LemonButton
type="tertiary"
size="small"
fullWidth
className={cn(isZero && 'opacity-50')}
- disabledReason={isZero && !selected ? 'No matching logs for the current filters' : undefined}
- icon={<LemonCheckbox checked={selected} className="pointer-events-none" />}
+ disabledReason={isZero && !isActive ? 'No matching logs for the current filters' : undefined}
+ aria-label={`${option.label}, ${stateLabel}`}
+ icon={
+ excluded ? (
+ // Deliberately not LemonCheckbox's `indeterminate` — that means "partially
+ // selected", while this box means "negated".
+ <span
+ aria-hidden
+ className="flex items-center justify-center w-4 h-4 rounded border-[1.5px] border-danger text-danger shrink-0 pointer-events-none"
+ >
+ <IconMinusSmall className="text-sm" />
+ </span>
+ ) : (
+ <span aria-hidden className="flex">
+ <LemonCheckbox checked={selected} className="pointer-events-none" />
+ </span>
+ )
+ }
onClick={() => onToggle(option.value)}
data-attr={`logs-facet-${slug}-${option.value}`}
>
<span className="flex items-center gap-2 min-w-0 w-full">
{option.color && <span className={cn('w-1 h-3.5 rounded-full shrink-0', option.color)} />}
- <span className="truncate flex-1">{option.label}</span>
+ <span className={cn('truncate flex-1', excluded && 'line-through text-muted')}>{option.label}</span>
{option.count != null && (
<span className="shrink-0 text-muted tabular-nums">{humanFriendlyLargeNumber(option.count)}</span>
)}
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx b/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
index 4a12aeadd697..5a2436759ff0 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/FacetRail.tsx
@@ -18,7 +18,7 @@ import {
facetsByGroup,
filterFacetsByName,
mergeSelectedIntoOptions,
- resourceAttributeValues,
+ resourceAttributeSelection,
} from './facets'
const DEFAULT_WIDTH_PX = 240
@@ -63,12 +63,12 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
const renderFacet = (facet: FacetConfig): JSX.Element => {
const { source } = facet
- // Selection: column facets read their dedicated filter field; resource-attribute facets read
- // their log_resource_attribute filter out of the group.
- const selected =
+ // Selection: column facets read their dedicated filter field (include-only); resource-attribute
+ // facets read their log_resource_attribute filters out of the group, both polarities.
+ const { included: selected, excluded } =
source.type === 'resourceAttribute'
- ? resourceAttributeValues(filterGroup, source.key)
- : selectedByKey[source.filterKey]
+ ? resourceAttributeSelection(filterGroup, source.key)
+ : { included: selectedByKey[source.filterKey], excluded: [] }
// Values + counts come from the cross-filtered endpoint, keyed by facet.key.
const fetched: FacetOption[] = (facetValues[facet.key] ?? []).map((r) => ({
value: r.value,
@@ -93,6 +93,7 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
title={facet.title}
options={options}
selected={selected}
+ excluded={excluded}
onToggle={onToggle}
loading={loading}
collapsed={collapsed}
@@ -102,19 +103,20 @@ export function FacetRail({ id }: FacetRailProps): JSX.Element {
)
}
- // Dynamic facet: values + counts come from the cross-filtered endpoint, plus any selected
- // 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.
+ // Dynamic facet: values + counts come from the cross-filtered endpoint, plus any selected or
+ // excluded values it didn't return (zero matches in scope, or below the top-N cutoff) so an
+ // active filter — e.g. from an old saved-view URL — is always visible and removable.
return (
<Facet
key={facet.key}
title={facet.title}
options={mergeSelectedIntoOptions(
fetched,
- selected,
+ [...selected, ...excluded],
facet.searchable ? facetSearch[facet.key] : undefined
)}
selected={selected}
+ excluded={excluded}
onToggle={onToggle}
loading={loading}
emptyLabel={facet.emptyLabel}
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.test.ts
index 6dc99ae86c41..94190d0ebf8d 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.test.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.test.ts
@@ -5,7 +5,7 @@ import { UniversalFiltersGroup } from '~/types'
import { logsViewerFiltersLogic } from '../Filters/logsViewerFiltersLogic'
import { facetRailLogic } from './facetRailLogic'
-import { FacetSource, resourceAttributeValues } from './facets'
+import { FacetSelection, FacetSource, resourceAttributeSelection } from './facets'
const LEVEL_SOURCE: FacetSource = { type: 'column', column: 'severity_text', filterKey: 'severityLevels' }
const SERVICE_SOURCE: FacetSource = { type: 'column', column: 'service_name', filterKey: 'serviceNames' }
@@ -90,38 +90,35 @@ describe('facetRailLogic', () => {
})
})
- describe('resource attribute toggling', () => {
- const read = (): string[] => resourceAttributeValues(filtersLogic.values.filterGroup, 'k8s.namespace.name')
-
- it('adds, accumulates (OR), and removes values as a log_resource_attribute filter in the group', async () => {
+ 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, 'argocd')
+ logic.actions.toggleFacetValue(NAMESPACE_SOURCE, value)
).toFinishAllListeners()
- expect(read()).toEqual(['argocd'])
+ }
- await expectLogic(logic, () =>
- logic.actions.toggleFacetValue(NAMESPACE_SOURCE, 'kube-system')
- ).toFinishAllListeners()
- expect(read()).toEqual(['argocd', 'kube-system'])
+ it('cycles a value included → excluded → cleared through the shared filters logic', async () => {
+ await click('argocd')
+ expect(read()).toEqual({ included: ['argocd'], excluded: [] })
- await expectLogic(logic, () =>
- logic.actions.toggleFacetValue(NAMESPACE_SOURCE, 'argocd')
- ).toFinishAllListeners()
- expect(read()).toEqual(['kube-system'])
+ 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([])
})
- it('removing the last value drops the filter from the group entirely', async () => {
- await expectLogic(logic, () =>
- logic.actions.toggleFacetValue(NAMESPACE_SOURCE, 'argocd')
- ).toFinishAllListeners()
- expect(read()).toEqual(['argocd'])
+ 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: [] })
- await expectLogic(logic, () =>
- logic.actions.toggleFacetValue(NAMESPACE_SOURCE, 'argocd')
- ).toFinishAllListeners()
- expect(read()).toEqual([])
- // the single inner group holds no filters once the last value is removed
- expect((filtersLogic.values.filterGroup.values[0] as UniversalFiltersGroup).values).toEqual([])
+ await click('argocd')
+ expect(read()).toEqual({ included: ['kube-system'], excluded: ['argocd'] })
})
})
})
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.ts
index 1ea4c656c4a4..b9659827c538 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facetRailLogic.ts
@@ -5,7 +5,7 @@ import { LogSeverityLevel } from '~/queries/schema/schema-general'
import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'
import type { UniversalFiltersGroup } from '../../../../../../frontend/src/types'
-import { FacetSource, toggleResourceAttributeFilter } from './facets'
+import { FacetSource, cycleResourceAttributeFilter } from './facets'
export interface FacetRailLogicProps {
id: string
@@ -106,8 +106,9 @@ export const facetRailLogic = kea<facetRailLogicType>([
toggleFacetValue: ({ source, value }) => {
const { severityLevels, serviceNames, filterGroup } = logsViewerFiltersLogic({ id: props.id }).values
if (source.type === 'resourceAttribute') {
- // Selection lives as a log_resource_attribute filter inside the group.
- actions.setFilterGroup(toggleResourceAttributeFilter(filterGroup, source.key, value), false)
+ // 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)
} else if (source.filterKey === 'severityLevels') {
actions.setSeverityLevels(toggleMembership(severityLevels, value as LogSeverityLevel))
} else if (source.filterKey === 'serviceNames') {
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
index 0c421b2d601f..b38e8f2c348e 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.test.ts
@@ -1,5 +1,13 @@
+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
+
import { FacetOption } from './Facet'
-import { FacetConfig, filterFacetsByName, mergeSelectedIntoOptions } from './facets'
+import {
+ FacetConfig,
+ cycleResourceAttributeFilter,
+ filterFacetsByName,
+ mergeSelectedIntoOptions,
+ resourceAttributeSelection,
+} from './facets'
const facet = (key: string, title: string, group: string): FacetConfig => ({
key,
@@ -44,6 +52,13 @@ describe('facets', () => {
['selected value already fetched is not duplicated', ['api'], undefined, ['api', 'worker']],
['missing selected value is prepended', ['batch-exports'], undefined, ['batch-exports', 'api', 'worker']],
['multiple missing values keep selection order', ['b', 'a'], undefined, ['b', 'a', 'api', 'worker']],
+ // A value hand-edited into both polarities reaches here twice (included ++ excluded).
+ [
+ 'a value repeated across polarities is not duplicated',
+ ['dup', 'dup'],
+ undefined,
+ ['dup', 'api', 'worker'],
+ ],
['missing selected value not matching the search is omitted', ['batch-exports'], 'api', ['api', 'worker']],
[
'search match is a case-insensitive substring',
@@ -63,4 +78,104 @@ 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'],
+ })
+ })
+ })
+ })
})
diff --git a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
index 561ac4338d1f..e082b9bee8ff 100644
--- a/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
+++ b/products/logs/frontend/components/LogsViewer/FacetRail/facets.ts
@@ -31,7 +31,8 @@ export type FacetField = 'severity_text' | 'service_name'
*
* - `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 a `log_resource_attribute` property filter inside the filterGroup.
+ * 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.
*/
export type FacetSource =
| { type: 'column'; column: FacetField; filterKey: FacetFilterKey }
@@ -69,39 +70,86 @@ function innerFilters(group: UniversalFiltersGroup | undefined): LogResourceAttr
return ((group?.values?.[0] as UniversalFiltersGroup | undefined)?.values ?? []) as LogResourceAttributeFilter[]
}
-function isResourceAttributeFilter(filter: LogResourceAttributeFilter, key: string): boolean {
- return filter?.type === PropertyFilterType.LogResourceAttribute && filter?.key === key
+/**
+ * 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[]
}
-/** Values currently selected for a resource-attribute facet, read from the log_resource_attribute filter. */
-export function resourceAttributeValues(group: UniversalFiltersGroup | undefined, key: string): string[] {
- const existing = innerFilters(group).find((f) => isResourceAttributeFilter(f, key))
- const value = existing?.value
+// 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(filter: LogResourceAttributeFilter, key: string): boolean {
+ return (
+ filter?.type === PropertyFilterType.LogResourceAttribute &&
+ filter?.key === key &&
+ RAIL_OPERATORS.includes(filter?.operator)
+ )
+}
+
+function filterValues(filter: LogResourceAttributeFilter): 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),
+ }
+}
+
/**
- * Add or remove `value` from a resource-attribute facet's selection, returning a new filterGroup.
- * Multi-select is one log_resource_attribute filter per key with an array value (logs have no `in` operator).
+ * 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 toggleResourceAttributeFilter(
+export function cycleResourceAttributeFilter(
group: UniversalFiltersGroup | undefined,
key: string,
value: string
): UniversalFiltersGroup {
- const current = resourceAttributeValues(group, key)
- const next = current.includes(value) ? current.filter((v) => v !== value) : [...current, value]
- const others = innerFilters(group).filter((f) => !isResourceAttributeFilter(f, key))
- const values: LogResourceAttributeFilter[] =
- next.length > 0
- ? [
- ...others,
- { key, type: PropertyFilterType.LogResourceAttribute, operator: PropertyOperator.Exact, value: next },
- ]
- : others
+ 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]
+ }
+
+ const values = 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 }] }
}
@@ -198,7 +246,8 @@ export function filterFacetsByName(facets: FacetConfig[], query: string): FacetC
}
/**
- * Ensure every selected value of a dynamic facet renders even when absent from the fetched list —
+ * Ensure every selected (included or excluded) value of a dynamic facet renders even when absent
+ * from the fetched list —
* a filter from a URL or saved view can reference a value with no matches in the current scope
* (or one below the top-N cutoff), and without a visible row it can't be seen or toggled off.
* Missing values are prepended with a zero count. An active type-ahead search still applies to
@@ -207,7 +256,9 @@ export function filterFacetsByName(facets: FacetConfig[], query: string): FacetC
export function mergeSelectedIntoOptions(fetched: FacetOption[], selected: string[], search?: string): FacetOption[] {
const needle = (search ?? '').trim().toLowerCase()
const fetchedValues = new Set(fetched.map((option) => option.value))
- const missing = selected
+ // Dedupe: callers pass included+excluded concatenated, and a value hand-edited into both
+ // polarities appears in both — without this it would inject a duplicate-keyed row.
+ const missing = Array.from(new Set(selected))
.filter((value) => !fetchedValues.has(value))
.filter((value) => !needle || value.toLowerCase().includes(needle))
.map((value) => ({ value, label: value, count: 0 }))