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(replay): derive match-any operand from nested filter groups (#65388)

Tue Haulund26fcf66dd44b
diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
index 4697c9444380..f89811a031c1 100644
--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
@@ -77,6 +77,7 @@ import { sessionRecordingEventUsageLogic } from '../sessionRecordingEventUsageLo
import { CurrentFilterIndicator } from './CurrentFilterIndicator'
import { DurationFilter } from './DurationFilter'
import { ProductAnalyticsOverLimitBanner } from './ProductAnalyticsOverLimitBanner'
+import { deriveOperand } from './recordingsQueryConversions'
import { SavedFilters } from './SavedFilters'
function HideRecordingsMenu(): JSX.Element {
@@ -748,8 +749,18 @@ export const ReplayFiltersTab = ({
)}
<div className="flex items-center py-2 justify-between">
<AndOrFilterSelect
- value={filters.filter_group.type}
+ // Reflect the effective operand, not just the outer group: legacy saved filters can
+ // carry the match-any on the inner group while the outer stays AND. Toggling syncs
+ // both below, so interacting normalizes the structure.
+ value={deriveOperand(filters.filter_group)}
onChange={(type) => {
+ // Clicking the already-effective operand is a no-op — don't rewrite the
+ // group or mark the saved filter dirty just because the displayed value
+ // came from a legacy inner group.
+ if (type === deriveOperand(filters.filter_group)) {
+ return
+ }
+
let values = filters.filter_group.values
// set the type on the nested child when only using a single filter group
diff --git a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts
index 7dc4509ccc41..e10ecb516411 100644
--- a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts
+++ b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.test.ts
@@ -5,6 +5,7 @@ import {
LogEntryPropertyFilter,
PropertyFilterType,
PropertyOperator,
+ RecordingUniversalFilters,
} from '~/types'
import {
@@ -219,3 +220,28 @@ describe('convertUniversalFiltersToRecordingsQuery ∘ recordingsQueryToUniversa
expect(back.properties).toEqual([])
})
})
+
+describe('convertUniversalFiltersToRecordingsQuery operand derivation', () => {
+ const VISITED_PAGE: AnyPropertyFilter = {
+ type: PropertyFilterType.Recording,
+ key: 'visited_page',
+ value: '/cart',
+ operator: PropertyOperator.IContains,
+ }
+ const uf = (outer: FilterLogicalOperator, inner: FilterLogicalOperator): RecordingUniversalFilters =>
+ ({
+ date_from: '-3d',
+ date_to: null,
+ duration: [],
+ filter_test_accounts: false,
+ filter_group: { type: outer, values: [{ type: inner, values: [VISITED_PAGE] }] },
+ }) as RecordingUniversalFilters
+
+ it.each([
+ ['inner group only', FilterLogicalOperator.And, FilterLogicalOperator.Or, FilterLogicalOperator.Or],
+ ['no group', FilterLogicalOperator.And, FilterLogicalOperator.And, FilterLogicalOperator.And],
+ ['outer group only', FilterLogicalOperator.Or, FilterLogicalOperator.And, FilterLogicalOperator.Or],
+ ])('match-any on %s yields operand %s/%s -> %s', (_name, outer, inner, expected) => {
+ expect(convertUniversalFiltersToRecordingsQuery(uf(outer, inner)).operand).toBe(expected)
+ })
+})
diff --git a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
index 5de2aa8428fc..66158b1945fa 100644
--- a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
+++ b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
@@ -8,6 +8,7 @@ import {
isEventFilter,
isLogEntryPropertyFilter,
isRecordingPropertyFilter,
+ isUniversalGroupFilterLike,
} from 'lib/components/UniversalFilters/utils'
import { isString } from 'lib/utils/guards'
@@ -19,6 +20,7 @@ import {
PropertyOperator,
RecordingDurationFilter,
RecordingUniversalFilters,
+ UniversalFiltersGroup,
UniversalFiltersGroupValue,
} from '~/types'
@@ -28,6 +30,25 @@ export const DEFAULT_RECORDING_FILTERS_ORDER_BY = 'start_time'
const DURATION_KEYS = new Set(['duration', 'active_seconds', 'inactive_seconds'])
+/**
+ * `RecordingsQuery` carries a single `operand`, but the universal filter is a tree of AND/OR groups
+ * whose leaves we flatten. The "match any" toggle normally syncs the outer and inner group types, but
+ * the nested-group editor can set OR on the inner group while the outer stays AND. Reading only the
+ * outer group would then silently drop the user's "match any" intent. Treat the query as OR when any
+ * group in the tree is OR so that intent survives the flattening.
+ *
+ * Mirror: keep in sync with `_derive_operand` in posthog/session_recordings/playlist_filters.py.
+ */
+export function deriveOperand(group: UniversalFiltersGroup): FilterLogicalOperator {
+ if (group.type === FilterLogicalOperator.Or) {
+ return FilterLogicalOperator.Or
+ }
+ const hasOrDescendant = (group.values ?? []).some(
+ (value) => isUniversalGroupFilterLike(value) && deriveOperand(value) === FilterLogicalOperator.Or
+ )
+ return hasOrDescendant ? FilterLogicalOperator.Or : FilterLogicalOperator.And
+}
+
export function isValidRecordingOrder(order: unknown): boolean {
return !!order && isString(order) && VALID_RECORDING_ORDERS.includes(order as RecordingOrder)
}
@@ -135,7 +156,7 @@ export function convertUniversalFiltersToRecordingsQuery(universalFilters: Recor
having_predicates,
comment_text,
filter_test_accounts: universalFilters.filter_test_accounts,
- operand: universalFilters.filter_group.type,
+ operand: deriveOperand(universalFilters.filter_group),
limit: universalFilters.limit,
session_ids: universalFilters.session_ids,
}
diff --git a/posthog/session_recordings/playlist_filters.py b/posthog/session_recordings/playlist_filters.py
index b7c0cd27e1f7..61c41f4554a6 100644
--- a/posthog/session_recordings/playlist_filters.py
+++ b/posthog/session_recordings/playlist_filters.py
@@ -46,6 +46,44 @@ def asRecordingPropertyFilter(filter: dict[str, Any]) -> RecordingPropertyFilter
)
+def _flatten_filter_group_values(values: Optional[list[Any]]) -> list[dict[str, Any]]:
+ """Recursively flatten nested universal-filter groups into their leaf filters.
+
+ Mirrors the frontend's filtersFromUniversalFilterGroups — a single-level read misses
+ filters nested under inner groups (and saved filters do nest them).
+ """
+ leaves: list[dict[str, Any]] = []
+ for item in values or []:
+ if not isinstance(item, dict):
+ continue
+ if isinstance(item.get("values"), list):
+ leaves.extend(_flatten_filter_group_values(item["values"]))
+ else:
+ leaves.append(item)
+ return leaves
+
+
+def _derive_operand(filter_group: Optional[dict[str, Any]]) -> FilterLogicalOperator:
+ """Treat the query as OR when any group in the tree is OR.
+
+ The "match any" operand can sit on the inner group (set via the nested-group editor) while
+ the outer group stays AND. Reading only the outer group would silently drop that intent, so
+ mirror the frontend's deriveOperand and let OR anywhere in the tree win.
+ """
+ if not isinstance(filter_group, dict):
+ return FilterLogicalOperator.AND_
+ if filter_group.get("type") == FilterLogicalOperator.OR_:
+ return FilterLogicalOperator.OR_
+ if any(
+ isinstance(value, dict)
+ and isinstance(value.get("values"), list)
+ and _derive_operand(value) == FilterLogicalOperator.OR_
+ for value in filter_group.get("values") or []
+ ):
+ return FilterLogicalOperator.OR_
+ return FilterLogicalOperator.AND_
+
+
def convert_legacy_filters_to_universal_filters(filters: Optional[dict[str, Any]] = None) -> dict[str, Any]:
"""
Convert legacy filters to universal filters format.
@@ -150,19 +188,15 @@ def convert_filters_to_recordings_query(filters: dict[str, Any]) -> RecordingsQu
This is the Python equivalent of the frontend's convertUniversalFiltersToRecordingsQuery function.
"""
- # Extract filters from the filter group
- extracted_filters = []
- if filters.get("filter_group") and filters["filter_group"].get("values"):
- # Get the first group (which should be the only one)
- group = filters["filter_group"]["values"][0]
- if group and group.get("values"):
- extracted_filters = group["values"]
+ extracted_filters = _flatten_filter_group_values((filters.get("filter_group") or {}).get("values"))
- events = []
- actions = []
- properties = []
- console_log_filters = []
- having_predicates = []
+ # Heterogeneous builder lists — each holds raw filter dicts and/or RecordingPropertyFilter
+ # objects that RecordingsQuery accepts via its property-filter unions.
+ events: list[Any] = []
+ actions: list[Any] = []
+ properties: list[Any] = []
+ console_log_filters: list[Any] = []
+ having_predicates: list[Any] = []
# Get order and duration filter
order = filters.get("order")
@@ -184,21 +218,9 @@ def convert_filters_to_recordings_query(filters: dict[str, Any]) -> RecordingsQu
properties.append(f)
elif filter_type == "recording":
if f.get("key") == "visited_page":
- events.append(
- {
- "id": "$pageview",
- "name": "$pageview",
- "type": "events",
- "properties": [
- {
- "type": "event",
- "key": "$current_url",
- "value": f.get("value"),
- "operator": f.get("operator"),
- }
- ],
- }
- )
+ # A recording property filtered over the session's all_urls — matches the frontend
+ # converter and the list query, rather than a divergent $pageview/$current_url event.
+ properties.append(f)
elif f.get("key") == "snapshot_source" and f.get("value"):
having_predicates.append(f)
else:
@@ -219,7 +241,7 @@ def convert_filters_to_recordings_query(filters: dict[str, Any]) -> RecordingsQu
console_log_filters=console_log_filters,
having_predicates=having_predicates,
filter_test_accounts=filters.get("filter_test_accounts"),
- operand=filters.get("filter_group", {}).get("type", FilterLogicalOperator.AND_),
+ operand=_derive_operand(filters.get("filter_group")),
limit=filters.get("limit"),
)
except ValidationError as e:
@@ -235,6 +257,6 @@ def convert_filters_to_recordings_query(filters: dict[str, Any]) -> RecordingsQu
actions=actions,
console_log_filters=console_log_filters,
filter_test_accounts=filters.get("filter_test_accounts"),
- operand=filters.get("filter_group", {}).get("type", FilterLogicalOperator.AND_),
+ operand=_derive_operand(filters.get("filter_group")),
)
raise
diff --git a/posthog/session_recordings/test/test_playlist_filters.py b/posthog/session_recordings/test/test_playlist_filters.py
new file mode 100644
index 000000000000..858dff2bd56a
--- /dev/null
+++ b/posthog/session_recordings/test/test_playlist_filters.py
@@ -0,0 +1,70 @@
+from django.test.testcases import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.schema import FilterLogicalOperator, RecordingPropertyFilter
+
+from posthog.session_recordings.playlist_filters import convert_filters_to_recordings_query
+
+
+def _visited_page(value: str) -> dict:
+ return {"type": "recording", "key": "visited_page", "value": value, "operator": "icontains"}
+
+
+def _filters(outer_type: str, inner_type: str, values: list[dict]) -> dict:
+ return {
+ "date_from": "-30d",
+ "filter_test_accounts": False,
+ "filter_group": {"type": outer_type, "values": [{"type": inner_type, "values": values}]},
+ }
+
+
+class TestConvertFiltersToRecordingsQuery(SimpleTestCase):
+ @parameterized.expand(
+ [
+ # "match any" set on the inner group while the outer stays AND must still produce OR
+ ("inner_or", "AND", "OR", FilterLogicalOperator.OR_),
+ ("all_and", "AND", "AND", FilterLogicalOperator.AND_),
+ ("outer_or", "OR", "AND", FilterLogicalOperator.OR_),
+ ]
+ )
+ def test_operand_is_or_when_any_group_is_or(self, _name, outer, inner, expected):
+ query = convert_filters_to_recordings_query(_filters(outer, inner, [_visited_page("/cart")]))
+ assert query.operand == expected
+
+ def test_visited_page_becomes_recording_property_not_event(self):
+ filters = _filters("OR", "OR", [_visited_page("/cart"), _visited_page("/orders")])
+ query = convert_filters_to_recordings_query(filters)
+ assert query.events == []
+ props = query.properties or []
+ assert len(props) == 2
+ assert all(isinstance(p, RecordingPropertyFilter) and p.key == "visited_page" for p in props)
+
+ def test_nested_filters_are_flattened(self):
+ # Filters nested one extra level deep must still be extracted, not dropped
+ filters = {
+ "date_from": "-30d",
+ "filter_group": {
+ "type": "AND",
+ "values": [{"type": "OR", "values": [{"type": "AND", "values": [_visited_page("/cart")]}]}],
+ },
+ }
+ query = convert_filters_to_recordings_query(filters)
+ assert len(query.properties or []) == 1
+ assert query.operand == FilterLogicalOperator.OR_
+
+ @parameterized.expand(
+ [
+ ("or_three_levels_down", "OR", FilterLogicalOperator.OR_),
+ ("deep_all_and", "AND", FilterLogicalOperator.AND_),
+ ]
+ )
+ def test_operand_derivation_through_deep_nesting(self, _name, deepest_type, expected):
+ filters = {
+ "filter_group": {
+ "type": "AND",
+ "values": [{"type": "AND", "values": [{"type": deepest_type, "values": [_visited_page("/cart")]}]}],
+ },
+ }
+ query = convert_filters_to_recordings_query(filters)
+ assert query.operand == expected