: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(logs): reconcile a picked filter with the filters already applied (#84526)
Jimmy Zhu852eb1b93d9b
diff --git a/frontend/src/lib/components/UniversalFilters/UniversalFilters.tsx b/frontend/src/lib/components/UniversalFilters/UniversalFilters.tsxindex ce4fc0f81126..7a7d6ea14cf3 100644--- a/frontend/src/lib/components/UniversalFilters/UniversalFilters.tsx+++ b/frontend/src/lib/components/UniversalFilters/UniversalFilters.tsx@@ -96,6 +96,8 @@ const Value = ({onChange,onRemove,initiallyOpen = false,+ open: controlledOpen,+ onOpenChange,metadataSource,className,operatorAllowlist,@@ -106,6 +108,13 @@ const Value = ({onChange: (property: UniversalFilterValue) => voidonRemove?: () => voidinitiallyOpen?: boolean+ /**+ * Drives the editor popover from the parent. Leave it undefined for the default behavior, where+ * the chip owns its own open state. A caller that needs to open a chip already on screen passes+ * this rather than remounting it, since a remount also resets everything else the chip holds.+ */+ open?: boolean+ onOpenChange?: (open: boolean) => voidmetadataSource?: AnyDataNodeclassName?: stringoperatorAllowlist?: OperatorValueSelectProps['operatorAllowlist']@@ -117,7 +126,12 @@ const Value = ({const isAction = isActionFilter(filter)const isEditable = isEditableFilter(filter)- const [open, setOpen] = useState<boolean>(isEditable && initiallyOpen)+ const [uncontrolledOpen, setUncontrolledOpen] = useState<boolean>(isEditable && initiallyOpen)+ const open = controlledOpen !== undefined ? isEditable && controlledOpen : uncontrolledOpen+ const setOpen = (next: boolean): void => {+ setUncontrolledOpen(next)+ onOpenChange?.(next)+ }const [changingEvent, setChangingEvent] = useState<boolean>(false)// allowEntityNegation gates only the creation of new negations. Existing negation valuesdiff --git a/products/logs/frontend/LogsScene.stories.tsx b/products/logs/frontend/LogsScene.stories.tsxindex bb6c6dd18b27..a6ca2ce36374 100644--- a/products/logs/frontend/LogsScene.stories.tsx+++ b/products/logs/frontend/LogsScene.stories.tsx@@ -373,26 +373,30 @@ const facetValuesMock: MockSignature = async ({ request }) => {return [200, { results }]}+// The taxonomic filter asks for `attribute_type=log|resource` and reads a paginated list whose items+// carry their own propertyFilterType (see the Log attributes / Resource attributes groups in+// taxonomicFilterLogic). Answering any other shape leaves those groups empty in the picker.+function attributeTypeOf(request: Request): PropertyFilterType.LogAttribute | PropertyFilterType.LogResourceAttribute {+ return new URL(request.url).searchParams.get('attribute_type') === 'resource'+ ? PropertyFilterType.LogResourceAttribute+ : PropertyFilterType.LogAttribute+}+const attributesMock: MockSignature = async ({ request }) => {await delayIfNotTestRunner()- const type = (new URL(request.url).searchParams.get('attribute_type') ?? 'log_attribute') as- | PropertyFilterType.LogAttribute- | PropertyFilterType.LogResourceAttribute- const results = Object.keys(attributeExamples[type]).map((key) => ({- id: key,- name: key,- type: type,- }))- return [200, results]+ const type = attributeTypeOf(request)+ const search = (new URL(request.url).searchParams.get('search') ?? '').toLowerCase()+ const results = Object.keys(attributeExamples[type])+ .filter((key) => !search || key.toLowerCase().includes(search))+ .map((name) => ({ name, propertyFilterType: type, matchedOn: 'key' }))+ return [200, { results, count: results.length }]}const valuesMock: MockSignature = async ({ request }) => {await delayIfNotTestRunner()const url = new URL(request.url)const key = url.searchParams.get('key') ?? ''- const type = (url.searchParams.get('attribute_type') ?? 'log_attribute') as- | PropertyFilterType.LogAttribute- | PropertyFilterType.LogResourceAttribute+ const type = attributeTypeOf(request)const results = (attributeExamples[type][key] ?? []).map((value) => ({id: value,name: value,@@ -487,6 +491,10 @@ export default {// while the handwritten ApiRequest helpers are environment-scoped.mswDecorator({get: {+ // Both prefixes, because both callers exist: the taxonomic filter asks the+ // environment-scoped path, and facetPresenceLogic asks the project-scoped one through+ // the generated client. Answering only one empties the other's list.+ '/api/environments/:team_id/logs/attributes': attributesMock,'/api/projects/:team_id/logs/attributes': attributesMock,'/api/environments/:team_id/logs/values': valuesMock,'/api/environments/:team_id/logs/has_logs': () => [200, { hasLogs: true }],diff --git a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.test.ts b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.test.tsindex 854b6d01bb50..fce2f1291bd3 100644--- a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.test.ts+++ b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.test.ts@@ -46,6 +46,12 @@ describe('addLogsValueFilter', () => {expect(addLogsValueFilter(LOGS_GROUP, 'message', messageSearchItem('foobar'), existing)).toHaveLength(2)})+ it('reconciles with an existing filter on the same attribute instead of duplicating it', () => {+ const existing = addLogsValueFilter(LOGS_GROUP, 'message', messageSearchItem('foobar'), [])++ expect(addLogsValueFilter(LOGS_GROUP, 'message', messageSearchItem('foobar'), existing)).toEqual(existing)+ })+// The regression: without recording the complete filter here, the only record of this selection is// taxonomicFilterLogic's, which drops the value — so re-selecting from "Recent" yields `message`// with nothing to match on.diff --git a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsx b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsxindex 146ed31ed40e..fe3209fa7c0a 100644--- a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsx+++ b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsFilterBar.tsx@@ -25,11 +25,18 @@ import {AnyPropertyFilter,FilterLogicalOperator,PropertyFilterType,+ PropertyFilterValue,PropertyOperator,UniversalFiltersGroup,} from '~/types'import { logsViewerDataLogic } from 'products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic'+import { filterValues, isSameFilterTarget } from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'+import {+ filterTarget,+ logsSelection,+ mergeFilterIntoValues,+} from 'products/logs/frontend/components/LogsViewer/Filters/logsFilterAdd'import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'import { LogsDateRangePicker } from '../LogsDateRangePicker/LogsDateRangePicker'@@ -144,12 +151,13 @@ export function addLogsValueFilter(})}- return [...currentValues, newPropertyFilter]+ return mergeFilterIntoValues(currentValues, newPropertyFilter)}export const LogsFilterSearch = (): JSX.Element => {const [visible, setVisible] = useState<boolean>(false)const { utcDateRange, queryFilterGroup, columnQueryFields } = useValues(logsViewerFiltersLogic)+ const { focusFilter } = useActions(logsViewerFiltersLogic)const { addGroupFilter, setGroupValues } = useActions(universalFiltersLogic)const { filterGroup } = useValues(universalFiltersLogic)@@ -170,14 +178,19 @@ export const LogsFilterSearch = (): JSX.Element => {...columnQueryFields,},onChange: (taxonomicGroup, value, item) => {- if (item.value === undefined) {+ setVisible(false)+ // Recording the selection back to recents stays with taxonomicFilterLogic, which does it+ // for every pick; this only decides how the selection lands in the group.+ const selection = logsSelection(filterGroup.values, taxonomicGroup, value, item)+ if (selection.kind === 'merge') {+ setGroupValues(mergeFilterIntoValues(filterGroup.values, selection.filter))+ } else if (selection.kind === 'valueItem') {+ setGroupValues(addLogsValueFilter(taxonomicGroup, value, item, filterGroup.values))+ } else if (selection.kind === 'focus') {+ focusFilter(selection.target)+ } else {addGroupFilter(taxonomicGroup, value, item)- setVisible(false)- return}-- setGroupValues(addLogsValueFilter(taxonomicGroup, value, item, filterGroup.values))- setVisible(false)},onEnter: onClose,autoSelectItem: true,@@ -211,17 +224,33 @@ export const LogsFilterSearch = (): JSX.Element => {)}-const FilterGroupValues = ({ allowInitiallyOpen }: { allowInitiallyOpen: boolean }): JSX.Element | null => {+const FilterGroupValues = ({+ allowInitiallyOpen,+ focusable = false,+}: {+ allowInitiallyOpen: boolean+ /** Only the top-level list owns focus: a nested group's indices are its own. */+ focusable?: boolean+}): JSX.Element | null => {const { filterGroup } = useValues(universalFiltersLogic)const { replaceGroupValue, removeGroupValue } = useActions(universalFiltersLogic)+ const { focusedFilter } = useValues(logsViewerFiltersLogic)+ const { focusFilter } = useActions(logsViewerFiltersLogic)if (filterGroup.values.length === 0) {return null}+ // One chip at a time: an attribute can hold a chip per polarity (`= api` beside `≠ worker`), and+ // matching every chip on the target would open both popovers over each other.+ const focusedIndex = focusable+ ? filterGroup.values.findIndex((entry) => isSameFilterTarget(filterTarget(entry), focusedFilter))+ : -1+return (<>{filterGroup.values.map((filterOrGroup, index) => {+ const isFocused = focusedIndex >= 0 && index === focusedIndexreturn isUniversalGroupFilterLike(filterOrGroup) ? (<UniversalFilters.Group index={index} key={index} group={filterOrGroup}><FilterGroupValues allowInitiallyOpen={allowInitiallyOpen} />@@ -231,9 +260,34 @@ const FilterGroupValues = ({ allowInitiallyOpen }: { allowInitiallyOpen: booleankey={index}index={index}filter={filterOrGroup}- onRemove={() => removeGroupValue(index)}+ onRemove={() => {+ // Nothing else clears it, and a target left pointing at a chip that is+ // gone opens the next chip on that attribute the moment one appears.+ if (isFocused) {+ focusFilter(null)+ }+ removeGroupValue(index)+ }}onChange={(value) => replaceGroupValue(index, value)}- initiallyOpen={allowInitiallyOpen && filterOrGroup.type != PropertyFilterType.HogQL}+ // Only a chip that still needs a value opens itself: that is the one the+ // user just added from the picker and has to fill in. A chip that arrives+ // complete came from the facet rail or a recent, and popping an editor over+ // the page on every rail click is noise.+ initiallyOpen={+ allowInitiallyOpen &&+ filterOrGroup.type != PropertyFilterType.HogQL &&+ filterValues(filterOrGroup as { value?: PropertyFilterValue }).length === 0+ }+ open={isFocused ? true : undefined}+ onOpenChange={+ isFocused+ ? (next) => {+ if (!next) {+ focusFilter(null)+ }+ }+ : undefined+ }/>)})}@@ -253,7 +307,7 @@ export const LogsAppliedFilters = (): JSX.Element | null => {return (<div className="flex gap-1 items-center flex-wrap">- <FilterGroupValues allowInitiallyOpen={allowInitiallyOpen} />+ <FilterGroupValues allowInitiallyOpen={allowInitiallyOpen} focusable /></div>)}diff --git a/products/logs/frontend/components/LogsViewer/Filters/logsFilterAdd.test.ts b/products/logs/frontend/components/LogsViewer/Filters/logsFilterAdd.test.tsnew file mode 100644index 000000000000..7e491121cad0--- /dev/null+++ b/products/logs/frontend/components/LogsViewer/Filters/logsFilterAdd.test.ts@@ -0,0 +1,299 @@+import { TaxonomicFilterGroup, TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'++import { PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'++import { LogsFilterTarget } from './logsFilterAdd'+import { appliedEqualityTarget, logsSelection, mergeFilterIntoValues, selectionTarget } from './logsFilterAdd'++const LOGS_GROUP = { name: 'Logs', type: TaxonomicFilterGroupType.Logs } as TaxonomicFilterGroup+const LOG_ATTRIBUTES_GROUP = {+ name: 'Log attributes',+ type: TaxonomicFilterGroupType.LogAttributes,+} as TaxonomicFilterGroup++type FilterEntry = UniversalFiltersGroup['values'][number]++const logFilter = (key: string, operator: PropertyOperator, value?: string | string[]): FilterEntry =>+ ({ key, type: PropertyFilterType.Log, operator, value }) as FilterEntry++const attributeFilter = (key: string, operator: PropertyOperator, value?: string | string[]): FilterEntry =>+ ({ key, type: PropertyFilterType.LogAttribute, operator, value }) as FilterEntry++const resourceFilter = (key: string, operator: PropertyOperator, value?: string | string[]): FilterEntry =>+ ({ key, type: PropertyFilterType.LogResourceAttribute, operator, value }) as FilterEntry++/** Applies a pick that must reconcile, failing loudly if the decision came out as something else. */+const applyPick = (values: FilterEntry[], group: TaxonomicFilterGroup, item: Record<string, any>): FilterEntry[] => {+ const selection = logsSelection(values, group, 'service_name', item)+ if (selection.kind !== 'merge') {+ throw new Error(`expected a merge, got ${selection.kind}`)+ }+ return mergeFilterIntoValues(values, selection.filter)+}++describe('logsFilterAdd', () => {+ describe('mergeFilterIntoValues', () => {+ // Picking a filter that contradicts a standing one used to leave both in the group, which ANDs+ // `IN (x)` with `NOT IN (x)` and returns no logs at all.+ it('cancels the opposite polarity for the value being added', () => {+ const existing = [logFilter('service_name', PropertyOperator.IsNot, ['posthog-db-1'])]+ expect(+ mergeFilterIntoValues(existing, logFilter('service_name', PropertyOperator.Exact, ['posthog-db-1']))+ ).toEqual([logFilter('service_name', PropertyOperator.Exact, ['posthog-db-1'])])+ })++ it('keeps the values of the opposite polarity it was not asked about', () => {+ const existing = [logFilter('service_name', PropertyOperator.IsNot, ['api', 'worker'])]+ expect(mergeFilterIntoValues(existing, logFilter('service_name', PropertyOperator.Exact, ['api']))).toEqual(+ [+ logFilter('service_name', PropertyOperator.IsNot, ['worker']),+ logFilter('service_name', PropertyOperator.Exact, ['api']),+ ]+ )+ })++ it('merges into the filter already holding that polarity rather than adding a second one', () => {+ const existing = [logFilter('service_name', PropertyOperator.Exact, ['api'])]+ expect(+ mergeFilterIntoValues(existing, logFilter('service_name', PropertyOperator.Exact, ['worker']))+ ).toEqual([logFilter('service_name', PropertyOperator.Exact, ['api', 'worker'])])+ })++ it('does not repeat a value the filter already carries', () => {+ const existing = [logFilter('service_name', PropertyOperator.Exact, ['api'])]+ expect(mergeFilterIntoValues(existing, logFilter('service_name', PropertyOperator.Exact, ['api']))).toEqual(+ [logFilter('service_name', PropertyOperator.Exact, ['api'])]+ )+ })++ it('normalizes a scalar value into the list it merges into', () => {+ const existing = [logFilter('service_name', PropertyOperator.Exact, 'api')]+ expect(+ mergeFilterIntoValues(existing, logFilter('service_name', PropertyOperator.Exact, 'worker'))+ ).toEqual([logFilter('service_name', PropertyOperator.Exact, ['api', 'worker'])])+ })++ it.each<[string, FilterEntry, FilterEntry]>([+ // A resource attribute maps to a group of its own, so its type is never in doubt and a+ // resource attribute named service_name stays separate from the service_name column.+ [+ 'a resource attribute of the same name',+ logFilter('service_name', PropertyOperator.Exact, ['api']),+ resourceFilter('service_name', PropertyOperator.Exact, ['worker']),+ ],+ [+ 'a different key',+ logFilter('service_name', PropertyOperator.Exact, ['api']),+ logFilter('severity_level', PropertyOperator.Exact, ['error']),+ ],+ ])('leaves %s alone', (_, existing, incoming) => {+ expect(mergeFilterIntoValues([existing], incoming)).toEqual([existing, incoming])+ })++ // Two substring matches on one attribute are a legitimate AND, unlike two equality filters.+ it('appends a second contains filter on the same attribute', () => {+ const existing = [logFilter('message', PropertyOperator.IContains, 'timeout')]+ const incoming = logFilter('message', PropertyOperator.IContains, 'retry')+ expect(mergeFilterIntoValues(existing, incoming)).toEqual([...existing, incoming])+ })++ // Merging compares values as strings, but a filter keeps whatever type it stored.+ it('leaves a non-string value alone when merging into it', () => {+ const numeric = {+ key: 'status',+ type: PropertyFilterType.Log,+ operator: PropertyOperator.Exact,+ value: [500],+ } as unknown as FilterEntry+ const incoming = {+ key: 'status',+ type: PropertyFilterType.Log,+ operator: PropertyOperator.Exact,+ value: ['503'],+ } as unknown as FilterEntry++ expect(mergeFilterIntoValues([numeric], incoming)).toEqual([+ { key: 'status', type: PropertyFilterType.Log, operator: PropertyOperator.Exact, value: [500, '503'] },+ ])+ })++ it('drops an identical repeat of a non-equality filter', () => {+ const existing = [logFilter('message', PropertyOperator.IContains, 'timeout')]+ expect(+ mergeFilterIntoValues(existing, logFilter('message', PropertyOperator.IContains, 'timeout'))+ ).toEqual(existing)+ })++ it('appends a value-less filter, which has nothing to merge on yet', () => {+ const existing = [logFilter('service_name', PropertyOperator.Exact, ['api'])]+ const incoming = logFilter('severity_level', PropertyOperator.Exact, undefined)+ expect(mergeFilterIntoValues(existing, incoming)).toEqual([...existing, incoming])+ })++ it('carries a nested group through untouched', () => {+ const nested = {+ type: 'OR',+ values: [attributeFilter('distinct_id', PropertyOperator.Exact, ['7'])],+ } as unknown as FilterEntry+ const incoming = logFilter('service_name', PropertyOperator.Exact, ['api'])+ expect(mergeFilterIntoValues([nested], incoming)).toEqual([nested, incoming])+ })+ })++ describe('appliedEqualityTarget', () => {+ const values = [+ logFilter('message', PropertyOperator.IContains, 'timeout'),+ logFilter('service_name', PropertyOperator.IsNot, ['api']),+ ]++ it.each<[string, PropertyFilterType, string, LogsFilterTarget | null]>([+ [+ 'the equality filter on that attribute',+ PropertyFilterType.Log,+ 'service_name',+ { key: 'service_name', type: PropertyFilterType.Log },+ ],+ [+ 'a log attribute pick matching the column of that name',+ PropertyFilterType.LogAttribute,+ 'service_name',+ { key: 'service_name', type: PropertyFilterType.Log },+ ],+ [+ 'no match for a resource attribute of that name',+ PropertyFilterType.LogResourceAttribute,+ 'service_name',+ null,+ ],+ ['no match for another key', PropertyFilterType.Log, 'severity_level', null],+ // A contains filter is an independent predicate, so picking that attribute again adds one+ // rather than editing the filter already there.+ ['no match for a contains filter', PropertyFilterType.Log, 'message', null],+ ])('finds %s', (_, type, key, expected) => {+ expect(appliedEqualityTarget(values, { type, key })).toEqual(expected)+ })++ it('returns null when the selection maps to no attribute', () => {+ expect(appliedEqualityTarget(values, null)).toBeNull()+ })+ })++ // The reported sequences, in both orders. A recent is recorded under the Log attributes group even+ // when it came from a `log` column filter, so the group cannot decide the attribute.+ describe('picking a recent against an applied filter', () => {+ const recentOf = (+ operator: PropertyOperator,+ type: PropertyFilterType = PropertyFilterType.Log+ ): Record<string, any> => ({+ name: 'service_name',+ _recentContext: {+ sourceGroupType: TaxonomicFilterGroupType.LogAttributes,+ sourceGroupName: 'Log attributes',+ sourceValue: 'service_name',+ propertyFilter: { key: 'service_name', type, operator, value: ['posthog-db-1'] },+ },+ })+ const applied = (operator: PropertyOperator): FilterEntry =>+ ({ key: 'service_name', type: PropertyFilterType.Log, operator, value: ['posthog-db-1'] }) as FilterEntry+ const applyRecent = (values: FilterEntry[], item: Record<string, any>): FilterEntry[] =>+ applyPick(values, LOG_ATTRIBUTES_GROUP, item)++ it.each<[string, PropertyOperator, PropertyOperator]>([+ ['an applied = replaced by a picked ≠', PropertyOperator.Exact, PropertyOperator.IsNot],+ ['an applied ≠ replaced by a picked =', PropertyOperator.IsNot, PropertyOperator.Exact],+ ])('leaves one filter for %s', (_, appliedOperator, pickedOperator) => {+ expect(applyRecent([applied(appliedOperator)], recentOf(pickedOperator))).toEqual([applied(pickedOperator)])+ })++ // A recent for a `log` column filter maps back to `log_attribute`, so before this the picked+ // filter targeted an attribute of the same name and landed beside the column filter.+ it('reuses the applied field when the picked type disagrees on the same key', () => {+ const result = applyRecent(+ [applied(PropertyOperator.IsNot)],+ recentOf(PropertyOperator.Exact, PropertyFilterType.LogAttribute)+ )++ expect(result).toEqual([applied(PropertyOperator.Exact)])+ })++ // Picking both polarities straight from recents, with no facet-rail click involved.+ it('leaves one filter when both polarities are picked in turn', () => {+ const first = applyRecent([], recentOf(PropertyOperator.Exact))+ expect(first).toEqual([applied(PropertyOperator.Exact)])++ expect(applyRecent(first, recentOf(PropertyOperator.IsNot))).toEqual([applied(PropertyOperator.IsNot)])+ })++ it('keeps a filter on a genuinely different key', () => {+ const other = logFilter('severity_level', PropertyOperator.Exact, ['error'])+ const result = applyRecent([other, applied(PropertyOperator.IsNot)], recentOf(PropertyOperator.Exact))++ expect(result).toEqual([other, applied(PropertyOperator.Exact)])+ })++ // The bare-key row the picker derives from a complete recent. Opening the applied filter has to+ // leave its value alone, so the reported "adds an empty second chip" cannot happen.+ it.each<[string, PropertyOperator]>([+ ['an applied =', PropertyOperator.Exact],+ ['an applied ≠', PropertyOperator.IsNot],+ ])('opens %s when the bare key is picked, without touching its value', (_, operator) => {+ const values = [applied(operator)]+ const bare = {+ name: 'service_name',+ _recentContext: {+ sourceGroupType: TaxonomicFilterGroupType.LogAttributes,+ sourceGroupName: 'Log attributes',+ sourceValue: 'service_name',+ },+ }++ expect(logsSelection(values, LOG_ATTRIBUTES_GROUP, 'service_name', bare)).toEqual({+ kind: 'focus',+ target: { key: 'service_name', type: PropertyFilterType.Log },+ })+ expect(values).toEqual([applied(operator)])+ })+ })++ describe('rows the search matched on a value', () => {+ // Those rows carry the value as matchedValue, and the shared builder pre-fills it. Read as a+ // bare key instead, the pick was dropped and the standing filter merely reopened.+ const valueRow = {+ name: 'service_name',+ propertyFilterType: PropertyFilterType.Log,+ matchedOn: 'value',+ matchedValue: 'posthog-web',+ }++ it.each<[string, FilterEntry[]]>([+ ['against the applied filter', [logFilter('service_name', PropertyOperator.IsNot, ['posthog-web'])]],+ ['when the attribute has no filter yet', []],+ ])('reconciles the matched value %s', (_, applied) => {+ expect(applyPick(applied, LOG_ATTRIBUTES_GROUP, valueRow)).toEqual([+ logFilter('service_name', PropertyOperator.Exact, ['posthog-web']),+ ])+ })+ })++ describe('selectionTarget', () => {+ it("prefers the item's own property-filter type over its group's", () => {+ const item = { propertyFilterType: PropertyFilterType.LogResourceAttribute }++ expect(selectionTarget(LOGS_GROUP, 'service.name', item)).toEqual({+ type: PropertyFilterType.LogResourceAttribute,+ key: 'service.name',+ })+ })++ it('falls back to the type its group maps to', () => {+ expect(selectionTarget(LOGS_GROUP, 'service_name', {})).toEqual({+ type: PropertyFilterType.Log,+ key: 'service_name',+ })+ })++ it('has no target when the selection carries no key', () => {+ expect(selectionTarget(LOGS_GROUP, null, {})).toBeNull()+ })+ })+})diff --git a/products/logs/frontend/components/LogsViewer/Filters/logsFilterAdd.ts b/products/logs/frontend/components/LogsViewer/Filters/logsFilterAdd.tsnew file mode 100644index 000000000000..8f594322b0a0--- /dev/null+++ b/products/logs/frontend/components/LogsViewer/Filters/logsFilterAdd.ts@@ -0,0 +1,260 @@+import { deepEqual as equal } from 'fast-equals'++import { taxonomicFilterTypeToPropertyFilterType } from 'lib/components/PropertyFilters/utils'+import {+ hasRecentContext,+ isCompleteRecentPropertyFilter,+} from 'lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic'+import { TaxonomicFilterGroup, TaxonomicFilterValue } from 'lib/components/TaxonomicFilter/types'+import { uniqueBy } from 'lib/utils/arrays'++import { PropertyFilterType, PropertyFilterValue, PropertyOperator, UniversalFiltersGroup } from '~/types'++import {+ EQUALITY_OPERATORS,+ FacetFilterTarget,+ filterValues,+ isSameFilterTarget,+} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'++/**+ * Reconciling a newly picked filter with the filters the logs bar already holds.+ *+ * Adding a filter used to append unconditionally, so picking `service_name = api` while+ * `service_name ≠ api` was active left both in the group and the query returned nothing. The rules+ * below keep the invariant the facet rail keeps (see FacetRail/facetFilters.ts): one filter per+ * attribute and polarity, and no value on both sides at once.+ */++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 the+// entries are narrowed to this shape and cast back at the boundary — same approach as facetFilters.ts.+interface ReconcilableFilter {+ key: string+ type: PropertyFilterType+ operator?: PropertyOperator+ value?: PropertyFilterValue+}++/** The attribute a filter applies to. Two filters reconcile only when both parts match. */+export type LogsFilterTarget = FacetFilterTarget++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+}++/** The attribute a filter targets, or null for entries that target none (nested groups, entities). */+export function filterTarget(entry: FilterEntry): LogsFilterTarget | null {+ const filter = asFilter(entry)+ return filter ? { type: filter.type, key: String(filter.key) } : null+}++function isSameTarget(entry: FilterEntry, target: LogsFilterTarget): boolean {+ return isSameFilterTarget(filterTarget(entry), target)+}++/**+ * The applied filter a new selection on `target` should reuse, named by the target it is stored+ * under, or null when there is none.+ *+ * Only an equality filter counts. Two `message icontains` filters are a legitimate AND, so picking+ * that attribute again means adding one, not editing the one already there. The reconciled target+ * comes back rather than the caller's, because the two can name different types for one key.+ */+export function appliedEqualityTarget(values: FilterEntry[], target: LogsFilterTarget | null): LogsFilterTarget | null {+ if (!target) {+ return null+ }+ const reconciled = reconcileTarget(values, target)+ const applied = values.some((entry) => {+ const filter = asFilter(entry)+ return (+ filter !== null &&+ isSameTarget(entry, reconciled) &&+ filter.operator !== undefined &&+ EQUALITY_OPERATORS.includes(filter.operator)+ )+ })+ return applied ? reconciled : null+}++// Values are compared as strings because that is what the picker and the URL round-trip them as, but+// the stored value keeps its own type (see filterValues).+function valueKey(value: unknown): string {+ return String(value)+}++function withValues(filter: ReconcilableFilter, values: unknown[]): FilterEntry {+ return { ...filter, value: values } as unknown as FilterEntry+}++/**+ * Add `incoming` to `values`, folding it into an existing filter on the same attribute where that is+ * what the user meant:+ *+ * - an equality filter merges its values into the matching polarity, and drops those values from the+ * opposite polarity, so `= x` cancels a standing `≠ x` instead of contradicting it+ * - any other operator appends, unless the identical filter is already there+ */+export function mergeFilterIntoValues(values: FilterEntry[], incoming: FilterEntry): FilterEntry[] {+ const filter = asFilter(incoming)+ if (!filter) {+ // A nested group names no attribute, so there is nothing to reconcile it against.+ return [...values, incoming]+ }+ const target = reconcileTarget(values, { type: filter.type, key: String(filter.key) })+ const operator = filter.operator++ if (!operator || !EQUALITY_OPERATORS.includes(operator)) {+ const incomingKeys = filterValues(filter).map(valueKey)+ const alreadyThere = values.some((entry) => {+ const existing = asFilter(entry)+ return (+ existing !== null &&+ isSameTarget(entry, target) &&+ existing.operator === operator &&+ equal(filterValues(existing).map(valueKey), incomingKeys)+ )+ })+ return alreadyThere ? values : [...values, incoming]+ }++ const incomingValues = filterValues(filter)+ if (incomingValues.length === 0) {+ // An equality filter with no value yet is a chip the user still has to fill in, so there is+ // nothing to merge on.+ return [...values, incoming]+ }++ const incomingKeys = incomingValues.map(valueKey)+ let mergedIntoExisting = false+ const reconciled = values+ .map((entry): FilterEntry | null => {+ const existing = asFilter(entry)+ if (!existing || !isSameTarget(entry, target)) {+ return entry+ }+ if (existing.operator === operator) {+ mergedIntoExisting = true+ return withValues(existing, uniqueBy([...filterValues(existing), ...incomingValues], valueKey))+ }+ if (existing.operator === OPPOSITE_OPERATOR[operator]) {+ const remaining = filterValues(existing).filter((v) => !incomingKeys.includes(valueKey(v)))+ return remaining.length > 0 ? withValues(existing, remaining) : null+ }+ return entry+ })+ .filter((entry): entry is FilterEntry => entry !== null)++ if (mergedIntoExisting) {+ return reconciled+ }+ // Adopt the reconciled type so a keyed pick never adds a second chip for a field nobody filtered.+ return [...reconciled, withValues({ ...filter, type: target.type }, incomingValues)]+}++/**+ * The attribute a taxonomic selection would filter on.+ *+ * The group a selection arrives under cannot decide this on its own: both `log` and `log_attribute`+ * filters are recorded under the Log attributes group, and mapping that group back always yields+ * `log_attribute`. A recent recorded from a `service_name` column filter would then resolve to an+ * attribute of the same name, which is a different field. So a filter the selection carries decides+ * the type, and the group is the last resort.+ */+export function selectionTarget(+ taxonomicGroup: TaxonomicFilterGroup,+ value: TaxonomicFilterValue,+ item: any+): LogsFilterTarget | null {+ const carried = hasRecentContext(item) ? asFilter(item._recentContext.propertyFilter as FilterEntry) : null+ const type =+ carried?.type ?? item?.propertyFilterType ?? taxonomicFilterTypeToPropertyFilterType(taxonomicGroup.type)+ const key = carried?.key ?? value+ return type && key != null ? { type, key: String(key) } : null+}++// The two types the picker cannot tell apart: PROPERTY_FILTER_TYPE_TO_TAXONOMIC_FILTER_GROUP_TYPE+// records both under the Log attributes group, so mapping that group back can only ever answer+// `log_attribute`. Resource attributes map to a group of their own and stay distinct.+const AMBIGUOUS_TYPES: PropertyFilterType[] = [PropertyFilterType.Log, PropertyFilterType.LogAttribute]++/**+ * The attribute an incoming filter reconciles against. When no filter on that exact type and key is+ * applied but one shares the key under the ambiguous pair above, the applied one wins: two filters+ * that both render `service_name = api` read as a duplicate whichever field each one queries.+ */+function reconcileTarget(values: FilterEntry[], target: LogsFilterTarget): LogsFilterTarget {+ if (values.some((entry) => isSameTarget(entry, target)) || !AMBIGUOUS_TYPES.includes(target.type)) {+ return target+ }+ const sameKey = values+ .map(asFilter)+ .find((filter) => filter !== null && String(filter.key) === target.key && AMBIGUOUS_TYPES.includes(filter.type))+ return sameKey ? { type: sameKey.type, key: String(sameKey.key) } : target+}++/** What the filter bar should do with a dropdown selection, given the filters it already holds. */+export type LogsSelection =+ | { kind: 'merge'; filter: FilterEntry }+ | { kind: 'valueItem' }+ | { kind: 'focus'; target: LogsFilterTarget }+ | { kind: 'new' }++/**+ * Decide how a taxonomic selection applies to the filters already in the bar. Every outcome other+ * than `new` exists because appending unconditionally is what produced contradictory pairs like+ * `service_name ≠ x` beside `service_name = x`, and duplicate empty chips on a filtered attribute.+ *+ * - `merge`: the selection carries a complete filter (a recent), so reconcile it into the group+ * - `valueItem`: the Logs group's free-text item, whose filter the caller builds and records+ * - `focus`: this attribute already has an equality filter, so open it instead of adding another+ * - `new`: nothing on this attribute yet, so let the shared filter logic build it+ */+export function logsSelection(+ values: FilterEntry[],+ taxonomicGroup: TaxonomicFilterGroup,+ value: TaxonomicFilterValue,+ item: any+): LogsSelection {+ const recentFilter = hasRecentContext(item) ? item._recentContext.propertyFilter : undefined+ // Only a recent that carries something to apply merges. A recent without a value is the bare-key+ // row the picker derives from a complete one, and it falls through to the reuse path below. The+ // shared addGroupFilter pushes any filter a recent carries, so an incomplete one has to be caught+ // here or it lands as a second chip on an attribute that already has one.+ if (recentFilter && isCompleteRecentPropertyFilter(recentFilter)) {+ return { kind: 'merge', filter: recentFilter as FilterEntry }+ }+ if (item?.value !== undefined) {+ return { kind: 'valueItem' }+ }+ // A row the backend surfaced because the search matched a *value* carries it as `matchedValue`,+ // and the shared filter builder pre-fills it (createDefaultPropertyFilter). Without this it looks+ // like a bare key, and picking one while the attribute is already filtered would drop the value.+ const target = selectionTarget(taxonomicGroup, value, item)+ if (target && item?.matchedOn === 'value' && typeof item.matchedValue === 'string') {+ return {+ kind: 'merge',+ filter: {+ ...target,+ operator: PropertyOperator.Exact,+ value: [item.matchedValue],+ } as unknown as FilterEntry,+ }+ }+ // The applied filter's own target, not the one derived from the group: the bar matches chips by+ // target, and the derived type can disagree with the applied one (see reconcileTarget).+ const matched = appliedEqualityTarget(values, target)+ return matched ? { kind: 'focus', target: matched } : { kind: 'new' }+}diff --git a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.tsindex ae7c0252d63f..7d427ea68b98 100644--- a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts+++ b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts@@ -35,6 +35,7 @@ import {facetSelection,setFacetIncluded,} from 'products/logs/frontend/components/LogsViewer/FacetRail/facetFilters'+import { LogsFilterTarget } 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']@@ -153,6 +154,7 @@ export interface logsViewerFiltersLogicValues {dateRange: DateRangefilterGroup: UniversalFiltersGroupfilters: LogsViewerFilters+ focusedFilter: LogsFilterTarget | nullid: stringopenFilterOnInsert: booleanpersonId: string | undefined@@ -179,6 +181,9 @@ export interface logsViewerFiltersLogicActions {propertyType: PropertyFilterTypevalue: string}+ focusFilter: (target: LogsFilterTarget | null) => {+ target: FacetFilterTarget | null+ }setDateRange: (dateRange: DateRange) => {dateRange: DateRange}@@ -249,6 +254,8 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([// setting individual filterssetDateRange: (dateRange: DateRange) => ({ dateRange }),setSearchTerm: (searchTerm: LogsQuery['searchTerm']) => ({ searchTerm }),+ // Ask the chips bar to open the filter on this attribute for editing.+ focusFilter: (target: LogsFilterTarget | null) => ({ target }),setFilterGroup: (filterGroup: UniversalFiltersGroup, openFilterOnInsert: boolean = true) => ({filterGroup,openFilterOnInsert,@@ -316,6 +323,15 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([setFilterGroup: (_, { openFilterOnInsert }) => openFilterOnInsert,},],+ // The attribute whose chip the bar holds open, or null for none. Keyed on the attribute+ // rather than a position: filters come and go, and a stale index would open whichever+ // filter shifted into that slot.+ focusedFilter: [+ null as LogsFilterTarget | null,+ {+ focusFilter: (_, { target }) => target,+ },+ ],pinnedFilters: [undefined as UniversalFiltersGroup | undefined,{