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): correct the person property rewrite behind its feature flag (#91971)

Kim Svatos Duganb6293d2c7d5f
diff --git a/posthog/session_recordings/queries/sub_queries/events_subquery.py b/posthog/session_recordings/queries/sub_queries/events_subquery.py
index fd34e23119d1..9f72619c4738 100644
--- a/posthog/session_recordings/queries/sub_queries/events_subquery.py
+++ b/posthog/session_recordings/queries/sub_queries/events_subquery.py
@@ -11,6 +11,7 @@ from posthog.schema import (
EventPropertyFilter,
EventsNode,
HogQLQueryModifiers,
+ PersonsOnEventsMode,
PropertyOperator,
RecordingsQuery,
)
@@ -48,6 +49,15 @@ REPLAY_NEGATIVE_BLOCKLIST_TRUNCATED_COUNTER = Counter(
"A replay exclusion blocklist hit its row cap, so some sessions were not excluded from the results",
)
+# Modes where events.person_id is resolved through person_distinct_id_overrides, so it follows
+# a person merge instead of reporting whoever the event was attributed to at ingest.
+PERSON_ID_OVERRIDE_MODES = frozenset(
+ {
+ PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS,
+ PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED,
+ }
+)
+
# Person properties eligible for hybrid query optimization
# These are high-selectivity identity properties where the three-stage query provides value
HYBRID_QUERY_ELIGIBLE_PROPERTIES = {
@@ -179,6 +189,9 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
This solves the "late identification problem" where filtering by person properties
in standard PoE mode only finds sessions where those properties existed at event time.
+
+ The flag is the only switch. Turn it off and this path is dead, whatever mode the
+ project is in.
"""
return feature_enabled_or_false(
"enable-hybrid-poe-replay-filtering",
@@ -277,19 +290,18 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
def _build_sessions_query(
self,
- distinct_ids_subquery: ast.SelectQuery,
+ person_match: ast.Expr,
) -> ast.SelectQuery:
"""
- Stage 3: Build query to find all sessions for the distinct_ids from Stage 2.
-
- This finds all session_ids from events where the distinct_id matches any of
- the distinct_ids from Stage 2, within the query date range (with buffers).
+ Final stage: every session an event attributes to the matching persons, within the
+ query date range (with buffers).
Args:
- distinct_ids_subquery: The query from Stage 2 that returns distinct_ids
+ person_match: how an event is tied back to those persons, either by resolved
+ person id or by one of their distinct ids
Returns:
- SelectQuery that finds all session_ids for those distinct_ids
+ SelectQuery that finds all session_ids for those persons
"""
# Calculate date range with ±1 day buffer to match events_subquery behavior
# Events can arrive before session starts or after it ends
@@ -306,11 +318,7 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
left=ast.Field(chain=["team_id"]),
right=ast.Constant(value=self._team.pk),
),
- ast.CompareOperation(
- op=ast.CompareOperationOp.In,
- left=ast.Field(chain=["distinct_id"]),
- right=distinct_ids_subquery,
- ),
+ person_match,
ast.CompareOperation(
op=ast.CompareOperationOp.GtEq,
left=ast.Field(chain=["timestamp"]),
@@ -321,11 +329,11 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
left=ast.Field(chain=["timestamp"]),
right=ast.Constant(value=date_to_buffered),
),
- ast.CompareOperation(
- op=ast.CompareOperationOp.NotEq,
- left=ast.Call(name="empty", args=[_event_session_id_field()]),
- right=ast.Constant(value=1),
- ),
+ # notEmpty, not `empty(...) != 1`: an absent session id reads as NULL, and
+ # HogQL prints `!=` as ifNull(notEquals(...), 1), so the NULL would compare
+ # true and reach the GROUP BY. The caller matches this against the replay
+ # table's non-nullable session_id, which rejects a NULL in the set.
+ ast.Call(name="notEmpty", args=[_event_session_id_field()]),
]
),
group_by=[_event_session_id_field()], # DISTINCT session_id
@@ -422,17 +430,36 @@ class ReplayFiltersEventsSubQuery(SessionRecordingsListingBaseQuery):
except Exception as e:
posthoganalytics.capture_exception(e, properties={"context": "hybrid_query_monitoring"})
- # Build the three-stage query using Pure AST
- # Stage 1: Find person_ids from persons table
+ # Stage 1: the persons whose properties match
persons_query = self._build_persons_query(person_properties, person_id_limit)
- # Stage 2: Find distinct_ids for those person_ids
- distinct_ids_query = self._build_distinct_ids_query(persons_query)
-
- # Stage 3: Find sessions for those distinct_ids
- sessions_query = self._build_sessions_query(distinct_ids_query)
+ if self._team.person_on_events_mode in PERSON_ID_OVERRIDE_MODES:
+ # events.person_id already resolves through the overrides table in these modes, so it
+ # follows a merge: an event sent under an anonymous distinct id reports the person it
+ # was later merged into. Matching on it reaches pre-identification sessions directly,
+ # the same way the person profile's replay tab does.
+ #
+ # This trusts person_distinct_id_overrides to hold the merge. A merge that reached
+ # person_distinct_ids but not the overrides table would be missed here and found by
+ # the distinct-id expansion below, which reads the other table. The two are written
+ # by the same merge path, so they only diverge while one lags.
+ return self._build_sessions_query(
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["person_id"]),
+ right=persons_query,
+ )
+ )
- return sessions_query
+ # Otherwise events.person_id is the value frozen at ingest and does not follow a merge,
+ # so the persons have to be expanded to their distinct ids first.
+ return self._build_sessions_query(
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["distinct_id"]),
+ right=self._build_distinct_ids_query(persons_query),
+ )
+ )
def _get_queries_for_matching(
self, select_expr: ast.Expr, group_by: list[ast.Expr], union_entities: bool = False
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_person_property_hybrid_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_person_property_hybrid_query.py
index 64c4291357f9..f6713c3ab3f5 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_person_property_hybrid_query.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_person_property_hybrid_query.py
@@ -1,13 +1,16 @@
from freezegun import freeze_time
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, create_person_id_override_by_distinct_id
from unittest.mock import patch
from django.test import override_settings
from django.utils.timezone import now
from dateutil.relativedelta import relativedelta
+from parameterized import parameterized
-from posthog.schema import PersonPropertyFilter, PropertyOperator, RecordingsQuery
+from posthog.schema import PersonPropertyFilter, PersonsOnEventsMode, PropertyOperator, RecordingsQuery
+
+from posthog.hogql import ast
from posthog.clickhouse.client import sync_execute
from posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL
@@ -40,48 +43,60 @@ class TestPersonPropertyHybridQuery(ClickhouseTestMixin, APIBaseTest):
def an_hour_ago(self):
return (now() - relativedelta(hours=1)).replace(microsecond=0, second=0)
- def test_hybrid_query_disabled_by_default(self) -> None:
- with freeze_time("2021-08-21T20:00:00.000Z"):
- anonymous_id = "anonymous_user_123"
- identified_id = "identified_user_123"
- session_id_after = "session_after_identification"
+ def _subquery_for_mode(self, mode: PersonsOnEventsMode) -> ReplayFiltersEventsSubQuery:
+ self.team.modifiers = {"personsOnEventsMode": mode.value}
+ return ReplayFiltersEventsSubQuery(team=self.team, query=RecordingsQuery())
- create_person(
- team=self.team,
- distinct_ids=[anonymous_id, identified_id],
- properties={"email": "[email protected]"},
- )
+ @parameterized.expand(
+ [
+ (PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS,),
+ (PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS,),
+ (PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED,),
+ (PersonsOnEventsMode.DISABLED,),
+ ]
+ )
+ @patch("posthoganalytics.feature_enabled", return_value=False)
+ def test_hybrid_query_stays_off_in_every_mode_while_the_flag_is_off(
+ self, mode: PersonsOnEventsMode, mock_feature_enabled
+ ) -> None:
+ assert self._subquery_for_mode(mode)._is_hybrid_query_mode_enabled() is False
- produce_replay_summary(
- distinct_id=identified_id,
- session_id=session_id_after,
- first_timestamp=self.an_hour_ago,
- team_id=self.team.id,
- )
- create_event(
- identified_id,
- self.an_hour_ago,
- team=self.team,
- event_name="$pageview",
- properties={"$session_id": session_id_after},
- )
+ @parameterized.expand(
+ [
+ (PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS, "person_id"),
+ (PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED, "person_id"),
+ (PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS, "distinct_id"),
+ (PersonsOnEventsMode.DISABLED, "distinct_id"),
+ ]
+ )
+ def test_hybrid_query_matches_on_person_id_only_when_overrides_apply(
+ self, mode: PersonsOnEventsMode, expected_column: str
+ ) -> None:
+ subquery = self._subquery_for_mode(mode)
- self._assert_query_matches_session_ids(
- {
- "properties": [
- {
- "key": "email",
- "value": "[email protected]",
- "type": "person",
- "operator": "exact",
- }
- ]
- },
- [session_id_after],
- )
+ query = subquery._get_person_id_based_sessions_query(
+ [
+ PersonPropertyFilter(
+ key="email",
+ operator=PropertyOperator.EXACT,
+ type="person",
+ )
+ ]
+ )
+
+ assert isinstance(query.where, ast.And)
+ matched = {
+ expr.left.chain[-1]
+ for expr in query.where.exprs
+ if isinstance(expr, ast.CompareOperation) and isinstance(expr.left, ast.Field)
+ }
+ unusable_column = "distinct_id" if expected_column == "person_id" else "person_id"
+ assert expected_column in matched
+ assert unusable_column not in matched
@patch("posthoganalytics.feature_enabled", return_value=True)
- def test_hybrid_query_enabled_finds_sessions(self, mock_feature_enabled) -> None:
+ def test_hybrid_query_finds_pre_identification_sessions(self, mock_feature_enabled) -> None:
with freeze_time("2021-08-21T20:00:00.000Z"):
anonymous_id = "anonymous_user_456"
identified_id = "identified_user_456"
@@ -122,6 +137,16 @@ class TestPersonPropertyHybridQuery(ClickhouseTestMixin, APIBaseTest):
properties={"$session_id": session_id_after},
)
+ # Carries no $session_id, so it reads as NULL. It must not reach the session id
+ # set the replay table is matched against, which rejects a NULL.
+ create_event(identified_id, self.an_hour_ago, team=self.team)
+
+ # The merge itself. The anonymous event was written before the person existed, so it
+ # still carries a pre-merge person_id, and only this override row ties it to the
+ # person the identify produced. That is the shape a real merge leaves behind, and it
+ # is what makes events.person_id resolve to the merged person in an override mode.
+ create_person_id_override_by_distinct_id(anonymous_id, identified_id, self.team.pk)
+
self._assert_query_matches_session_ids(
{
"properties": [