: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(replay): return matching events when several event filters are ANDed (#76371)
Marcel Poelker0e54823f92af
diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.pyindex b7466b622572..49888d456ff4 100644--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py@@ -406,18 +406,28 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):return sessions_query- def _get_queries_for_matching(self, select_expr: ast.Expr, group_by: list[ast.Expr]) -> list[ast.SelectQuery]:+ def _get_queries_for_matching(+ self, select_expr: ast.Expr, group_by: list[ast.Expr], union_entities: bool = False+ ) -> list[ast.SelectQuery]:"""takes each filter in the query that can be queried from the events tableand makes a separate query for eachthis might be slower than the previous approach of having one huge event querybut that approach is horribly complex, and we keep getting bug reportsthat are avoidable with a simpler approach++ `union_entities` merges the event/action filters into a single subquery, for callers that+ intersect the subqueries by event id rather than by session id (see+ `get_query_for_event_id_matching`)."""gathered_exprs: list[ast.Expr] = []event_where_exprs = self._event_predicates(self.entities, self._team)if event_where_exprs:- gathered_exprs += event_where_exprs+ gathered_exprs += (+ [ast.Or(exprs=event_where_exprs)]+ if union_entities and len(event_where_exprs) > 1+ else event_where_exprs+ )# Skip event properties with negative operators since they're handled by _negative_guard_queryskip_negative_properties = self._query.operand == "AND"@@ -511,11 +521,21 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):return self._negative_blocklist_query()def get_query_for_event_id_matching(self) -> ast.SelectQuery | ast.SelectSetQuery:+ """+ The ids of a session's events that matched ANY ONE of the query's event/action filters,+ still combined with the query's property filters under its operand. Deliberately weaker+ than the session-id matching path: it does not prove the session satisfied every filter+ (that's a question about the session, which `get_queries_for_session_id_matching`+ answers), it names the events that made the session relevant.+ """# Subqueries only need to return uuid for the GlobalIn comparisonselect_queries: list[ast.SelectQuery] = self._get_queries_for_matching(select_expr=ast.Field(chain=["uuid"]),# when matching we want to select flag lists of event UUIds so we group by session_id, and then uuidgroup_by=[_event_session_id_field(), ast.Field(chain=["uuid"])],+ # The subqueries are intersected by event id below, and an event has exactly one name,+ # so keeping one subquery per entity would match nothing as soon as there are two.+ union_entities=True,)select_exprs: list[ast.Expr] = []for q in select_queries:diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.pyindex 411211b55d9d..f9d1d0573f3a 100644--- a/posthog/session_recordings/test/test_session_recordings.py+++ b/posthog/session_recordings/test/test_session_recordings.py@@ -1368,6 +1368,88 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)for result in results:assert "timestamp" in result+ @parameterized.expand(+ [+ (+ # The shape the experiment recordings tab sends once a metric is picked: the+ # exposure event ANDed with the metric's event. No single event carries both+ # names, so intersecting per-filter matches by event id finds nothing — the+ # event filters must be unioned before the session's events are matched.+ "disjoint_event_names",+ [+ {"id": "$feature_flag_called", "type": "events", "order": 0, "name": "$feature_flag_called"},+ {+ "id": "alert creation completed",+ "type": "events",+ "order": 1,+ "name": "alert creation completed",+ },+ ],+ [+ ("$feature_flag_called", {}, True),+ ("an event neither filter asks for", {}, False),+ ("alert creation completed", {}, True),+ ],+ ),+ (+ # Two predicates that can match the same event row: the union is deliberately+ # wider than the intersection. Every pageview is returned, not only the+ # /checkout ones — same semantics as the client-side 'name' match path, which+ # highlights on event name alone whatever the operand.+ "overlapping_predicates_return_the_union",+ [+ {"id": "$pageview", "type": "events", "order": 0, "name": "$pageview"},+ {+ "id": "$pageview",+ "type": "events",+ "order": 1,+ "name": "$pageview",+ "properties": [+ {"key": "$current_url", "value": "/checkout", "operator": "icontains", "type": "event"}+ ],+ },+ ],+ [+ ("$pageview", {"$current_url": "https://example.com/home"}, True),+ ("an event neither filter asks for", {}, False),+ ("$pageview", {"$current_url": "https://example.com/checkout"}, True),+ ],+ ),+ ]+ )+ def test_get_matching_events_with_two_anded_event_filters(+ self, _name: str, event_filters: list[dict], session_events: list[tuple[str, dict, bool]]+ ) -> None:+ base_time = (now() - relativedelta(days=1)).replace(microsecond=0)++ session_id = str(uuid7())+ self.produce_replay_summary("user", session_id, base_time)+ expected_event_ids = []+ for seconds, (event_name, extra_properties, expected) in enumerate(session_events):+ event_id = _create_event(+ event=event_name,+ properties={"$session_id": session_id, **extra_properties},+ team=self.team,+ distinct_id=uuid7(),+ timestamp=base_time + timedelta(seconds=seconds + 1),+ )+ if expected:+ expected_event_ids.append(event_id)++ query_params = [+ f'session_ids=["{session_id}"]',+ f"events={json.dumps(event_filters)}",+ "operand=AND",+ ]++ response = self.client.get(+ f"/api/projects/{self.team.id}/session_recordings/matching_events?{'&'.join(query_params)}"+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ result_uuids = sorted([r["uuid"] for r in response.json()["results"]])+ assert result_uuids == sorted(expected_event_ids)+@pytest.mark.usefixtures("unittest_snapshot")def test_400_when_invalid_list_query(self) -> None:query_params = "&".join(