: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(groups): prefilter related events without losing person history (#109931)
Vasco de Krijger14bf570f5526
diff --git a/ee/clickhouse/queries/related_actors_query.py b/ee/clickhouse/queries/related_actors_query.pyindex b22bde21adb9..a707d533b8d3 100644--- a/ee/clickhouse/queries/related_actors_query.py+++ b/ee/clickhouse/queries/related_actors_query.py@@ -4,10 +4,11 @@ from typing import Any, Optional, Union, castfrom django.utils.timezone import now-from posthog.schema import HogQLQueryModifiers, MaterializationMode, ProductKey+from posthog.schema import HogQLQueryModifiers, MaterializationMode, PersonsOnEventsMode, ProductKeyfrom posthog.hogql import ast-from posthog.hogql.parser import parse_select+from posthog.hogql.modifiers import create_default_modifiers_for_team+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.clickhouse.query_tagging import Feature, tag_queries@@ -43,7 +44,9 @@ class RelatedActorsQuery:# Treat a missing group key as the empty string (not NULL), matching the legacy raw query# which read the non-nullable materialized `$group_N` column directly. This keeps the# `(index, key)` tuples in the IN-subquery non-nullable.- self._modifiers = HogQLQueryModifiers(materializationMode=MaterializationMode.LEGACY_NULL_AS_STRING)+ self._modifiers = create_default_modifiers_for_team(+ team, HogQLQueryModifiers(materializationMode=MaterializationMode.LEGACY_NULL_AS_STRING)+ )@propertydef is_aggregating_by_groups(self) -> bool:@@ -163,6 +166,40 @@ class RelatedActorsQuery:"actor_filter": actor_filter,},)+ if (+ isinstance(query, ast.SelectQuery)+ and not self.is_aggregating_by_groups+ and self._modifiers.personsOnEventsMode+ in (+ PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS,+ PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED,+ )+ ):+ # Detached IDs can own history without a current Personhog mapping. Include stored+ # ownership and all override candidates; the resolved person filter rejects stale versions.+ # Keep IN local so candidates and person resolution use the same shard's snapshot.+ # GLOBAL IN can miss overrides on shards whose replicas are ahead of the initiator.+ query.prewhere = parse_expr(+ """+ events.team_id = {team_id}+ AND timestamp > {after}+ AND timestamp < {before}+ AND (+ events.event_person_id = {person_id}+ OR events.distinct_id IN (+ SELECT distinct_id+ FROM raw_person_distinct_id_overrides+ WHERE person_id = {person_id}+ )+ )+ """,+ placeholders={+ "team_id": ast.Constant(value=self.team.pk),+ "after": ast.Constant(value=self._after),+ "before": ast.Constant(value=self._before),+ "person_id": ast.Constant(value=self.id),+ },+ )response = execute_hogql_query(query, team=self.team, modifiers=self._modifiers)results = response.resultsif not results:diff --git a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr b/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambrindex 984559d22cad..1732203a6397 100644--- a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr+++ b/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.ambr@@ -11,7 +11,10 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) ARRAY- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.`$group_0`), tuple(1, events.`$group_1`)]) AS tuples+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.`$group_0`), tuple(1, events.`$group_1`)]) AS tuples PREWHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), or(equals(events.person_id, '00000000-0000-0000-0000-000000000000'), in(events.distinct_id,+ (SELECT person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE and(equals(person_distinct_id_overrides.team_id, 99999), equals(person_distinct_id_overrides.person_id, '00000000-0000-0000-0000-000000000000'))))))WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,diff --git a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.new_events_schema.ambr b/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.new_events_schema.ambrindex 0ba374f2b768..3cdd15899b8d 100644--- a/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.new_events_schema.ambr+++ b/ee/clickhouse/queries/test/__snapshots__/test_related_actors_query.new_events_schema.ambr@@ -11,7 +11,10 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) ARRAY- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.properties.`$group_0`), tuple(1, events.properties.`$group_1`)]) AS tuples+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.properties.`$group_0`), tuple(1, events.properties.`$group_1`)]) AS tuples PREWHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), or(equals(events.person_id, '00000000-0000-0000-0000-000000000000'), in(events.distinct_id,+ (SELECT person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE and(equals(person_distinct_id_overrides.team_id, 99999), equals(person_distinct_id_overrides.person_id, '00000000-0000-0000-0000-000000000000'))))))WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,diff --git a/ee/clickhouse/queries/test/test_related_actors_query.py b/ee/clickhouse/queries/test/test_related_actors_query.pyindex 5f1e018fdb49..08c69278c1fe 100644--- a/ee/clickhouse/queries/test/test_related_actors_query.py+++ b/ee/clickhouse/queries/test/test_related_actors_query.py@@ -1,7 +1,7 @@from abc import ABC, abstractmethod-from datetime import datetime, timedelta+from datetime import UTC, datetime, timedeltafrom typing import cast-from uuid import uuid4+from uuid import UUID, uuid4import time_machinefrom posthog.test.base import (@@ -13,8 +13,13 @@ from posthog.test.base import (snapshot_clickhouse_queries,)+from parameterized import parameterized++from posthog.schema import PersonsOnEventsMode+from posthog.clickhouse.client import sync_executefrom posthog.models import Group+from posthog.models.event.util import create_eventfrom posthog.models.filters.utils import GroupTypeIndexfrom posthog.models.group.util import create_groupfrom posthog.test.persons import create_group_type_mapping@@ -201,3 +206,147 @@ class TestRelatedGroupsQuery(BaseRelatedActorsTest):group_results = [r for r in results if r.get("type") == "group"]assert len(group_results) == 0+++@time_machine.travel("2025-03-01T12:00:00Z", tick=False)+class TestRelatedGroupsPersonIdentity(ClickhouseTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ self.team.modifiers = {"personsOnEventsMode": PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS}+ create_group_type_mapping(group_type_index=0, team=self.team, project=self.project, group_type="company")++ def _record_group_visit(self, *, distinct_id: str, stored_person_id: UUID, group_key: str) -> None:+ create_group(team_id=self.team.pk, group_type_index=0, group_key=group_key)+ create_event(+ event_uuid=uuid4(),+ team=self.team,+ event="$pageview",+ distinct_id=distinct_id,+ person_id=stored_person_id,+ timestamp=RECENT_DATE.replace(tzinfo=UTC),+ properties={"$group_0": group_key},+ )++ def _set_override(self, distinct_id: str, person_id: UUID, *, version: int, is_deleted: bool = False) -> None:+ sync_execute(+ "INSERT INTO person_distinct_id_overrides (team_id, distinct_id, person_id, version, is_deleted) VALUES",+ [(self.team.pk, distinct_id, str(person_id), version, int(is_deleted))],+ )++ def _related_group_keys(self, person_id: UUID) -> set[str]:+ results = RelatedActorsQuery(team=self.team, group_type_index=None, id=str(person_id)).run()+ return {str(group["id"]) for group in results}++ @parameterized.expand(+ [+ ("merged_id_still_mapped", ["current-id", "historical-id"]),+ ("detached_id_no_longer_mapped", ["current-id"]),+ ]+ )+ def test_override_preserves_historical_group_with_or_without_current_mapping(+ self, _case: str, current_distinct_ids: list[str]+ ) -> None:+ person = _create_person(team=self.team, distinct_ids=current_distinct_ids)+ previous_owner_id = uuid4()+ self._record_group_visit(+ distinct_id="historical-id", stored_person_id=previous_owner_id, group_key="historical-company"+ )+ self._set_override("historical-id", person.uuid, version=1)++ assert self._related_group_keys(person.uuid) == {"historical-company"}++ def test_squashed_history_still_returns_the_historical_group_without_an_override(self) -> None:+ person = _create_person(team=self.team, distinct_ids=["current-id"])+ self._record_group_visit(+ distinct_id="detached-id", stored_person_id=person.uuid, group_key="historical-company"+ )++ assert self._related_group_keys(person.uuid) == {"historical-company"}++ def test_group_follows_the_new_owner_after_a_newer_override(self) -> None:+ previous_owner = _create_person(team=self.team, distinct_ids=["previous-owner-id"])+ new_owner = _create_person(team=self.team, distinct_ids=["new-owner-id"])+ self._record_group_visit(+ distinct_id="transferred-id", stored_person_id=previous_owner.uuid, group_key="transferred-company"+ )+ self._set_override("transferred-id", previous_owner.uuid, version=1)+ self._set_override("transferred-id", new_owner.uuid, version=2)++ assert self._related_group_keys(previous_owner.uuid) == set()+ assert self._related_group_keys(new_owner.uuid) == {"transferred-company"}++ def test_deleting_an_override_returns_the_group_to_the_stored_owner(self) -> None:+ stored_owner = _create_person(team=self.team, distinct_ids=["stored-owner-id"])+ override_owner = _create_person(team=self.team, distinct_ids=["override-owner-id"])+ self._record_group_visit(+ distinct_id="restored-id", stored_person_id=stored_owner.uuid, group_key="restored-company"+ )+ self._set_override("restored-id", override_owner.uuid, version=1)+ self._set_override("restored-id", override_owner.uuid, version=2, is_deleted=True)++ assert self._related_group_keys(stored_owner.uuid) == {"restored-company"}+ assert self._related_group_keys(override_owner.uuid) == set()++ def test_reusing_a_distinct_id_does_not_share_groups_between_people(self) -> None:+ current_owner = _create_person(team=self.team, distinct_ids=["reused-id"])+ previous_owner = _create_person(team=self.team, distinct_ids=["previous-owner-id"])+ self._record_group_visit(+ distinct_id="reused-id", stored_person_id=current_owner.uuid, group_key="current-owner-company"+ )+ self._record_group_visit(+ distinct_id="reused-id", stored_person_id=previous_owner.uuid, group_key="previous-owner-company"+ )++ assert self._related_group_keys(current_owner.uuid) == {"current-owner-company"}+ assert self._related_group_keys(previous_owner.uuid) == {"previous-owner-company"}++ def test_group_from_the_last_of_2501_override_candidates_is_not_lost(self) -> None:+ person = _create_person(team=self.team, distinct_ids=["current-id"])+ historical_ids = [f"historical-{index:04d}" for index in range(2501)]+ sync_execute(+ "INSERT INTO person_distinct_id_overrides (team_id, distinct_id, person_id, version) VALUES",+ [(self.team.pk, distinct_id, str(person.uuid), 1) for distinct_id in historical_ids],+ )+ self._record_group_visit(+ distinct_id=historical_ids[-1], stored_person_id=uuid4(), group_key="last-historical-company"+ )++ assert self._related_group_keys(person.uuid) == {"last-historical-company"}++ @parameterized.expand(+ [+ (PersonsOnEventsMode.DISABLED, {"current-mapping-company"}),+ (PersonsOnEventsMode.PERSON_ID_NO_OVERRIDE_PROPERTIES_ON_EVENTS, {"stored-owner-company"}),+ (+ PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS,+ {"stored-owner-company", "override-company"},+ ),+ (PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_JOINED, {"stored-owner-company", "override-company"}),+ ]+ )+ def test_project_identity_mode_decides_which_groups_belong_to_the_person(+ self, mode: PersonsOnEventsMode, expected_groups: set[str]+ ) -> None:+ self.team.modifiers = {"personsOnEventsMode": mode}+ person = _create_person(team=self.team, distinct_ids=["mapped-to-person-id"])+ other_person = _create_person(team=self.team, distinct_ids=["stored-with-person-id", "overridden-to-person-id"])+ self._record_group_visit(+ distinct_id="mapped-to-person-id", stored_person_id=other_person.uuid, group_key="current-mapping-company"+ )+ self._record_group_visit(+ distinct_id="stored-with-person-id", stored_person_id=person.uuid, group_key="stored-owner-company"+ )+ self._record_group_visit(+ distinct_id="overridden-to-person-id", stored_person_id=other_person.uuid, group_key="override-company"+ )+ self._set_override("overridden-to-person-id", person.uuid, version=1)++ assert self._related_group_keys(person.uuid) == expected_groups++ def test_event_history_returns_groups_even_without_a_person_record(self) -> None:+ event_only_person_id = uuid4()+ self._record_group_visit(+ distinct_id="event-only-id", stored_person_id=event_only_person_id, group_key="event-only-company"+ )++ assert self._related_group_keys(event_only_person_id) == {"event-only-company"}diff --git a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambrindex 2bdf7cb85221..25ebcc81ff0e 100644--- a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr+++ b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.ambr@@ -63,7 +63,10 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) ARRAY- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.`$group_0`), tuple(1, events.`$group_1`)]) AS tuples+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.`$group_0`), tuple(1, events.`$group_1`)]) AS tuples PREWHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), or(equals(events.person_id, '00000000-0000-0000-0000-000000000000'), in(events.distinct_id,+ (SELECT person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE and(equals(person_distinct_id_overrides.team_id, 99999), equals(person_distinct_id_overrides.person_id, '00000000-0000-0000-0000-000000000000'))))))WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,diff --git a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.new_events_schema.ambr b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.new_events_schema.ambrindex 2db95c73845d..4f65f7a10b3a 100644--- a/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.new_events_schema.ambr+++ b/ee/clickhouse/views/test/__snapshots__/test_clickhouse_groups.new_events_schema.ambr@@ -65,7 +65,10 @@WHERE equals(person_distinct_id_overrides.team_id, 99999)GROUP BY person_distinct_id_overrides.distinct_idHAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id) ARRAY- JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.properties.`$group_0`), tuple(1, events.properties.`$group_1`)]) AS tuples+ JOIN arrayFilter(x -> notEquals(x.2, ''), [tuple(0, events.properties.`$group_0`), tuple(1, events.properties.`$group_1`)]) AS tuples PREWHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), or(equals(events.person_id, '00000000-0000-0000-0000-000000000000'), in(events.distinct_id,+ (SELECT person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE and(equals(person_distinct_id_overrides.team_id, 99999), equals(person_distinct_id_overrides.person_id, '00000000-0000-0000-0000-000000000000'))))))WHERE and(equals(events.team_id, 99999), greater(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC')), equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), '00000000-0000-0000-0000-000000000000'))LIMIT 100 SETTINGS readonly=2,max_execution_time=60,diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.pyindex 2e2c2adf1f52..ae5daa3b76db 100644--- a/ee/clickhouse/views/test/test_clickhouse_groups.py+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py@@ -1,11 +1,17 @@import jsonimport base64from typing import Any, cast-from uuid import UUID+from uuid import UUID, uuid4import pytestimport time_machine-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, snapshot_clickhouse_queries+from posthog.test.base import (+ APIBaseTest,+ ClickhouseTestMixin,+ _create_event,+ create_person_id_override_by_distinct_id,+ snapshot_clickhouse_queries,+)from unittest import mockfrom unittest.mock import patch@@ -1172,6 +1178,30 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):],)+ @time_machine.travel("2021-05-10", tick=False)+ def test_related_groups_person_returns_current_and_detached_historical_groups(self) -> None:+ create_group_type_mapping(team=self.team, project=self.project, group_type_index=0, group_type="company")+ person = create_person(team=self.team, distinct_ids=["current-id"])+ for distinct_id, stored_person_id, group_key in [+ ("current-id", person.uuid, "current-company"),+ ("detached-id", uuid4(), "historical-company"),+ ]:+ create_group(team_id=self.team.pk, group_type_index=0, group_key=group_key)+ _create_event(+ event="$pageview",+ team=self.team,+ distinct_id=distinct_id,+ person_id=str(stored_person_id),+ timestamp="2021-05-05 00:00:00",+ properties={"$group_0": group_key},+ )+ create_person_id_override_by_distinct_id("detached-id", "current-id", self.team.pk, version=1)++ response = self.client.get(f"/api/projects/{self.team.id}/groups/related?id={person.uuid}")++ assert response.status_code == 200+ assert {group["group_key"] for group in response.json()} == {"current-company", "historical-company"}+def test_related_missing_id(self):response = self.client.get(f"/api/projects/{self.team.id}/groups/related?group_type_index=0")self.assertEqual(response.status_code, 400)