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): drop no-event sessions blocked by negative person filters (#107129)

Kim Svatos Dugan7faca20586ea
diff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.py
index cf0cdefda751..22818d7bd07e 100644
--- a/posthog/session_recordings/queries/session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py
@@ -19,6 +19,7 @@ from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.parser import parse_select
from posthog.hogql.property import property_to_expr
+from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.client.connection import ClickHouseUser
from posthog.clickhouse.query_tagging import tags_context
@@ -36,6 +37,7 @@ from posthog.session_recordings.queries.utils import (
UnexpectedQueryProperties,
_strip_person_and_event_and_cohort_properties,
expand_test_account_filters,
+ is_person_property_check_enabled,
is_session_property,
test_account_scoped_query,
)
@@ -303,7 +305,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
next_cursor = self._paginator.get_next_cursor()
return SessionRecordingQueryResult(
- results=(self._data_to_return(self._paginator.results)),
+ results=self._without_person_blocked_sessions(self._data_to_return(self._paginator.results)),
has_more_recording=self._paginator.has_more(),
timings=paginated_response.timings,
next_cursor=next_cursor,
@@ -480,6 +482,120 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):
"""Whether any filter narrows sessions by their events, so `events_timestamp_floor` can cost results."""
return any(b.get_queries_for_session_id_matching() for b in self._events_filter_builders())
+ @tracer.start_as_current_span("SessionRecordingListFromQuery._without_person_blocked_sessions")
+ def _without_person_blocked_sessions(self, results: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Drop fetched sessions whose person a negative person-property filter excludes.
+
+ In PoE mode those filters are events-based, so a session with no events passes them even
+ when its person matches the excluded value (the "filter out internal and test users" case).
+ The check needs the fetched rows' distinct ids, so it runs after selection: the page can
+ come back short, but the cursor comes from the unfiltered rows, so pagination skips
+ nothing. A session is dropped when any of its replay rows' distinct ids resolves to a
+ blocked person, matching the events blocklist's any-event semantics. Fail-open on error,
+ which returns the page the listing already produced.
+ """
+ # Callers that set skip_negative_blocklists evaluate negative filters against the fetched
+ # rows themselves, so the person check stays out of their way too.
+ if not results or self._skip_negative_blocklists:
+ return results
+
+ page_distinct_ids = list({row["distinct_id"] for row in results if row.get("distinct_id")})
+ if not page_distinct_ids:
+ return results
+
+ subqueries = [PersonsPropertiesSubQuery(self._team, self._query)]
+ if self._test_account_filters:
+ subqueries.append(
+ PersonsPropertiesSubQuery(
+ self._team, test_account_scoped_query(self._query, self._test_account_filters)
+ )
+ )
+ # Probe with the page's own ids: a None from every subquery means no negative person
+ # filter applies, so neither the flag read nor the queries below are needed.
+ if not any(sq.get_blocked_distinct_ids_query(page_distinct_ids) for sq in subqueries):
+ return results
+ if not is_person_property_check_enabled(self._team):
+ return results
+
+ try:
+ session_distinct_ids = self._session_distinct_ids(results)
+ all_distinct_ids = list({distinct_id for ids in session_distinct_ids.values() for distinct_id in ids})
+
+ blocked_distinct_ids: set[str] = set()
+ for subquery in subqueries:
+ blocked_query = subquery.get_blocked_distinct_ids_query(all_distinct_ids)
+ if blocked_query is None:
+ continue
+ response = execute_hogql_query(
+ query=blocked_query,
+ team=self._team,
+ # Same user as the listing query, so per-user property restrictions apply here too.
+ user=self._user,
+ query_type="SessionRecordingListPersonPropertyCheck",
+ modifiers=self._hogql_query_modifiers,
+ settings=self._person_check_query_settings(),
+ )
+ blocked_distinct_ids |= {row[0] for row in response.results or []}
+
+ blocked_sessions = {
+ session_id
+ for session_id, distinct_ids in session_distinct_ids.items()
+ if distinct_ids & blocked_distinct_ids
+ }
+ except Exception as e:
+ capture_exception(e)
+ return results
+
+ if not blocked_sessions:
+ return results
+ return [row for row in results if row["session_id"] not in blocked_sessions]
+
+ def _person_check_query_settings(self) -> HogQLGlobalSettings:
+ """The caller's execution-time limit also bounds the post-fetch person check queries.
+
+ A timeout must throw, not return partial rows: a partial blocked-id set would keep a
+ blocked session without entering the fail-open exception handler.
+ """
+ if self._max_execution_time is not None:
+ return HogQLGlobalSettings(max_execution_time=self._max_execution_time, timeout_overflow_mode="throw")
+ return HogQLGlobalSettings(timeout_overflow_mode="throw")
+
+ def _session_distinct_ids(self, results: list[dict[str, Any]]) -> dict[str, set[str]]:
+ """Every distinct id the fetched sessions' replay rows were written under, per session id.
+
+ The page carries one distinct id per session (`any(s.distinct_id)`), but a session
+ recorded under several distinct ids must be excluded when any of them resolves to a
+ blocked person. Bounded by the fetched rows' own time range, so the lookup stays on
+ the table's date-first sort key.
+ """
+ query = parse_select(
+ """
+ SELECT session_id, distinct_id
+ FROM raw_session_replay_events
+ WHERE session_id IN {session_ids}
+ AND min_first_timestamp >= {date_from}
+ AND min_first_timestamp <= {date_to}
+ GROUP BY session_id, distinct_id
+ """,
+ {
+ "session_ids": ast.Constant(value=[row["session_id"] for row in results]),
+ "date_from": ast.Constant(value=min(row["start_time"] for row in results)),
+ "date_to": ast.Constant(value=max(row["end_time"] for row in results)),
+ },
+ )
+ response = execute_hogql_query(
+ query=query,
+ team=self._team,
+ user=self._user,
+ query_type="SessionRecordingListPersonPropertyCheckDistinctIds",
+ modifiers=self._hogql_query_modifiers,
+ settings=self._person_check_query_settings(),
+ )
+ session_distinct_ids: dict[str, set[str]] = {}
+ for row in response.results or []:
+ session_distinct_ids.setdefault(row[0], set()).add(row[1])
+ return session_distinct_ids
+
def _events_filter_builders(self) -> list[ReplayFiltersEventsSubQuery]:
"""Every builder that can contribute an events subquery: the query's own, plus test accounts."""
builders = [ReplayFiltersEventsSubQuery(self._team, self._query, self._allow_event_property_expansion)]
diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.py
index 7dd490fecec3..eade999290f3 100644
--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py
+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py
@@ -30,7 +30,6 @@ from posthog.session_recordings.queries.sub_queries.base_query import SessionRec
from posthog.session_recordings.queries.sub_queries.group_key_resolver import resolved_group_key_expr
from posthog.session_recordings.queries.utils import (
INVERSE_OPERATOR_FOR,
- NEGATIVE_OPERATORS,
SessionRecordingQueryResult,
_entity_to_expr,
_node_from_entity,
@@ -38,6 +37,7 @@ from posthog.session_recordings.queries.utils import (
is_cohort_property,
is_event_property,
is_group_property,
+ is_negative_prop,
is_person_property,
)
from posthog.types import AnyPropertyFilter
@@ -93,18 +93,6 @@ def get_negative_entity_properties(
return negative_props
-def is_negative_prop(prop: AnyPropertyFilter) -> bool:
- if not hasattr(prop, "operator"):
- return False
- if prop.operator in NEGATIVE_OPERATORS:
- return True
- # NOT_IN is intentionally omitted from NEGATIVE_OPERATORS for event/person filters
- # (it has different semantics there), but for cohort filters it IS the negative form.
- if is_cohort_property(prop) and prop.operator == PropertyOperator.NOT_IN:
- return True
- return False
-
-
class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
def __init__(
self,
diff --git a/posthog/session_recordings/queries/sub_queries/person_props_subquery.py b/posthog/session_recordings/queries/sub_queries/person_props_subquery.py
index d4d1ca933532..82ea0af94085 100644
--- a/posthog/session_recordings/queries/sub_queries/person_props_subquery.py
+++ b/posthog/session_recordings/queries/sub_queries/person_props_subquery.py
@@ -1,12 +1,21 @@
-from posthog.schema import PropertyGroupFilterValue, RecordingsQuery
+from typing import cast
+
+from posthog.schema import PropertyGroupFilterValue, PropertyOperator, RecordingsQuery
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql.property import property_to_expr
+from posthog.constants import PropertyOperatorType
from posthog.models import Team
from posthog.session_recordings.queries.sub_queries.base_query import SessionRecordingsListingBaseQuery
-from posthog.session_recordings.queries.utils import is_person_property, poe_is_active
+from posthog.session_recordings.queries.utils import (
+ INVERSE_OPERATOR_FOR,
+ is_negative_prop,
+ is_person_property,
+ poe_is_active,
+)
+from posthog.types import AnyPropertyFilter
class PersonsPropertiesSubQuery(SessionRecordingsListingBaseQuery):
@@ -28,9 +37,52 @@ class PersonsPropertiesSubQuery(SessionRecordingsListingBaseQuery):
else:
return None
+ def get_blocked_distinct_ids_query(self, distinct_ids: list[str]) -> ast.SelectQuery | ast.SelectSetQuery | None:
+ """Which of `distinct_ids` resolve to a person that a negative person-property filter excludes.
+
+ In PoE mode negative person filters ride on the events-table blocklist, so a session with
+ no events is never excluded, even when its person matches the excluded value. This scoped
+ check reads the person record through the distinct id, so it needs no events. It follows
+ the blocklist's rules: negative filters only, AND operand only. It tests the person's
+ current properties, where the events path tests the properties at event time.
+ """
+ if not distinct_ids or not poe_is_active(self._team):
+ return None
+ if self.property_operand != PropertyOperatorType.AND:
+ return None
+
+ negative_props = [p for p in self._person_property_filters if is_negative_prop(p)]
+ if not negative_props:
+ return None
+
+ blocked_exprs: list[ast.Expr] = []
+ for prop in negative_props:
+ operator = cast(PropertyOperator, prop.operator) # type: ignore[union-attr]
+ inverted = prop.model_copy(update={"operator": INVERSE_OPERATOR_FOR[operator]})
+ blocked_exprs.append(property_to_expr(inverted, team=self._team))
+
+ # A person matching any one positive form is excluded, so the inverted filters combine with OR.
+ blocked = ast.Or(exprs=blocked_exprs) if len(blocked_exprs) > 1 else blocked_exprs[0]
+
+ return parse_select(
+ """
+ SELECT distinct_id
+ FROM person_distinct_ids
+ WHERE distinct_id IN {distinct_ids} AND {blocked}
+ """,
+ {
+ "distinct_ids": ast.Constant(value=distinct_ids),
+ "blocked": blocked,
+ },
+ )
+
+ @property
+ def _person_property_filters(self) -> list[AnyPropertyFilter]:
+ return [g for g in (self._query.properties or []) if is_person_property(g)]
+
@property
def person_properties(self) -> PropertyGroupFilterValue | None:
- person_property_groups = [g for g in (self._query.properties or []) if is_person_property(g)]
+ person_property_groups = self._person_property_filters
return self.property_group_with_operand(person_property_groups) if person_property_groups else None
@property
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
index 92e30f434bad..3129917b1a22 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
@@ -20,6 +20,7 @@ from posthog.test.base import (
from unittest.mock import ANY, patch
from django.conf import settings
+from django.test import override_settings
from django.utils.timezone import now
from dateutil.relativedelta import relativedelta
@@ -43,12 +44,14 @@ from posthog.session_recordings.queries.session_recording_list_from_query import
SessionRecordingQueryResult,
)
from posthog.session_recordings.queries.sub_queries.events_subquery import ReplayFiltersEventsSubQuery
+from posthog.session_recordings.queries.sub_queries.person_props_subquery import PersonsPropertiesSubQuery
from posthog.session_recordings.queries.test.listing_recordings.test_utils import (
assert_query_matches_session_ids,
create_event,
filter_recordings_by,
)
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
+from posthog.session_recordings.queries.utils import REPLAY_PERSON_PROPERTY_CHECK_FLAG
from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL
from posthog.test.persons import create_person
from posthog.test.test_utils import create_group_type_mapping_without_created_at
@@ -5673,3 +5676,125 @@ class TestClickhouseSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseT
assert sorted(r["session_id"] for r in result.results) == sorted(oldest_two)
assert result.has_more_recording is False
+
+
+@time_machine.travel("2021-01-01T13:46:23", tick=False)
+@override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=True)
+class TestNoEventSessionPersonPropertyFiltering(ClickhouseTestMixin, APIBaseTest):
+ """Sessions with no events, listed with negative person-property filters in PoE mode.
+
+ The events-based negative blocklist cannot exclude a session with no events, so the listing
+ runs a post-selection person check, gated by REPLAY_PERSON_PROPERTY_CHECK_FLAG.
+ """
+
+ def setUp(self):
+ super().setUp()
+ sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())
+
+ @property
+ def an_hour_ago(self):
+ return (now() - relativedelta(hours=1)).replace(microsecond=0, second=0)
+
+ def _session_with_no_events(self, label: str, email: str | None) -> str:
+ distinct_id = f"{label}-user"
+ if email is not None:
+ create_person(team=self.team, distinct_ids=[distinct_id], properties={"email": email})
+ session_id = f"{label}-session"
+ produce_replay_summary(
+ distinct_id=distinct_id,
+ session_id=session_id,
+ first_timestamp=self.an_hour_ago,
+ team_id=self.team.id,
+ ensure_analytics_event_in_session=False,
+ )
+ return session_id
+
+ def _person_check_flag(self, enabled: bool):
+ return patch(
+ "posthoganalytics.feature_enabled",
+ side_effect=lambda flag, *args, **kwargs: enabled and flag == REPLAY_PERSON_PROPERTY_CHECK_FLAG,
+ )
+
+ def test_negative_person_filter_drops_no_event_sessions_of_matching_persons(self):
+ blocked_session = self._session_with_no_events("person-check-blocked", "[email protected]")
+ kept_session = self._session_with_no_events("person-check-kept", "[email protected]")
+ anonymous_session = self._session_with_no_events("person-check-anonymous", None)
+
+ # A session recorded under two distinct ids: the page carries only one of them
+ # (any(s.distinct_id)), so the check must resolve both and block on either.
+ shared_session = self._session_with_no_events("person-check-shared", "[email protected]")
+ create_person(
+ team=self.team,
+ distinct_ids=["person-check-shared-second-user"],
+ properties={"email": "[email protected]"},
+ )
+ produce_replay_summary(
+ distinct_id="person-check-shared-second-user",
+ session_id=shared_session,
+ first_timestamp=self.an_hour_ago + relativedelta(seconds=30),
+ team_id=self.team.id,
+ ensure_analytics_event_in_session=False,
+ )
+
+ query = {
+ "properties": [
+ {"key": "email", "value": "internal.example.com", "operator": "not_icontains", "type": "person"}
+ ]
+ }
+
+ with self._person_check_flag(enabled=True):
+ assert_query_matches_session_ids(team=self.team, query=query, expected=[kept_session, anonymous_session])
+
+ with self._person_check_flag(enabled=False):
+ assert_query_matches_session_ids(
+ team=self.team,
+ query=query,
+ expected=[blocked_session, kept_session, anonymous_session, shared_session],
+ )
+
+ def test_skip_negative_blocklists_callers_get_the_unfiltered_page(self):
+ blocked_session = self._session_with_no_events("skip-blocklists-blocked", "[email protected]")
+
+ query = RecordingsQuery.model_validate(
+ {
+ "properties": [
+ {"key": "email", "value": "internal.example.com", "operator": "not_icontains", "type": "person"}
+ ]
+ }
+ )
+
+ with self._person_check_flag(enabled=True):
+ result = SessionRecordingListFromQuery(
+ query=query,
+ team=self.team,
+ hogql_query_modifiers=None,
+ skip_negative_blocklists=True,
+ ).run()
+
+ assert [row["session_id"] for row in result.results] == [blocked_session]
+
+ def test_test_account_filters_drop_no_event_sessions_of_matching_persons(self):
+ self._session_with_no_events("test-accounts-blocked", "[email protected]")
+ kept_session = self._session_with_no_events("test-accounts-kept", "[email protected]")
+
+ self.team.test_account_filters = [
+ {"key": "email", "value": "internal.example.com", "operator": "not_icontains", "type": "person"}
+ ]
+ self.team.save()
+
+ with self._person_check_flag(enabled=True):
+ assert_query_matches_session_ids(
+ team=self.team, query={"filter_test_accounts": True}, expected=[kept_session]
+ )
+
+ def test_blocked_distinct_ids_query_needs_negative_filters_and_the_and_operand(self):
+ negative = {"key": "email", "value": "internal.example.com", "operator": "not_icontains", "type": "person"}
+ positive = {"key": "email", "value": "internal.example.com", "operator": "icontains", "type": "person"}
+
+ def blocked_query(properties: list[dict], operand: str = "AND"):
+ query = RecordingsQuery.model_validate({"properties": properties, "operand": operand})
+ return PersonsPropertiesSubQuery(self.team, query).get_blocked_distinct_ids_query(["a-distinct-id"])
+
+ assert blocked_query([negative]) is not None
+ assert blocked_query([positive]) is None
+ assert blocked_query([negative], operand="OR") is None
diff --git a/posthog/session_recordings/queries/utils.py b/posthog/session_recordings/queries/utils.py
index 9083e4df1f0e..bd1523b0d704 100644
--- a/posthog/session_recordings/queries/utils.py
+++ b/posthog/session_recordings/queries/utils.py
@@ -50,6 +50,22 @@ def is_anonymous_cohort_fix_enabled(team: Team) -> bool:
return False
+REPLAY_PERSON_PROPERTY_CHECK_FLAG = "replay-list-person-property-check"
+
+
+def is_person_property_check_enabled(team: Team) -> bool:
+ """Gate for the post-selection person-property check on the recordings list.
+
+ When on, sessions whose person matches the positive form of a negative person-property
+ filter are dropped from the fetched page. This closes the PoE-mode gap where a session
+ with no events can never enter the events-based negative blocklist.
+ """
+ try:
+ return bool(posthoganalytics.feature_enabled(REPLAY_PERSON_PROPERTY_CHECK_FLAG, str(team.pk)))
+ except Exception:
+ return False
+
+
NEGATIVE_OPERATORS = [
PropertyOperator.IS_NOT_SET,
PropertyOperator.IS_NOT,
@@ -95,6 +111,18 @@ def is_cohort_property(p: AnyPropertyFilter) -> bool:
return bool(p_type and "cohort" in p_type)
+def is_negative_prop(prop: AnyPropertyFilter) -> bool:
+ if not hasattr(prop, "operator"):
+ return False
+ if prop.operator in NEGATIVE_OPERATORS:
+ return True
+ # NOT_IN is intentionally omitted from NEGATIVE_OPERATORS for event/person filters
+ # (it has different semantics there), but for cohort filters it IS the negative form.
+ if is_cohort_property(prop) and prop.operator == PropertyOperator.NOT_IN:
+ return True
+ return False
+
+
def is_session_property(p: AnyPropertyFilter) -> bool:
p_type = getattr(p, "type", None)
p_key = getattr(p, "key", "")