Skip to content

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

fix(logs,tracing): stop attribute row buttons stacking duplicate filters (#89623)

Jimmy Zhu1b293912a86e
diff --git a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.test.ts b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.test.ts
index 262915ff1a80..6dae746620f6 100644
--- a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.test.ts
+++ b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.test.ts
@@ -141,6 +141,25 @@ describe('logsViewerFiltersLogic', () => {
})
})
+ // The reconciliation rules themselves are covered in logsFilterAdd.test.ts; this pins that the
+ // attribute row buttons go through them, which they did not — a repeat click used to stack an
+ // identical chip, and a `+` after a `-` used to leave a pair matching no log.
+ describe('addFilter', () => {
+ it.each([
+ ['a repeat click', PropertyOperator.Exact, PropertyOperator.Exact],
+ ['a click cancelling an exclusion', PropertyOperator.IsNot, PropertyOperator.Exact],
+ ])('leaves one chip after %s', async (_label, first, second) => {
+ logic.actions.addFilter('service_name', 'api', first, PropertyFilterType.Log)
+ logic.actions.addFilter('service_name', 'api', second, PropertyFilterType.Log)
+ await expectLogic(logic).toFinishAllListeners()
+
+ const inner = logic.values.filters.filterGroup.values[0] as UniversalFiltersGroup
+ expect(inner.values).toEqual([
+ { key: 'service_name', value: ['api'], operator: second, type: PropertyFilterType.Log },
+ ])
+ })
+ })
+
describe('setFilterGroup fallback', () => {
it('falls back to default when given invalid filterGroup', async () => {
logic.actions.setFilterGroup(null as any)
diff --git a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
index 5c3efea1e902..5d1f06616992 100644
--- a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
@@ -34,7 +34,10 @@ import {
SEVERITY_LEVEL_FILTER,
setFacetIncluded,
} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'
-import { LogsFilterTarget } from 'products/logs/frontend/components/LogsViewer/Filters/logsFilterAdd'
+import {
+ LogsFilterTarget,
+ mergeFilterIntoValues,
+} from 'products/logs/frontend/components/LogsViewer/Filters/logsFilterAdd'
export const DEFAULT_DATE_RANGE = { date_from: '-1h', date_to: null }
const VALID_SEVERITY_LEVELS: readonly LogSeverityLevel[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal']
@@ -366,19 +369,24 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([
addFilter: ({ key, value, operator, propertyType }) => {
const currentGroup = values.filters.filterGroup.values[0] as UniversalFiltersGroup
- const newGroup: UniversalFiltersGroup = {
- ...currentGroup,
- values: [
- ...currentGroup.values,
- {
- key,
- value: [value],
- operator,
- type: propertyType,
- } as UniversalFiltersGroupValue,
- ],
+ // Reconciled rather than appended, so clicking the same attribute row twice does not
+ // stack a duplicate chip, and including a value cancels a standing exclusion of it.
+ // Same rules the search bar and the facet rail apply.
+ const reconciled = mergeFilterIntoValues(currentGroup.values, {
+ key,
+ value: [value],
+ operator,
+ type: propertyType,
+ } as UniversalFiltersGroupValue)
+
+ if (equal(reconciled, currentGroup.values)) {
+ // The click landed on filters that already say this. Writing an equal group would
+ // reload the list, the patterns pivot and the group-by breakdown for no change.
+ return
}
+ const newGroup: UniversalFiltersGroup = { ...currentGroup, values: reconciled }
+
actions.setFilterGroup({ ...values.filters.filterGroup, values: [newGroup] }, false)
},
})),
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/SpanAttributes.tsx b/products/tracing/frontend/components/VirtualizedSpanList/SpanAttributes.tsx
index adcd9537249b..a3c045792a8e 100644
--- a/products/tracing/frontend/components/VirtualizedSpanList/SpanAttributes.tsx
+++ b/products/tracing/frontend/components/VirtualizedSpanList/SpanAttributes.tsx
@@ -13,6 +13,9 @@ import { tracingFiltersLogic } from 'products/tracing/frontend/tracingFiltersLog
const APPLIED_INDICATOR_MS = 2000
+// The indicator names the state the click leaves behind, not the write, because a click on a value
+// already filtered reconciles to the same group and writes nothing (see spanFilterAdd.ts).
+
interface AttributeRow {
key: string
value: string
@@ -69,7 +72,7 @@ export function SpanAttributes({
render: (_: unknown, record: AttributeRow) => (
<div className="flex gap-x-0">
{appliedFilter?.key === record.key && appliedFilter.direction === 'include' ? (
- <LemonButton size="xsmall" tooltip="Filter added">
+ <LemonButton size="xsmall" tooltip="Filter applied">
<IconCheck className="text-success" />
</LemonButton>
) : (
@@ -86,7 +89,7 @@ export function SpanAttributes({
</LemonButton>
)}
{appliedFilter?.key === record.key && appliedFilter.direction === 'exclude' ? (
- <LemonButton size="xsmall" tooltip="Filter added">
+ <LemonButton size="xsmall" tooltip="Filter applied">
<IconCheck className="text-success" />
</LemonButton>
) : (
diff --git a/products/tracing/frontend/spanFilterAdd.ts b/products/tracing/frontend/spanFilterAdd.ts
new file mode 100644
index 000000000000..e00bf7034991
--- /dev/null
+++ b/products/tracing/frontend/spanFilterAdd.ts
@@ -0,0 +1,120 @@
+/**
+ * Reconciling a filter added from a span attribute row with the filters the bar already holds.
+ *
+ * The row buttons used to append unconditionally, so clicking `+` twice left two identical chips,
+ * and clicking `+` after `-` on the same value left `attr = x` beside `attr ≠ x`, which matches no
+ * span. The rules below keep the invariant the facet rail keeps (see FacetRail/facets.ts): one
+ * filter per attribute and polarity, and no value on both sides at once.
+ *
+ * Logs holds the same rules in Filters/logsFilterAdd.ts, over a superset that also reconciles the
+ * ambiguous `log` / `log_attribute` pair its picker produces. Two copies is what the products
+ * convention allows; a third consumer is the point to lift the shared core into lib/.
+ */
+
+import { uniqueBy } from 'lib/utils/arrays'
+
+import { PropertyFilterType, PropertyFilterValue, PropertyOperator, UniversalFiltersGroup } from '~/types'
+
+type FilterEntry = UniversalFiltersGroup['values'][number]
+
+// The parts of a property filter this module reads. AnyPropertyFilter is a union whose members
+// disagree on `operator` and `value`, and spreading one back produces a type nothing accepts, so
+// entries are narrowed to this shape and cast back at the boundary — same approach as facets.ts.
+interface ReconcilableFilter {
+ key: string
+ type: PropertyFilterType
+ operator?: PropertyOperator
+ value?: PropertyFilterValue
+}
+
+// A row button only ever writes one of these two. Any other operator on the same key (an
+// `icontains` typed into the bar) is a legitimate AND, so it neither absorbs nor blocks a click.
+const OPPOSITE_OPERATOR: Partial<Record<PropertyOperator, PropertyOperator>> = {
+ [PropertyOperator.Exact]: PropertyOperator.IsNot,
+ [PropertyOperator.IsNot]: PropertyOperator.Exact,
+}
+
+function asFilter(entry: FilterEntry): ReconcilableFilter | null {
+ if (entry == null || typeof entry !== 'object' || 'values' in entry || !('key' in entry) || !('type' in entry)) {
+ return null
+ }
+ const filter = entry as unknown as ReconcilableFilter
+ return filter.key != null && filter.type != null ? filter : null
+}
+
+// Values are compared as strings because that is what the attribute rows and the URL round-trip
+// them as, but the stored value keeps its own type.
+function valueKey(value: unknown): string {
+ return String(value)
+}
+
+function filterValues(filter: ReconcilableFilter): unknown[] {
+ if (Array.isArray(filter.value)) {
+ return filter.value
+ }
+ return filter.value != null ? [filter.value] : []
+}
+
+function withValues(filter: ReconcilableFilter, values: unknown[]): FilterEntry {
+ return { ...filter, value: values } as unknown as FilterEntry
+}
+
+export interface SpanFilterMerge {
+ /** The inner group's values with `incoming` folded in. */
+ values: FilterEntry[]
+ /**
+ * The entry that ended up carrying the incoming value — the one just appended, or the existing
+ * filter it merged into. The bar addresses chips by identity, so it needs this rather than an
+ * index.
+ */
+ filter: FilterEntry
+}
+
+/**
+ * Add `incoming` to `values`, folding it into an existing filter on the same attribute where that is
+ * what the click meant:
+ *
+ * - an equality filter merges its values into the matching polarity, so clicking the same row again
+ * changes nothing, and drops those values from the opposite polarity, so `= x` cancels a standing
+ * `≠ x` instead of contradicting it
+ * - anything else appends
+ */
+export function mergeSpanFilter(values: FilterEntry[], incoming: FilterEntry): SpanFilterMerge {
+ const filter = asFilter(incoming)
+ const operator = filter?.operator
+ const opposite = operator ? OPPOSITE_OPERATOR[operator] : undefined
+ const incomingValues = filter ? filterValues(filter) : []
+ if (!filter || !operator || !opposite || incomingValues.length === 0) {
+ return { values: [...values, incoming], filter: incoming }
+ }
+
+ const incomingKeys = incomingValues.map(valueKey)
+ const reconciled: FilterEntry[] = []
+ let merged: FilterEntry | null = null
+
+ for (const entry of values) {
+ const existing = asFilter(entry)
+ if (!existing || existing.type !== filter.type || existing.key !== filter.key) {
+ reconciled.push(entry)
+ continue
+ }
+ if (existing.operator === operator) {
+ merged = withValues(existing, uniqueBy([...filterValues(existing), ...incomingValues], valueKey))
+ reconciled.push(merged)
+ continue
+ }
+ if (existing.operator === opposite) {
+ const remaining = filterValues(existing).filter((v) => !incomingKeys.includes(valueKey(v)))
+ if (remaining.length > 0) {
+ reconciled.push(withValues(existing, remaining))
+ }
+ continue
+ }
+ reconciled.push(entry)
+ }
+
+ if (merged) {
+ return { values: reconciled, filter: merged }
+ }
+ return { values: [...reconciled, incoming], filter: incoming }
+}
diff --git a/products/tracing/frontend/tracingFiltersLogic.test.ts b/products/tracing/frontend/tracingFiltersLogic.test.ts
index 95d39e347f5c..a26db4017d2a 100644
--- a/products/tracing/frontend/tracingFiltersLogic.test.ts
+++ b/products/tracing/frontend/tracingFiltersLogic.test.ts
@@ -193,6 +193,51 @@ describe('tracingFiltersLogic', () => {
const inner = logic.values.filterGroup.values[0] as UniversalFiltersGroup
expect(logic.values.suppressAutoOpenFilter).toBe(inner.values[inner.values.length - 1])
})
+
+ // The row buttons are one click away from each other, so a repeat click used to stack an
+ // identical chip and a `+` after a `-` used to leave a pair matching no span. The
+ // suppression assertion pins the merged entry, not the discarded incoming one — the bar
+ // matches by identity, so a stale reference pops the editor open on a chip nobody touched.
+ it('folds a repeat click into the chip already there', () => {
+ logic.actions.addFilter('http.method', 'GET')
+ logic.actions.addFilter('http.method', 'GET')
+
+ const inner = logic.values.filterGroup.values[0] as UniversalFiltersGroup
+ expect(inner.values).toEqual([
+ {
+ key: 'http.method',
+ value: ['GET'],
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.SpanAttribute,
+ },
+ ])
+ expect(logic.values.suppressAutoOpenFilter).toBe(inner.values[0])
+ })
+
+ // Separate from the fold test above, which needs the flag already armed by its first add.
+ it('does not defer a refresh for a click that changes nothing', () => {
+ logic.actions.addFilter('http.method', 'GET')
+ logic.actions.refreshDeferredFilters()
+
+ logic.actions.addFilter('http.method', 'GET')
+
+ expect(logic.values.hasDeferredFilterRefresh).toBe(false)
+ })
+
+ it('cancels a standing exclusion instead of contradicting it', () => {
+ logic.actions.addFilter('http.method', 'GET', PropertyOperator.IsNot)
+ logic.actions.addFilter('http.method', 'GET', PropertyOperator.Exact)
+
+ const inner = logic.values.filterGroup.values[0] as UniversalFiltersGroup
+ expect(inner.values).toEqual([
+ {
+ key: 'http.method',
+ value: ['GET'],
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.SpanAttribute,
+ },
+ ])
+ })
})
describe('refreshDeferredFilters', () => {
diff --git a/products/tracing/frontend/tracingFiltersLogic.ts b/products/tracing/frontend/tracingFiltersLogic.ts
index 82dd940a5502..32432c157666 100644
--- a/products/tracing/frontend/tracingFiltersLogic.ts
+++ b/products/tracing/frontend/tracingFiltersLogic.ts
@@ -25,6 +25,8 @@ import {
UniversalFiltersGroupValue,
} from '~/types'
+import { mergeSpanFilter } from 'products/tracing/frontend/spanFilterAdd'
+
export const DEFAULT_DATE_RANGE: DateRange = { date_from: '-1h', date_to: null }
export const DEFAULT_TIMEZONE: string = 'UTC'
export const DEFAULT_SERVICE_NAMES: string[] = []
@@ -434,12 +436,13 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
suppressAutoOpenForFilter: (_, { filter }) => filter,
},
],
- // Set when a filter is added while the trace drawer is open (so its query is deferred);
- // cleared once that deferred query has actually run.
+ // Set when a filter write skips its own query (the drawer is covering the list);
+ // cleared once that deferred query has actually run. Keyed on the write rather than on
+ // `addFilter`, so a click that reconciles to the filters already applied defers nothing.
hasDeferredFilterRefresh: [
false,
{
- addFilter: () => true,
+ setFilterGroup: (state, { skipQuery }) => skipQuery || state,
refreshDeferredFilters: () => false,
},
],
@@ -554,14 +557,25 @@ export const tracingFiltersLogic = kea<tracingFiltersLogicType>([
listeners(({ actions, values }) => ({
addFilter: ({ key, value, operator, propertyType }) => {
const currentGroup = values.filterGroup.values[0] as UniversalFiltersGroup
- const newFilterValue = { key, value: [value], operator, type: propertyType } as UniversalFiltersGroupValue
- const newGroup: UniversalFiltersGroup = {
- ...currentGroup,
- values: [...currentGroup.values, newFilterValue],
+ // Reconciled rather than appended, so clicking the same attribute row twice does not
+ // stack a duplicate chip, and including a value cancels a standing exclusion of it.
+ const merged = mergeSpanFilter(currentGroup.values, {
+ key,
+ value: [value],
+ operator,
+ type: propertyType,
+ } as UniversalFiltersGroupValue)
+
+ if (equal(merged.values, currentGroup.values)) {
+ // The click landed on filters that already say this. Writing an equal group would
+ // re-render the bar and defer a re-query for a filter set that never moved.
+ return
}
- actions.suppressAutoOpenForFilter(newFilterValue)
+ const newGroup: UniversalFiltersGroup = { ...currentGroup, values: merged.values }
+
+ actions.suppressAutoOpenForFilter(merged.filter as UniversalFiltersGroupValue)
// Update the chips immediately, but defer the actual query — added from inside the
// trace drawer, so re-querying now would only change data the drawer is covering.
actions.setFilterGroup({ ...values.filterGroup, values: [newGroup] }, true)