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(error-tracking): respect OR/AND operator in issues list filters (#57057)

Catalin Irimie2d1d02427500
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 11ede7bcac72..32fb6733911d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2405,12 +2405,24 @@ importers:
'@storybook/react':
specifier: '*'
+ '@testing-library/jest-dom':
+ specifier: '*'
+ version: 5.17.0
+ '@testing-library/react':
+ specifier: '*'
+ '@testing-library/user-event':
+ specifier: '*'
+ version: 14.6.1(@testing-library/[email protected])
'@types/d3':
specifier: '*'
version: 7.4.3
'@types/react':
specifier: 18.3.27
version: 18.3.27
+ '@types/react-dom':
+ specifier: 18.3.7
+ version: 18.3.7(@types/[email protected])
clsx:
specifier: '*'
version: 1.2.1
@@ -2447,6 +2459,9 @@ importers:
react:
specifier: 18.3.1
version: 18.3.1
+ react-dom:
+ specifier: 18.3.1
+ version: 18.3.1([email protected])
ts-pattern:
specifier: '*'
version: 4.3.0
@@ -2456,6 +2471,10 @@ importers:
use-resize-observer:
specifier: '*'
+ devDependencies:
+ kea-test-utils:
+ specifier: 'catalog:'
products/event_definitions: {}
diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py
index bf3f6e522cdd..2a189b01a3b2 100644
--- a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py
@@ -49,7 +49,7 @@ class ErrorTrackingQueryRunner(AnalyticsQueryRunner[ErrorTrackingQueryResponse])
@cached_property
def _builder(self) -> ErrorTrackingQueryV1Builder | ErrorTrackingQueryV2Builder | ErrorTrackingQueryV3Builder:
if self.query.useQueryV3:
- return ErrorTrackingQueryV3Builder(self.query, self.date_from, self.date_to)
+ return ErrorTrackingQueryV3Builder(self.query, self.team, self.date_from, self.date_to)
if self.query.useQueryV2:
return ErrorTrackingQueryV2Builder(self.query, self.date_from, self.date_to)
return ErrorTrackingQueryV1Builder(self.query, self.team, self.date_from, self.date_to)
diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v1.py b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v1.py
index 81ef3100cef8..64dd00583e2e 100644
--- a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v1.py
+++ b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v1.py
@@ -1,9 +1,16 @@
import datetime
from typing import cast
-from posthog.schema import ErrorTrackingIssueFilter, ErrorTrackingQuery, HogQLFilters, PropertyGroupFilterValue
+from posthog.schema import (
+ ErrorTrackingIssueFilter,
+ ErrorTrackingQuery,
+ FilterLogicalOperator,
+ HogQLFilters,
+ PropertyGroupFilterValue,
+)
from posthog.hogql import ast
+from posthog.hogql.property import property_to_expr
from posthog.models.filters.mixins.utils import cached_property
from posthog.models.property.util import property_to_django_filter
@@ -38,7 +45,7 @@ class ErrorTrackingQueryV1Builder:
def hogql_filters(self) -> HogQLFilters:
return HogQLFilters(
filterTestAccounts=self.query.filterTestAccounts,
- properties=cast(list, self._hogql_properties),
+ properties=None if self._manual_hogql_property_expr is not None else cast(list, self._hogql_properties),
)
def process_results(self, columns: list[str], rows: list) -> list:
@@ -70,6 +77,8 @@ class ErrorTrackingQueryV1Builder:
@property
def _where(self) -> ast.And:
exprs = build_event_where_exprs(self.query, self.date_from, self.date_to)
+ if self._manual_hogql_property_expr is not None:
+ exprs.append(self._manual_hogql_property_expr)
# Prefetch issue IDs from Postgres to filter results by properties not available in CH.
# This is a stopgap — breaks at scale if the list grows too large.
@@ -144,3 +153,31 @@ class ErrorTrackingQueryV1Builder:
@cached_property
def _hogql_properties(self):
return [v for v in self._properties if not isinstance(v, (ErrorTrackingIssueFilter, PropertyGroupFilterValue))]
+
+ @cached_property
+ def _manual_hogql_property_expr(self) -> ast.Expr | None:
+ event_filter = self._event_filter_without_issue_filters()
+ if not isinstance(event_filter, PropertyGroupFilterValue):
+ return None
+ has_nested_group = any(isinstance(value, PropertyGroupFilterValue) for value in event_filter.values)
+ if event_filter.type != FilterLogicalOperator.OR_ and not has_nested_group:
+ return None
+ if len(event_filter.values) <= 1 and not has_nested_group:
+ return None
+ return property_to_expr(event_filter, self.team, scope="event")
+
+ def _event_filter_without_issue_filters(self) -> object | None:
+ if not self.query.filterGroup or not self.query.filterGroup.values:
+ return None
+ return self._without_issue_filters(self.query.filterGroup.values[0])
+
+ def _without_issue_filters(self, value: object) -> object | None:
+ if isinstance(value, ErrorTrackingIssueFilter):
+ return None
+ if not isinstance(value, PropertyGroupFilterValue):
+ return value
+
+ values = [filtered for child in value.values if (filtered := self._without_issue_filters(child)) is not None]
+ if not values:
+ return None
+ return value.model_copy(update={"values": values})
diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v3.py b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v3.py
index bc9065a1779d..1ff63285f30d 100644
--- a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v3.py
+++ b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v3.py
@@ -1,19 +1,21 @@
import datetime
-from typing import cast
+from typing import Any, cast
from django.core.exceptions import ValidationError
from posthog.schema import (
ErrorTrackingIssueFilter,
ErrorTrackingQuery,
+ FilterLogicalOperator,
HogQLFilters,
PropertyGroupFilterValue,
PropertyOperator,
)
from posthog.hogql import ast
+from posthog.hogql.property import property_to_expr
-from posthog.models.filters.mixins.utils import cached_property
+from posthog.models.team.team import Team
from products.error_tracking.backend.hogql_queries.error_tracking_query_runner_utils import (
extract_aggregations,
@@ -33,8 +35,9 @@ class ErrorTrackingQueryV3Builder:
This avoids Postgres and the old overrides table entirely.
"""
- def __init__(self, query: ErrorTrackingQuery, date_from: datetime.datetime, date_to: datetime.datetime):
+ def __init__(self, query: ErrorTrackingQuery, team: Team, date_from: datetime.datetime, date_to: datetime.datetime):
self.query = query
+ self.team = team
self.date_from = date_from
self.date_to = date_to
@@ -48,9 +51,11 @@ class ErrorTrackingQueryV3Builder:
)
def hogql_filters(self) -> HogQLFilters:
+ # User-supplied properties are handled directly in `_where_exprs` so the
+ # OR/AND operator on `filterGroup.values[0]` is respected. The `{filters}`
+ # placeholder is left in place to apply `filterTestAccounts` only.
return HogQLFilters(
filterTestAccounts=self.query.filterTestAccounts,
- properties=cast(list, self._hogql_properties),
)
def process_results(self, columns: list[str], rows: list) -> list:
@@ -335,10 +340,9 @@ class ErrorTrackingQueryV3Builder:
)
)
- for prop in self._issue_properties:
- expr = self._issue_property_to_ast(prop)
- if expr is not None:
- exprs.append(expr)
+ user_expr = self._user_filter_expr()
+ if user_expr is not None:
+ exprs.append(user_expr)
return exprs
@@ -351,17 +355,30 @@ class ErrorTrackingQueryV3Builder:
return {"id": str(role_id), "type": "role"}
return None
- @cached_property
- def _properties(self):
- return self.query.filterGroup.values[0].values if self.query.filterGroup else []
+ def _user_filter_expr(self) -> ast.Expr | None:
+ """Build a single AST expression for user-supplied filters from `filterGroup`,
+ preserving nested OR/AND groups while routing issue-level filters to the
+ denormalized issue fields.
+ """
+ if not self.query.filterGroup or not self.query.filterGroup.values:
+ return None
+ return self._filter_value_to_ast(self.query.filterGroup.values[0])
+
+ def _filter_value_to_ast(self, value: object) -> ast.Expr | None:
+ if isinstance(value, ErrorTrackingIssueFilter):
+ return self._issue_property_to_ast(value)
- @cached_property
- def _issue_properties(self) -> list[ErrorTrackingIssueFilter]:
- return [v for v in self._properties if isinstance(v, ErrorTrackingIssueFilter)]
+ if isinstance(value, PropertyGroupFilterValue):
+ sub_exprs = [expr for child in value.values if (expr := self._filter_value_to_ast(child)) is not None]
+ if not sub_exprs:
+ return None
+ if len(sub_exprs) == 1:
+ return sub_exprs[0]
+ if value.type == FilterLogicalOperator.OR_:
+ return ast.Or(exprs=sub_exprs)
+ return ast.And(exprs=sub_exprs)
- @cached_property
- def _hogql_properties(self):
- return [v for v in self._properties if not isinstance(v, ErrorTrackingIssueFilter | PropertyGroupFilterValue)]
+ return property_to_expr(cast(Any, value), self.team, scope="event")
def _issue_property_to_ast(self, prop: ErrorTrackingIssueFilter) -> ast.Expr | None:
key = "description" if prop.key == "issue_description" else prop.key
diff --git a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v3.ambr b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v3.ambr
index 295fc618bf21..16acbe996402 100644
--- a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v3.ambr
+++ b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v3.ambr
@@ -469,7 +469,7 @@
WHERE equals(person.team_id, 99999)
GROUP BY person.id
HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), equals(e.event, '$exception'), isNotNull(e__fingerprint_issue_state.issue_id), ifNull(equals(e__person.properties___email, '[email protected]'), 0), greaterOrEquals(e.timestamp, toDateTime(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), 'UTC')), lessOrEquals(e.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')))
+ WHERE and(equals(e.team_id, 99999), equals(e.event, '$exception'), isNotNull(e__fingerprint_issue_state.issue_id), greaterOrEquals(e.timestamp, toDateTime(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), 'UTC')), lessOrEquals(e.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')), ifNull(equals(e__person.properties___email, '[email protected]'), 0))
GROUP BY id
ORDER BY last_seen DESC
LIMIT 101
diff --git a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
index 3a5de8a08857..4faa802523b9 100644
--- a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner.py
@@ -22,6 +22,7 @@ from posthog.schema import (
DateRange,
ErrorTrackingIssueFilter,
ErrorTrackingQuery,
+ EventPropertyFilter,
FilterLogicalOperator,
PersonPropertyFilter,
PropertyGroupFilter,
@@ -739,6 +740,52 @@ class TestErrorTrackingQueryRunner(ErrorTrackingQueryRunnerTestsMixin, Clickhous
__test__ = True
use_v2 = False
+ @freeze_time("2022-01-10T12:11:00")
+ def test_event_filter_group_operator(self):
+ firefox_issue_id = "01936e80-aa51-746f-aec4-cdf16a5c5333"
+ chrome_issue_id = "01936e80-aa51-746f-aec4-cdf16a5c5334"
+ safari_issue_id = "01936e80-aa51-746f-aec4-cdf16a5c5335"
+ self.create_events_and_issue(
+ issue_id=firefox_issue_id,
+ fingerprint="firefox_issue_fingerprint",
+ distinct_ids=[self.distinct_id_one],
+ additional_properties={"$browser": "Firefox"},
+ )
+ self.create_events_and_issue(
+ issue_id=chrome_issue_id,
+ fingerprint="chrome_issue_fingerprint",
+ distinct_ids=[self.distinct_id_one],
+ additional_properties={"$browser": "Chrome"},
+ )
+ self.create_events_and_issue(
+ issue_id=safari_issue_id,
+ fingerprint="safari_issue_fingerprint",
+ distinct_ids=[self.distinct_id_one],
+ additional_properties={"$browser": "Safari"},
+ )
+ flush_persons_and_events()
+
+ browser_filters = [
+ EventPropertyFilter(key="$browser", value=["Firefox"], operator=PropertyOperator.EXACT),
+ EventPropertyFilter(key="$browser", value=["Chrome"], operator=PropertyOperator.EXACT),
+ ]
+
+ or_results = self._calculate(
+ filterGroup=PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[PropertyGroupFilterValue(type=FilterLogicalOperator.OR_, values=browser_filters)],
+ )
+ )["results"]
+ self.assertEqual({result["id"] for result in or_results}, {firefox_issue_id, chrome_issue_id})
+
+ and_results = self._calculate(
+ filterGroup=PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[PropertyGroupFilterValue(type=FilterLogicalOperator.AND_, values=browser_filters)],
+ )
+ )["results"]
+ self.assertEqual([result["id"] for result in and_results], [])
+
class TestSearchTokenizer(TestCase):
test_cases = [
diff --git a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner_v3.py b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner_v3.py
index 49ff8a6933eb..275ec3f832be 100644
--- a/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner_v3.py
+++ b/products/error_tracking/backend/hogql_queries/test/test_error_tracking_query_runner_v3.py
@@ -1,8 +1,22 @@
+from datetime import UTC, datetime
+
from freezegun import freeze_time
from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTestKeepIdentities, flush_persons_and_events
from parameterized import parameterized
+from posthog.schema import (
+ DateRange,
+ ErrorTrackingIssueFilter,
+ ErrorTrackingQuery,
+ EventPropertyFilter,
+ FilterLogicalOperator,
+ PropertyGroupFilter,
+ PropertyGroupFilterValue,
+ PropertyOperator,
+)
+
+from products.error_tracking.backend.hogql_queries.error_tracking_query_runner_v3 import ErrorTrackingQueryV3Builder
from products.error_tracking.backend.hogql_queries.test.test_error_tracking_query_runner import (
ErrorTrackingQueryRunnerTestsMixin,
)
@@ -126,6 +140,100 @@ class TestErrorTrackingQueryRunnerV3(
results = self._calculate(assignee={"type": "role", "id": str(role.id)})["results"]
self.assertEqual([x["id"] for x in results], [issue_id])
+ @parameterized.expand(
+ [
+ (
+ "or_returns_union",
+ FilterLogicalOperator.OR_,
+ # issue_one (TypeError) and issue_two (ReferenceError) both match
+ [True, True, False],
+ ),
+ (
+ "and_returns_intersection",
+ FilterLogicalOperator.AND_,
+ # No issue has both names — AND yields empty
+ [False, False, False],
+ ),
+ ]
+ )
+ @freeze_time("2022-01-10T12:11:00")
+ def test_filter_group_operator(self, _name, operator: FilterLogicalOperator, expected_membership: list[bool]):
+ results = self._calculate(
+ filterGroup=PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=operator,
+ values=[
+ ErrorTrackingIssueFilter(
+ key="name", value=[self.issue_name_one], operator=PropertyOperator.EXACT
+ ),
+ ErrorTrackingIssueFilter(
+ key="name", value=[self.issue_name_two], operator=PropertyOperator.EXACT
+ ),
+ ],
+ )
+ ],
+ )
+ )["results"]
+ result_ids = {r["id"] for r in results}
+ expected_ids = {
+ issue_id
+ for issue_id, included in zip(
+ [self.issue_id_one, self.issue_id_two, self.issue_id_three], expected_membership
+ )
+ if included
+ }
+ self.assertEqual(result_ids, expected_ids)
+
+ @freeze_time("2022-01-10T12:11:00")
+ def test_nested_filter_group_routes_issue_filters_to_issue_fields(self):
+ filter_group = PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.OR_,
+ values=[
+ EventPropertyFilter(key="$browser", value=["Firefox"], operator=PropertyOperator.EXACT),
+ EventPropertyFilter(key="$browser", value=["Chrome"], operator=PropertyOperator.EXACT),
+ ErrorTrackingIssueFilter(
+ key="name", value=[self.issue_name_one], operator=PropertyOperator.EXACT
+ ),
+ ],
+ ),
+ EventPropertyFilter(
+ key="$exception_issue_id", value=[self.issue_id_one], operator=PropertyOperator.EXACT
+ ),
+ ],
+ )
+ ],
+ )
+
+ builder = ErrorTrackingQueryV3Builder(
+ query=ErrorTrackingQuery(
+ kind="ErrorTrackingQuery",
+ dateRange=DateRange(date_from="-7d"),
+ filterGroup=filter_group,
+ orderBy="last_seen",
+ volumeResolution=1,
+ useQueryV3=True,
+ ),
+ team=self.team,
+ date_from=datetime(2022, 1, 3, tzinfo=UTC),
+ date_to=datetime(2022, 1, 10, tzinfo=UTC),
+ )
+ user_filter_expr = builder._user_filter_expr()
+ assert user_filter_expr is not None
+ user_filter_hogql = user_filter_expr.to_hogql()
+ self.assertIn("e.issue_name", user_filter_hogql)
+ self.assertNotIn("properties.name", user_filter_hogql)
+
+ results = self._calculate(filterGroup=filter_group)["results"]
+ self.assertEqual([r["id"] for r in results], [self.issue_id_one])
+
@freeze_time("2022-01-10T12:11:00")
def test_status(self):
from products.error_tracking.backend.models import ErrorTrackingIssue
diff --git a/products/error_tracking/frontend/components/IssueFilters/FilterGroup.test.tsx b/products/error_tracking/frontend/components/IssueFilters/FilterGroup.test.tsx
new file mode 100644
index 000000000000..ceebe6985836
--- /dev/null
+++ b/products/error_tracking/frontend/components/IssueFilters/FilterGroup.test.tsx
@@ -0,0 +1,79 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { BindLogic, Provider } from 'kea'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import {
+ EventPropertyFilter,
+ FilterLogicalOperator,
+ PropertyFilterType,
+ PropertyOperator,
+ UniversalFiltersGroup,
+} from '~/types'
+
+import { FilterGroup } from './FilterGroup'
+import { issueFiltersLogic } from './issueFiltersLogic'
+
+jest.mock('lib/components/PropertyFilters/components/PropertyFilterIcon', () => ({
+ PropertyFilterIcon: (): JSX.Element => <span />,
+}))
+
+const LOGIC_KEY = 'test'
+
+const firefoxFilter: EventPropertyFilter = {
+ type: PropertyFilterType.Event,
+ key: '$browser',
+ operator: PropertyOperator.Exact,
+ value: ['Firefox'],
+}
+
+const chromeFilter: EventPropertyFilter = {
+ type: PropertyFilterType.Event,
+ key: '$browser',
+ operator: PropertyOperator.Exact,
+ value: ['Chrome'],
+}
+
+describe('FilterGroup', () => {
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/quick_filters/': { results: [] },
+ },
+ })
+ initKeaTests()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('shows and updates the operator for OR filter groups', async () => {
+ const logic = issueFiltersLogic({ logicKey: LOGIC_KEY })
+ logic.mount()
+ logic.actions.setFilterGroup({
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.Or, values: [firefoxFilter, chromeFilter] }],
+ })
+
+ render(
+ <Provider>
+ <BindLogic logic={issueFiltersLogic} props={{ logicKey: LOGIC_KEY }}>
+ <FilterGroup />
+ </BindLogic>
+ </Provider>
+ )
+
+ expect(screen.getByText('Any')).toBeInTheDocument()
+
+ await userEvent.click(screen.getByText('All'))
+
+ const inner = logic.values.filterGroup.values[0] as UniversalFiltersGroup
+ expect(inner.type).toBe(FilterLogicalOperator.And)
+
+ logic.unmount()
+ })
+})
diff --git a/products/error_tracking/frontend/components/IssueFilters/FilterGroup.tsx b/products/error_tracking/frontend/components/IssueFilters/FilterGroup.tsx
index 80d8bec789c6..9640302de202 100644
--- a/products/error_tracking/frontend/components/IssueFilters/FilterGroup.tsx
+++ b/products/error_tracking/frontend/components/IssueFilters/FilterGroup.tsx
@@ -2,7 +2,7 @@ import { BindLogic, useActions, useValues } from 'kea'
import { useRef, useState } from 'react'
import { useDebouncedCallback } from 'use-debounce'
-import { LemonDropdown } from '@posthog/lemon-ui'
+import { LemonDropdown, LemonSegmentedButton } from '@posthog/lemon-ui'
import { InfiniteSelectResults } from 'lib/components/TaxonomicFilter/InfiniteSelectResults'
import { TaxonomicFilterSearchInput } from 'lib/components/TaxonomicFilter/TaxonomicFilter'
@@ -13,7 +13,7 @@ import { universalFiltersLogic } from 'lib/components/UniversalFilters/universal
import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
-import { FilterLogicalOperator, PropertyFilterType, UniversalFiltersGroup } from '~/types'
+import { FilterLogicalOperator, PropertyFilterType, UniversalFiltersGroup, UniversalFiltersGroupValue } from '~/types'
import { TAXONOMIC_FILTER_LOGIC_KEY, TAXONOMIC_GROUP_TYPES } from './consts'
import { issueFiltersLogic } from './issueFiltersLogic'
@@ -83,37 +83,76 @@ const UniversalSearch = ({
return (
<BindLogic logic={taxonomicFilterLogic} props={taxonomicFilterLogicProps}>
- <LemonDropdown
- overlay={
- <div className="w-[400px] md:w-[600px]">
- <InfiniteSelectResults
- focusInput={() => searchInputRef.current?.focus()}
- taxonomicFilterLogicProps={taxonomicFilterLogicProps}
- popupAnchorElement={floatingRef.current}
+ <div className="flex w-full min-w-0 items-center gap-1">
+ <FilterOperatorToggle />
+ <div className="min-w-0 flex-1">
+ <LemonDropdown
+ overlay={
+ <div className="w-[400px] md:w-[600px]">
+ <InfiniteSelectResults
+ focusInput={() => searchInputRef.current?.focus()}
+ taxonomicFilterLogicProps={taxonomicFilterLogicProps}
+ popupAnchorElement={floatingRef.current}
+ />
+ </div>
+ }
+ visible={visible}
+ closeOnClickInside={false}
+ floatingRef={floatingRef}
+ onClickOutside={() => onClose()}
+ >
+ <TaxonomicFilterSearchInput
+ prefix={<UniversalFilterGroup taxonomicGroupTypes={taxonomicGroupTypes} />}
+ onClick={() => setVisible(true)}
+ searchInputRef={searchInputRef}
+ onClose={() => onClose()}
+ onChange={onChange}
+ size="small"
+ autoFocus={false}
+ fullWidth
+ placeholder="Add a filter or search..."
/>
- </div>
- }
- visible={visible}
- closeOnClickInside={false}
- floatingRef={floatingRef}
- onClickOutside={() => onClose()}
- >
- <TaxonomicFilterSearchInput
- prefix={<UniversalFilterGroup taxonomicGroupTypes={taxonomicGroupTypes} />}
- onClick={() => setVisible(true)}
- searchInputRef={searchInputRef}
- onClose={() => onClose()}
- onChange={onChange}
- size="small"
- autoFocus={false}
- fullWidth
- placeholder="Add a filter or search..."
- />
- </LemonDropdown>
+ </LemonDropdown>
+ </div>
+ </div>
</BindLogic>
)
}
+const FILTER_LOGICAL_OPERATOR_OPTIONS = [
+ {
+ value: FilterLogicalOperator.And,
+ label: 'All',
+ tooltip: 'Match all filters',
+ },
+ {
+ value: FilterLogicalOperator.Or,
+ label: 'Any',
+ tooltip: 'Match any filter',
+ },
+]
+
+const FilterOperatorToggle = (): JSX.Element | null => {
+ const { filterGroup } = useValues(universalFiltersLogic)
+ const { setGroupType } = useActions(universalFiltersLogic)
+ const showOperatorToggle = filterGroup.values.length > 1 || filterGroup.type === FilterLogicalOperator.Or
+
+ if (!showOperatorToggle) {
+ return null
+ }
+
+ return (
+ <div className="shrink-0">
+ <LemonSegmentedButton
+ value={filterGroup.type}
+ onChange={(type) => setGroupType(type)}
+ options={FILTER_LOGICAL_OPERATOR_OPTIONS}
+ size="xsmall"
+ />
+ </div>
+ )
+}
+
const UniversalFilterGroup = ({
taxonomicGroupTypes = TAXONOMIC_GROUP_TYPES,
}: {
@@ -127,7 +166,7 @@ const UniversalFilterGroup = ({
return (
<>
- {filterGroup.values.map((filterOrGroup, index) => {
+ {filterGroup.values.map((filterOrGroup: UniversalFiltersGroupValue, index: number) => {
return isUniversalGroupFilterLike(filterOrGroup) ? (
<UniversalFilters.Group index={index} key={index} group={filterOrGroup}>
<UniversalSearch taxonomicGroupTypes={taxonomicGroupTypes} />
diff --git a/products/error_tracking/frontend/components/IssueFilters/issueFiltersLogic.test.ts b/products/error_tracking/frontend/components/IssueFilters/issueFiltersLogic.test.ts
new file mode 100644
index 000000000000..3bb2413f3865
--- /dev/null
+++ b/products/error_tracking/frontend/components/IssueFilters/issueFiltersLogic.test.ts
@@ -0,0 +1,173 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { quickFiltersLogic } from 'lib/components/QuickFilters'
+import { quickFiltersSectionLogic } from 'lib/components/QuickFilters/quickFiltersSectionLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { QuickFilterContext } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import {
+ EventPropertyFilter,
+ FilterLogicalOperator,
+ PropertyFilterType,
+ PropertyOperator,
+ QuickFilter,
+ UniversalFiltersGroup,
+} from '~/types'
+
+import { issueFiltersLogic } from './issueFiltersLogic'
+
+const LOGIC_KEY = 'test'
+
+const mockEnvFilter: QuickFilter = {
+ id: 'filter-env',
+ name: 'Environment',
+ property_name: '$environment',
+ type: 'manual-options',
+ options: [{ id: 'opt-prod', value: 'production', label: 'Production', operator: PropertyOperator.Exact }],
+ contexts: [QuickFilterContext.ErrorTrackingIssueFilters],
+ created_at: '2024-01-01',
+ updated_at: '2024-01-01',
+}
+
+describe('issueFiltersLogic', () => {
+ let logic: ReturnType<typeof issueFiltersLogic.build>
+ let quickFiltersSection: ReturnType<typeof quickFiltersSectionLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/quick_filters/': { results: [mockEnvFilter] },
+ },
+ })
+ initKeaTests()
+ logic = issueFiltersLogic({ logicKey: LOGIC_KEY })
+ logic.mount()
+ quickFiltersLogic({ context: QuickFilterContext.ErrorTrackingIssueFilters }).mount()
+ quickFiltersSection = quickFiltersSectionLogic({
+ context: QuickFilterContext.ErrorTrackingIssueFilters,
+ logicKey: LOGIC_KEY,
+ })
+ quickFiltersSection.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ quickFiltersSection.unmount()
+ })
+
+ describe('mergedFilterGroup', () => {
+ const propA: EventPropertyFilter = {
+ type: PropertyFilterType.Event,
+ key: '$browser',
+ operator: PropertyOperator.Exact,
+ value: ['Chrome'],
+ }
+ const propB: EventPropertyFilter = {
+ type: PropertyFilterType.Event,
+ key: '$os',
+ operator: PropertyOperator.Exact,
+ value: ['Linux'],
+ }
+
+ it('preserves OR operator from filterGroup when no quick filters are selected', async () => {
+ const filterGroup: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.Or, values: [propA, propB] }],
+ }
+
+ await expectLogic(logic, () => {
+ logic.actions.setFilterGroup(filterGroup)
+ }).toFinishAllListeners()
+
+ const merged = logic.values.mergedFilterGroup
+ const inner = merged.values[0] as UniversalFiltersGroup
+ expect(inner.type).toBe(FilterLogicalOperator.Or)
+ expect(inner.values).toEqual([propA, propB])
+ })
+
+ it('preserves AND operator from filterGroup when no quick filters are selected', async () => {
+ const filterGroup: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: [propA, propB] }],
+ }
+
+ await expectLogic(logic, () => {
+ logic.actions.setFilterGroup(filterGroup)
+ }).toFinishAllListeners()
+
+ const merged = logic.values.mergedFilterGroup
+ const inner = merged.values[0] as UniversalFiltersGroup
+ expect(inner.type).toBe(FilterLogicalOperator.And)
+ expect(inner.values).toEqual([propA, propB])
+ })
+
+ it('falls back to AND when filterGroup has no inner values', async () => {
+ const merged = logic.values.mergedFilterGroup
+ const inner = merged.values[0] as UniversalFiltersGroup
+ expect(inner.type).toBe(FilterLogicalOperator.And)
+ expect(inner.values).toEqual([])
+ })
+
+ it('nests OR omnisearch group when quick filters are also selected', async () => {
+ const filterGroup: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.Or, values: [propA, propB] }],
+ }
+
+ await expectLogic(logic, () => {
+ logic.actions.setFilterGroup(filterGroup)
+ quickFiltersSection.actions.setQuickFilterValue(
+ mockEnvFilter.id,
+ mockEnvFilter.property_name,
+ mockEnvFilter.options[0]
+ )
+ }).toFinishAllListeners()
+
+ const merged = logic.values.mergedFilterGroup
+ const inner = merged.values[0] as UniversalFiltersGroup
+ // Outer-inner stays AND so the OR group AND's with the quick filter.
+ expect(inner.type).toBe(FilterLogicalOperator.And)
+ const nestedOr = inner.values[0] as UniversalFiltersGroup
+ expect(nestedOr.type).toBe(FilterLogicalOperator.Or)
+ expect(nestedOr.values).toEqual([propA, propB])
+ expect(inner.values.slice(1)).toEqual([
+ {
+ type: PropertyFilterType.Event,
+ key: mockEnvFilter.property_name,
+ operator: PropertyOperator.Exact,
+ value: ['production'],
+ },
+ ])
+ })
+
+ it('flattens AND omnisearch with quick filters into a single AND list', async () => {
+ const filterGroup: UniversalFiltersGroup = {
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: [propA] }],
+ }
+
+ await expectLogic(logic, () => {
+ logic.actions.setFilterGroup(filterGroup)
+ quickFiltersSection.actions.setQuickFilterValue(
+ mockEnvFilter.id,
+ mockEnvFilter.property_name,
+ mockEnvFilter.options[0]
+ )
+ }).toFinishAllListeners()
+
+ const merged = logic.values.mergedFilterGroup
+ const inner = merged.values[0] as UniversalFiltersGroup
+ expect(inner.type).toBe(FilterLogicalOperator.And)
+ expect(inner.values).toEqual([
+ propA,
+ {
+ type: PropertyFilterType.Event,
+ key: mockEnvFilter.property_name,
+ operator: PropertyOperator.Exact,
+ value: ['production'],
+ },
+ ])
+ })
+ })
+})
diff --git a/products/error_tracking/frontend/components/IssueFilters/issueFiltersLogic.ts b/products/error_tracking/frontend/components/IssueFilters/issueFiltersLogic.ts
index 97b1bd8661ee..6cf090085ee4 100644
--- a/products/error_tracking/frontend/components/IssueFilters/issueFiltersLogic.ts
+++ b/products/error_tracking/frontend/components/IssueFilters/issueFiltersLogic.ts
@@ -88,6 +88,7 @@ export const issueFiltersLogic = kea<issueFiltersLogicType>([
selectedQuickFilters: Record<string, SelectedQuickFilter>
): UniversalFiltersGroup => {
let omnisearchFilters: any[] = []
+ let omnisearchType: FilterLogicalOperator = FilterLogicalOperator.And
if (
!!filterGroup.values &&
Array.isArray(filterGroup.values) &&
@@ -95,6 +96,7 @@ export const issueFiltersLogic = kea<issueFiltersLogicType>([
isUniversalGroupFilterLike(filterGroup.values[0])
) {
omnisearchFilters = filterGroup.values[0].values
+ omnisearchType = filterGroup.values[0].type ?? FilterLogicalOperator.And
}
const filtersFromQuickFilters = Object.values(selectedQuickFilters).map((qf: SelectedQuickFilter) => {
@@ -108,12 +110,26 @@ export const issueFiltersLogic = kea<issueFiltersLogicType>([
}
})
+ // Quick filters always AND with the user's omnisearch group. When the user picked OR
+ // and there are quick filters, nest the omnisearch group so its OR is preserved while
+ // ANDing with the quick filters.
+ const shouldNestOmnisearch =
+ omnisearchType === FilterLogicalOperator.Or &&
+ omnisearchFilters.length > 1 &&
+ filtersFromQuickFilters.length > 0
+
+ const innerValues = shouldNestOmnisearch
+ ? [{ type: FilterLogicalOperator.Or, values: omnisearchFilters }, ...filtersFromQuickFilters]
+ : [...omnisearchFilters, ...filtersFromQuickFilters]
+
+ const innerType = filtersFromQuickFilters.length === 0 ? omnisearchType : FilterLogicalOperator.And
+
return {
type: FilterLogicalOperator.And,
values: [
{
- type: FilterLogicalOperator.And,
- values: [...omnisearchFilters, ...filtersFromQuickFilters],
+ type: innerType,
+ values: innerValues,
},
],
} as UniversalFiltersGroup
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.test.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.test.ts
new file mode 100644
index 000000000000..49678995113a
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.test.ts
@@ -0,0 +1,106 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import {
+ ErrorTrackingIssueFilter,
+ EventPropertyFilter,
+ FilterLogicalOperator,
+ PropertyFilterType,
+ PropertyOperator,
+ UniversalFiltersGroup,
+} from '~/types'
+
+import { issueFiltersLogic } from '../../../../components/IssueFilters/issueFiltersLogic'
+import { ERROR_TRACKING_SCENE_LOGIC_KEY } from '../../errorTrackingSceneLogic'
+import { errorTrackingInsightsLogic } from './errorTrackingInsightsLogic'
+
+describe('errorTrackingInsightsLogic', () => {
+ let issueFilters: ReturnType<typeof issueFiltersLogic.build>
+ let insights: ReturnType<typeof errorTrackingInsightsLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/environments/:team_id/quick_filters/': { results: [] },
+ },
+ })
+ initKeaTests()
+ jest.spyOn(api, 'query').mockResolvedValue({ results: [[0, 0, 0, 0]] } as any)
+ issueFilters = issueFiltersLogic({ logicKey: ERROR_TRACKING_SCENE_LOGIC_KEY })
+ issueFilters.mount()
+ insights = errorTrackingInsightsLogic()
+ insights.mount()
+ })
+
+ afterEach(() => {
+ insights.unmount()
+ issueFilters.unmount()
+ jest.restoreAllMocks()
+ })
+
+ it('strips issue filters from nested groups before building insights queries', async () => {
+ const firefoxFilter: EventPropertyFilter = {
+ type: PropertyFilterType.Event,
+ key: '$browser',
+ operator: PropertyOperator.Exact,
+ value: ['Firefox'],
+ }
+ const chromeFilter: EventPropertyFilter = {
+ type: PropertyFilterType.Event,
+ key: '$browser',
+ operator: PropertyOperator.Exact,
+ value: ['Chrome'],
+ }
+ const issueFilter: ErrorTrackingIssueFilter = {
+ type: PropertyFilterType.ErrorTrackingIssue,
+ key: 'name',
+ operator: PropertyOperator.Exact,
+ value: ['TypeError'],
+ }
+ const quickFilter: EventPropertyFilter = {
+ type: PropertyFilterType.Event,
+ key: '$lib',
+ operator: PropertyOperator.Exact,
+ value: ['posthog-js'],
+ }
+
+ await expectLogic(insights, () => {
+ issueFilters.actions.setFilterGroup({
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.Or,
+ values: [firefoxFilter, issueFilter, chromeFilter],
+ },
+ quickFilter,
+ ],
+ },
+ ],
+ })
+ }).toFinishAllListeners()
+
+ const inner = insights.values.insightsFilterGroup.values[0] as UniversalFiltersGroup
+ expect(inner.values).toEqual([
+ {
+ type: FilterLogicalOperator.Or,
+ values: [firefoxFilter, chromeFilter],
+ },
+ quickFilter,
+ ])
+ expect(JSON.stringify(insights.values.exceptionVolumeQuery)).not.toContain(
+ PropertyFilterType.ErrorTrackingIssue
+ )
+
+ const lastSummaryStatsQuery = jest.mocked(api.query).mock.calls.at(-1)?.[0] as any
+ expect(lastSummaryStatsQuery.filters.properties).toEqual(inner.values)
+ expect(JSON.stringify(lastSummaryStatsQuery.filters.properties)).not.toContain(
+ PropertyFilterType.ErrorTrackingIssue
+ )
+ })
+})
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.ts
index a1cf0919d6ee..5fba59bddec9 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/insights/errorTrackingInsightsLogic.ts
@@ -4,9 +4,16 @@ import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
import api from 'lib/api'
+import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utils'
import { HogQLQueryResponse, InsightVizNode, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
-import { AnyPropertyFilter, FilterLogicalOperator, PropertyFilterType, UniversalFiltersGroup } from '~/types'
+import {
+ AnyPropertyFilter,
+ FilterLogicalOperator,
+ PropertyFilterType,
+ UniversalFiltersGroup,
+ UniversalFiltersGroupValue,
+} from '~/types'
import { issueFiltersLogic } from '../../../../components/IssueFilters/issueFiltersLogic'
import { ERROR_TRACKING_SCENE_LOGIC_KEY } from '../../errorTrackingSceneLogic'
@@ -26,6 +33,25 @@ export interface InsightsSummaryStats {
crashFreeRate: number
}
+function stripIssueFiltersFromGroup(group: UniversalFiltersGroup): UniversalFiltersGroup {
+ const values = group.values.reduce<UniversalFiltersGroupValue[]>((strippedValues, filter) => {
+ if (isUniversalGroupFilterLike(filter)) {
+ const strippedGroup = stripIssueFiltersFromGroup(filter)
+ if (strippedGroup.values.length > 0) {
+ strippedValues.push(strippedGroup)
+ }
+ return strippedValues
+ }
+
+ if (filter.type !== PropertyFilterType.ErrorTrackingIssue) {
+ strippedValues.push(filter)
+ }
+ return strippedValues
+ }, [])
+
+ return { ...group, values }
+}
+
export const errorTrackingInsightsLogic = kea<errorTrackingInsightsLogicType>([
path([
'products',
@@ -55,12 +81,7 @@ export const errorTrackingInsightsLogic = kea<errorTrackingInsightsLogicType>([
const inner = mergedFilterGroup.values[0] as UniversalFiltersGroup
return {
type: FilterLogicalOperator.And,
- values: [
- {
- ...inner,
- values: inner.values.filter((f: any) => f.type !== PropertyFilterType.ErrorTrackingIssue),
- },
- ],
+ values: [stripIssueFiltersFromGroup(inner)],
} as UniversalFiltersGroup
},
],
diff --git a/products/error_tracking/package.json b/products/error_tracking/package.json
index 3afaa519892d..887f5583fc06 100644
--- a/products/error_tracking/package.json
+++ b/products/error_tracking/package.json
@@ -11,6 +11,9 @@
"kea-subscriptions": "catalog:",
"posthog-js": "catalog:"
},
+ "devDependencies": {
+ "kea-test-utils": "catalog:"
+ },
"peerDependencies": {
"@dnd-kit/core": "*",
"@dnd-kit/modifiers": "*",
@@ -19,14 +22,19 @@
"@posthog/icons": "*",
"@storybook/addon-actions": "*",
"@storybook/react": "*",
+ "@testing-library/jest-dom": "*",
+ "@testing-library/react": "*",
+ "@testing-library/user-event": "*",
"@types/d3": "*",
"@types/react": "*",
+ "@types/react-dom": "*",
"clsx": "*",
"cva": "1.0.0-beta.3",
"d3": "*",
"fast-deep-equal": "*",
"fuse.js": "*",
"react": "*",
+ "react-dom": "*",
"ts-pattern": "*",
"use-debounce": "*",
"use-resize-observer": "*"