: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
chore(django): personhog test setup for removing ORM completely (#65615)
Nick Beste653e2780eaf
diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.mdindex c8173eae1116..8ff092fd5230 100644--- a/.agents/skills/writing-tests/SKILL.md+++ b/.agents/skills/writing-tests/SKILL.md@@ -95,6 +95,8 @@ Escalating to the next rung is the last resort, not the default.- **No doc comments** in Python tests (house rule).- Mock only **true boundaries** — network, external APIs, the clock, queues.Don't mock your own internal helpers (that's how change-detector tests are born).+- **Person/group/cohort data:** use the helpers in `posthog/test/persons.py` (`create_person`, `create_group`, `create_group_type_mapping`, `add_cohort_members`, etc.) — never `Person.objects.create()` or similar ORM calls directly.+ See [`posthog/test/AGENTS.md`](../../posthog/test/AGENTS.md) for the full API reference and rationale.### Frontend (Jest)diff --git a/conftest.py b/conftest.pyindex 2cfa52e12086..618683b4c50f 100644--- a/conftest.py+++ b/conftest.py@@ -47,3 +47,20 @@ def pytest_unconfigure() -> None:# gone — observed as exit code 139 (SIGSEGV) on the Temporal CI shards. Restore the# default heap state so shutdown behaves exactly as without the boot window.gc.unfreeze()++[email protected](autouse=True)+def _activate_personhog_fake(request):+ """Force all person/group reads through the personhog fake for every test.++ The fake is seeded explicitly by the test helpers in posthog.test.persons+ (create_person, create_group, etc.) — no signals are used. Tests in+ personhog_client/ manage their own client and are excluded.+ """+ if "personhog_client" in str(request.node.path):+ yield+ return+ from posthog.test.personhog_fake import activate_personhog_fake # noqa: PLC0415, I001 — lazy import avoids connecting signals before Django is ready++ with activate_personhog_fake():+ yielddiff --git a/ee/clickhouse/models/test/test_cohort.py b/ee/clickhouse/models/test/test_cohort.pyindex 6d2d2afa049c..24f1a691215e 100644--- a/ee/clickhouse/models/test/test_cohort.py+++ b/ee/clickhouse/models/test/test_cohort.py@@ -27,12 +27,12 @@ from posthog.hogql.constants import MAX_SELECT_COHORT_CALCULATION_LIMITfrom posthog.clickhouse.client import sync_executefrom posthog.models.filters import Filterfrom posthog.models.organization import Organization-from posthog.models.person import Personfrom posthog.models.person.sql import GET_LATEST_PERSON_SQL, GET_PERSON_IDS_BY_FILTERfrom posthog.models.property.util import parse_prop_grouped_clausesfrom posthog.models.team import Teamfrom posthog.queries.person_distinct_id_query import get_team_distinct_ids_queryfrom posthog.queries.util import PersonPropertiesMode+from posthog.test.persons import create_personfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort@@ -537,12 +537,12 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertIn(str(user3.uuid), results)def test_insert_by_distinct_id_or_email(self):- Person.objects.create(team_id=self.team.pk, distinct_ids=["1"])- Person.objects.create(team_id=self.team.pk, distinct_ids=["123"])- Person.objects.create(team_id=self.team.pk, distinct_ids=["2"])+ create_person(team_id=self.team.pk, distinct_ids=["1"])+ create_person(team_id=self.team.pk, distinct_ids=["123"])+ create_person(team_id=self.team.pk, distinct_ids=["2"])# Team leakageteam2 = Team.objects.create(organization=self.organization)- Person.objects.create(team=team2, distinct_ids=["1"])+ create_person(team=team2, distinct_ids=["1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)cohort.insert_users_by_list(["1", "123"])@@ -552,7 +552,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertEqual(cohort.is_calculating, False)# test SQLi- Person.objects.create(team_id=self.team.pk, distinct_ids=["'); truncate person_static_cohort; --"])+ create_person(team_id=self.team.pk, distinct_ids=["'); truncate person_static_cohort; --"])cohort.insert_users_by_list(["'); truncate person_static_cohort; --", "123"])results = sync_execute("select count(1) from person_static_cohort where team_id = %(team_id)s",@@ -573,9 +573,9 @@ class TestCohort(ClickhouseTestMixin, BaseTest):def test_insert_cohort_hogql_query_with_distinct_id(self):from products.cohorts.backend.models.util import insert_cohort_query_actors_into_ch- p1 = Person.objects.create(team_id=self.team.pk, distinct_ids=["user1"])- p2 = Person.objects.create(team_id=self.team.pk, distinct_ids=["user2"])- Person.objects.create(team_id=self.team.pk, distinct_ids=["user3"])+ p1 = create_person(team_id=self.team.pk, distinct_ids=["user1"])+ p2 = create_person(team_id=self.team.pk, distinct_ids=["user2"])+ create_person(team_id=self.team.pk, distinct_ids=["user3"])# Create a cohort with a HogQL query that returns distinct_idcohort = Cohort.objects.create(@@ -599,12 +599,12 @@ class TestCohort(ClickhouseTestMixin, BaseTest):@snapshot_clickhouse_insert_cohortpeople_queriesdef test_cohortpeople_basic(self):- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["1"],properties={"$some_prop": "something", "$another_prop": "something"},)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["2"],properties={"$some_prop": "something", "$another_prop": "something"},@@ -634,7 +634,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):def test_cohortpeople_action_basic(self):action = _create_action(team=self.team, name="$pageview")- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["1"],properties={"$some_prop": "something", "$another_prop": "something"},@@ -648,7 +648,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):timestamp=datetime.now() - timedelta(hours=12),)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["2"],properties={"$some_prop": "something", "$another_prop": "something"},@@ -676,7 +676,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):def _setup_actions_with_different_counts(self):action = _create_action(team=self.team, name="$pageview")- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["1"],properties={"$some_prop": "something", "$another_prop": "something"},@@ -697,7 +697,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):timestamp=datetime.now() - timedelta(days=0, hours=12),)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["2"],properties={"$some_prop": "something", "$another_prop": "something"},@@ -719,7 +719,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):timestamp=datetime.now() - timedelta(days=0, hours=12),)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["3"],properties={"$some_prop": "something", "$another_prop": "something"},@@ -733,13 +733,13 @@ class TestCohort(ClickhouseTestMixin, BaseTest):timestamp=datetime.now() - timedelta(days=0, hours=12),)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["4"],properties={"$some_prop": "something", "$another_prop": "something"},)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["5"],properties={"$some_prop": "something", "$another_prop": "something"},@@ -781,12 +781,12 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertEqual(len(results), 1)def test_cohortpeople_deleted_person(self):- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["1"],properties={"$some_prop": "something", "$another_prop": "something"},)- p2 = Person.objects.create(+ p2 = create_person(team_id=self.team.pk,distinct_ids=["2"],properties={"$some_prop": "something", "$another_prop": "something"},@@ -815,12 +815,12 @@ class TestCohort(ClickhouseTestMixin, BaseTest):def test_cohortpeople_prop_changed(self):with freeze_time((datetime.now() - timedelta(days=3)).strftime("%Y-%m-%d")):- p1 = Person.objects.create(+ p1 = create_person(team_id=self.team.pk,distinct_ids=["1"],properties={"$some_prop": "something", "$another_prop": "something"},)- p2 = Person.objects.create(+ p2 = create_person(team_id=self.team.pk,distinct_ids=["2"],properties={"$some_prop": "something", "$another_prop": "something"},@@ -862,12 +862,12 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertEqual(results[0][0], p1.uuid)def test_cohort_change(self):- p1 = Person.objects.create(+ p1 = create_person(team_id=self.team.pk,distinct_ids=["1"],properties={"$some_prop": "something", "$another_prop": "something"},)- p2 = Person.objects.create(+ p2 = create_person(team_id=self.team.pk,distinct_ids=["2"],properties={"$some_prop": "another", "$another_prop": "another"},@@ -912,12 +912,12 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertEqual(results[0][0], p2.uuid)def test_static_cohort_precalculated(self):- Person.objects.create(team_id=self.team.pk, distinct_ids=["1"])- Person.objects.create(team_id=self.team.pk, distinct_ids=["123"])- Person.objects.create(team_id=self.team.pk, distinct_ids=["2"])+ create_person(team_id=self.team.pk, distinct_ids=["1"])+ create_person(team_id=self.team.pk, distinct_ids=["123"])+ create_person(team_id=self.team.pk, distinct_ids=["2"])# Team leakageteam2 = Team.objects.create(organization=self.organization)- Person.objects.create(team=team2, distinct_ids=["1"])+ create_person(team=team2, distinct_ids=["1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, last_calculation=timezone.now())cohort.insert_users_by_list(["1", "123"])@@ -929,8 +929,8 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertQueryMatchesSnapshot(sql)def test_cohortpeople_with_valid_other_cohort_filter(self):- Person.objects.create(team_id=self.team.pk, distinct_ids=["1"], properties={"foo": "bar"})- Person.objects.create(team_id=self.team.pk, distinct_ids=["2"], properties={"foo": "non"})+ create_person(team_id=self.team.pk, distinct_ids=["1"], properties={"foo": "bar"})+ create_person(team_id=self.team.pk, distinct_ids=["2"], properties={"foo": "non"})cohort0: Cohort = Cohort.objects.create(team=self.team,@@ -1234,8 +1234,8 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertEqual(result[0][1], "2") # distinct_id '2' is the one in cohortdef test_cohortpeople_with_nonexistent_other_cohort_filter(self):- Person.objects.create(team_id=self.team.pk, distinct_ids=["1"], properties={"foo": "bar"})- Person.objects.create(team_id=self.team.pk, distinct_ids=["2"], properties={"foo": "non"})+ create_person(team_id=self.team.pk, distinct_ids=["1"], properties={"foo": "bar"})+ create_person(team_id=self.team.pk, distinct_ids=["2"], properties={"foo": "non"})cohort1: Cohort = Cohort.objects.create(team=self.team,@@ -1272,7 +1272,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):)# satiesfies all conditions- p1 = Person.objects.create(+ p1 = create_person(team_id=self.team.pk,distinct_ids=["p1"],properties={"name": "test", "email": "[email protected]"},@@ -1293,7 +1293,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):)# doesn't satisfy action- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["p2"],properties={"name": "test", "email": "[email protected]"},@@ -1314,7 +1314,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):)# satisfies special condition (not pushed down person property in OR group)- p3 = Person.objects.create(+ p3 = create_person(team_id=self.team.pk,distinct_ids=["p3"],properties={"name": "special", "email": "[email protected]"},@@ -1401,17 +1401,17 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertCountEqual([p1.uuid, p3.uuid], [r[0] for r in result])def test_update_cohort(self):- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["1"],properties={"$some_prop": "something"},)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["2"],properties={"$another_prop": "something"},)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["3"],properties={"$another_prop": "something"},@@ -1446,17 +1446,17 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertEqual(len(results), 1)def test_cohort_versioning(self):- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["1"],properties={"$some_prop": "something"},)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["2"],properties={"$another_prop": "something"},)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["3"],properties={"$another_prop": "something"},@@ -1526,13 +1526,13 @@ class TestCohort(ClickhouseTestMixin, BaseTest):action = Action.objects.create(team=self.team, name="all events", steps_json=[{"event": None}])# Create two people- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["1"],properties={"$some_prop": "something", "$another_prop": "something"},)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["2"],properties={"$some_prop": "something", "$another_prop": "something"},@@ -1566,7 +1566,7 @@ class TestCohort(ClickhouseTestMixin, BaseTest):self.assertEqual(len(results), 2)# Create a person with no events- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["3"],properties={"$some_prop": "something", "$another_prop": "something"},diff --git a/ee/clickhouse/models/test/test_filters.py b/ee/clickhouse/models/test/test_filters.pyindex 8069b63dfc39..f28335d9aa82 100644--- a/ee/clickhouse/models/test/test_filters.py+++ b/ee/clickhouse/models/test/test_filters.py@@ -5,7 +5,7 @@ from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _crefrom posthog.clickhouse.client import query_with_columns, sync_executefrom posthog.constants import FILTER_TEST_ACCOUNTS-from posthog.models import Element, Organization, Person, Team+from posthog.models import Element, Organization, Teamfrom posthog.models.event.sql import GET_EVENTS_WITH_PROPERTIESfrom posthog.models.event.util import ClickhouseEventSerializerfrom posthog.models.filters import Filter@@ -13,6 +13,7 @@ from posthog.models.filters.retention_filter import RetentionFilterfrom posthog.models.filters.test.test_filter import TestFilter as PGTestFiltersfrom posthog.models.property.util import parse_prop_grouped_clausesfrom posthog.queries.util import PersonPropertiesMode+from posthog.test.persons import create_personfrom posthog.test.test_journeys import journeys_forfrom products.cohorts.backend.models.cohort import Cohort@@ -1220,7 +1221,7 @@ class TestFiltering(ClickhouseTestMixin, BaseTest):def test_person_cohort_properties(self):person1_distinct_id = "person1"- Person.objects.create(+ create_person(team=self.team,distinct_ids=[person1_distinct_id],properties={"$some_prop": "something"},@@ -1233,7 +1234,7 @@ class TestFiltering(ClickhouseTestMixin, BaseTest):)person2_distinct_id = "person2"- Person.objects.create(+ create_person(team=self.team,distinct_ids=[person2_distinct_id],properties={"$some_prop": "different"},diff --git a/ee/clickhouse/queries/funnels/test/breakdown_cases.py b/ee/clickhouse/queries/funnels/test/breakdown_cases.pyindex 54ed2baffa6a..a6d1eefa1813 100644--- a/ee/clickhouse/queries/funnels/test/breakdown_cases.py+++ b/ee/clickhouse/queries/funnels/test/breakdown_cases.py@@ -6,10 +6,10 @@ from posthog.test.base import APIBaseTest, also_test_with_person_on_events_v2, sfrom posthog.constants import INSIGHT_FUNNELSfrom posthog.models.filters import Filterfrom posthog.models.group.util import create_group-from posthog.models.group_type_mapping import GroupTypeMappingfrom posthog.models.instance_setting import override_instance_configfrom posthog.queries.funnels.funnel_unordered import ClickhouseFunnelUnorderedfrom posthog.queries.funnels.test.breakdown_cases import FunnelStepResult, assert_funnel_results_equal+from posthog.test.persons import create_group_type_mappingfrom posthog.test.test_journeys import journeys_for@@ -22,10 +22,10 @@ def funnel_breakdown_group_test_factory(Funnel, FunnelPerson, _create_event, _crreturn [val["id"] for val in serialized_result]def _create_groups(self):- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="company", group_type_index=1)diff --git a/ee/clickhouse/queries/test/test_event_query.py b/ee/clickhouse/queries/test/test_event_query.pyindex ebd76b332885..ef3809785f45 100644--- a/ee/clickhouse/queries/test/test_event_query.py+++ b/ee/clickhouse/queries/test/test_event_query.py@@ -12,8 +12,8 @@ from posthog.models.element import Elementfrom posthog.models.entity import Entityfrom posthog.models.filters import Filterfrom posthog.models.group.util import create_group-from posthog.models.person import Personfrom posthog.queries.trends.trends_event_query import TrendsEventQuery+from posthog.test.persons import create_personfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action@@ -211,7 +211,7 @@ class TestEventQuery(ClickhouseTestMixin, APIBaseTest):})- Person.objects.create(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "test"})+ create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "test"})_create_event(team=self.team,event="$pageview",@@ -219,7 +219,7 @@ class TestEventQuery(ClickhouseTestMixin, APIBaseTest):timestamp="2020-01-02T12:00:00Z",)- Person.objects.create(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "foo"})+ create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "foo"})_create_event(team=self.team,event="$pageview",@@ -249,8 +249,8 @@ class TestEventQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queries@freeze_time("2021-01-21")def test_account_filters(self):- Person.objects.create(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})- Person.objects.create(team_id=self.team.pk, distinct_ids=["person_2"], properties={"name": "Jane"})+ create_person(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})+ create_person(team_id=self.team.pk, distinct_ids=["person_2"], properties={"name": "Jane"})_create_event(event="event_name", team=self.team, distinct_id="person_1")_create_event(event="event_name", team=self.team, distinct_id="person_2")@@ -277,8 +277,8 @@ class TestEventQuery(ClickhouseTestMixin, APIBaseTest):self._run_query(filter)def test_action_with_person_property_filter(self):- Person.objects.create(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})- Person.objects.create(team_id=self.team.pk, distinct_ids=["person_2"], properties={"name": "Jane"})+ create_person(team_id=self.team.pk, distinct_ids=["person_1"], properties={"name": "John"})+ create_person(team_id=self.team.pk, distinct_ids=["person_2"], properties={"name": "Jane"})_create_event(event="event_name", team=self.team, distinct_id="person_1")_create_event(event="event_name", team=self.team, distinct_id="person_2")@@ -312,7 +312,7 @@ class TestEventQuery(ClickhouseTestMixin, APIBaseTest):materialize("events", "test_prop")- Person.objects.create(team_id=self.team.pk, distinct_ids=["p1"], properties={"key": "value"})+ create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"key": "value"})_create_event(team=self.team,event="$pageview",@@ -321,7 +321,7 @@ class TestEventQuery(ClickhouseTestMixin, APIBaseTest):properties={"test_prop": "hi"},)- Person.objects.create(team_id=self.team.pk, distinct_ids=["p2"], properties={"key_2": "value_2"})+ create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"key_2": "value_2"})_create_event(team=self.team,event="$pageview",@@ -446,9 +446,9 @@ class TestEventQuery(ClickhouseTestMixin, APIBaseTest):properties={"another": "value"},)- Person.objects.create(team_id=self.team.pk, distinct_ids=["p1"], properties={"$browser": "test"})- Person.objects.create(team_id=self.team.pk, distinct_ids=["p2"], properties={"$browser": "foobar"})- Person.objects.create(team_id=self.team.pk, distinct_ids=["p3"], properties={"$browser": "test"})+ create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"$browser": "test"})+ create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"$browser": "foobar"})+ create_person(team_id=self.team.pk, distinct_ids=["p3"], properties={"$browser": "test"})_create_event(team=self.team,diff --git a/ee/clickhouse/queries/test/test_lifecycle.py b/ee/clickhouse/queries/test/test_lifecycle.pyindex ea7c1aa0b7d7..8fd982307bc0 100644--- a/ee/clickhouse/queries/test/test_lifecycle.py+++ b/ee/clickhouse/queries/test/test_lifecycle.py@@ -8,9 +8,9 @@ from django.utils.timezone import nowfrom posthog.constants import FILTER_TEST_ACCOUNTS, TRENDS_LIFECYCLEfrom posthog.models.filters.filter import Filterfrom posthog.models.group.util import create_group-from posthog.models.person import Personfrom posthog.queries.test.test_lifecycle import TestLifecycleBasefrom posthog.queries.trends.trends import Trends+from posthog.test.persons import create_personfrom posthog.test.test_journeys import journeys_forfrom posthog.test.test_utils import create_group_type_mapping_without_created_at@@ -38,10 +38,10 @@ class TestClickhouseLifecycle(TestLifecycleBase):)with freeze_time("2020-01-11T12:00:00Z"):- Person.objects.create(distinct_ids=["person1"], team_id=self.team.pk)+ create_person(distinct_ids=["person1"], team_id=self.team.pk)with freeze_time("2020-01-09T12:00:00Z"):- Person.objects.create(distinct_ids=["person2"], team_id=self.team.pk)+ create_person(distinct_ids=["person2"], team_id=self.team.pk)journeys_for({@@ -100,7 +100,7 @@ class TestClickhouseLifecycle(TestLifecycleBase):def test_lifecycle_edge_cases(self):# This test tests behavior when created_at is different from first matching event and dormant/resurrecting/returning logicwith freeze_time("2020-01-11T12:00:00Z"):- Person.objects.create(distinct_ids=["person1"], team_id=self.team.pk)+ create_person(distinct_ids=["person1"], team_id=self.team.pk)journeys_for({@@ -263,7 +263,7 @@ class TestClickhouseLifecycle(TestLifecycleBase):def _setup_returning_lifecycle_data(self, days):with freeze_time("2019-01-01T12:00:00Z"):- Person.objects.create(+ create_person(distinct_ids=["person1"],team_id=self.team.pk,properties={"email": "[email protected]"},diff --git a/ee/clickhouse/queries/test/test_related_actors_query.py b/ee/clickhouse/queries/test/test_related_actors_query.pyindex 39266b74abe2..f4c777f5becc 100644--- a/ee/clickhouse/queries/test/test_related_actors_query.py+++ b/ee/clickhouse/queries/test/test_related_actors_query.py@@ -14,9 +14,10 @@ from posthog.test.base import ()from posthog.clickhouse.client import sync_execute-from posthog.models import Group, GroupTypeMapping+from posthog.models import Groupfrom posthog.models.filters.utils import GroupTypeIndexfrom posthog.models.group.util import create_group+from posthog.test.persons import create_group_type_mappingfrom ee.clickhouse.queries.related_actors_query import RelatedActorsQuery@@ -31,10 +32,10 @@ class BaseRelatedActorsTest(ABC, ClickhouseTestMixin, APIBaseTest):self.unrelated_person = _create_person(distinct_ids=["user3"], team=self.team)self.old_related_person = _create_person(distinct_ids=["user4"], team=self.team)- self.org_group_type = GroupTypeMapping.objects.create(+ self.org_group_type = create_group_type_mapping(group_type_index=0, team=self.team, project=self.project, group_type="org")- self.instance_group_type = GroupTypeMapping.objects.create(+ self.instance_group_type = create_group_type_mapping(group_type_index=1, team=self.team, project=self.project, group_type="instance")org_type_index = cast(GroupTypeIndex, self.org_group_type.group_type_index)diff --git a/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_person.py b/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_person.pyindex 68d536e8bdfe..bb7f527d3544 100644--- a/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_person.py+++ b/ee/clickhouse/views/test/funnel/test_clickhouse_funnel_person.py@@ -17,7 +17,7 @@ from rest_framework import statusfrom posthog.constants import INSIGHT_FUNNELSfrom posthog.models.group.util import create_groupfrom posthog.models.instance_setting import get_instance_setting-from posthog.models.person import Person+from posthog.test.persons import create_person, delete_personclass TestFunnelPerson(ClickhouseTestMixin, APIBaseTest):@@ -31,7 +31,7 @@ class TestFunnelPerson(ClickhouseTestMixin, APIBaseTest):for i in range(num):if delete:- person = Person.objects.create(distinct_ids=[f"user_{i}"], team=self.team)+ person = create_person(distinct_ids=[f"user_{i}"], team=self.team)else:_create_person(distinct_ids=[f"user_{i}"], team=self.team)_create_event(@@ -56,7 +56,7 @@ class TestFunnelPerson(ClickhouseTestMixin, APIBaseTest):properties={"$browser": "Chrome", "$group_0": "g0"},)if delete:- person.delete()+ delete_person(person)def test_basic_format(self):self._create_sample_data(5)diff --git a/ee/clickhouse/views/test/test_clickhouse_groups.py b/ee/clickhouse/views/test/test_clickhouse_groups.pyindex 25eef7bd9de0..bcd9aa5327ab 100644--- a/ee/clickhouse/views/test/test_clickhouse_groups.py+++ b/ee/clickhouse/views/test/test_clickhouse_groups.py@@ -21,14 +21,19 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.helpers.dashboard_templates import create_group_type_mapping_detail_dashboard-from posthog.models import GroupTypeMapping, GroupUsageMetric, Person, PropertyDefinition+from posthog.models import GroupTypeMapping, GroupUsageMetric, PropertyDefinitionfrom posthog.models.filters.utils import GroupTypeIndexfrom posthog.models.group.group import Groupfrom posthog.models.group.util import ListGroupsResult, create_group, list_groups, raw_create_group_ch-from posthog.models.group_type_mapping import GROUP_TYPES_CACHE_KEY_PREFIX, GROUP_TYPES_STALE_CACHE_KEY_PREFIX+from posthog.models.group_type_mapping import (+ GROUP_TYPES_CACHE_KEY_PREFIX,+ GROUP_TYPES_STALE_CACHE_KEY_PREFIX,+ update_group_type_mapping_fields,+)from posthog.models.organization import Organizationfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.models.team.team import Team+from posthog.test.persons import create_group_type_mapping, create_personfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.notebooks.backend.models import Notebook, ResourceNotebook@@ -1522,8 +1527,7 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):)dashboard = create_group_type_mapping_detail_dashboard(group_type, self.user)- group_type.detail_dashboard_id = dashboard.id- group_type.save()+ update_group_type_mapping_fields(group_type, fields={"detail_dashboard_id": dashboard.id}, caller_tag="test")response = self.client.put(f"/api/projects/{self.team.id}/groups_types/create_detail_dashboard",@@ -1571,9 +1575,9 @@ class GroupsViewSetTestCase(ClickhouseTestMixin, APIBaseTest):uuid = UUID("01795392-cc00-0003-7dc7-67a694604d72")- Person.objects.create(uuid=uuid, team_id=self.team.pk, distinct_ids=["1", "2"])- Person.objects.create(team_id=self.team.pk, distinct_ids=["3"])- Person.objects.create(team_id=self.team.pk, distinct_ids=["4"])+ create_person(uuid=uuid, team=self.team, distinct_ids=["1", "2"])+ create_person(team=self.team, distinct_ids=["3"])+ create_person(team=self.team, distinct_ids=["4"])create_group(self.team.pk, 0, "0::0")create_group(self.team.pk, 0, "0::1")@@ -1658,9 +1662,7 @@ class GroupsTypesViewSetTestCase(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)def test_create_detail_dashboard(self):- GroupTypeMapping.objects.create(- team=self.team, project=self.project, group_type="organization", group_type_index=0- )+ create_group_type_mapping(team=self.team, project=self.project, group_type="organization", group_type_index=0)response = self.client.put(self.url + "/create_detail_dashboard", {"group_type_index": 0})@@ -1752,9 +1754,7 @@ class GroupsTypesViewSetTestCase(APIBaseTest):self.assertNotIn("detail_dashboard_id", response.json()[0])def test_update_metadata_invalidates_cache(self):- GroupTypeMapping.objects.create(- team=self.team, project=self.project, group_type="organization", group_type_index=0- )+ create_group_type_mapping(team=self.team, project=self.project, group_type="organization", group_type_index=0)cache_key, stale_cache_key = self._seed_cache()response = self.client.patch(@@ -1768,9 +1768,7 @@ class GroupsTypesViewSetTestCase(APIBaseTest):self.assertEqual(cache.get(stale_cache_key)[0]["name_singular"], "org")def test_destroy_invalidates_cache(self):- GroupTypeMapping.objects.create(- team=self.team, project=self.project, group_type="organization", group_type_index=0- )+ create_group_type_mapping(team=self.team, project=self.project, group_type="organization", group_type_index=0)cache_key, stale_cache_key = self._seed_cache()response = self.client.delete(self.url + "/0")@@ -1780,9 +1778,7 @@ class GroupsTypesViewSetTestCase(APIBaseTest):self.assertIsNone(cache.get(stale_cache_key))def test_create_detail_dashboard_invalidates_cache(self):- GroupTypeMapping.objects.create(- team=self.team, project=self.project, group_type="organization", group_type_index=0- )+ create_group_type_mapping(team=self.team, project=self.project, group_type="organization", group_type_index=0)cache_key, stale_cache_key = self._seed_cache()response = self.client.put(self.url + "/create_detail_dashboard", {"group_type_index": 0})@@ -1792,9 +1788,7 @@ class GroupsTypesViewSetTestCase(APIBaseTest):self.assertIsNone(cache.get(stale_cache_key))def test_set_default_columns_invalidates_cache(self):- GroupTypeMapping.objects.create(- team=self.team, project=self.project, group_type="organization", group_type_index=0- )+ create_group_type_mapping(team=self.team, project=self.project, group_type="organization", group_type_index=0)cache_key, stale_cache_key = self._seed_cache()response = self.client.put(@@ -1812,7 +1806,7 @@ class GroupsTypesViewSetTestCase(APIBaseTest):from ee.models.rbac.access_control import AccessControl- group_type = GroupTypeMapping.objects.create(+ group_type = create_group_type_mapping(team=self.team, project=self.project, group_type="organization", group_type_index=0)self.organization_membership.level = OrganizationMembership.Level.MEMBER@@ -1843,7 +1837,7 @@ class GroupsTypesViewSetTestCase(APIBaseTest):def test_update_metadata_admin_can_modify_protected_fields(self):from posthog.models.organization import OrganizationMembership- group_type = GroupTypeMapping.objects.create(+ group_type = create_group_type_mapping(team=self.team, project=self.project, group_type="organization", group_type_index=0)self.organization_membership.level = OrganizationMembership.Level.ADMIN@@ -1864,14 +1858,14 @@ class GroupsTypesViewSetTestCase(APIBaseTest):class GroupUsageMetricViewSetTestCase(APIBaseTest):def setUp(self):super().setUp()- self.group_type = GroupTypeMapping.objects.create(+ self.group_type = create_group_type_mapping(team=self.team, project=self.project, group_type="organization", group_type_index=0)self.url = f"/api/projects/{self.team.id}/groups_types/{str(self.group_type.group_type_index)}/metrics"self.other_org = Organization.objects.create(name="other org")self.other_team = Team.objects.create(organization=self.other_org, name="other team")- self.other_group_type = GroupTypeMapping.objects.create(+ self.other_group_type = create_group_type_mapping(team=self.other_team, project_id=self.other_team.project_id, group_type="company", group_type_index=0)self.other_url = (diff --git a/ee/hogai/chat_agent/taxonomy/test/test_entities.py b/ee/hogai/chat_agent/taxonomy/test/test_entities.pyindex 124b434b409c..e4ab1e7e5791 100644--- a/ee/hogai/chat_agent/taxonomy/test/test_entities.py+++ b/ee/hogai/chat_agent/taxonomy/test/test_entities.py@@ -2,7 +2,7 @@ from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTestfrom unittest.mock import patchfrom posthog.models.group_type_mapping import invalidate_group_types_cache-from posthog.models.person import Person+from posthog.test.persons import create_personfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.event_definitions.backend.models.property_definition import PropertyDefinition@@ -49,7 +49,7 @@ class TestEntities(ClickhouseTestMixin, NonAtomicBaseTest):type=PropertyDefinition.Type.PERSON,)- Person.objects.create(+ create_person(team=self.team,distinct_ids=["test-user"],properties={"name": "Test User"},diff --git a/posthog/api/test/__snapshots__/test_person.ambr b/posthog/api/test/__snapshots__/test_person.ambrindex da8516e47da9..57ff6181986e 100644--- a/posthog/api/test/__snapshots__/test_person.ambr+++ b/posthog/api/test/__snapshots__/test_person.ambr@@ -13,20 +13,6 @@LIMIT 100 SETTINGS optimize_aggregation_in_order = 1'''# ----# name: TestPerson.test_filter_person_email_materialized- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND has(['[email protected]'], "pmat_email")- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ---# name: TestPerson.test_filter_person_list'''/* user_id:0 request:_snapshot_ */@@ -184,47 +170,6 @@LIMIT 20'''# ----# name: TestPerson.test_person_property_values_materialized- '''- /* user_id:0 request:_snapshot_ */- SELECT value,- uniq(id) - uniqIf(id, is_deleted != 0) as c- FROM- (SELECT "pmat_random_prop" as value,- is_deleted,- id- FROM person- WHERE team_id = 99999- AND value IS NOT NULL- AND value != ''- ORDER BY id DESC- LIMIT 100000)- GROUP BY value- HAVING c > 0- ORDER BY c DESC- LIMIT 20- '''-# ----# name: TestPerson.test_person_property_values_materialized.1- '''- /* user_id:0 request:_snapshot_ */- SELECT value,- uniq(id) - uniqIf(id, is_deleted != 0) as c- FROM- (SELECT "pmat_random_prop" as value,- is_deleted,- id- FROM person- WHERE team_id = 99999- AND value ILIKE '%qw%'- ORDER BY id DESC- LIMIT 100000)- GROUP BY value- HAVING c > 0- ORDER BY c DESC- LIMIT 20- '''-# ---# name: TestPerson.test_properties'''/* user_id:0 request:_snapshot_ */@@ -263,44 +208,6 @@LIMIT 100 SETTINGS optimize_aggregation_in_order = 1'''# ----# name: TestPerson.test_properties_materialized- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND id IN- (SELECT id- FROM person- WHERE team_id = 99999- AND (notEmpty("pmat_email")))- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- AND (notEmpty(argMax(person."pmat_email", version)))- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ----# name: TestPerson.test_properties_materialized.1- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND id IN- (SELECT id- FROM person- WHERE team_id = 99999- AND ("pmat_email" ILIKE '%another@gm%'))- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- AND (argMax(person."pmat_email", version) ILIKE '%another@gm%')- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ---# name: TestPerson.test_search'''/* user_id:0 request:_snapshot_ */@@ -379,84 +286,6 @@LIMIT 100 SETTINGS optimize_aggregation_in_order = 1'''# ----# name: TestPerson.test_search_materialized- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND id IN- (SELECT id- FROM person- WHERE team_id = 99999- AND (("pmat_email" ILIKE '%another@gm%')- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = 'another@gm')))- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- AND ((argMax(person."pmat_email", version) ILIKE '%another@gm%')- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = 'another@gm'))- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ----# name: TestPerson.test_search_materialized.1- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND id IN- (SELECT id- FROM person- WHERE team_id = 99999- AND (("pmat_email" ILIKE '%distinct_id_3%')- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = 'distinct_id_3')))- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- AND ((argMax(person."pmat_email", version) ILIKE '%distinct_id_3%')- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = 'distinct_id_3'))- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ---# name: TestPerson.test_search_person_id'''/* user_id:0 request:_snapshot_ */@@ -498,47 +327,6 @@LIMIT 100 SETTINGS optimize_aggregation_in_order = 1'''# ----# name: TestPerson.test_search_person_id_materialized- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND id IN- (SELECT id- FROM person- WHERE team_id = 99999- AND (("pmat_email" ILIKE '%00000000-0000-4000-8000-000000000000%')- OR (id = '00000000-0000-4000-8000-000000000000'- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = '00000000-0000-4000-8000-000000000000'))))- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- AND ((argMax(person."pmat_email", version) ILIKE '%00000000-0000-4000-8000-000000000000%')- OR (id = '00000000-0000-4000-8000-000000000000'- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = '00000000-0000-4000-8000-000000000000')))- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ---# name: TestPersonFromClickhouse.test_filter_person_email'''/* user_id:0 request:_snapshot_ */@@ -553,20 +341,6 @@LIMIT 100 SETTINGS optimize_aggregation_in_order = 1'''# ----# name: TestPersonFromClickhouse.test_filter_person_email_materialized- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND has(['[email protected]'], "pmat_email")- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ---# name: TestPersonFromClickhouse.test_filter_person_list'''/* user_id:0 request:_snapshot_ */@@ -724,47 +498,6 @@LIMIT 20'''# ----# name: TestPersonFromClickhouse.test_person_property_values_materialized- '''- /* user_id:0 request:_snapshot_ */- SELECT value,- uniq(id) - uniqIf(id, is_deleted != 0) as c- FROM- (SELECT "pmat_random_prop" as value,- is_deleted,- id- FROM person- WHERE team_id = 99999- AND value IS NOT NULL- AND value != ''- ORDER BY id DESC- LIMIT 100000)- GROUP BY value- HAVING c > 0- ORDER BY c DESC- LIMIT 20- '''-# ----# name: TestPersonFromClickhouse.test_person_property_values_materialized.1- '''- /* user_id:0 request:_snapshot_ */- SELECT value,- uniq(id) - uniqIf(id, is_deleted != 0) as c- FROM- (SELECT "pmat_random_prop" as value,- is_deleted,- id- FROM person- WHERE team_id = 99999- AND value ILIKE '%qw%'- ORDER BY id DESC- LIMIT 100000)- GROUP BY value- HAVING c > 0- ORDER BY c DESC- LIMIT 20- '''-# ---# name: TestPersonFromClickhouse.test_properties'''/* user_id:0 request:_snapshot_ */@@ -803,44 +536,6 @@LIMIT 100 SETTINGS optimize_aggregation_in_order = 1'''# ----# name: TestPersonFromClickhouse.test_properties_materialized- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND id IN- (SELECT id- FROM person- WHERE team_id = 99999- AND (notEmpty("pmat_email")))- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- AND (notEmpty(argMax(person."pmat_email", version)))- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ----# name: TestPersonFromClickhouse.test_properties_materialized.1- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND id IN- (SELECT id- FROM person- WHERE team_id = 99999- AND ("pmat_email" ILIKE '%another@gm%'))- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- AND (argMax(person."pmat_email", version) ILIKE '%another@gm%')- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ---# name: TestPersonFromClickhouse.test_search'''/* user_id:0 request:_snapshot_ */@@ -919,84 +614,6 @@LIMIT 100 SETTINGS optimize_aggregation_in_order = 1'''# ----# name: TestPersonFromClickhouse.test_search_materialized- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND id IN- (SELECT id- FROM person- WHERE team_id = 99999- AND (("pmat_email" ILIKE '%another@gm%')- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = 'another@gm')))- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- AND ((argMax(person."pmat_email", version) ILIKE '%another@gm%')- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = 'another@gm'))- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ----# name: TestPersonFromClickhouse.test_search_materialized.1- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND id IN- (SELECT id- FROM person- WHERE team_id = 99999- AND (("pmat_email" ILIKE '%distinct_id_3%')- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = 'distinct_id_3')))- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- AND ((argMax(person."pmat_email", version) ILIKE '%distinct_id_3%')- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = 'distinct_id_3'))- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ---# name: TestPersonFromClickhouse.test_search_person_id'''/* user_id:0 request:_snapshot_ */@@ -1038,44 +655,3 @@LIMIT 100 SETTINGS optimize_aggregation_in_order = 1'''# ----# name: TestPersonFromClickhouse.test_search_person_id_materialized- '''- /* user_id:0 request:_snapshot_ */- SELECT id- FROM person- WHERE team_id = 99999- AND id IN- (SELECT id- FROM person- WHERE team_id = 99999- AND (("pmat_email" ILIKE '%00000000-0000-4000-8000-000000000000%')- OR (id = '00000000-0000-4000-8000-000000000000'- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = '00000000-0000-4000-8000-000000000000'))))- GROUP BY id- HAVING max(is_deleted) = 0- AND argMax(person.created_at, version) < now() + INTERVAL 1 DAY- AND ((argMax(person."pmat_email", version) ILIKE '%00000000-0000-4000-8000-000000000000%')- OR (id = '00000000-0000-4000-8000-000000000000'- OR id IN- (SELECT person_id- FROM- (SELECT distinct_id,- argMax(person_id, version) as person_id- FROM person_distinct_id2- WHERE team_id = 99999- GROUP BY distinct_id- HAVING argMax(is_deleted, version) = 0)- WHERE distinct_id = '00000000-0000-4000-8000-000000000000')))- ORDER BY argMax(person.created_at, version) DESC, id DESC- LIMIT 100 SETTINGS optimize_aggregation_in_order = 1- '''-# ---diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex f230cea5ed94..1eeef9533b65 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -22,7 +22,11 @@ from posthog.helpers.dashboard_templates import create_group_type_mapping_detailfrom posthog.models import Filter, Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.file_system.file_system_view_log import FileSystemViewLog-from posthog.models.group_type_mapping import GROUP_TYPES_CACHE_KEY_PREFIX, GROUP_TYPES_STALE_CACHE_KEY_PREFIX+from posthog.models.group_type_mapping import (+ GROUP_TYPES_CACHE_KEY_PREFIX,+ GROUP_TYPES_STALE_CACHE_KEY_PREFIX,+ update_group_type_mapping_fields,+)from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.project import Projectfrom posthog.models.quick_filter import QuickFilter@@ -997,8 +1001,7 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):)dashboard = create_group_type_mapping_detail_dashboard(group_type, self.user)- group_type.detail_dashboard_id = dashboard.id- group_type.save()+ update_group_type_mapping_fields(group_type, fields={"detail_dashboard_id": dashboard.id}, caller_tag="test")cache_key = f"{GROUP_TYPES_CACHE_KEY_PREFIX}{self.team.project_id}"stale_cache_key = f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{self.team.project_id}"diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex c01387759c43..59b5afab0ada 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -39,6 +39,7 @@ from posthog.tasks.calculate_cohort import (increment_version_and_enqueue_calculate_cohort,insert_cohort_from_filters,)+from posthog.test.persons import create_personfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort, CohortType@@ -134,8 +135,8 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin):self.team.app_urls = ["http://somewebsite.com"]self.team.save()- Person.objects.create(team=self.team, properties={"team_id": 5})- Person.objects.create(team=self.team, properties={"team_id": 6})+ create_person(team=self.team, properties={"team_id": 5})+ create_person(team=self.team, properties={"team_id": 6})# Make sure the endpoint works with and without the trailing slashresponse = self.client.post(@@ -306,8 +307,8 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchindef test_list_cohorts_is_not_nplus1(self, patch_calculate_cohort, patch_capture):self.team.app_urls = ["http://somewebsite.com"]self.team.save()- Person.objects.create(team=self.team, properties={"team_id": 5})- Person.objects.create(team=self.team, properties={"team_id": 6})+ create_person(team=self.team, properties={"team_id": 5})+ create_person(team=self.team, properties={"team_id": 6})response = self.client.post(f"/api/projects/{self.team.id}/cohorts",@@ -338,10 +339,10 @@ class TestCohort(TestExportMixin, ClickhouseTestMixin, APIBaseTest, QueryMatchin"""Test CSV upload end-to-end with actual celery task execution"""self.team.app_urls = ["http://somewebsite.com"]self.team.save()- Person.objects.create(team=self.team, properties={"email": "[email protected]"})- Person.objects.create(team=self.team, distinct_ids=["123"])- Person.objects.create(team=self.team, distinct_ids=["456"])- Person.objects.create(team=self.team, distinct_ids=["0"]) # Test edge case: '0' as distinct_id+ create_person(team=self.team, properties={"email": "[email protected]"})+ create_person(team=self.team, distinct_ids=["123"])+ create_person(team=self.team, distinct_ids=["456"])+ create_person(team=self.team, distinct_ids=["0"]) # Test edge case: '0' as distinct_idcsv = SimpleUploadedFile("example.csv",@@ -839,9 +840,9 @@ [email protected]self, distinct_id_column_header, patch_calculate_cohort_from_list):"""Test multi-column CSV upload with distinct_id column"""- person1 = Person.objects.create(team=self.team, distinct_ids=["user123"])- person2 = Person.objects.create(team=self.team, distinct_ids=["user456"])- person3 = Person.objects.create(team=self.team, distinct_ids=["0"]) # Test edge case: '0' as distinct_id+ person1 = create_person(team=self.team, distinct_ids=["user123"])+ person2 = create_person(team=self.team, distinct_ids=["user456"])+ person3 = create_person(team=self.team, distinct_ids=["0"]) # Test edge case: '0' as distinct_idcsv = SimpleUploadedFile("multicolumn.csv",@@ -912,8 +913,8 @@ Jane Smith,25self, person_id_column_header, patch_calculate_cohort_from_list):"""Test CSV upload with person_id column using async task"""- person1 = Person.objects.create(team=self.team, distinct_ids=["user123"])- person2 = Person.objects.create(team=self.team, distinct_ids=["user456"])+ person1 = create_person(team=self.team, distinct_ids=["user123"])+ person2 = create_person(team=self.team, distinct_ids=["user456"])csv = SimpleUploadedFile(f"{person_id_column_header}.csv",@@ -950,16 +951,16 @@ Jane Smith,{person2.uuid},[email protected])def test_static_cohort_csv_upload_person_id_preference_over_email(self, patch_calculate_cohort_from_list):"""Test that person_id is preferred over email when both columns are present"""- person1 = Person.objects.create(team=self.team, distinct_ids=["user123"])- person2 = Person.objects.create(team=self.team, distinct_ids=["user456"])+ person1 = create_person(team=self.team, distinct_ids=["user123"])+ person2 = create_person(team=self.team, distinct_ids=["user456"])# Create persons with emails that would match if email was used instead- person_with_email1 = Person.objects.create(+ person_with_email1 = create_person(team=self.team,distinct_ids=["email_user1"],properties={"email": "[email protected]"},)- person_with_email2 = Person.objects.create(+ person_with_email2 = create_person(team=self.team,distinct_ids=["email_user2"],properties={"email": "[email protected]"},@@ -1004,16 +1005,16 @@ Jane Smith,{person2.uuid},[email protected])def test_static_cohort_csv_upload_distinct_id_preference_over_email(self, patch_calculate_cohort_from_list):"""Test that distinct_id is preferred over email when both columns are present"""- person1 = Person.objects.create(team=self.team, distinct_ids=["user123"])- person2 = Person.objects.create(team=self.team, distinct_ids=["user456"])+ person1 = create_person(team=self.team, distinct_ids=["user123"])+ person2 = create_person(team=self.team, distinct_ids=["user456"])# Create persons with emails that would match if email was used instead- person_with_email1 = Person.objects.create(+ person_with_email1 = create_person(team=self.team,distinct_ids=["email_user1"],properties={"email": "[email protected]"},)- person_with_email2 = Person.objects.create(+ person_with_email2 = create_person(team=self.team,distinct_ids=["email_user2"],properties={"email": "[email protected]"},@@ -1053,8 +1054,8 @@ Jane Smith,user456,[email protected]self.assertNotIn(str(person_with_email2.uuid), person_uuids_in_cohort)def test_static_cohort_with_manually_added_person_ids(self):- person1 = Person.objects.create(team=self.team, distinct_ids=["user123"])- person2 = Person.objects.create(team=self.team, distinct_ids=["user456"])+ person1 = create_person(team=self.team, distinct_ids=["user123"])+ person2 = create_person(team=self.team, distinct_ids=["user456"])response = self.client.post(f"/api/projects/{self.team.id}/cohorts/",@@ -1087,8 +1088,8 @@ Jane Smith,user456,[email protected]def test_static_cohort_csv_and_manually_added(self):"""Test CSV upload with person_id column using async task"""- person1 = Person.objects.create(team=self.team, distinct_ids=["user123"])- person2 = Person.objects.create(team=self.team, distinct_ids=["user456"])+ person1 = create_person(team=self.team, distinct_ids=["user123"])+ person2 = create_person(team=self.team, distinct_ids=["user456"])csv = SimpleUploadedFile(f"{person1}.csv",@@ -1126,8 +1127,8 @@ John Doe,{person1.uuid},[email protected]@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")def test_static_cohort_csv_upload_person_id_preference_over_distinct_id(self, patch_calculate_cohort_from_list):"""Test that person_id is preferred over distinct_id when both columns are present"""- person1 = Person.objects.create(team=self.team, distinct_ids=["distinct123"])- person2 = Person.objects.create(team=self.team, distinct_ids=["distinct456"])+ person1 = create_person(team=self.team, distinct_ids=["distinct123"])+ person2 = create_person(team=self.team, distinct_ids=["distinct456"])csv = SimpleUploadedFile("both_columns.csv",@@ -1159,7 +1160,7 @@ Jane Smith,{person2.uuid},ignore_this_too,[email protected]@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")def test_static_cohort_csv_upload_with_empty_person_ids(self, patch_calculate_cohort_from_list):"""Test CSV with person_id column but some empty values"""- person1 = Person.objects.create(team=self.team, distinct_ids=["user123"])+ person1 = create_person(team=self.team, distinct_ids=["user123"])csv = SimpleUploadedFile("empty_person_ids.csv",@@ -1270,7 +1271,7 @@ Jane Smith,25@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")def test_static_cohort_csv_upload_single_column_backwards_compatibility(self, patch_calculate_cohort_from_list):"""Test that single-column CSV still works (backwards compatibility)"""- Person.objects.create(team=self.team, distinct_ids=["legacy_user"])+ create_person(team=self.team, distinct_ids=["legacy_user"])csv = SimpleUploadedFile("single_column.csv",@@ -1301,8 +1302,8 @@ another_user@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")def test_static_cohort_csv_upload_single_column_person_ids(self, patch_calculate_cohort_from_list):"""Test that single-column CSV with person_id header is treated as person UUIDs"""- person1 = Person.objects.create(team=self.team)- person2 = Person.objects.create(team=self.team)+ person1 = create_person(team=self.team)+ person2 = create_person(team=self.team)csv = SimpleUploadedFile("person_ids.csv",@@ -1335,8 +1336,8 @@ another_user@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")def test_static_cohort_csv_upload_whitespace_handling(self, patch_calculate_cohort_from_list):"""Test that whitespace is properly trimmed from distinct IDs in multi-column CSV"""- Person.objects.create(team=self.team, distinct_ids=["user123"])- Person.objects.create(team=self.team, distinct_ids=["user456"])+ create_person(team=self.team, distinct_ids=["user123"])+ create_person(team=self.team, distinct_ids=["user456"])csv = SimpleUploadedFile("whitespace.csv",@@ -1369,8 +1370,8 @@ Jane Smith, user456 ,[email protected]@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")def test_static_cohort_csv_upload_with_commas_in_distinct_ids(self, patch_calculate_cohort_from_list):"""Test that CSV quoting/escaping works when distinct IDs contain commas"""- Person.objects.create(team=self.team, distinct_ids=["user,123"])- Person.objects.create(team=self.team, distinct_ids=["user,456,special"])+ create_person(team=self.team, distinct_ids=["user,123"])+ create_person(team=self.team, distinct_ids=["user,456,special"])csv = SimpleUploadedFile("comma_ids.csv",@@ -1403,8 +1404,8 @@ Jane Smith, user456 ,[email protected]@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")def test_static_cohort_csv_upload_with_quotes_in_distinct_ids(self, patch_calculate_cohort_from_list):"""Test that CSV escaping works when distinct IDs contain quotes"""- Person.objects.create(team=self.team, distinct_ids=['user"123'])- Person.objects.create(team=self.team, distinct_ids=['user"special"456'])+ create_person(team=self.team, distinct_ids=['user"123'])+ create_person(team=self.team, distinct_ids=['user"special"456'])csv = SimpleUploadedFile("quote_ids.csv",@@ -1437,8 +1438,8 @@ Jane Smith, user456 ,[email protected]@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")def test_static_cohort_csv_upload_with_inconsistent_column_count(self, patch_calculate_cohort_from_list):"""Test that rows with incorrect column count are gracefully skipped in multi-column CSV"""- Person.objects.create(team=self.team, distinct_ids=["user123"])- Person.objects.create(team=self.team, distinct_ids=["user456"])+ create_person(team=self.team, distinct_ids=["user123"])+ create_person(team=self.team, distinct_ids=["user456"])csv = SimpleUploadedFile("inconsistent_columns.csv",@@ -1476,7 +1477,7 @@ user789@patch("posthog.tasks.calculate_cohort.calculate_cohort_from_list.delay")def test_static_cohort_csv_sets_is_calculating(self, patch_calculate_cohort_from_list):"""Test that is_calculating is set to True immediately when CSV is uploaded"""- Person.objects.create(team=self.team, distinct_ids=["user123"])+ create_person(team=self.team, distinct_ids=["user123"])csv = SimpleUploadedFile("test.csv",@@ -1546,9 +1547,9 @@ user456):self.team.app_urls = ["http://somewebsite.com"]self.team.save()- Person.objects.create(team=self.team, properties={"email": "[email protected]"})- Person.objects.create(team=self.team, distinct_ids=["123"])- Person.objects.create(team=self.team, distinct_ids=["456"])+ create_person(team=self.team, properties={"email": "[email protected]"})+ create_person(team=self.team, distinct_ids=["123"])+ create_person(team=self.team, distinct_ids=["456"])csv = SimpleUploadedFile("example.csv",@@ -1587,8 +1588,8 @@ [email protected],self.team.app_urls = ["http://somewebsite.com"]self.team.save()- Person.objects.create(team=self.team, properties={"prop": 5})- Person.objects.create(team=self.team, properties={"prop": 6})+ create_person(team=self.team, properties={"prop": 5})+ create_person(team=self.team, properties={"prop": 6})self.client.post(f"/api/projects/{self.team.id}/cohorts",@@ -1611,7 +1612,7 @@ [email protected],self.assertEqual(len(response["results"]), 0)def test_cohort_list_with_type_filter(self):- Person.objects.create(team=self.team, properties={"prop": 5})+ create_person(team=self.team, properties={"prop": 5})# Create dynamic cohortself.client.post(@@ -1642,7 +1643,7 @@ [email protected],self.assertFalse(response["results"][0]["is_static"])def test_cohort_list_with_created_by_filter(self):- Person.objects.create(team=self.team, properties={"prop": 5})+ create_person(team=self.team, properties={"prop": 5})# Create cohorts by self.userself.client.post(@@ -1689,7 +1690,7 @@ [email protected],self.assertEqual(len(response["results"]), 0)def test_cohort_list_with_combined_filters(self):- Person.objects.create(team=self.team, properties={"prop": 5})+ create_person(team=self.team, properties={"prop": 5})# Create dynamic cohortself.client.post(@@ -2102,8 +2103,8 @@ [email protected],def test_cohort_activity_log(self, patch_on_commit):self.team.app_urls = ["http://somewebsite.com"]self.team.save()- Person.objects.create(team=self.team, properties={"prop": 5})- Person.objects.create(team=self.team, properties={"prop": 6})+ create_person(team=self.team, properties={"prop": 5})+ create_person(team=self.team, properties={"prop": 6})self.client.post(f"/api/projects/{self.team.id}/cohorts",@@ -2227,7 +2228,7 @@ [email protected],num_people = 3person_uuids = []for i in range(num_people):- person = Person.objects.create(+ person = create_person(team=self.team,distinct_ids=[f"user_{i}"],properties={"email": f"user{i}@example.com"},@@ -2275,7 +2276,7 @@ [email protected],num_people = 10person_uuids = []for i in range(num_people):- person = Person.objects.create(+ person = create_person(team=self.team,distinct_ids=[f"user_{i}"],properties={"email": f"user{i}@example.com"},@@ -2357,17 +2358,17 @@ [email protected],def test_csv_export_new(self):# Test 100s of distinct_ids, we only want ~10- Person.objects.create(+ create_person(distinct_ids=["person3"] + [f"person_{i}" for i in range(4, 100)],team_id=self.team.pk,properties={"$some_prop": "something"},)- Person.objects.create(+ create_person(distinct_ids=["person1"],team_id=self.team.pk,properties={"$some_prop": "something", "email": "[email protected]"},)- Person.objects.create(distinct_ids=["person2"], team_id=self.team.pk, properties={})+ create_person(distinct_ids=["person2"], team_id=self.team.pk, properties={})cohort = Cohort.objects.create(team=self.team,groups=[{"properties": [{"key": "$some_prop", "value": "something", "type": "person"}]}],@@ -2485,12 +2486,12 @@ [email protected],self.assertEqual(len(response.json()["results"]), 1, response)def test_filter_by_static_cohort(self):- Person.objects.create(team_id=self.team.pk, distinct_ids=["1"])- Person.objects.create(team_id=self.team.pk, distinct_ids=["123"])- Person.objects.create(team_id=self.team.pk, distinct_ids=["2"])+ create_person(team_id=self.team.pk, distinct_ids=["1"])+ create_person(team_id=self.team.pk, distinct_ids=["123"])+ create_person(team_id=self.team.pk, distinct_ids=["2"])# Team leakageteam2 = Team.objects.create(organization=self.organization)- Person.objects.create(team=team2, distinct_ids=["1"])+ create_person(team=team2, distinct_ids=["1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, last_calculation=timezone.now())cohort.insert_users_by_list(["1", "123"])@@ -3133,8 +3134,8 @@ [email protected],def test_creating_update_and_calculating_ignore_bad_filters(self, patch_calculate_cohort, patch_capture):self.team.app_urls = ["http://somewebsite.com"]self.team.save()- Person.objects.create(team=self.team, properties={"team_id": 5})- Person.objects.create(team=self.team, properties={"team_id": 6})+ create_person(team=self.team, properties={"team_id": 5})+ create_person(team=self.team, properties={"team_id": 6})# Make sure the endpoint works with and without the trailing slashresponse = self.client.post(@@ -6165,12 +6166,12 @@ class TestCohortTypeIntegration(APIBaseTest):)def test_static_cohort_csv_upload_with_email_column_only(self, patch_calculate_cohort_from_list):"""Test CSV upload with only email column using async task"""- person1 = Person.objects.create(+ person1 = create_person(team=self.team,distinct_ids=["user123"],properties={"email": "[email protected]"},)- person2 = Person.objects.create(+ person2 = create_person(team=self.team,distinct_ids=["user456"],properties={"email": "[email protected]"},@@ -6218,16 +6219,16 @@ [email protected])def test_static_cohort_csv_upload_person_id_preference_over_email(self, patch_calculate_cohort_from_list):"""Test that person_id is preferred over email when both columns are present"""- person1 = Person.objects.create(team=self.team, distinct_ids=["user123"])- person2 = Person.objects.create(team=self.team, distinct_ids=["user456"])+ person1 = create_person(team=self.team, distinct_ids=["user123"])+ person2 = create_person(team=self.team, distinct_ids=["user456"])# Create persons with emails that would match if email was used instead- person_with_email1 = Person.objects.create(+ person_with_email1 = create_person(team=self.team,distinct_ids=["email_user1"],properties={"email": "[email protected]"},)- person_with_email2 = Person.objects.create(+ person_with_email2 = create_person(team=self.team,distinct_ids=["email_user2"],properties={"email": "[email protected]"},@@ -6272,16 +6273,16 @@ Jane Smith,{person2.uuid},[email protected])def test_static_cohort_csv_upload_distinct_id_preference_over_email(self, patch_calculate_cohort_from_list):"""Test that distinct_id is preferred over email when both columns are present"""- person1 = Person.objects.create(team=self.team, distinct_ids=["user123"])- person2 = Person.objects.create(team=self.team, distinct_ids=["user456"])+ person1 = create_person(team=self.team, distinct_ids=["user123"])+ person2 = create_person(team=self.team, distinct_ids=["user456"])# Create persons with emails that would match if email was used instead- person_with_email1 = Person.objects.create(+ person_with_email1 = create_person(team=self.team,distinct_ids=["email_user1"],properties={"email": "[email protected]"},)- person_with_email2 = Person.objects.create(+ person_with_email2 = create_person(team=self.team,distinct_ids=["email_user2"],properties={"email": "[email protected]"},@@ -6326,9 +6327,7 @@ Jane Smith,user456,[email protected]CSV upload with an email column always uses the ClickHouse pmat_emailmaterialized column for lookup, regardless of CSV header casing."""- person = Person.objects.create(- team=self.team, distinct_ids=["user_email"], properties={"email": "[email protected]"}- )+ person = create_person(team=self.team, distinct_ids=["user_email"], properties={"email": "[email protected]"})csv_file = SimpleUploadedFile("emails.csv",diff --git a/posthog/api/test/test_cohort_personhog.py b/posthog/api/test/test_cohort_personhog.pyindex 6004968a7ae5..75934f60a4df 100644--- a/posthog/api/test/test_cohort_personhog.py+++ b/posthog/api/test/test_cohort_personhog.py@@ -1,31 +1,20 @@"""Tests that cohort API endpoints produce identical results-via the ORM and personhog paths."""+via the personhog path."""from posthog.test.base import APIBaseTest, BaseTest-from parameterized import parameterized_classfrom rest_framework import status-from posthog.models.person import Personfrom posthog.models.person.util import validate_person_uuids_exist-from posthog.personhog_client.test_helpers import PersonhogTestMixin+from posthog.test.personhog_fake import get_active_fake+from posthog.test.persons import create_personfrom products.cohorts.backend.models.cohort import Cohort-@parameterized_class(("personhog",), [(False,), (True,)])-class TestValidatePersonUuidsExist(PersonhogTestMixin, BaseTest):+class TestValidatePersonUuidsExist(BaseTest):def _create_person_with_uuid(self, *, team, uuid, distinct_ids):- """Create a person in the DB (and fake client when personhog is active)."""- person = Person.objects.create(team=team, uuid=uuid, distinct_ids=distinct_ids)- if self._fake_client is not None:- self._fake_client.add_person(- team_id=team.pk,- person_id=person.pk,- uuid=str(person.uuid),- distinct_ids=distinct_ids,- )- return person+ return create_person(team=team, uuid=uuid, distinct_ids=distinct_ids)def test_returns_matching_uuids(self):uuid_a = "550e8400-e29b-41d4-a716-446655440000"@@ -38,7 +27,7 @@ class TestValidatePersonUuidsExist(PersonhogTestMixin, BaseTest):result = validate_person_uuids_exist(self.team.pk, [uuid_a, uuid_b, uuid_c])assert set(result) == {uuid_a, uuid_b}- self._assert_personhog_called("get_persons_by_uuids")+ get_active_fake().assert_called("get_persons_by_uuids")def test_filters_cross_team_results(self):uuid_a = "550e8400-e29b-41d4-a716-446655440000"@@ -59,7 +48,7 @@ class TestValidatePersonUuidsExist(PersonhogTestMixin, BaseTest):result = validate_person_uuids_exist(self.team.pk, [uuid_missing])assert result == []- self._assert_personhog_called("get_persons_by_uuids")+ get_active_fake().assert_called("get_persons_by_uuids")def test_output_is_list_of_uuid_strings(self):uuid_a = "550e8400-e29b-41d4-a716-446655440000"@@ -72,16 +61,15 @@ class TestValidatePersonUuidsExist(PersonhogTestMixin, BaseTest):assert len(uuids) > 0assert all(isinstance(u, str) for u in uuids)- self._assert_personhog_called("get_persons_by_uuids")+ get_active_fake().assert_called("get_persons_by_uuids")UUID_NONEXISTENT = "550e8400-e29b-41d4-a716-446655440099"-@parameterized_class(("personhog",), [(False,), (True,)])-class TestRemovePersonFromStaticCohort(PersonhogTestMixin, APIBaseTest):+class TestRemovePersonFromStaticCohort(APIBaseTest):def test_removes_person_and_routes_through_personhog(self):- person = self._seed_person(team=self.team, distinct_ids=["d1"], properties={"email": "[email protected]"})+ person = create_person(team=self.team, distinct_ids=["d1"], properties={"email": "[email protected]"})cohort = Cohort.objects.create(team=self.team, name="static", is_static=True)cohort.insert_users_by_list(["d1"])@@ -93,7 +81,7 @@ class TestRemovePersonFromStaticCohort(PersonhogTestMixin, APIBaseTest):assert resp.status_code == status.HTTP_200_OKassert resp.json()["success"] is True- self._assert_personhog_called("get_person_by_uuid")+ get_active_fake().assert_called("get_person_by_uuid")def test_returns_404_for_nonexistent_person(self):cohort = Cohort.objects.create(team=self.team, name="static", is_static=True)@@ -105,4 +93,4 @@ class TestRemovePersonFromStaticCohort(PersonhogTestMixin, APIBaseTest):)assert resp.status_code == status.HTTP_404_NOT_FOUND- self._assert_personhog_called("get_person_by_uuid")+ get_active_fake().assert_called("get_person_by_uuid")diff --git a/posthog/api/test/test_event.py b/posthog/api/test/test_event.pyindex 072f172ff2f7..9cd0635f047f 100644--- a/posthog/api/test/test_event.py+++ b/posthog/api/test/test_event.py@@ -23,8 +23,9 @@ from dateutil.relativedelta import relativedeltafrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import Element, Organization, Person, PropertyDefinition, User+from posthog.models import Element, Organization, PropertyDefinition, Userfrom posthog.models.event.query_event_list import insight_query_with_columns+from posthog.test.persons import create_personfrom posthog.test.test_journeys import journeys_forfrom products.actions.backend.models.action import Action@@ -146,7 +147,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):assert response.json() == self.validation_error_response("Properties are unparsable!", "invalid_input")def test_filter_events_by_precalculated_cohort(self):- Person.objects.create(team_id=self.team.pk, distinct_ids=["p1"], properties={"key": "value"})+ create_person(team=self.team, distinct_ids=["p1"], properties={"key": "value"})_create_event(team=self.team,event="$pageview",@@ -154,7 +155,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):timestamp="2020-01-02T12:00:00Z",)- Person.objects.create(team_id=self.team.pk, distinct_ids=["p2"], properties={"key": "value"})+ create_person(team=self.team, distinct_ids=["p2"], properties={"key": "value"})_create_event(team=self.team,event="$pageview",@@ -162,7 +163,7 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):timestamp="2020-01-02T12:00:00Z",)- Person.objects.create(team_id=self.team.pk, distinct_ids=["p3"], properties={"key_2": "value_2"})+ create_person(team=self.team, distinct_ids=["p3"], properties={"key_2": "value_2"})_create_event(team=self.team,event="$pageview",diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.pyindex 9c28bcadea7c..87207b14bb9d 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -30,8 +30,12 @@ from posthog.models.async_deletion import AsyncDeletion, DeletionTypefrom posthog.models.person import PersonDistinctIdfrom posthog.models.person.missing_person import uuidFromDistinctIdfrom posthog.models.person.sql import PERSON_DISTINCT_ID2_TABLE-from posthog.models.person.util import create_person, create_person_distinct_id+from posthog.models.person.util import (+ create_person as create_person_in_ch,+ create_person_distinct_id,+)from posthog.personhog_client.fake_client import fake_personhog_client+from posthog.test.persons import add_distinct_id, create_personfrom products.cohorts.backend.models.cohort import Cohort@@ -1467,18 +1471,13 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# Create person A with UUID derived from the distinct_id (same UUID that split will use)person_a_uuid = uuidFromDistinctId(self.team.pk, "deleted_user")- person_a = Person.objects.create(+ person_a = create_person(team=self.team,uuid=person_a_uuid,version=0,)- PersonDistinctId.objects.create(- team_id=self.team.pk,- person=person_a,- distinct_id="deleted_user",- version=0,- )- create_person(+ add_distinct_id(person=person_a, distinct_id="deleted_user", version=0)+ create_person_in_ch(team_id=self.team.pk,uuid=str(person_a.uuid),version=0,@@ -1503,12 +1502,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# Manually add the deleted distinct_id to person B (simulating a merge scenario)# This would happen in a real scenario where events come in for the deleted distinct_id- PersonDistinctId.objects.create(- team_id=self.team.pk,- person=person_b,- distinct_id="deleted_user",- version=2,- )+ add_distinct_id(person=person_b, distinct_id="deleted_user", version=2)create_person_distinct_id(team_id=self.team.pk,distinct_id="deleted_user",@@ -1649,7 +1643,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):for index in range(0, 19):created_ids.append(str(index + 100))- Person.objects.create( # creating without _create_person to guarentee created_at ordering+ create_person( # creating without _create_person to guarentee created_at orderingteam=self.team,distinct_ids=[str(index + 100)],properties={"$browser": "whatever", "$os": "Windows"},@@ -1659,10 +1653,10 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# In this case Clickhouse will return a user that then doesn't get returned by postgres.# We would return an empty "next" url.# Now we just return 9 people instead- create_person(team_id=self.team.pk, version=0)+ create_person_in_ch(team_id=self.team.pk, version=0)returned_ids = []- with self.assertNumQueries(11):+ with self.assertNumQueries(9):response = self.client.get("/api/person/?limit=10").json()self.assertEqual(len(response["results"]), 9)returned_ids += [x["distinct_ids"][0] for x in response["results"]]@@ -1673,12 +1667,12 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):created_ids.reverse() # ids are returned in desc orderself.assertEqual(returned_ids, created_ids, returned_ids)- with self.assertNumQueries(11):+ with self.assertNumQueries(9):response_include_total = self.client.get("/api/person/?limit=10&include_total").json()self.assertEqual(response_include_total["count"], 20) # With `include_total`, the total count is returned toodef test_retrieve_person(self):- person = Person.objects.create( # creating without _create_person to guarentee created_at ordering+ person = create_person( # creating without _create_person to guarentee created_at orderingteam=self.team, distinct_ids=["123456789"])@@ -1689,7 +1683,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):assert response["distinct_ids"] == ["123456789"]def test_retrieve_person_by_uuid(self):- person = Person.objects.create( # creating without _create_person to guarentee created_at ordering+ person = create_person( # creating without _create_person to guarentee created_at orderingteam=self.team, distinct_ids=["123456789"])@@ -1778,7 +1772,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):shared_uuid = str(uuid4())# Phase 1: Person and distinct_id exist in CH as deleted- create_person(+ create_person_in_ch(uuid=shared_uuid,team_id=self.team.pk,is_deleted=True,@@ -1795,13 +1789,8 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# Phase 2: New event reuses the distinct_id, creating a new person in PG# with the same deterministic UUID. The signal writes to CH with version=0,# which is ignored because 0 < 105.- person = Person.objects.create(team_id=self.team.pk, properties={"abcdefg": 11112}, version=0, uuid=shared_uuid)- PersonDistinctId.objects.create(- team_id=self.team.pk,- person=person,- distinct_id="distinct_id",- version=0,- )+ person = create_person(team=self.team, properties={"abcdefg": 11112}, version=0, uuid=shared_uuid)+ add_distinct_id(person=person, distinct_id="distinct_id", version=0)# Phase 3: Resetresponse = self.client.post(@@ -1842,7 +1831,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):# Verify: PG person version is updated so future plugin-server updates aren't ignoredperson.refresh_from_db()- assert person.version > 105+ assert person.version is not None and person.version > 105@mock.patch(f"{posthog.models.person.deletion.__name__}.create_person_distinct_id",@@ -1851,28 +1840,14 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):@pytest.mark.flaky(reruns=2)def test_reset_person_distinct_id_not_found(self, mocked_ch_call):# person who shouldn't be changed- person_not_changed_1 = Person.objects.create(- team_id=self.team.pk, properties={"abcdef": 1111}, version=0, uuid=uuid4()- )+ person_not_changed_1 = create_person(team=self.team, properties={"abcdef": 1111}, version=0, uuid=uuid4())# distinct id no update- PersonDistinctId.objects.create(- team_id=self.team.pk,- person=person_not_changed_1,- distinct_id="distinct_id-1",- version=0,- )+ add_distinct_id(person=person_not_changed_1, distinct_id="distinct_id-1", version=0)# deleted person not re-used- person_deleted_1 = Person.objects.create(- team_id=self.team.pk, properties={"abcdef": 1111}, version=0, uuid=uuid4()- )- PersonDistinctId.objects.create(- team_id=self.team.pk,- person=person_deleted_1,- distinct_id="distinct_id-del-1",- version=16,- )+ person_deleted_1 = create_person(team=self.team, properties={"abcdef": 1111}, version=0, uuid=uuid4())+ add_distinct_id(person=person_deleted_1, distinct_id="distinct_id-del-1", version=16)person_deleted_1.delete()response = self.client.post(@@ -2075,7 +2050,7 @@ class TestPersonFromClickhouse(TestPerson):for index in range(0, 19):created_ids.append(str(index + 100))- Person.objects.create( # creating without _create_person to guarentee created_at ordering+ create_person( # creating without _create_person to guarentee created_at orderingteam=self.team,distinct_ids=[str(index + 100)],properties={"$browser": "whatever", "$os": "Windows"},diff --git a/posthog/api/test/test_person_personhog.py b/posthog/api/test/test_person_personhog.pyindex a5024c8d111c..1234c4d126b0 100644--- a/posthog/api/test/test_person_personhog.py+++ b/posthog/api/test/test_person_personhog.py@@ -1,19 +1,15 @@-"""Tests that person API endpoints produce identical results-via the ORM and personhog paths.+"""Tests that person API endpoints produce identical results via personhog.Covers retrieve, update, split, delete_property, batch_by_distinct_ids, and-person deletion — extracted from test_person.py so both code paths are-validated with @parameterized_class.+person deletion — extracted from test_person.py."""from posthog.test.base import APIBaseTestfrom unittest import mock-from parameterized import parameterized_classfrom rest_framework import statusfrom posthog.models import Organization, Person, Team-from posthog.models.person import PersonDistinctIdfrom posthog.personhog_client.test_helpers import PersonhogTestMixinfrom products.cohorts.backend.models.cohort import Cohort@@ -21,7 +17,6 @@ from products.cohorts.backend.models.cohort import CohortUUID_NONEXISTENT = "550e8400-e29b-41d4-a716-446655440000"-@parameterized_class(("personhog",), [(False,), (True,)])class TestRetrievePerson(PersonhogTestMixin, APIBaseTest):def test_retrieve_by_uuid(self):person = self._seed_person(@@ -76,7 +71,6 @@ class TestRetrievePerson(PersonhogTestMixin, APIBaseTest):assert resp.status_code == status.HTTP_404_NOT_FOUND-@parameterized_class(("personhog",), [(False,), (True,)])class TestUpdatePerson(PersonhogTestMixin, APIBaseTest):@mock.patch("posthog.api.person.capture_internal")def test_update_properties_by_uuid(self, mock_capture):@@ -120,7 +114,6 @@ class TestUpdatePerson(PersonhogTestMixin, APIBaseTest):self._assert_personhog_called("get_person")-@parameterized_class(("personhog",), [(False,), (True,)])class TestSplitPerson(PersonhogTestMixin, APIBaseTest):@mock.patch("posthog.api.person.split_person")def test_split_by_uuid(self, mock_split):@@ -151,7 +144,6 @@ class TestSplitPerson(PersonhogTestMixin, APIBaseTest):mock_split.delay.assert_not_called()-@parameterized_class(("personhog",), [(False,), (True,)])class TestCohortsByPerson(PersonhogTestMixin, APIBaseTest):def test_cohorts_by_uuid(self):person = self._seed_person(@@ -182,7 +174,6 @@ class TestCohortsByPerson(PersonhogTestMixin, APIBaseTest):assert resp.status_code == status.HTTP_404_NOT_FOUND-@parameterized_class(("personhog",), [(False,), (True,)])class TestDeleteProperty(PersonhogTestMixin, APIBaseTest):@mock.patch("posthog.api.person.capture_internal")def test_uuid_lookup(self, mock_capture):@@ -238,7 +229,6 @@ class TestDeleteProperty(PersonhogTestMixin, APIBaseTest):assert resp.status_code != 201-@parameterized_class(("personhog",), [(False,), (True,)])class TestBatchByDistinctIds(PersonhogTestMixin, APIBaseTest):def test_happy_path(self):self._seed_person(team=self.team, distinct_ids=["user_1"], properties={"email": "[email protected]"})@@ -343,7 +333,6 @@ class TestBatchByDistinctIds(PersonhogTestMixin, APIBaseTest):assert distinct_ids[200] not in results-@parameterized_class(("personhog",), [(False,), (True,)])class TestDestroyPerson(PersonhogTestMixin, APIBaseTest):def test_destroy_returns_202(self):person = self._seed_person(team=self.team, distinct_ids=["did-1"])@@ -367,10 +356,6 @@ class TestDestroyPerson(PersonhogTestMixin, APIBaseTest):assert calls[0].request.team_id == self.team.pkassert list(calls[0].request.person_uuids) == [str(person.uuid)]- if not self.personhog:- assert Person.objects.filter(team_id=self.team.pk, uuid=person.uuid).count() == 0- assert PersonDistinctId.objects.filter(team_id=self.team.pk, person_id=person.pk).count() == 0-def test_destroy_nonexistent_returns_404(self):resp = self.client.delete(f"/api/person/{UUID_NONEXISTENT}/")@@ -387,7 +372,6 @@ class TestDestroyPerson(PersonhogTestMixin, APIBaseTest):self._assert_personhog_not_called("delete_persons")-@parameterized_class(("personhog",), [(False,), (True,)])class TestBulkDeletePersons(PersonhogTestMixin, APIBaseTest):def test_bulk_delete_by_ids(self):p1 = self._seed_person(team=self.team, distinct_ids=["did-1"])@@ -411,10 +395,6 @@ class TestBulkDeletePersons(PersonhogTestMixin, APIBaseTest):assert calls[0].request.team_id == self.team.pkassert set(calls[0].request.person_uuids) == {str(p1.uuid), str(p2.uuid)}- if not self.personhog:- assert Person.objects.filter(team_id=self.team.pk).count() == 0- assert PersonDistinctId.objects.filter(team_id=self.team.pk).count() == 0-def test_bulk_delete_by_distinct_ids(self):p1 = self._seed_person(team=self.team, distinct_ids=["did-1"])p2 = self._seed_person(team=self.team, distinct_ids=["did-2"])@@ -435,9 +415,6 @@ class TestBulkDeletePersons(PersonhogTestMixin, APIBaseTest):assert calls[0].request.team_id == self.team.pkassert set(calls[0].request.person_uuids) == {str(p1.uuid), str(p2.uuid)}- if not self.personhog:- assert Person.objects.filter(team_id=self.team.pk).count() == 0-def test_bulk_delete_with_keep_person(self):p1 = self._seed_person(team=self.team, distinct_ids=["did-1"])@@ -503,8 +480,3 @@ class TestBulkDeletePersons(PersonhogTestMixin, APIBaseTest):if calls:# Only the successful person should be sent to personhog for PG deletionassert list(calls[0].request.person_uuids) == [str(p2.uuid)]-- if not self.personhog:- # p1 should still exist (CH delete failed), p2 should be gone- assert Person.objects.filter(team_id=self.team.pk, uuid=p1.uuid).count() == 1- assert Person.objects.filter(team_id=self.team.pk, uuid=p2.uuid).count() == 0diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.pyindex d1bfa70dcb4f..d87e13b86f42 100644--- a/posthog/api/test/test_project.py+++ b/posthog/api/test/test_project.py@@ -12,6 +12,7 @@ from posthog.models.person import Personfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.project import Projectfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.test.persons import create_personclass TestProjectAPI(team_api_test_factory()): # type: ignore@@ -445,7 +446,7 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoredef test_team_deletion_does_not_cascade_to_persons(self):"""Verify that deleting Team directly doesn't CASCADE delete Persons (on_delete=DO_NOTHING)."""# Create a Person- person = Person.objects.create(team=self.team)+ person = create_person(team=self.team)person_id = person.id# Delete the team directly (not via API, bypassing manual delete)diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 553130569c80..0be4f9b9d19b 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -567,18 +567,18 @@ def team_api_test_factory():self.assertEqual(Team.objects.filter(organization=self.organization).count(), 2)# from posthog.models.insight_caching_state import InsightCachingState- from posthog.models.person import Person+ from posthog.test.persons import add_cohort_members, add_distinct_id, create_person- from products.cohorts.backend.models.cohort import Cohort, CohortPeople+ from products.cohorts.backend.models.cohort import Cohortfrom products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagHashKeyOverridecohort = Cohort.objects.create(team=team, created_by=self.user, name="test")- person = Person.objects.create(+ person = create_person(team=team,distinct_ids=["example_id"],properties={"email": "[email protected]", "team": "posthog"},)- person.add_distinct_id("test")+ add_distinct_id(person=person, distinct_id="test")flag = FeatureFlag.objects.create(team=team,name="test",@@ -591,7 +591,7 @@ def team_api_test_factory():feature_flag_key=flag.key,hash_key="test",)- CohortPeople.objects.create(cohort_id=cohort.pk, person_id=person.pk)+ add_cohort_members(cohort, [person])EarlyAccessFeature.objects.create(team=team,name="Test flag",diff --git a/posthog/async_migrations/test/test_0007_persons_and_groups_on_events_backfill.py b/posthog/async_migrations/test/test_0007_persons_and_groups_on_events_backfill.pyindex 26cd887a9a9b..1ee6837105ab 100644--- a/posthog/async_migrations/test/test_0007_persons_and_groups_on_events_backfill.py+++ b/posthog/async_migrations/test/test_0007_persons_and_groups_on_events_backfill.py@@ -8,12 +8,12 @@ from posthog.async_migrations.runner import start_async_migrationfrom posthog.async_migrations.setup import get_async_migration_definition, setup_async_migrationsfrom posthog.async_migrations.test.util import AsyncMigrationBaseTestfrom posthog.clickhouse.client import query_with_columns, sync_execute-from posthog.models import Personfrom posthog.models.async_migration import AsyncMigration, AsyncMigrationError, MigrationStatusfrom posthog.models.event.util import create_eventfrom posthog.models.group.util import create_groupfrom posthog.models.person.util import create_person, create_person_distinct_id, delete_personfrom posthog.models.utils import UUIDT+from posthog.test.persons import create_person as create_test_personpytestmark = pytest.mark.async_migrations@@ -210,8 +210,8 @@ class Test0007PersonsAndGroupsOnEventsBackfill(AsyncMigrationBaseTest, Clickhousdef test_deleted_data_persons(self):distinct_id = "not-reused-id" # distinct ID re-use isn't supported after person deletioncreate_event(event_uuid=uuid1, team=self.team, distinct_id=distinct_id, event="$pageview")- person = Person.objects.create(- team_id=self.team.pk,+ person = create_test_person(+ team=self.team,distinct_ids=[distinct_id],properties={"$some_prop": "something", "$another_prop": "something"},)diff --git a/posthog/dags/tests/max_ai/test_snapshot_team_data.py b/posthog/dags/tests/max_ai/test_snapshot_team_data.pyindex 5539b6238389..b2b717409e44 100644--- a/posthog/dags/tests/max_ai/test_snapshot_team_data.py+++ b/posthog/dags/tests/max_ai/test_snapshot_team_data.py@@ -13,7 +13,8 @@ from posthog.schema import (TeamTaxonomyItem,)-from posthog.models import GroupTypeMapping, Organization, Project, Team+from posthog.models import Organization, Project, Team+from posthog.test.persons import create_group_type_mappingfrom products.event_definitions.backend.models.property_definition import PropertyDefinitionfrom products.posthog_ai.dags.snapshot_team_data import (@@ -322,7 +323,7 @@ def test_snapshot_actors_property_taxonomy_dumps_with_group_type_mapping(mock_check_dump_exists.return_value = False# Create a GroupTypeMapping for the team- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=team,project=team.project,group_type="organization",diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.pyindex d73f1660ff75..8b132d18d4d5 100644--- a/posthog/dags/tests/test_data_deletion_requests.py+++ b/posthog/dags/tests/test_data_deletion_requests.py@@ -32,7 +32,7 @@ from posthog.dags.data_deletion_requests import (load_property_removal_request,)from posthog.models.data_deletion_request import DataDeletionRequest, ExecutionMode, RequestStatus, RequestType-from posthog.models.person import Person+from posthog.test.persons import create_personTEAM_ID = 99999@@ -1563,7 +1563,7 @@ def test_delete_person_events_op_noop_when_disabled(cluster: ClickhouseCluster):def test_delete_person_events_op_resolves_distinct_ids_to_uuids(cluster: ClickhouseCluster):# When the request was submitted by distinct_id, the events op must resolve to UUIDs# because the CH events table is keyed by person_id (UUID).- p = Person.objects.create(team_id=TEAM_ID, uuid=uuid4(), distinct_ids=["distinct-only"])+ p = create_person(team_id=TEAM_ID, uuid=uuid4(), distinct_ids=["distinct-only"])bystander_uuid = str(uuid4())now = datetime.now()@@ -1597,7 +1597,7 @@ def test_delete_person_events_op_resolves_distinct_ids_to_uuids(cluster: Clickho@pytest.mark.django_dbdef test_delete_person_recordings_op_calls_helper_when_enabled():p_uuid = str(uuid4())- Person.objects.create(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])+ create_person(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])ctx = PersonRemovalContext(request_id=str(uuid4()),team_id=TEAM_ID,@@ -1633,7 +1633,7 @@ def test_delete_person_recordings_op_noop_when_disabled():@pytest.mark.django_dbdef test_delete_person_profiles_op_calls_helper_when_enabled():p_uuid = str(uuid4())- Person.objects.create(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])+ create_person(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])ctx = PersonRemovalContext(request_id=str(uuid4()),team_id=TEAM_ID,@@ -1671,7 +1671,7 @@ def test_delete_person_profiles_op_records_per_person_errors_in_metadata():# logs, but the op returns normally so the request can finalize to COMPLETED and the# operator can issue a follow-up request for the failed UUIDs.p_uuid = str(uuid4())- Person.objects.create(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])+ create_person(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])ctx = PersonRemovalContext(request_id=str(uuid4()),team_id=TEAM_ID,@@ -1698,7 +1698,7 @@ def test_delete_person_profiles_op_records_per_person_errors_in_metadata():@pytest.mark.django_dbdef test_data_deletion_request_person_removal_lifecycle(cluster: ClickhouseCluster):p_uuid = str(uuid4())- Person.objects.create(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])+ create_person(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])request = DataDeletionRequest.objects.create(team_id=TEAM_ID,request_type=RequestType.PERSON_REMOVAL,diff --git a/posthog/dags/tests/test_detach_distinct_id.py b/posthog/dags/tests/test_detach_distinct_id.pyindex 100b633ad95a..1ecf378cac36 100644--- a/posthog/dags/tests/test_detach_distinct_id.py+++ b/posthog/dags/tests/test_detach_distinct_id.py@@ -13,6 +13,7 @@ from posthog.dags.detach_distinct_id import (detach_distinct_id_job,)from posthog.kafka_client.topics import KAFKA_PERSON_DISTINCT_ID+from posthog.test.persons import add_distinct_id, create_personPERSON_UUID = "5e00024e-cb68-59f6-821f-6150fcffc431"PERSON_PK = 42@@ -328,13 +329,9 @@ class TestDetachDistinctIdIntegration:@pytest.fixturedef person_with_two_distinct_ids(self, team):- from posthog.models.person import Person, PersonDistinctId-- person = Person.objects.create(team_id=team.id, version=1)- pdi_keep = PersonDistinctId.objects.create(team=team, person=person, distinct_id="keep_this", version=0)- pdi_detach = PersonDistinctId.objects.create(- team=team, person=person, distinct_id="$posthog_cookieless", version=3- )+ person = create_person(team_id=team.id, version=1)+ pdi_keep = add_distinct_id(person=person, distinct_id="keep_this", version=0)+ pdi_detach = add_distinct_id(person=person, distinct_id="$posthog_cookieless", version=3)return person, pdi_keep, pdi_detach@staticmethod@@ -429,10 +426,8 @@ class TestDetachDistinctIdIntegration:@patch("posthog.dags.detach_distinct_id.sync_execute")def test_fails_when_only_distinct_id(self, mock_sync_execute, team):- from posthog.models.person import Person, PersonDistinctId-- person = Person.objects.create(team_id=team.id, version=1)- PersonDistinctId.objects.create(team=team, person=person, distinct_id="$posthog_cookieless", version=3)+ person = create_person(team_id=team.id, version=1)+ add_distinct_id(person=person, distinct_id="$posthog_cookieless", version=3)producer = MagicMock()result = detach_distinct_id_job.execute_in_process(diff --git a/posthog/dags/tests/test_person_property_reconciliation.py b/posthog/dags/tests/test_person_property_reconciliation.pyindex 6d960c5f13f0..b96e29930dcc 100644--- a/posthog/dags/tests/test_person_property_reconciliation.py+++ b/posthog/dags/tests/test_person_property_reconciliation.py@@ -5791,7 +5791,7 @@ class TestBatchCommitsEndToEnd:get_person_property_updates_from_clickhouse,process_persons_in_batches,)- from posthog.models import Person+ from posthog.test.persons import create_personnum_persons = 5batch_size = 2@@ -5807,7 +5807,7 @@ class TestBatchCommitsEndToEnd:# Create persons in Postgres with old property valuespersons = []for i in range(num_persons):- person = Person.objects.create(+ person = create_person(team_id=team_id,properties={"email": f"old_{i}@example.com", "counter": i},properties_last_updated_at={@@ -5929,6 +5929,7 @@ class TestBatchCommitsEndToEnd:assert person.version == 2, f"Person {i} version not incremented. Expected 2, got {person.version}"# properties_last_updated_at should have new timestamp for email+ assert person.properties_last_updated_at is not Noneassert "email" in person.properties_last_updated_at, (f"Person {i} properties_last_updated_at missing 'email' key")@@ -5939,6 +5940,7 @@ class TestBatchCommitsEndToEnd:)# properties_last_operation should be 'set' for email+ assert person.properties_last_operation is not Noneassert person.properties_last_operation.get("email") == "set", (f"Person {i} properties_last_operation['email'] should be 'set', "f"got '{person.properties_last_operation.get('email')}'"@@ -5960,7 +5962,7 @@ class TestBatchCommitsEndToEnd:get_person_property_updates_from_clickhouse,process_persons_in_batches,)- from posthog.models import Person+ from posthog.test.persons import create_personteam_id = team.id@@ -5971,7 +5973,7 @@ class TestBatchCommitsEndToEnd:# Create only 3 persons in Postgrespersons = []for i in range(3):- person = Person.objects.create(+ person = create_person(team_id=team_id,properties={"name": f"old_name_{i}"},properties_last_updated_at={"name": "2024-01-01T00:00:00+00:00"},@@ -6099,6 +6101,7 @@ class TestBatchCommitsEndToEnd:assert person.version == 2, f"Person {i} version not incremented. Expected 2, got {person.version}"# properties_last_updated_at should have new timestamp+ assert person.properties_last_updated_at is not Noneassert "name" in person.properties_last_updated_at, (f"Person {i} properties_last_updated_at missing 'name' key")@@ -6108,6 +6111,7 @@ class TestBatchCommitsEndToEnd:)# properties_last_operation should be 'set'+ assert person.properties_last_operation is not Noneassert person.properties_last_operation.get("name") == "set", (f"Person {i} properties_last_operation['name'] should be 'set', "f"got '{person.properties_last_operation.get('name')}'"@@ -6202,10 +6206,10 @@ class TestKafkaClickHouseRoundTrip:from posthog.dags.person_property_reconciliation import publish_person_to_kafkafrom posthog.kafka_client.client import _KafkaProducer- from posthog.models import Person+ from posthog.test.persons import create_person# Create person in Postgres- person = Person.objects.create(+ person = create_person(team_id=team.id,properties={"email": "[email protected]", "name": "Kafka Test User"},version=1,@@ -6267,10 +6271,10 @@ class TestKafkaClickHouseRoundTrip:from posthog.dags.person_property_reconciliation import publish_person_to_kafkafrom posthog.kafka_client.client import _KafkaProducer- from posthog.models import Person+ from posthog.test.persons import create_person# Create person in Postgres with version 1- person = Person.objects.create(+ person = create_person(team_id=team.id,properties={"email": "[email protected]"},version=1,@@ -6358,7 +6362,7 @@ class TestKafkaClickHouseRoundTrip:from posthog.dags.person_property_reconciliation import person_property_reconciliation_jobfrom posthog.kafka_client.client import _KafkaProducer- from posthog.models import Person+ from posthog.test.persons import create_person# Time setup - create a bug window that includes our test eventsnow = datetime.now().replace(microsecond=0)@@ -6367,7 +6371,7 @@ class TestKafkaClickHouseRoundTrip:event_ts = now - timedelta(days=5)# Create person in Postgres with old property value- person = Person.objects.create(+ person = create_person(team_id=team.id,properties={"email": "[email protected]", "unchanged": "value"},properties_last_updated_at={@@ -6528,7 +6532,8 @@ class TestKafkaClickHouseRoundTrip:from posthog.dags.person_property_reconciliation import person_property_reconciliation_jobfrom posthog.kafka_client.client import _KafkaProducer- from posthog.models import Organization, Person, Team+ from posthog.models import Organization, Team+ from posthog.test.persons import create_person# Create two organizations and teams for isolationorg1 = Organization.objects.create(name="Test Org 1 for timestamp permutations")@@ -6574,7 +6579,7 @@ class TestKafkaClickHouseRoundTrip:# Create persons in Postgres for team 1persons_team1 = {}for suffix, _person_ts, _event_ts, _expected, prop_name in test_cases_team1:- person = Person.objects.create(+ person = create_person(team_id=team1.id,properties={prop_name: "old_value"},properties_last_updated_at={prop_name: "2020-01-01T00:00:00+00:00"},@@ -6586,7 +6591,7 @@ class TestKafkaClickHouseRoundTrip:# Create persons in Postgres for team 2persons_team2 = {}for suffix, _person_ts, _event_ts, _expected, prop_name in test_cases_team2:- person = Person.objects.create(+ person = create_person(team_id=team2.id,properties={prop_name: "old_value"},properties_last_updated_at={prop_name: "2020-01-01T00:00:00+00:00"},diff --git a/posthog/dags/tests/test_person_property_reconciliation_restore.py b/posthog/dags/tests/test_person_property_reconciliation_restore.pyindex b13f17d7fd97..2833c5dd6fb5 100644--- a/posthog/dags/tests/test_person_property_reconciliation_restore.py+++ b/posthog/dags/tests/test_person_property_reconciliation_restore.py@@ -21,6 +21,7 @@ from posthog.dags.person_property_reconciliation_restore import ()from posthog.models import Organization, Person, Teamfrom posthog.person_db_router import PERSONS_DB_FOR_WRITE+from posthog.test.persons import create_persondef create_backup_entry(@@ -589,7 +590,7 @@ class TestRestoreIntegration:@pytest.fixturedef person(self, team):"""Create a test person."""- return Person.objects.create(+ return create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": "[email protected]"},@@ -626,7 +627,7 @@ class TestRestoreIntegration:"""Test fetching backup entries filtered by person_ids."""job_id = f"test-job-{uuid_module.uuid4()}"- person2 = Person.objects.create(+ person2 = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": "[email protected]"},@@ -665,7 +666,7 @@ class TestRestoreIntegration:# Create a second team with a personteam2 = Team.objects.create(organization=organization, name="Test Team 2")- person2 = Person.objects.create(+ person2 = create_person(team_id=team2.id,uuid=uuid_module.uuid4(),properties={"email": "[email protected]"},@@ -711,7 +712,7 @@ class TestRestoreIntegration:persons = []for team in [team1, team2]:for i in range(5):- p = Person.objects.create(+ p = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": f"p{i}@example.com"},@@ -762,7 +763,7 @@ class TestRestoreIntegration:for team in [team1, team2]:persons[team.id] = []for i in range(3):- p = Person.objects.create(+ p = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": f"p{i}@example.com"},@@ -811,7 +812,7 @@ class TestRestoreIntegration:# Create multiple personspersons = []for i in range(5):- p = Person.objects.create(+ p = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": f"person{i}@example.com", "index": i},@@ -832,7 +833,7 @@ class TestRestoreIntegration:def test_fetch_persons_by_ids_partial(self, team):"""Test batch fetching when some ids don't exist."""- person = Person.objects.create(+ person = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": "[email protected]"},@@ -1101,13 +1102,13 @@ class TestRestoreJobEndToEnd:job_id = f"test-job-{uuid_module.uuid4()}"# Create test persons- person1 = Person.objects.create(+ person1 = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": "[email protected]", "name": "Current Name"},version=5,)- person2 = Person.objects.create(+ person2 = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": "[email protected]"},@@ -1197,13 +1198,13 @@ class TestRestoreJobEndToEnd:team2 = Team.objects.create(organization=organization, name="Test Team 2")# Create persons in both teams- person1 = Person.objects.create(+ person1 = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": "[email protected]"},version=2,)- person2 = Person.objects.create(+ person2 = create_person(team_id=team2.id,uuid=uuid_module.uuid4(),properties={"email": "[email protected]"},@@ -1279,7 +1280,7 @@ class TestRestoreJobEndToEnd:job_id = f"test-job-{uuid_module.uuid4()}"- person = Person.objects.create(+ person = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": "[email protected]"},@@ -1355,7 +1356,7 @@ class TestRestoreJobEndToEnd:persons[team.id] = []for p in range(4):- person = Person.objects.create(+ person = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={@@ -1457,7 +1458,7 @@ class TestRestoreJobEndToEnd:persons[team.id] = []for p in range(3):- person = Person.objects.create(+ person = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": f"current_t{t}_p{p}@example.com", "status": "current"},@@ -1553,7 +1554,7 @@ class TestRestoreJobEndToEnd:persons[team.id] = []for p in range(5):- person = Person.objects.create(+ person = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": f"current_t{t}_p{p}@example.com", "restored": False},@@ -1646,7 +1647,7 @@ class TestRestoreJobEndToEnd:persons[team.id] = []for p in range(4):- person = Person.objects.create(+ person = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={@@ -1771,7 +1772,7 @@ class TestRestoreJobEndToEnd:for p in range(3):# Current state has properties added after backup- person = Person.objects.create(+ person = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={@@ -1870,7 +1871,7 @@ class TestRestoreJobEndToEnd:persons[team.id] = []for p in range(persons_per_team[t]):- person = Person.objects.create(+ person = create_person(team_id=team.id,uuid=uuid_module.uuid4(),properties={"email": f"current_t{t}_p{p}@example.com"},diff --git a/posthog/hogql/database/schema/test/test_cohort_people.py b/posthog/hogql/database/schema/test/test_cohort_people.pyindex 28a785d90482..f5f78e50e132 100644--- a/posthog/hogql/database/schema/test/test_cohort_people.py+++ b/posthog/hogql/database/schema/test/test_cohort_people.py@@ -3,24 +3,24 @@ from posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_query-from posthog.models import Person+from posthog.test.persons import create_personfrom products.cohorts.backend.models.cohort import Cohortclass TestCohortPeopleTable(ClickhouseTestMixin, APIBaseTest):def test_select_star(self):- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["1"],properties={"$some_prop": "something", "$another_prop": "something1"},)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["2"],properties={"$some_prop": "something", "$another_prop": "something2"},)- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["3"],properties={"$some_prop": "not something", "$another_prop": "something3"},@@ -53,7 +53,7 @@ class TestCohortPeopleTable(ClickhouseTestMixin, APIBaseTest):assert response.results[1][2] == "something2"def test_empty_version(self):- Person.objects.create(+ create_person(team_id=self.team.pk,distinct_ids=["1"],properties={"$some_prop": "something", "$another_prop": "something1"},diff --git a/posthog/hogql/database/schema/test/test_groups_revenue_analytics.py b/posthog/hogql/database/schema/test/test_groups_revenue_analytics.pyindex f54a05c106c2..3ea446fb5be6 100644--- a/posthog/hogql/database/schema/test/test_groups_revenue_analytics.py+++ b/posthog/hogql/database/schema/test/test_groups_revenue_analytics.py@@ -16,7 +16,7 @@ from posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.models.group.util import create_group-from posthog.models.group_type_mapping import GroupTypeMapping+from posthog.test.persons import create_group_type_mappingfrom products.data_tools.backend.models.join import DataWarehouseJoinfrom products.revenue_analytics.backend.views.schemas.customer import SCHEMA@@ -182,10 +182,10 @@ class TestGroupsRevenueAnalyticsMixin(RevenueAnalyticsTestBase):def _setup_join(self):# Create some mappings- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="company", group_type_index=1)diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex 210b71615255..b6b59c017c79 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -19,6 +19,10 @@ from posthog.models import Group, GroupTypeMapping, GroupUsageMetric, Organizatifrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.project import Projectfrom posthog.models.scoping import team_scope+from posthog.test.persons import (+ create_group as _create_group_helper,+ create_group_type_mapping,+)from products.actions.backend.models.action import Actionfrom products.ai_observability.backend.models.review_queues import ReviewQueue, ReviewQueueItem@@ -355,13 +359,11 @@ def _create_feature_flag(team: Team, label: str) -> FeatureFlag:def _create_group(team: Team, label: str) -> Group:- return Group.objects.create(team=team, group_key=f"group_{label}", group_type_index=0, version=0)+ return _create_group_helper(team=team, group_key=f"group_{label}", group_type_index=0, version=0)def _create_group_type_mapping(team: Team, label: str) -> GroupTypeMapping:- return GroupTypeMapping.objects.create(- team=team, project=team.project, group_type=f"type_{label}", group_type_index=0- )+ return create_group_type_mapping(team=team, project=team.project, group_type=f"type_{label}", group_type_index=0)def _create_integration(team: Team, label: str):diff --git a/posthog/hogql/test/test_group_filtering.py b/posthog/hogql/test/test_group_filtering.pyindex 27bff19aaa01..b3252053c3f5 100644--- a/posthog/hogql/test/test_group_filtering.py+++ b/posthog/hogql/test/test_group_filtering.py@@ -11,8 +11,8 @@ from posthog.hogql.database.database import Databasefrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import prepare_and_print_ast-from posthog.models import GroupTypeMappingfrom posthog.models.group_type_mapping import invalidate_group_types_cache+from posthog.test.persons import create_group_type_mappingclass TestGroupKeyFiltering(APIBaseTest):@@ -25,7 +25,7 @@ class TestGroupKeyFiltering(APIBaseTest):def _create_mapping_and_rebuild(self, **kwargs):"""Create a GroupTypeMapping, invalidate cache, and rebuild database."""- GroupTypeMapping.objects.create(**kwargs)+ create_group_type_mapping(**kwargs)def _rebuild_database(self):invalidate_group_types_cache(self.team.project_id)diff --git a/posthog/hogql_queries/groups/test/test_groups_query_runner.py b/posthog/hogql_queries/groups/test/test_groups_query_runner.pyindex 9515192b13eb..d391d68981ed 100644--- a/posthog/hogql_queries/groups/test/test_groups_query_runner.py+++ b/posthog/hogql_queries/groups/test/test_groups_query_runner.py@@ -11,8 +11,8 @@ from django.utils import timezonefrom posthog.schema import GroupPropertyFilter, GroupsQuery, PropertyOperatorfrom posthog.hogql_queries.groups.groups_query_runner import GroupsQueryRunner-from posthog.models import GroupTypeMappingfrom posthog.models.group.util import create_group, raw_create_group_ch+from posthog.test.persons import create_group_type_mappingfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType@@ -169,7 +169,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):@freeze_time("2025-01-01")@snapshot_clickhouse_queriesdef test_search_ranking(self):- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)test_groups = [@@ -210,7 +210,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_search_ranking_with_key_fallback(self):"""Test search ranking when groups don't have name property and fall back to key"""- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)test_groups = [@@ -246,7 +246,7 @@ class TestGroupsQueryRunner(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_search_ordering_with_user_orderby(self):"""Test that similarity ordering comes after user-specified orderBy, not after default created_at DESC"""- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)test_groups = [diff --git a/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel.ambr b/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel.ambrindex e3620256fea2..e28c953c404a 100644--- a/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel.ambr+++ b/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel.ambr@@ -752,6 +752,16 @@'''# ---# name: TestFOSSFunnelUDF.test_funnel_with_static_cohort_step_filter+ '''+ SELECT person_id+ FROM person_static_cohort+ WHERE team_id = 99999+ AND cohort_id = 99999+ AND person_id IN ['00000000-0000-4000-8000-000000000001']+ GROUP BY person_id+ '''+# ---+# name: TestFOSSFunnelUDF.test_funnel_with_static_cohort_step_filter.1'''SELECT sum(step_1) AS step_1,sum(step_2) AS step_2,diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_persons.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_persons.pyindex 2502d6d8cf71..563cbfcf3bcc 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_persons.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_persons.py@@ -9,6 +9,7 @@ from posthog.test.base import (_create_event,_create_person,also_test_with_materialized_columns,+ flush_persons_and_events,snapshot_clickhouse_queries,)from unittest.mock import patch@@ -35,7 +36,6 @@ from posthog.schema import (from posthog.hogql_queries.actors_query_runner import ActorsQueryRunnerfrom posthog.hogql_queries.insights.funnels.funnels_query_runner import FunnelsQueryRunnerfrom posthog.models.event.util import bulk_create_events-from posthog.models.person.util import bulk_create_personsfrom posthog.models.team.team import Teamfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.test.test_journeys import journeys_for@@ -77,7 +77,8 @@ def get_actors(class TestFunnelPersons(ClickhouseTestMixin, APIBaseTest):def _create_sample_data_multiple_dropoffs(self):for i in range(35):- bulk_create_persons([{"distinct_ids": [f"user_{i}"], "team_id": self.team.pk}])+ _create_person(distinct_ids=[f"user_{i}"], team=self.team)+ flush_persons_and_events()events = []for i in range(5):events.append(diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py b/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.pyindex ac2cc8eb2acf..bf921d29c3b3 100644--- a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py+++ b/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py@@ -45,8 +45,8 @@ from posthog.hogql_queries.insights.retention.test.retention_base_query_variantfrom posthog.hogql_queries.insights.retention.test.utils import pad, pluckfrom posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, BREAKDOWN_OTHER_STRING_LABELfrom posthog.models.group.util import create_group-from posthog.models.person import Personfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME+from posthog.test.persons import create_personfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action@@ -5214,8 +5214,8 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixi@snapshot_clickhouse_queriesdef test_retention_aggregation_sum(self):"""Test retention with SUM aggregation on a property"""- Person.objects.create(team=self.team, distinct_ids=["user1"])- Person.objects.create(team=self.team, distinct_ids=["user2"])+ create_person(team=self.team, distinct_ids=["user1"])+ create_person(team=self.team, distinct_ids=["user2"])# User 1:# Day 0: $pageview with revenue=10@@ -5286,8 +5286,8 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixidef test_retention_aggregation_avg(self):"""Test retention with AVG aggregation on a property"""- Person.objects.create(team=self.team, distinct_ids=["user1"])- Person.objects.create(team=self.team, distinct_ids=["user2"])+ create_person(team=self.team, distinct_ids=["user1"])+ create_person(team=self.team, distinct_ids=["user2"])# User 1:# Day 0: $pageview with revenue=10@@ -5351,8 +5351,8 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixidef test_retention_aggregation_multiple_events_same_day(self):"""Test that multiple events on the same day are correctly summed"""- Person.objects.create(team=self.team, distinct_ids=["user1"])- Person.objects.create(team=self.team, distinct_ids=["user2"])+ create_person(team=self.team, distinct_ids=["user1"])+ create_person(team=self.team, distinct_ids=["user2"])# User 1: Multiple events on Day 1 and Day 2_create_events(@@ -5564,8 +5564,8 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixi# When start and return events are different, return events that happen after the# start event within interval 0 should be included in the interval 0 aggregation.# This is the primary use case: e.g. "signed_up" (no revenue) → "purchased" (revenue).- Person.objects.create(team=self.team, distinct_ids=["user1"])- Person.objects.create(team=self.team, distinct_ids=["user2"])+ create_person(team=self.team, distinct_ids=["user1"])+ create_person(team=self.team, distinct_ids=["user2"])# user1: signed_up at hour 10, then purchased at hour 12 (after signup) → should be counted# user1: purchased at hour 14 on day 1@@ -5610,7 +5610,7 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixi@snapshot_clickhouse_queriesdef test_retention_aggregation_different_events_ignores_start_event_property_value(self):- Person.objects.create(team=self.team, distinct_ids=["user1"])+ create_person(team=self.team, distinct_ids=["user1"])_create_events(self.team, [("user1", _date(0, hour=10), {"revenue": 999})], event="signed_up")_create_events(self.team, [("user1", _date(0, hour=12), {"revenue": 50})], event="purchased")@@ -5637,7 +5637,7 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixidef test_retention_aggregation_different_events_interval_0_excludes_return_before_start(self):# Return events that happen BEFORE the start event in the same interval must NOT be# counted in interval 0, even when start and return events are different event types.- Person.objects.create(team=self.team, distinct_ids=["user1"])+ create_person(team=self.team, distinct_ids=["user1"])# user1: purchased at hour 8 (before signup) → should NOT count for interval 0# user1: signed_up at hour 10@@ -5674,7 +5674,7 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixidef test_retention_aggregation_same_events_interval_0_unchanged(self):# When start and return events are the same, the interval 0 behavior is unchanged:# only the start event itself contributes to interval 0 (no double-counting).- Person.objects.create(team=self.team, distinct_ids=["user1"])+ create_person(team=self.team, distinct_ids=["user1"])_create_events(self.team,@@ -5705,8 +5705,8 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixidef test_retention_aggregation_different_events_avg_interval_0(self):# AVG aggregation with different start/return events includes return events in interval 0.- Person.objects.create(team=self.team, distinct_ids=["user1"])- Person.objects.create(team=self.team, distinct_ids=["user2"])+ create_person(team=self.team, distinct_ids=["user1"])+ create_person(team=self.team, distinct_ids=["user2"])_create_events(self.team,@@ -5743,8 +5743,8 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixidef test_retention_aggregation_person_property_sum(self):"""Aggregating on a person property reads person.properties, not event.properties."""- Person.objects.create(team=self.team, distinct_ids=["high_value"], properties={"account_value": 100})- Person.objects.create(team=self.team, distinct_ids=["low_value"], properties={"account_value": 10})+ create_person(team=self.team, distinct_ids=["high_value"], properties={"account_value": 100})+ create_person(team=self.team, distinct_ids=["low_value"], properties={"account_value": 10})# Both users perform $pageview on Day 0 and Day 1.# The event itself has no revenue property — value comes solely from person properties.@@ -5782,8 +5782,8 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixidef test_retention_aggregation_person_property_avg(self):"""AVG over a person property divides the sum by the number of distinct actors."""- Person.objects.create(team=self.team, distinct_ids=["user_a"], properties={"score": 80})- Person.objects.create(team=self.team, distinct_ids=["user_b"], properties={"score": 60})+ create_person(team=self.team, distinct_ids=["user_a"], properties={"score": 80})+ create_person(team=self.team, distinct_ids=["user_b"], properties={"score": 60})_create_events(self.team,@@ -5954,9 +5954,9 @@ class TestClickhouseRetentionGroupAggregation(properties={},)- Person.objects.create(team=self.team, distinct_ids=["person1", "alias1"])- Person.objects.create(team=self.team, distinct_ids=["person2"])- Person.objects.create(team=self.team, distinct_ids=["person3"])+ create_person(team=self.team, distinct_ids=["person1", "alias1"])+ create_person(team=self.team, distinct_ids=["person2"])+ create_person(team=self.team, distinct_ids=["person3"])_create_events(self.team,@@ -6646,11 +6646,11 @@ class TestClickhouseRetentionGroupAggregation(# empty string and actual value, causing major countries to drop from top breakdown list# Create person who will have country property added later- person_no_country = Person.objects.create(team=self.team, distinct_ids=["person_no_country"], properties={})+ person_no_country = create_person(team=self.team, distinct_ids=["person_no_country"], properties={})# Create person who always has country# person_with_country- Person.objects.create(team=self.team, distinct_ids=["person_with_country"], properties={"country": "Taiwan"})+ create_person(team=self.team, distinct_ids=["person_with_country"], properties={"country": "Taiwan"})# Create events for both people_create_events(@@ -6679,7 +6679,7 @@ class TestClickhouseRetentionGroupAggregation(# Create many other people with unique countries to fill up breakdown slots# This simulates the real scenario where major countries get pushed outfor i in range(20):- Person.objects.create(team=self.team, distinct_ids=[f"person_{i}"], properties={"country": f"Country_{i}"})+ create_person(team=self.team, distinct_ids=[f"person_{i}"], properties={"country": f"Country_{i}"})_create_events(self.team, [(f"person_{i}", _date(0)), (f"person_{i}", _date(1))])query = {@@ -6726,7 +6726,7 @@ class TestClickhouseRetentionGroupAggregation(# they are counted using their most recent property value for ranking purposes.# Create a user whose country changes from '' -> 'Canada' -> 'USA' over time- person_changing = Person.objects.create(+ person_changing = create_person(team=self.team,distinct_ids=["person_changing"],properties={}, # Initially no country@@ -6750,12 +6750,12 @@ class TestClickhouseRetentionGroupAggregation(_create_events(self.team, [("person_changing", _date(2))])# Create a baseline USA user to ensure USA gets ranked properly- Person.objects.create(team=self.team, distinct_ids=["usa_baseline"], properties={"country": "USA"})+ create_person(team=self.team, distinct_ids=["usa_baseline"], properties={"country": "USA"})_create_events(self.team, [("usa_baseline", _date(0))])# Create some other countries to fill up breakdown slotsfor i in range(15):- Person.objects.create(team=self.team, distinct_ids=[f"other_{i}"], properties={"country": f"Other_{i}"})+ create_person(team=self.team, distinct_ids=[f"other_{i}"], properties={"country": f"Other_{i}"})_create_events(self.team, [(f"other_{i}", _date(0))])query = {@@ -6801,25 +6801,25 @@ class TestClickhouseRetentionGroupAggregation(# Create countries with different user counts to test ranking# USA: 5 users (should be #1)for i in range(5):- Person.objects.create(team=self.team, distinct_ids=[f"usa_user_{i}"], properties={"country": "USA"})+ create_person(team=self.team, distinct_ids=[f"usa_user_{i}"], properties={"country": "USA"})_create_events(self.team, [(f"usa_user_{i}", _date(0))])# Canada: 3 users (should be #2)for i in range(3):- Person.objects.create(team=self.team, distinct_ids=[f"can_user_{i}"], properties={"country": "Canada"})+ create_person(team=self.team, distinct_ids=[f"can_user_{i}"], properties={"country": "Canada"})_create_events(self.team, [(f"can_user_{i}", _date(0))])# Germany: 2 users (should be #3)for i in range(2):- Person.objects.create(team=self.team, distinct_ids=[f"ger_user_{i}"], properties={"country": "Germany"})+ create_person(team=self.team, distinct_ids=[f"ger_user_{i}"], properties={"country": "Germany"})_create_events(self.team, [(f"ger_user_{i}", _date(0))])# France: 1 user (should be grouped into "Other" with breakdown_limit=3)- Person.objects.create(team=self.team, distinct_ids=["fra_user"], properties={"country": "France"})+ create_person(team=self.team, distinct_ids=["fra_user"], properties={"country": "France"})_create_events(self.team, [("fra_user", _date(0))])# Spain: 1 user (should be grouped into "Other" with breakdown_limit=3)- Person.objects.create(team=self.team, distinct_ids=["spa_user"], properties={"country": "Spain"})+ create_person(team=self.team, distinct_ids=["spa_user"], properties={"country": "Spain"})_create_events(self.team, [("spa_user", _date(0))])query = {@@ -6876,7 +6876,7 @@ class TestClickhouseRetentionGroupAggregation(# - Does first event at 11 PM on Day 0# - Does return event at 1 AM on Day 1 (only 2 hours later, same 24h window)# - Does return event at 11 PM on Day 1 (24 hours later, next 24h window)- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"])+ _person1 = create_person(team=self.team, distinct_ids=["person1"])_create_events(self.team,[@@ -6933,7 +6933,7 @@ class TestClickhouseRetentionGroupAggregation(# - Does first event at 1 AM on Day 1# - Does return event at 11 PM on Day 1 (22 hours later, same 24h window)# - Does return event at 2 AM on Day 2 (25 hours later, next 24h window)- _person2 = Person.objects.create(team=self.team, distinct_ids=["person2"])+ _person2 = create_person(team=self.team, distinct_ids=["person2"])_create_events(self.team,[@@ -6982,8 +6982,8 @@ class TestClickhouseRetentionGroupAggregation(def test_retention_24h_window_with_person_breakdown(self):# Test 24-hour windows with person property breakdown- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"], properties={"country": "USA"})- _person2 = Person.objects.create(team=self.team, distinct_ids=["person2"], properties={"country": "Canada"})+ _person1 = create_person(team=self.team, distinct_ids=["person1"], properties={"country": "USA"})+ _person2 = create_person(team=self.team, distinct_ids=["person2"], properties={"country": "Canada"})_create_events(self.team,@@ -7021,7 +7021,7 @@ class TestClickhouseRetentionGroupAggregation(def test_retention_24h_window_with_event_breakdown(self):# Test 24-hour windows with event property breakdown- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"])+ _person1 = create_person(team=self.team, distinct_ids=["person1"])_create_events(self.team,@@ -7057,8 +7057,8 @@ class TestClickhouseRetentionGroupAggregation(def test_retention_24h_window_first_time_ever(self):# Test 24-hour windows with first-ever retention- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"])- _person2 = Person.objects.create(team=self.team, distinct_ids=["person2"])+ _person1 = create_person(team=self.team, distinct_ids=["person1"])+ _person2 = create_person(team=self.team, distinct_ids=["person2"])_create_events(self.team,@@ -7093,7 +7093,7 @@ class TestClickhouseRetentionGroupAggregation(def test_retention_24h_window_first_time_matching_filters(self):# Test 24-hour windows with first time matching filters- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"])+ _person1 = create_person(team=self.team, distinct_ids=["person1"])_create_events(self.team,@@ -7134,9 +7134,9 @@ class TestClickhouseRetentionGroupAggregation(def test_retention_24h_window_with_minimum_occurrences(self):# Test 24-hour windows with minimum occurrences- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"])- _person2 = Person.objects.create(team=self.team, distinct_ids=["person2"])- _person3 = Person.objects.create(team=self.team, distinct_ids=["person3"])+ _person1 = create_person(team=self.team, distinct_ids=["person1"])+ _person2 = create_person(team=self.team, distinct_ids=["person2"])+ _person3 = create_person(team=self.team, distinct_ids=["person3"])_create_events(self.team,@@ -7175,7 +7175,7 @@ class TestClickhouseRetentionGroupAggregation(def test_retention_24h_window_with_week_interval(self):# Test 24-hour windows with weekly intervals# With week period and 24h windows, it uses 7-day (168 hour) rolling windows- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"])+ _person1 = create_person(team=self.team, distinct_ids=["person1"])_create_events(self.team,@@ -7210,7 +7210,7 @@ class TestClickhouseRetentionGroupAggregation(def test_retention_24h_window_with_properties_on_events(self):# Test 24-hour windows with properties on start and return events- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"])+ _person1 = create_person(team=self.team, distinct_ids=["person1"])_create_events(self.team,@@ -7257,7 +7257,7 @@ class TestClickhouseRetentionGroupAggregation(name="USA Cohort",)- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"], properties={"country": "USA"})+ _person1 = create_person(team=self.team, distinct_ids=["person1"], properties={"country": "USA"})_create_events(self.team,@@ -7880,7 +7880,7 @@ class TestClickhouseRetentionGroupAggregation(def test_retention_24h_window_weekly_cohorts(self):# Test 24-hour windows with weekly retention cohorts# Week period with 24h windows uses 7-day (168 hour) rolling windows- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"])+ _person1 = create_person(team=self.team, distinct_ids=["person1"])_create_events(self.team,@@ -7914,7 +7914,7 @@ class TestClickhouseRetentionGroupAggregation(def test_retention_24h_window_monthly_cohorts(self):# Test 24-hour windows with monthly retention cohorts# Month period with 24h windows uses 30-day (720 hour) rolling windows- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"])+ _person1 = create_person(team=self.team, distinct_ids=["person1"])_create_events(self.team,@@ -7950,8 +7950,8 @@ class TestClickhouseRetentionGroupAggregation(def test_retention_24h_window_weekly_with_breakdown(self):# Test 24-hour windows with weekly cohorts and breakdown- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"], properties={"country": "USA"})- _person2 = Person.objects.create(team=self.team, distinct_ids=["person2"], properties={"country": "Canada"})+ _person1 = create_person(team=self.team, distinct_ids=["person1"], properties={"country": "USA"})+ _person2 = create_person(team=self.team, distinct_ids=["person2"], properties={"country": "Canada"})_create_events(self.team,@@ -7989,7 +7989,7 @@ class TestClickhouseRetentionGroupAggregation(def test_retention_24h_window_monthly_first_time_ever(self):# Test 24-hour windows with monthly cohorts and first-ever retention- _person1 = Person.objects.create(team=self.team, distinct_ids=["person1"])+ _person1 = create_person(team=self.team, distinct_ids=["person1"])_create_events(self.team,@@ -8034,12 +8034,12 @@ class TestClickhouseRetentionGroupAggregation(# # USA: 10 unique users, each starting a cohort once on Day 0# for i in range(10):- # Person.objects.create(team=self.team, distinct_ids=[f"usa_user_{i}"], properties={"country": "USA"})+ # create_person(team=self.team, distinct_ids=[f"usa_user_{i}"], properties={"country": "USA"})# _create_events(self.team, [(f"usa_user_{i}", _date(0))])# # Canada: 3 unique users, but they are very active and start cohorts on 5 different days# for i in range(3):- # Person.objects.create(team=self.team, distinct_ids=[f"can_user_{i}"], properties={"country": "Canada"})+ # create_person(team=self.team, distinct_ids=[f"can_user_{i}"], properties={"country": "Canada"})# for day in range(5):# _create_events(self.team, [(f"can_user_{i}", _date(day))])diff --git a/posthog/hogql_queries/insights/trends/test/test_trends.py b/posthog/hogql_queries/insights/trends/test/test_trends.pyindex 9fd0a4264ee0..8daaab79f672 100644--- a/posthog/hogql_queries/insights/trends/test/test_trends.py+++ b/posthog/hogql_queries/insights/trends/test/test_trends.py@@ -39,6 +39,7 @@ from posthog.models.instance_setting import get_instance_setting, override_instafrom posthog.models.person.util import create_person_distinct_idfrom posthog.models.team.team import Teamfrom posthog.models.utils import uuid7+from posthog.test.persons import create_personfrom posthog.test.test_journeys import journeys_forfrom posthog.test.test_utils import create_group_type_mapping_without_created_at@@ -9093,7 +9094,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):def test_breakdown_by_group_props_with_person_filter(self):self._create_groups()- Person.objects.create(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})+ create_person(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})self._create_event(event="sign up",@@ -9137,7 +9138,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):def test_filtering_with_group_props(self):self._create_groups()- Person.objects.create(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})+ create_person(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})self._create_event(event="$pageview",distinct_id="person1",@@ -9190,7 +9191,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):def test_filtering_with_group_props_event_with_no_group_data(self):self._create_groups()- Person.objects.create(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})+ create_person(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})self._create_event(event="$pageview",distinct_id="person1",@@ -9246,7 +9247,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):def test_breakdown_by_group_props_with_person_filter_person_on_events(self):self._create_groups()- Person.objects.create(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})+ create_person(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})self._create_event(event="sign up",@@ -9291,7 +9292,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):def test_filtering_with_group_props_person_on_events(self):self._create_groups()- Person.objects.create(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})+ create_person(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})self._create_event(event="$pageview",distinct_id="person1",diff --git a/posthog/hogql_queries/test/test_actor_strategies_personhog.py b/posthog/hogql_queries/test/test_actor_strategies_personhog.pyindex 3e46412d6d14..dc81244fc485 100644--- a/posthog/hogql_queries/test/test_actor_strategies_personhog.py+++ b/posthog/hogql_queries/test/test_actor_strategies_personhog.py@@ -6,14 +6,13 @@ from unittest.mock import patchfrom django.utils import timezone-from parameterized import parameterized_class-from posthog.schema import ActorsQueryfrom posthog.hogql_queries.actor_strategies import PersonStrategyfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.models import Team-from posthog.personhog_client.test_helpers import PersonhogTestMixin+from posthog.models.person import Person+from posthog.test.persons import create_person, update_persondef _make_strategy(team) -> PersonStrategy:@@ -22,10 +21,9 @@ def _make_strategy(team) -> PersonStrategy:return PersonStrategy(team=team, query=query, paginator=paginator)-@parameterized_class(("personhog",), [(False,), (True,)])-class TestPersonStrategyGetActors(PersonhogTestMixin, BaseTest):+class TestPersonStrategyGetActors(BaseTest):def test_basic_person_lookup(self):- person = self._seed_person(+ person = create_person(team=self.team,distinct_ids=["did-1"],properties={"email": "[email protected]"},@@ -43,11 +41,8 @@ class TestPersonStrategyGetActors(PersonhogTestMixin, BaseTest):assert "distinct_ids" in entryassert "did-1" in entry["distinct_ids"]- self._assert_personhog_called("get_persons_by_uuids")- self._assert_personhog_called("get_distinct_ids_for_persons")-def test_distinct_ids_included(self):- person = self._seed_person(+ person = create_person(team=self.team,distinct_ids=["did-a", "did-b", "did-c"],properties={},@@ -64,7 +59,7 @@ class TestPersonStrategyGetActors(PersonhogTestMixin, BaseTest):# result so consumers reading distinct_ids[0] (person links, CSV exports) get the# human-readable ID rather than the auto-generated anonymous one.anonymous_id = "0190f8e1-1234-7abc-89de-f0123456789a"- person = self._seed_person(+ person = create_person(team=self.team,distinct_ids=[anonymous_id, "[email protected]"],properties={},@@ -78,9 +73,9 @@ class TestPersonStrategyGetActors(PersonhogTestMixin, BaseTest):assert set(entry["distinct_ids"]) == {anonymous_id, "[email protected]"}def test_multiple_persons(self):- p1 = self._seed_person(team=self.team, distinct_ids=["u1"], properties={"n": "1"})- p2 = self._seed_person(team=self.team, distinct_ids=["u2"], properties={"n": "2"})- p3 = self._seed_person(team=self.team, distinct_ids=["u3"], properties={"n": "3"})+ p1 = create_person(team=self.team, distinct_ids=["u1"], properties={"n": "1"})+ p2 = create_person(team=self.team, distinct_ids=["u2"], properties={"n": "2"})+ p3 = create_person(team=self.team, distinct_ids=["u3"], properties={"n": "3"})strategy = _make_strategy(self.team)result = strategy.get_actors([str(p1.uuid), str(p2.uuid), str(p3.uuid)])@@ -91,7 +86,7 @@ class TestPersonStrategyGetActors(PersonhogTestMixin, BaseTest):assert result[str(p3.uuid)]["properties"] == {"n": "3"}def test_missing_persons_excluded(self):- person = self._seed_person(team=self.team, distinct_ids=["real"], properties={})+ person = create_person(team=self.team, distinct_ids=["real"], properties={})fake_uuid = str(uuid4())strategy = _make_strategy(self.team)@@ -110,7 +105,7 @@ class TestPersonStrategyGetActors(PersonhogTestMixin, BaseTest):def test_batching(self):persons = []for i in range(5):- p = self._seed_person(team=self.team, distinct_ids=[f"batch-{i}"], properties={"i": i})+ p = create_person(team=self.team, distinct_ids=[f"batch-{i}"], properties={"i": i})persons.append(p)strategy = _make_strategy(self.team)@@ -123,24 +118,16 @@ class TestPersonStrategyGetActors(PersonhogTestMixin, BaseTest):def test_sort_by_created_at_descending(self):now = timezone.now()- p_old = self._seed_person(team=self.team, distinct_ids=["old"], properties={})- p_mid = self._seed_person(team=self.team, distinct_ids=["mid"], properties={})- p_new = self._seed_person(team=self.team, distinct_ids=["new"], properties={})-- from posthog.models.person import Person+ p_old = create_person(team=self.team, distinct_ids=["old"], properties={})+ p_mid = create_person(team=self.team, distinct_ids=["mid"], properties={})+ p_new = create_person(team=self.team, distinct_ids=["new"], properties={})Person.objects.filter(pk=p_old.pk).update(created_at=now - timedelta(hours=3))Person.objects.filter(pk=p_mid.pk).update(created_at=now - timedelta(hours=1))Person.objects.filter(pk=p_new.pk).update(created_at=now)-- if self._fake_client is not None:- self._fake_client._persons_by_uuid[(self.team.pk, str(p_old.uuid))].created_at = int(- (now - timedelta(hours=3)).timestamp() * 1000- )- self._fake_client._persons_by_uuid[(self.team.pk, str(p_mid.uuid))].created_at = int(- (now - timedelta(hours=1)).timestamp() * 1000- )- self._fake_client._persons_by_uuid[(self.team.pk, str(p_new.uuid))].created_at = int(now.timestamp() * 1000)+ for p in [p_old, p_mid, p_new]:+ p.refresh_from_db()+ update_person(p)strategy = _make_strategy(self.team)result = strategy.get_actors(@@ -153,8 +140,8 @@ class TestPersonStrategyGetActors(PersonhogTestMixin, BaseTest):def test_cross_team_isolation(self):other_team = Team.objects.create(organization=self.organization, name="Other Team")- other_person = self._seed_person(team=other_team, distinct_ids=["other"], properties={})- own_person = self._seed_person(team=self.team, distinct_ids=["own"], properties={})+ other_person = create_person(team=other_team, distinct_ids=["other"], properties={})+ own_person = create_person(team=self.team, distinct_ids=["own"], properties={})strategy = _make_strategy(self.team)result = strategy.get_actors([str(own_person.uuid), str(other_person.uuid)])diff --git a/posthog/hogql_queries/test/test_personhog_routing.py b/posthog/hogql_queries/test/test_personhog_routing.pyindex 8e2ae4050283..78906c3ed0dd 100644--- a/posthog/hogql_queries/test/test_personhog_routing.py+++ b/posthog/hogql_queries/test/test_personhog_routing.py@@ -1,19 +1,17 @@"""Tests that personId lookups in EventsQueryRunner and SessionsQueryRunner-produce identical AST output via the ORM and personhog paths."""+produce the expected AST output."""from typing import Optional, castfrom posthog.test.base import BaseTest-from parameterized import parameterized_class-from posthog.schema import EventsQuery, SessionsQueryfrom posthog.hogql import astfrom posthog.hogql_queries.events_query_runner import EventsQueryRunnerfrom posthog.hogql_queries.sessions_query_runner import SessionsQueryRunner-from posthog.personhog_client.test_helpers import PersonhogTestMixin+from posthog.test.persons import create_personUUID_NONEXISTENT = "550e8400-e29b-41d4-a716-446655440000"@@ -52,18 +50,15 @@ def _extract_distinct_id_field_chain(where: Optional[ast.Expr]) -> list[str | inreturn field.chain-@parameterized_class(("personhog",), [(False,), (True,)])-class TestEventsQueryRunnerPersonRouting(PersonhogTestMixin, BaseTest):+class TestEventsQueryRunnerPersonRouting(BaseTest):def test_uuid_person_id_expands_distinct_ids(self):- person = self._seed_person(team=self.team, distinct_ids=["id1", "id2"])+ person = create_person(team=self.team, distinct_ids=["id1", "id2"])query = EventsQuery(kind="EventsQuery", select=["*"], personId=str(person.uuid), orderBy=[])query_ast = EventsQueryRunner(query=query, team=self.team).to_query()ids = _extract_person_distinct_ids_from_where(query_ast.where)assert set(ids) == {"id1", "id2"}- self._assert_personhog_called("get_person_by_uuid")- self._assert_personhog_called("get_distinct_ids_for_person")def test_uuid_person_id_not_found_returns_empty(self):query = EventsQuery(kind="EventsQuery", select=["*"], personId=UUID_NONEXISTENT, orderBy=[])@@ -71,18 +66,15 @@ class TestEventsQueryRunnerPersonRouting(PersonhogTestMixin, BaseTest):ids = _extract_person_distinct_ids_from_where(query_ast.where)assert ids == []- self._assert_personhog_called("get_person_by_uuid")def test_integer_person_id_expands_distinct_ids(self):- person = self._seed_person(team=self.team, distinct_ids=["id1", "id2"])+ person = create_person(team=self.team, distinct_ids=["id1", "id2"])query = EventsQuery(kind="EventsQuery", select=["*"], personId=str(person.pk), orderBy=[])query_ast = EventsQueryRunner(query=query, team=self.team).to_query()ids = _extract_person_distinct_ids_from_where(query_ast.where)assert set(ids) == {"id1", "id2"}- self._assert_personhog_not_called("get_person_by_uuid")- self._assert_personhog_called("get_person")def test_invalid_person_id_returns_empty(self):query = EventsQuery(kind="EventsQuery", select=["*"], personId="not-a-uuid-or-int", orderBy=[])@@ -90,22 +82,17 @@ class TestEventsQueryRunnerPersonRouting(PersonhogTestMixin, BaseTest):ids = _extract_person_distinct_ids_from_where(query_ast.where)assert ids == []- self._assert_personhog_not_called("get_person_by_uuid")- self._assert_personhog_not_called("get_person")-@parameterized_class(("personhog",), [(False,), (True,)])-class TestSessionsQueryRunnerPersonRouting(PersonhogTestMixin, BaseTest):+class TestSessionsQueryRunnerPersonRouting(BaseTest):def test_uuid_person_id_expands_distinct_ids(self):- person = self._seed_person(team=self.team, distinct_ids=["id1", "id2"])+ person = create_person(team=self.team, distinct_ids=["id1", "id2"])query = SessionsQuery(kind="SessionsQuery", select=["session_id"], personId=str(person.uuid))query_ast = SessionsQueryRunner(query=query, team=self.team).to_query()ids = _extract_person_distinct_ids_from_where(query_ast.where)assert set(ids) == {"id1", "id2"}- self._assert_personhog_called("get_person_by_uuid")- self._assert_personhog_called("get_distinct_ids_for_person")def test_uuid_person_id_not_found_returns_empty(self):query = SessionsQuery(kind="SessionsQuery", select=["session_id"], personId=UUID_NONEXISTENT)@@ -113,18 +100,15 @@ class TestSessionsQueryRunnerPersonRouting(PersonhogTestMixin, BaseTest):ids = _extract_person_distinct_ids_from_where(query_ast.where)assert ids == []- self._assert_personhog_called("get_person_by_uuid")def test_integer_person_id_expands_distinct_ids(self):- person = self._seed_person(team=self.team, distinct_ids=["id1", "id2"])+ person = create_person(team=self.team, distinct_ids=["id1", "id2"])query = SessionsQuery(kind="SessionsQuery", select=["session_id"], personId=str(person.pk))query_ast = SessionsQueryRunner(query=query, team=self.team).to_query()ids = _extract_person_distinct_ids_from_where(query_ast.where)assert set(ids) == {"id1", "id2"}- self._assert_personhog_not_called("get_person_by_uuid")- self._assert_personhog_called("get_person")def test_invalid_person_id_returns_empty(self):query = SessionsQuery(kind="SessionsQuery", select=["session_id"], personId="not-a-uuid-or-int")@@ -132,18 +116,16 @@ class TestSessionsQueryRunnerPersonRouting(PersonhogTestMixin, BaseTest):ids = _extract_person_distinct_ids_from_where(query_ast.where)assert ids == []- self._assert_personhog_not_called("get_person_by_uuid")- self._assert_personhog_not_called("get_person")def test_person_join_qualifies_distinct_id_chain(self):- person = self._seed_person(team=self.team, distinct_ids=["id1"])+ person = create_person(team=self.team, distinct_ids=["id1"])query_without_join = SessionsQuery(kind="SessionsQuery", select=["session_id"], personId=str(person.uuid))ast_without = SessionsQueryRunner(query=query_without_join, team=self.team).to_query()assert _extract_distinct_id_field_chain(ast_without.where) == ["distinct_id"]def test_person_join_qualifies_distinct_id_chain_with_person_select(self):- person = self._seed_person(team=self.team, distinct_ids=["id1"])+ person = create_person(team=self.team, distinct_ids=["id1"])query_with_join = SessionsQuery(kind="SessionsQuery", select=["session_id", "person_display_name"], personId=str(person.uuid)diff --git a/posthog/management/commands/test/test_background_delete_model.py b/posthog/management/commands/test/test_background_delete_model.pyindex d6c4a4d7b801..cc46a37a05c5 100644--- a/posthog/management/commands/test/test_background_delete_model.py+++ b/posthog/management/commands/test/test_background_delete_model.py@@ -5,6 +5,7 @@ from django.core.management.base import CommandErrorfrom posthog.management.commands.background_delete_model import Commandfrom posthog.models.person.person import Person+from posthog.test.persons import create_personclass TestBackgroundDeleteModel(BaseTest):@@ -52,8 +53,8 @@ class TestBackgroundDeleteModel(BaseTest):mock_task.delay.return_value = MagicMock(id="test-task-id")# Create some test persons- Person.objects.create(team=self.team, properties={})- Person.objects.create(team=self.team, properties={})+ create_person(team=self.team, properties={})+ create_person(team=self.team, properties={})self.command.handle("posthog.Person", team_id=self.team.id)@@ -66,7 +67,7 @@ class TestBackgroundDeleteModel(BaseTest):def test_dry_run_does_not_start_task(self, mock_task):"""Test that dry run shows info but doesn't start task"""# Create some test persons- Person.objects.create(team=self.team, properties={})+ create_person(team=self.team, properties={})self.command.handle("posthog.Person", team_id=self.team.id, dry_run=True)@@ -104,7 +105,7 @@ class TestBackgroundDeleteModel(BaseTest):def test_confirmation_cancelled(self, mock_input, mock_task):"""Test that task is not started when confirmation is cancelled"""# Create some test persons- Person.objects.create(team=self.team, properties={})+ create_person(team=self.team, properties={})self.command.handle("posthog.Person", team_id=self.team.id)@@ -152,8 +153,8 @@ class TestBackgroundDeleteModel(BaseTest):mock_task.delay.return_value = MagicMock(id="test-task-id")# Create some test persons- Person.objects.create(team=self.team, properties={})- Person.objects.create(team=self.team, properties={})+ create_person(team=self.team, properties={})+ create_person(team=self.team, properties={})# Try to use a batch size larger than the limitwith patch("builtins.input", return_value="DELETE 2 RECORDS"):@@ -169,8 +170,8 @@ class TestBackgroundDeleteModel(BaseTest):def test_synchronous_execution(self, mock_input, mock_task):"""Test that synchronous flag runs task directly instead of using .delay()"""# Create some test persons- Person.objects.create(team=self.team, properties={})- Person.objects.create(team=self.team, properties={})+ create_person(team=self.team, properties={})+ create_person(team=self.team, properties={})self.command.handle("posthog.Person", team_id=self.team.id, synchronous=True)@@ -193,11 +194,11 @@ class TestBackgroundDeleteModel(BaseTest):team2 = Team.objects.create(organization=self.organization, name="Team 2")# Create persons across multiple teams- Person.objects.create(team=self.team, properties={}) # Team 1- Person.objects.create(team=self.team, properties={}) # Team 1- Person.objects.create(team=team2, properties={}) # Team 2- Person.objects.create(team=team2, properties={}) # Team 2- Person.objects.create(team=team2, properties={}) # Team 2+ create_person(team=self.team, properties={}) # Team 1+ create_person(team=self.team, properties={}) # Team 1+ create_person(team=team2, properties={}) # Team 2+ create_person(team=team2, properties={}) # Team 2+ create_person(team=team2, properties={}) # Team 2# Verify initial countsself.assertEqual(Person.objects.filter(team=self.team).count(), 2)diff --git a/posthog/models/event/test_query_event_list_personhog.py b/posthog/models/event/test_query_event_list_personhog.pyindex eac6e6ef7da9..190e0a5cb296 100644--- a/posthog/models/event/test_query_event_list_personhog.py+++ b/posthog/models/event/test_query_event_list_personhog.py@@ -1,40 +1,37 @@-"""Tests that parse_request_params person lookups produce identical results-via the ORM and personhog paths."""+"""Tests that parse_request_params person lookups produce identical results."""from zoneinfo import ZoneInfofrom posthog.test.base import BaseTest-from parameterized import parameterized_class-from posthog.models.event.query_event_list import parse_request_params-from posthog.personhog_client.test_helpers import PersonhogTestMixin+from posthog.test.personhog_fake import get_active_fake+from posthog.test.persons import create_personUUID_NONEXISTENT = "550e8400-e29b-41d4-a716-446655440000"-@parameterized_class(("personhog",), [(False,), (True,)])-class TestParseRequestParamsPersonRouting(PersonhogTestMixin, BaseTest):+class TestParseRequestParamsPersonRouting(BaseTest):def test_uuid_person_id_resolves_distinct_ids(self):- person = self._seed_person(team=self.team, distinct_ids=["id1", "id2"])+ person = create_person(team=self.team, distinct_ids=["id1", "id2"])_result, params = parse_request_params({"person_id": str(person.uuid)}, self.team, ZoneInfo("UTC"))assert set(params["distinct_ids"]) == {"id1", "id2"}- self._assert_personhog_called("get_person_by_uuid")- self._assert_personhog_called("get_distinct_ids_for_person")+ get_active_fake().assert_called("get_person_by_uuid")+ get_active_fake().assert_called("get_distinct_ids_for_person")def test_uuid_person_id_not_found_returns_empty(self):_result, params = parse_request_params({"person_id": UUID_NONEXISTENT}, self.team, ZoneInfo("UTC"))assert params["distinct_ids"] == []- self._assert_personhog_called("get_person_by_uuid")+ get_active_fake().assert_called("get_person_by_uuid")def test_integer_person_id_resolves_distinct_ids(self):- person = self._seed_person(team=self.team, distinct_ids=["id1", "id2"])+ person = create_person(team=self.team, distinct_ids=["id1", "id2"])_result, params = parse_request_params({"person_id": str(person.pk)}, self.team, ZoneInfo("UTC"))assert set(params["distinct_ids"]) == {"id1", "id2"}- self._assert_personhog_not_called("get_person_by_uuid")- self._assert_personhog_called("get_person")+ get_active_fake().assert_not_called("get_person_by_uuid")+ get_active_fake().assert_called("get_person")diff --git a/posthog/models/group/test_util.py b/posthog/models/group/test_util.pyindex ed1c69436613..d9d9b8808c30 100644--- a/posthog/models/group/test_util.py+++ b/posthog/models/group/test_util.py@@ -1,6 +1,6 @@from types import SimpleNamespace-from unittest.mock import MagicMock, patch+from unittest.mock import ANY, MagicMock, patchfrom django.db import DatabaseErrorfrom django.test import SimpleTestCase, override_settings@@ -61,7 +61,7 @@ class TestGetGroupByKey(SimpleTestCase):assert result is mock_groupmock_routing_counter.labels.assert_called_once_with(- operation="get_group_by_key", source="django_orm", client_name="posthog-django"+ operation="get_group_by_key", source="django_orm", client_name=ANY)@patch(_ROUTING_ERRORS_PATCH)@@ -86,7 +86,7 @@ class TestGetGroupByKey(SimpleTestCase):assert result is fake_modelmock_convert.assert_called_once_with(proto_group)mock_routing_counter.labels.assert_called_with(- operation="get_group_by_key", source="personhog", client_name="posthog-django"+ operation="get_group_by_key", source="personhog", client_name=ANY)mock_errors_counter.labels.assert_not_called()@@ -107,7 +107,7 @@ class TestGetGroupByKey(SimpleTestCase):assert result is Nonemock_routing_counter.labels.assert_called_with(- operation="get_group_by_key", source="personhog", client_name="posthog-django"+ operation="get_group_by_key", source="personhog", client_name=ANY)@parameterized.expand(@@ -140,7 +140,7 @@ class TestGetGroupByKey(SimpleTestCase):operation="get_group_by_key",source="personhog",error_type="grpc_error",- client_name="posthog-django",+ client_name=ANY,)calls = [str(c) for c in mock_routing_counter.labels.call_args_list]assert any("django_orm" in c for c in calls)@@ -224,7 +224,7 @@ class TestGetGroupsByIdentifiers(SimpleTestCase):assert result == [model1, model2]mock_routing_counter.labels.assert_called_with(- operation="get_groups_by_identifiers", source="personhog", client_name="posthog-django"+ operation="get_groups_by_identifiers", source="personhog", client_name=ANY)mock_errors_counter.labels.assert_not_called()@@ -276,7 +276,7 @@ class TestGetGroupsByIdentifiers(SimpleTestCase):operation="get_groups_by_identifiers",source="personhog",error_type="grpc_error",- client_name="posthog-django",+ client_name=ANY,)calls = [str(c) for c in mock_routing_counter.labels.call_args_list]assert any("django_orm" in c for c in calls)@@ -298,7 +298,7 @@ class TestGetGroupsByIdentifiers(SimpleTestCase):assert result == orm_groupsmock_routing_counter.labels.assert_called_once_with(- operation="get_groups_by_identifiers", source="django_orm", client_name="posthog-django"+ operation="get_groups_by_identifiers", source="django_orm", client_name=ANY)@parameterized.expand(@@ -347,7 +347,7 @@ class TestGetGroupByKeyEdgeCases(SimpleTestCase):assert result is Nonemock_routing_counter.labels.assert_called_with(- operation="get_group_by_key", source="personhog", client_name="posthog-django"+ operation="get_group_by_key", source="personhog", client_name=ANY)@patch(_ROUTING_ERRORS_PATCH)@@ -502,7 +502,7 @@ class TestGetGroupsByTypeIndices(SimpleTestCase):assert len(call_args.group_identifiers) == 4mock_routing_counter.labels.assert_called_with(- operation="get_groups_by_type_indices", source="personhog", client_name="posthog-django"+ operation="get_groups_by_type_indices", source="personhog", client_name=ANY)mock_errors_counter.labels.assert_not_called()@@ -575,7 +575,7 @@ class TestGetGroupsByTypeIndices(SimpleTestCase):assert result == orm_groupsmock_routing_counter.labels.assert_called_once_with(- operation="get_groups_by_type_indices", source="django_orm", client_name="posthog-django"+ operation="get_groups_by_type_indices", source="django_orm", client_name=ANY)@parameterized.expand(@@ -704,9 +704,7 @@ class TestCreateGroup(SimpleTestCase):assert req.group_type_index == self.group_type_indexassert req.group_key == self.group_keyassert b'"name": "Acme"' in req.group_properties- mock_routing_counter.labels.assert_called_with(- operation="create_group", source="personhog", client_name="posthog-django"- )+ mock_routing_counter.labels.assert_called_with(operation="create_group", source="personhog", client_name=ANY)mock_ch.assert_called_once()@patch("posthog.models.group.util.raw_create_group_ch")@@ -731,7 +729,7 @@ class TestCreateGroup(SimpleTestCase):assert result is mock_groupmock_objects.create.assert_called_once()mock_routing_counter.labels.assert_called_with(- operation="create_group", source="django_orm", client_name="posthog-django"+ operation="create_group", source="django_orm", client_name=ANY)@parameterized.expand(@@ -769,7 +767,7 @@ class TestCreateGroup(SimpleTestCase):operation="create_group",source="personhog",error_type="grpc_error",- client_name="posthog-django",+ client_name=ANY,)@patch("posthog.models.group.util.raw_create_group_ch")@@ -818,9 +816,7 @@ class TestSaveGroup(SimpleTestCase):assert req.update_mask == ["group_properties"]assert b'"name": "Acme"' in req.group_propertiesgroup.save.assert_not_called()- mock_routing_counter.labels.assert_called_with(- operation="group_save", source="personhog", client_name="posthog-django"- )+ mock_routing_counter.labels.assert_called_with(operation="group_save", source="personhog", client_name=ANY)@patch(_ROUTING_TOTAL_PATCH)@patch(_CLIENT_PATCH)@@ -831,9 +827,7 @@ class TestSaveGroup(SimpleTestCase):save_group(group)group.save.assert_called_once()- mock_routing_counter.labels.assert_called_with(- operation="group_save", source="django_orm", client_name="posthog-django"- )+ mock_routing_counter.labels.assert_called_with(operation="group_save", source="django_orm", client_name=ANY)@parameterized.expand([@@ -859,5 +853,5 @@ class TestSaveGroup(SimpleTestCase):operation="group_save",source="personhog",error_type="grpc_error",- client_name="posthog-django",+ client_name=ANY,)diff --git a/posthog/models/person/test/test_batched_personhog_helpers.py b/posthog/models/person/test/test_batched_personhog_helpers.pyindex aba655223769..d1206e26221c 100644--- a/posthog/models/person/test/test_batched_personhog_helpers.py+++ b/posthog/models/person/test/test_batched_personhog_helpers.py@@ -1,4 +1,4 @@-from unittest.mock import MagicMock, patch+from unittest.mock import ANY, MagicMock, patchfrom django.test import SimpleTestCase@@ -81,7 +81,7 @@ class TestBatchedGetPersonsByUuids(SimpleTestCase):assert len(result) == 2assert mock_metric.labels.call_count == 2- mock_metric.labels.assert_any_call(operation="test_op", client_name="posthog-django")+ mock_metric.labels.assert_any_call(operation="test_op", client_name=ANY)@patch("posthog.models.person.util.PERSONHOG_BATCH_SIZE", 2)def test_preserves_order_across_batches(self):diff --git a/posthog/models/person/test/test_bulk_delete_helpers.py b/posthog/models/person/test/test_bulk_delete_helpers.pyindex d7c53af2a077..3460dcd7cee8 100644--- a/posthog/models/person/test/test_bulk_delete_helpers.py+++ b/posthog/models/person/test/test_bulk_delete_helpers.py@@ -2,37 +2,36 @@ from posthog.test.base import BaseTestfrom unittest.mock import patchfrom posthog.models.async_deletion import AsyncDeletion, DeletionType-from posthog.models.person import Personfrom posthog.models.person.bulk_delete import (delete_persons_profile,queue_person_event_deletion,queue_person_recording_deletion,resolve_persons_for_deletion,)+from posthog.test.persons import create_personclass ResolvePersonsTests(BaseTest):def test_resolves_by_uuid(self):- p = Person.objects.create(team=self.team, distinct_ids=["a"], properties={})+ p = create_person(team=self.team, distinct_ids=["a"], properties={})result = resolve_persons_for_deletion(self.team.pk, uuids=[str(p.uuid)], distinct_ids=None)assert [r.uuid for r in result] == [p.uuid]def test_resolves_by_distinct_id(self):- p = Person.objects.create(team=self.team, distinct_ids=["did-x"], properties={})+ p = create_person(team=self.team, distinct_ids=["did-x"], properties={})result = resolve_persons_for_deletion(self.team.pk, uuids=None, distinct_ids=["did-x"])assert [r.uuid for r in result] == [p.uuid]def test_uuids_take_precedence_over_distinct_ids(self):- p1 = Person.objects.create(team=self.team, distinct_ids=["d1"], properties={})- Person.objects.create(team=self.team, distinct_ids=["d2"], properties={})+ p1 = create_person(team=self.team, distinct_ids=["d1"], properties={})+ create_person(team=self.team, distinct_ids=["d2"], properties={})result = resolve_persons_for_deletion(self.team.pk, uuids=[str(p1.uuid)], distinct_ids=["d2"])assert {r.uuid for r in result} == {p1.uuid}- def test_caches_distinct_ids_via_prefetch(self):- p = Person.objects.create(team=self.team, distinct_ids=["a", "b"], properties={})+ def test_resolved_person_has_distinct_ids(self):+ p = create_person(team=self.team, distinct_ids=["a", "b"], properties={})[resolved] = resolve_persons_for_deletion(self.team.pk, uuids=[str(p.uuid)], distinct_ids=None)- assert hasattr(resolved, "distinct_ids_cache")- assert sorted(d.distinct_id for d in resolved.distinct_ids_cache) == ["a", "b"]+ assert sorted(resolved.distinct_ids) == ["a", "b"]def test_returns_empty_when_neither(self):assert resolve_persons_for_deletion(self.team.pk, uuids=None, distinct_ids=None) == []@@ -40,7 +39,7 @@ class ResolvePersonsTests(BaseTest):class QueueEventDeletionTests(BaseTest):def test_creates_one_async_deletion_per_person(self):- p = Person.objects.create(team=self.team, distinct_ids=["a"], properties={})+ p = create_person(team=self.team, distinct_ids=["a"], properties={})queue_person_event_deletion(self.team.pk, [p], actor=self.user)assert (AsyncDeletion.objects.filter(@@ -50,7 +49,7 @@ class QueueEventDeletionTests(BaseTest):)def test_ignores_duplicate_queueing(self):- p = Person.objects.create(team=self.team, distinct_ids=["a"], properties={})+ p = create_person(team=self.team, distinct_ids=["a"], properties={})queue_person_event_deletion(self.team.pk, [p], actor=self.user)queue_person_event_deletion(self.team.pk, [p], actor=self.user)assert AsyncDeletion.objects.filter(team_id=self.team.pk).count() == 1@@ -58,7 +57,7 @@ class QueueEventDeletionTests(BaseTest):class DeletePersonsProfileTests(BaseTest):def test_deletes_persons_via_helpers(self):- p = Person.objects.create(team=self.team, distinct_ids=["a"], properties={})+ p = create_person(team=self.team, distinct_ids=["a"], properties={})with (patch("posthog.models.person.bulk_delete.delete_person") as ch_delete,patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,@@ -70,8 +69,8 @@ class DeletePersonsProfileTests(BaseTest):pg_delete.assert_called_once_with(self.team.pk, [p])def test_collects_errors_and_skips_failed_persons_in_pg_batch(self):- p1 = Person.objects.create(team=self.team, distinct_ids=["a"], properties={})- p2 = Person.objects.create(team=self.team, distinct_ids=["b"], properties={})+ p1 = create_person(team=self.team, distinct_ids=["a"], properties={})+ p2 = create_person(team=self.team, distinct_ids=["b"], properties={})with (patch("posthog.models.person.bulk_delete.delete_person",@@ -92,8 +91,8 @@ class QueueRecordingDeletionTests(BaseTest):conn.assert_not_called()def test_starts_workflow_per_person(self):- p1 = Person.objects.create(team=self.team, distinct_ids=["a"], properties={})- p2 = Person.objects.create(team=self.team, distinct_ids=["b"], properties={})+ p1 = create_person(team=self.team, distinct_ids=["a"], properties={})+ p2 = create_person(team=self.team, distinct_ids=["b"], properties={})with patch("posthog.models.person.bulk_delete._start_recording_workflows") as start:queue_person_recording_deletion(self.team.pk, [p1, p2], actor=self.user)start.assert_called_once()diff --git a/posthog/models/person/test/test_delete_persons_personhog.py b/posthog/models/person/test/test_delete_persons_personhog.pyindex 398c37e6baa5..650f60bdad0a 100644--- a/posthog/models/person/test/test_delete_persons_personhog.py+++ b/posthog/models/person/test/test_delete_persons_personhog.py@@ -6,7 +6,7 @@ Covers routing, fallback, and integration for:"""from posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch+from unittest.mock import ANY, MagicMock, patchfrom django.test import SimpleTestCase@@ -16,6 +16,7 @@ from posthog.models.person import Person, PersonDistinctIdfrom posthog.models.person.util import delete_persons_from_postgresfrom posthog.models.team.util import _delete_persons_for_teamsfrom posthog.personhog_client.fake_client import fake_personhog_client+from posthog.test.persons import create_person# ── Routing tests for delete_persons_from_postgres ─────��────────────@@ -74,7 +75,7 @@ class TestDeletePersonsFromPostgresRouting(SimpleTestCase):mock_person.delete.assert_called_once()mock_routing_counter.labels.assert_called_with(- operation="delete_persons", source=expected_source, client_name="posthog-django"+ operation="delete_persons", source=expected_source, client_name=ANY)if grpc_exception is not None and gate_on:@@ -163,7 +164,7 @@ class TestDeletePersonsForTeamsRouting(SimpleTestCase):class TestDeletePersonsFromPostgresIntegration(BaseTest):def test_orm_path_deletes_person_and_distinct_ids(self):- person = Person.objects.create(+ person = create_person(team=self.team,distinct_ids=["did-1", "did-2"],properties={"email": "[email protected]"},@@ -176,7 +177,7 @@ class TestDeletePersonsFromPostgresIntegration(BaseTest):assert PersonDistinctId.objects.filter(team_id=self.team.pk, person_id=person.pk).count() == 0def test_personhog_path_calls_rpc_with_correct_args(self):- person = Person.objects.create(+ person = create_person(team=self.team,distinct_ids=["did-1", "did-2"],properties={"email": "[email protected]"},@@ -191,7 +192,7 @@ class TestDeletePersonsFromPostgresIntegration(BaseTest):assert list(req.person_uuids) == [str(person.uuid)]def test_personhog_path_fallback_deletes_from_db(self):- person = Person.objects.create(+ person = create_person(team=self.team,distinct_ids=["did-1"],)@@ -204,8 +205,8 @@ class TestDeletePersonsFromPostgresIntegration(BaseTest):assert PersonDistinctId.objects.filter(team_id=self.team.pk, person_id=person.pk).count() == 0def test_multiple_persons_deleted(self):- p1 = Person.objects.create(team=self.team, distinct_ids=["a"])- p2 = Person.objects.create(team=self.team, distinct_ids=["b"])+ p1 = create_person(team=self.team, distinct_ids=["a"])+ p2 = create_person(team=self.team, distinct_ids=["b"])with fake_personhog_client(gate_enabled=False):delete_persons_from_postgres(self.team.pk, [p1, p2])@@ -216,8 +217,8 @@ class TestDeletePersonsFromPostgresIntegration(BaseTest):class TestDeletePersonsForTeamsIntegration(BaseTest):def test_orm_fallback_deletes_persons_and_distinct_ids(self):- Person.objects.create(team=self.team, distinct_ids=["did-1", "did-2"])- Person.objects.create(team=self.team, distinct_ids=["did-3"])+ create_person(team=self.team, distinct_ids=["did-1", "did-2"])+ create_person(team=self.team, distinct_ids=["did-3"])assert Person.objects.filter(team_id=self.team.pk).count() == 2assert PersonDistinctId.objects.filter(team_id=self.team.pk).count() == 3@@ -230,8 +231,8 @@ class TestDeletePersonsForTeamsIntegration(BaseTest):def test_personhog_path_calls_batch_rpc_per_team(self):other_team = self.organization.teams.create(name="Other Team")- p1 = Person.objects.create(team=self.team, distinct_ids=["a"])- p2 = Person.objects.create(team=other_team, distinct_ids=["b"])+ p1 = create_person(team=self.team, distinct_ids=["a"])+ p2 = create_person(team=other_team, distinct_ids=["b"])with fake_personhog_client(gate_enabled=True) as fake:fake.add_person(team_id=self.team.pk, person_id=p1.pk, uuid=str(p1.uuid), distinct_ids=["a"])@@ -245,8 +246,8 @@ class TestDeletePersonsForTeamsIntegration(BaseTest):assert other_team.pk in team_ids_calleddef test_personhog_batch_rpc_loops_until_done(self):- p1 = Person.objects.create(team=self.team, distinct_ids=["a"])- p2 = Person.objects.create(team=self.team, distinct_ids=["b"])+ p1 = create_person(team=self.team, distinct_ids=["a"])+ p2 = create_person(team=self.team, distinct_ids=["b"])with fake_personhog_client(gate_enabled=True) as fake:fake.add_person(team_id=self.team.pk, person_id=p1.pk, uuid=str(p1.uuid), distinct_ids=["a"])@@ -261,7 +262,7 @@ class TestDeletePersonsForTeamsIntegration(BaseTest):assert calls[-1].response.deleted_count == 0def test_personhog_fallback_on_error_deletes_via_orm(self):- Person.objects.create(team=self.team, distinct_ids=["did-1"])+ create_person(team=self.team, distinct_ids=["did-1"])with fake_personhog_client(gate_enabled=True) as fake:fake.delete_persons_batch_for_team = MagicMock(side_effect=RuntimeError("grpc timeout"))@@ -272,8 +273,8 @@ class TestDeletePersonsForTeamsIntegration(BaseTest):def test_cross_team_isolation(self):other_team = self.organization.teams.create(name="Other Team")- Person.objects.create(team=self.team, distinct_ids=["a"])- Person.objects.create(team=other_team, distinct_ids=["b"])+ create_person(team=self.team, distinct_ids=["a"])+ create_person(team=other_team, distinct_ids=["b"])with fake_personhog_client(gate_enabled=False):_delete_persons_for_teams([self.team.pk])diff --git a/posthog/models/person/test/test_point_in_time_properties.py b/posthog/models/person/test/test_point_in_time_properties.pyindex 64e0cab8ee3a..b21b3e666300 100644--- a/posthog/models/person/test/test_point_in_time_properties.py+++ b/posthog/models/person/test/test_point_in_time_properties.py@@ -11,14 +11,13 @@ from unittest.mock import patchfrom django.test import SimpleTestCase-from parameterized import parameterized_class-from posthog.models.person.point_in_time_properties import (build_person_properties_at_time,get_person_and_distinct_ids_for_identifier,)from posthog.personhog_client.fake_client import fake_personhog_client-from posthog.personhog_client.test_helpers import PersonhogTestMixin+from posthog.test.personhog_fake import get_active_fake+from posthog.test.persons import create_persondef _prop_row(@@ -301,10 +300,9 @@ class TestGetPersonAndDistinctIdsForIdentifierPersonhog(SimpleTestCase):assert dids == []-@parameterized_class(("personhog",), [(False,), (True,)])-class TestGetPersonAndDistinctIdsForIdentifierIntegration(PersonhogTestMixin, BaseTest):+class TestGetPersonAndDistinctIdsForIdentifierIntegration(BaseTest):def test_lookup_by_distinct_id(self):- person = self._seed_person(+ person = create_person(team=self.team,distinct_ids=["d1", "d2"],properties={"email": "[email protected]"},@@ -316,10 +314,10 @@ class TestGetPersonAndDistinctIdsForIdentifierIntegration(PersonhogTestMixin, Baassert str(result_person.uuid) == str(person.uuid)assert result_person.properties == {"email": "[email protected]"}assert set(result_dids) == {"d1", "d2"}- self._assert_personhog_called("get_persons_by_distinct_ids_in_team")+ get_active_fake().assert_called("get_persons_by_distinct_ids_in_team")def test_lookup_by_person_id(self):- person = self._seed_person(+ person = create_person(team=self.team,distinct_ids=["d1"],properties={"name": "Test"},@@ -332,7 +330,7 @@ class TestGetPersonAndDistinctIdsForIdentifierIntegration(PersonhogTestMixin, Baassert result_person is not Noneassert str(result_person.uuid) == str(person.uuid)assert result_dids == ["d1"]- self._assert_personhog_called("get_person_by_uuid")+ get_active_fake().assert_called("get_person_by_uuid")def test_person_not_found(self):result_person, result_dids = get_person_and_distinct_ids_for_identifier(self.team.pk, distinct_id="unknown")@@ -342,7 +340,7 @@ class TestGetPersonAndDistinctIdsForIdentifierIntegration(PersonhogTestMixin, Badef test_cross_team_isolation(self):other_team = self.organization.teams.create(name="Other Team")- self._seed_person(team=other_team, distinct_ids=["shared_did"])+ create_person(team=other_team, distinct_ids=["shared_did"])result_person, result_dids = get_person_and_distinct_ids_for_identifier(self.team.pk, distinct_id="shared_did")diff --git a/posthog/models/person/test/test_split_person.py b/posthog/models/person/test/test_split_person.pyindex 6d225c13222e..75c78d90d4f4 100644--- a/posthog/models/person/test/test_split_person.py+++ b/posthog/models/person/test/test_split_person.py@@ -7,6 +7,7 @@ from posthog.models import Personfrom posthog.models.person import PersonDistinctIdfrom posthog.models.person.missing_person import uuidFromDistinctIdfrom posthog.personhog_client.fake_client import FakePersonHogClient, fake_personhog_client+from posthog.test.persons import add_distinct_id, create_person@patch("posthog.models.person.util.create_person")@@ -28,17 +29,13 @@ class TestSplitPerson(BaseTest):properties: dict | None = None,version: int = 0,) -> Person:- person = Person.objects.create(+ person = create_person(team=self.team,properties=properties or {},version=version,)for distinct_id in distinct_ids:- PersonDistinctId.objects.create(- team=self.team,- person=person,- distinct_id=distinct_id,- )+ add_distinct_id(person=person, distinct_id=distinct_id)fake.add_person(team_id=self.team.id,person_id=person.id,diff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.pyindex f979fda08260..79d243d03d0d 100644--- a/posthog/models/test/test_group_type_mapping.py+++ b/posthog/models/test/test_group_type_mapping.py@@ -1,7 +1,7 @@from datetime import UTC, datetimefrom posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch+from unittest.mock import ANY, MagicMock, patchfrom django.test import SimpleTestCase, override_settings@@ -28,6 +28,7 @@ from posthog.models.group_type_mapping import (update_group_type_mapping_fields,)from posthog.personhog_client.fake_client import FakePersonHogClient+from posthog.test.persons import create_group_type_mappingfrom posthog.utils import get_safe_cache, safe_cache_delete, safe_cache_setfrom products.dashboards.backend.models.dashboard import Dashboard@@ -104,7 +105,7 @@ class TestGetGroupTypesForProjectRouting(SimpleTestCase):assert len(result) == 2mock_objects.filter.assert_not_called()mock_routing_counter.labels.assert_called_with(- operation="get_group_types_for_project", source="personhog", client_name="posthog-django"+ operation="get_group_types_for_project", source="personhog", client_name=ANY)mock_errors_counter.labels.assert_not_called()@@ -129,7 +130,7 @@ class TestGetGroupTypesForProjectRouting(SimpleTestCase):assert result == ORM_DATAmock_routing_counter.labels.assert_called_with(- operation="get_group_types_for_project", source="django_orm", client_name="posthog-django"+ operation="get_group_types_for_project", source="django_orm", client_name=ANY)mock_errors_counter.labels.assert_called_once()@@ -236,7 +237,7 @@ class TestGetGroupTypesForTeamRouting(SimpleTestCase):assert result == PERSONHOG_SUCCESS_DATAmock_objects.filter.assert_not_called()mock_routing_counter.labels.assert_called_with(- operation="get_group_types_for_team", source="personhog", client_name="posthog-django"+ operation="get_group_types_for_team", source="personhog", client_name=ANY)mock_errors_counter.labels.assert_not_called()@@ -264,7 +265,7 @@ class TestGetGroupTypesForTeamRouting(SimpleTestCase):operation="get_group_types_for_team",source="personhog",error_type="grpc_error",- client_name="posthog-django",+ client_name=ANY,)@parameterized.expand(@@ -368,7 +369,7 @@ class TestGetGroupTypesForProjectsRouting(SimpleTestCase):assert result == personhog_resultmock_objects.filter.assert_not_called()mock_routing_counter.labels.assert_called_with(- operation="get_group_types_for_projects", source="personhog", client_name="posthog-django"+ operation="get_group_types_for_projects", source="personhog", client_name=ANY)mock_errors_counter.labels.assert_not_called()@@ -421,7 +422,7 @@ class TestGetGroupTypesForProjectsRouting(SimpleTestCase):operation="get_group_types_for_projects",source="personhog",error_type="grpc_error",- client_name="posthog-django",+ client_name=ANY,)@patch("posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog")@@ -696,7 +697,7 @@ class TestCountGroupTypeMappingsPerTeam(SimpleTestCase):assert result == [{"team_id": 1, "total": 3}, {"team_id": 2, "total": 5}]mock_objects.values.assert_not_called()mock_routing_counter.labels.assert_called_with(- operation="count_group_type_mappings_per_team", source="personhog", client_name="posthog-django"+ operation="count_group_type_mappings_per_team", source="personhog", client_name=ANY)mock_errors_counter.labels.assert_not_called()@@ -723,7 +724,7 @@ class TestCountGroupTypeMappingsPerTeam(SimpleTestCase):operation="count_group_type_mappings_per_team",source="personhog",error_type="grpc_error",- client_name="posthog-django",+ client_name=ANY,)@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@@ -748,7 +749,7 @@ class TestCountGroupTypeMappingsPerTeam(SimpleTestCase):assert result == orm_datamock_routing_counter.labels.assert_called_with(- operation="count_group_type_mappings_per_team", source="django_orm", client_name="posthog-django"+ operation="count_group_type_mappings_per_team", source="django_orm", client_name=ANY)mock_errors_counter.labels.assert_not_called()@@ -817,7 +818,7 @@ class TestUpdateGroupTypeMappingFields(SimpleTestCase):assert req.name_plural == "Orgs"mock_objects.filter.assert_not_called()mock_routing_counter.labels.assert_called_with(- operation="update_group_type_mapping_fields", source="personhog", client_name="posthog-django"+ operation="update_group_type_mapping_fields", source="personhog", client_name=ANY)@patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")@@ -832,7 +833,7 @@ class TestUpdateGroupTypeMappingFields(SimpleTestCase):mock_objects.filter.assert_called_once_with(project_id=1, group_type_index=0)mock_objects.filter.return_value.update.assert_called_once_with(name_singular="Org")mock_routing_counter.labels.assert_called_with(- operation="update_group_type_mapping_fields", source="django_orm", client_name="posthog-django"+ operation="update_group_type_mapping_fields", source="django_orm", client_name=ANY)@parameterized.expand(@@ -862,7 +863,7 @@ class TestUpdateGroupTypeMappingFields(SimpleTestCase):operation="update_group_type_mapping_fields",source="personhog",error_type="grpc_error",- client_name="posthog-django",+ client_name=ANY,)@patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")@@ -943,7 +944,7 @@ class TestDeleteGroupTypeMapping(SimpleTestCase):assert req.group_type_index == 0instance.delete.assert_not_called()mock_routing_counter.labels.assert_called_with(- operation="delete_group_type_mapping", source="personhog", client_name="posthog-django"+ operation="delete_group_type_mapping", source="personhog", client_name=ANY)@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@@ -958,7 +959,7 @@ class TestDeleteGroupTypeMapping(SimpleTestCase):mock_objects.filter.assert_called_once_with(project_id=1, group_type_index=0)mock_objects.filter.return_value.delete.assert_called_once()mock_routing_counter.labels.assert_called_with(- operation="delete_group_type_mapping", source="django_orm", client_name="posthog-django"+ operation="delete_group_type_mapping", source="django_orm", client_name=ANY)@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@@ -1060,7 +1061,7 @@ class TestClearDashboardFromGroupTypeMapping(SimpleTestCase):mock_objects.using.assert_called_once()mock_invalidate.assert_called_once_with(1)mock_routing_counter.labels.assert_called_with(- operation="clear_dashboard_from_group_type_mapping", source="django_orm", client_name="posthog-django"+ operation="clear_dashboard_from_group_type_mapping", source="django_orm", client_name=ANY)@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@@ -1392,7 +1393,7 @@ class TestGroupTypesForProjectPathParity(BaseTest):created_at = datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC)dashboard = Dashboard.objects.create(team=self.team, name="orgs")- GroupTypeMapping.objects.create( # nosemgrep: no-direct-persons-db-orm+ create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="organization",@@ -1403,7 +1404,7 @@ class TestGroupTypesForProjectPathParity(BaseTest):detail_dashboard=dashboard,created_at=created_at,)- minimal = GroupTypeMapping.objects.create( # nosemgrep: no-direct-persons-db-orm+ minimal = create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="company",diff --git a/posthog/models/test/test_person_model.py b/posthog/models/test/test_person_model.pyindex 1e7c43431b9b..315cda78d28b 100644--- a/posthog/models/test/test_person_model.py+++ b/posthog/models/test/test_person_model.py@@ -3,9 +3,9 @@ from uuid import uuid4from posthog.test.base import BaseTestfrom posthog.clickhouse.client import sync_execute-from posthog.models import Person, PersonDistinctIdfrom posthog.models.event.util import create_eventfrom posthog.models.person.util import delete_person+from posthog.test.persons import add_distinct_id, create_persondef _create_event(**kwargs):@@ -16,13 +16,13 @@ def _create_event(**kwargs):class TestPerson(BaseTest):def test_person_is_identified(self):- person_identified = Person.objects.create(team=self.team, is_identified=True)- person_anonymous = Person.objects.create(team=self.team)+ person_identified = create_person(team=self.team, is_identified=True)+ person_anonymous = create_person(team=self.team)self.assertEqual(person_identified.is_identified, True)self.assertEqual(person_anonymous.is_identified, False)def test_delete_person(self):- person = Person.objects.create(+ person = create_person(team=self.team, version=15) # version be > 0 to check that we don't just assume 0 in deletesdelete_person(person)@@ -33,8 +33,8 @@ class TestPerson(BaseTest):self.assertEqual(ch_persons, [(str(person.uuid), 115, 1, "{}")])def test_delete_ch_distinct_ids(self):- person = Person.objects.create(team=self.team)- PersonDistinctId.objects.create(team=self.team, person=person, distinct_id="distinct_id1", version=15)+ person = create_person(team=self.team)+ add_distinct_id(person=person, distinct_id="distinct_id1", version=15)ch_distinct_ids = sync_execute("SELECT is_deleted FROM person_distinct_id2 FINAL WHERE team_id = %(team_id)s and distinct_id = %(distinct_id)s",diff --git a/posthog/models/test/test_person_override_model.py b/posthog/models/test/test_person_override_model.pyindex b2c63e8ae9d4..f6aaba25de06 100644--- a/posthog/models/test/test_person_override_model.py+++ b/posthog/models/test/test_person_override_model.py@@ -10,6 +10,7 @@ from django.db.utils import DEFAULT_DB_ALIAS, ConnectionHandler, IntegrityErrorfrom posthog.api.test.test_organization import create_organizationfrom posthog.api.test.test_team import create_teamfrom posthog.models import Person, PersonOverride, PersonOverrideMapping, Team+from posthog.test.persons import create_person# PersonOverride model is not actively used (see PR #23616)# Skip all tests in this module@@ -45,9 +46,9 @@ def people(team):override_person_uuid = uuid4()new_override_person_uuid = uuid4()- p1 = Person.objects.create(uuid=old_person_uuid, team=team)- p2 = Person.objects.create(uuid=override_person_uuid, team=team)- p3 = Person.objects.create(uuid=new_override_person_uuid, team=team)+ p1 = create_person(uuid=old_person_uuid, team=team)+ p2 = create_person(uuid=override_person_uuid, team=team)+ p3 = create_person(uuid=new_override_person_uuid, team=team)yield (p1, p2, p3)diff --git a/posthog/personhog_client/test_helpers.py b/posthog/personhog_client/test_helpers.pyindex 7882ff209573..7c9043f8c6a4 100644--- a/posthog/personhog_client/test_helpers.py+++ b/posthog/personhog_client/test_helpers.py@@ -1,23 +1,8 @@-"""Shared test helpers for personhog parameterized tests.+"""Shared test helpers for personhog tests.-Provides PersonhogTestMixin for use with @parameterized_class to run-integration tests against both ORM and personhog paths.--Usage::-- from parameterized import parameterized_class- from posthog.personhog_client.test_helpers import PersonhogTestMixin-- @parameterized_class(("personhog",), [(False,), (True,)])- class TestMyFeature(PersonhogTestMixin, BaseTest):- def test_something(self):- person = self._seed_person(- team=self.team,- distinct_ids=["user-1"],- properties={"email": "[email protected]"},- )- # ... exercise the code path ...- self._assert_personhog_called("get_person_by_distinct_id")+Provides PersonhogTestMixin with helper methods for tests that exercise+personhog-backed reads. The global conftest fixture activates the fake for+every test, so the mixin no longer manages its own client lifecycle."""from __future__ import annotations@@ -25,38 +10,24 @@ from __future__ import annotationsfrom typing import Anyfrom posthog.models.person import Person-from posthog.personhog_client.fake_client import FakePersonHogClient, fake_personhog_client+from posthog.personhog_client.fake_client import FakePersonHogClientclass PersonhogTestMixin:- """Mixin for ``@parameterized_class`` tests that run against both ORM and personhog.-- Expects ``self.personhog: bool`` to be set by ``@parameterized_class``.+ """Mixin providing convenience helpers for tests that exercise personhog reads.- * ``setUp`` conditionally activates ``fake_personhog_client()``- * ``_seed_person`` always creates a real DB ``Person`` **and**, when- personhog is active, registers it in the fake client- * ``_assert_personhog_called`` / ``_assert_personhog_not_called`` are- no-ops on the ORM path so assertions can be shared across both runs+ The global ``_activate_personhog_fake`` conftest fixture activates the fake+ for every test. This mixin exposes ``_fake_client`` pointing at that global+ fake, plus ``_seed_person``, ``_assert_personhog_called``, etc."""- personhog: bool = False- _personhog_cm: Any = None_fake_client: FakePersonHogClient | None = Nonedef setUp(self) -> None:super().setUp() # type: ignore[misc]- if self.personhog:- self._personhog_cm = fake_personhog_client()- self._fake_client = self._personhog_cm.__enter__()- else:- self._personhog_cm = None- self._fake_client = None+ from posthog.test.personhog_fake import get_active_fake- def tearDown(self) -> None:- if self._personhog_cm is not None:- self._personhog_cm.__exit__(None, None, None)- super().tearDown() # type: ignore[misc]+ self._fake_client = get_active_fake()def _seed_person(self,@@ -64,60 +35,28 @@ class PersonhogTestMixin:team: Any,distinct_ids: list[str],properties: dict | None = None,- **fake_overrides: Any,+ **_fake_overrides: Any,) -> Person:- """Create a person in the DB and optionally seed the fake personhog client.+ from posthog.test.persons import create_person- Always creates a real DB record (needed for the ORM path and any- secondary queries like ClickHouse joins). When ``self.personhog``- is ``True``, additionally registers the person in the fake client.-- Extra keyword arguments are forwarded to- ``FakePersonHogClient.add_person()`` and override the defaults- derived from the DB record.- """- person = Person.objects.create(+ return create_person(team=team,distinct_ids=distinct_ids,properties=properties or {},)- if self._fake_client is not None:- fake_kwargs: dict[str, Any] = {- "is_identified": person.is_identified,- "created_at": int(person.created_at.timestamp() * 1000) if person.created_at else 0,- }- fake_kwargs.update(fake_overrides)- self._fake_client.add_person(- team_id=team.pk,- person_id=person.pk,- uuid=str(person.uuid),- distinct_ids=distinct_ids,- properties=properties,- **fake_kwargs,- )- return persondef _seed_cohort_membership(self, *, person_id: int, cohort_id: int, is_member: bool = True) -> None:- """Seed a cohort membership in the fake personhog client. No-op on the ORM path.-- Mirrors the pattern of ``_seed_person``: callers still create real- ``CohortPeople`` DB rows (needed for the ORM fallback and any secondary- queries). This helper additionally registers the membership in the- fake client when personhog routing is active.- """+ """Seed a cohort membership in the fake personhog client."""if self._fake_client is not None:self._fake_client.add_cohort_membership(person_id=person_id, cohort_id=cohort_id, is_member=is_member)def _assert_personhog_called(self, method: str, *, times: int | None = None) -> list[Any]:- """Assert a personhog method was called. No-op on the ORM path.-- Returns the matched calls so tests can inspect request arguments.- """+ """Assert a personhog method was called. Returns matched calls for inspection."""if self._fake_client is not None:return self._fake_client.assert_called(method, times=times)return []def _assert_personhog_not_called(self, method: str) -> None:- """Assert a personhog method was NOT called. No-op on the ORM path."""+ """Assert a personhog method was NOT called."""if self._fake_client is not None:self._fake_client.assert_not_called(method)diff --git a/posthog/queries/funnels/test/__snapshots__/test_funnel.ambr b/posthog/queries/funnels/test/__snapshots__/test_funnel.ambrindex 465824da4286..6e1eeb0dd691 100644--- a/posthog/queries/funnels/test/__snapshots__/test_funnel.ambr+++ b/posthog/queries/funnels/test/__snapshots__/test_funnel.ambr@@ -1012,6 +1012,16 @@# ---# name: TestFOSSFunnel.test_funnel_with_static_cohort_step_filter'''+ SELECT person_id+ FROM person_static_cohort+ WHERE team_id = 99999+ AND cohort_id = 99999+ AND person_id IN ['00000000-0000-4000-8000-000000000001']+ GROUP BY person_id+ '''+# ---+# name: TestFOSSFunnel.test_funnel_with_static_cohort_step_filter.1+ '''SELECT countIf(steps = 1) step_1,countIf(steps = 2) step_2,diff --git a/posthog/queries/funnels/test/test_funnel_persons.py b/posthog/queries/funnels/test/test_funnel_persons.pyindex db549d9bd43f..f96641d2f28d 100644--- a/posthog/queries/funnels/test/test_funnel_persons.py+++ b/posthog/queries/funnels/test/test_funnel_persons.py@@ -8,6 +8,7 @@ from posthog.test.base import (_create_event,_create_person,also_test_with_materialized_columns,+ flush_persons_and_events,snapshot_clickhouse_queries,)@@ -16,7 +17,6 @@ from django.utils import timezonefrom posthog.constants import INSIGHT_FUNNELSfrom posthog.models import Filterfrom posthog.models.event.util import bulk_create_events-from posthog.models.person.util import bulk_create_personsfrom posthog.queries.funnels.funnel_persons import ClickhouseFunnelActorsfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.test.test_journeys import journeys_for@@ -32,7 +32,8 @@ PERSON_ID_COLUMN = 2class TestFunnelPersons(ClickhouseTestMixin, APIBaseTest):def _create_sample_data_multiple_dropoffs(self):for i in range(35):- bulk_create_persons([{"distinct_ids": [f"user_{i}"], "team_id": self.team.pk}])+ _create_person(distinct_ids=[f"user_{i}"], team=self.team)+ flush_persons_and_events()events = []for i in range(5):events.append(diff --git a/posthog/queries/test/test_actors_base_query.py b/posthog/queries/test/test_actors_base_query.pyindex aea8493467dd..fc6acff31b3d 100644--- a/posthog/queries/test/test_actors_base_query.py+++ b/posthog/queries/test/test_actors_base_query.py@@ -16,6 +16,7 @@ from posthog.queries.actor_base_query import (serialize_groups,serialize_people,)+from posthog.test.persons import create_groupclass TestActorsBaseQuery(ClickhouseTestMixin, APIBaseTest):@@ -105,14 +106,14 @@ class TestActorsBaseQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_postgres_queriesdef test_get_groups(self):- Group.objects.create(+ create_group(team=self.team,group_type_index=0,group_key="org_1",group_properties={"name": "Organization 1", "industry": "Tech"},version=1,)- Group.objects.create(+ create_group(team=self.team,group_type_index=0,group_key="org_2",@@ -129,14 +130,14 @@ class TestActorsBaseQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_postgres_queriesdef test_serialize_groups_with_values(self):- Group.objects.create(+ create_group(team=self.team,group_type_index=1,group_key="company_a",group_properties={"name": "Company A"},version=1,)- Group.objects.create(+ create_group(team=self.team,group_type_index=1,group_key="company_b",diff --git a/posthog/queries/test/test_trends.py b/posthog/queries/test/test_trends.pyindex a11661b2504c..3cb4622b9597 100644--- a/posthog/queries/test/test_trends.py+++ b/posthog/queries/test/test_trends.py@@ -44,6 +44,7 @@ from posthog.models.person.util import create_person_distinct_idfrom posthog.models.utils import uuid7from posthog.queries.trends.breakdown import BREAKDOWN_OTHER_STRING_LABELfrom posthog.queries.trends.trends import Trends+from posthog.test.persons import create_personfrom posthog.test.test_journeys import journeys_forfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom posthog.utils import generate_cache_key@@ -8244,7 +8245,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):def test_breakdown_by_group_props_with_person_filter(self):self._create_groups()- Person.objects.create(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})+ create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"})_create_event(event="sign up",@@ -8288,7 +8289,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):def test_filtering_with_group_props(self):self._create_groups()- Person.objects.create(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})+ create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"})_create_event(event="$pageview",distinct_id="person1",@@ -8341,7 +8342,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):def test_filtering_with_group_props_event_with_no_group_data(self):self._create_groups()- Person.objects.create(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})+ create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"})_create_event(event="$pageview",distinct_id="person1",@@ -8397,7 +8398,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):def test_breakdown_by_group_props_with_person_filter_person_on_events(self):self._create_groups()- Person.objects.create(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})+ create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"})_create_event(event="sign up",@@ -8442,7 +8443,7 @@ class TestTrends(ClickhouseTestMixin, APIBaseTest):def test_filtering_with_group_props_person_on_events(self):self._create_groups()- Person.objects.create(team_id=self.team.pk, distinct_ids=["person1"], properties={"key": "value"})+ create_person(team=self.team, distinct_ids=["person1"], properties={"key": "value"})_create_event(event="$pageview",distinct_id="person1",diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambrindex f83460c8f18d..23537a91c237 100644--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambr+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recordings_list_by_cohort.ambr@@ -513,6 +513,16 @@# ---# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties'''+ SELECT person_id+ FROM person_static_cohort+ WHERE team_id = 99999+ AND cohort_id = 99999+ AND person_id IN ['00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-000000000003']+ GROUP BY person_id+ '''+# ---+# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.1+ '''SELECT count(DISTINCT person_id)FROM cohortpeople@@ -521,7 +531,7 @@AND version = 0'''# ----# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.1+# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.2'''SELECT s.session_id AS session_id,any(s.team_id) AS `any(s.team_id)`,@@ -576,7 +586,7 @@use_hive_partitioning=0'''# ----# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.2+# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.3'''SELECT s.session_id AS session_id,any(s.team_id) AS `any(s.team_id)`,@@ -631,7 +641,7 @@use_hive_partitioning=0'''# ----# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.3+# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.4'''SELECT s.session_id AS session_id,any(s.team_id) AS `any(s.team_id)`,@@ -686,7 +696,7 @@use_hive_partitioning=0'''# ----# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.4+# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.5'''SELECT s.session_id AS session_id,any(s.team_id) AS `any(s.team_id)`,@@ -741,7 +751,7 @@use_hive_partitioning=0'''# ----# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.5+# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.6'''SELECT s.session_id AS session_id,any(s.team_id) AS `any(s.team_id)`,@@ -800,7 +810,7 @@use_hive_partitioning=0'''# ----# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.6+# name: TestSessionRecordingsListByCohort.test_filter_with_static_and_dynamic_cohort_properties.7'''SELECT s.session_id AS session_id,any(s.team_id) AS `any(s.team_id)`,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.pyindex 4bc79d8ef2a7..64c4291357f9 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@@ -11,7 +11,6 @@ from posthog.schema import PersonPropertyFilter, PropertyOperator, RecordingsQuefrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL-from posthog.models import Personfrom posthog.session_recordings.queries.sub_queries.events_subquery import ReplayFiltersEventsSubQueryfrom posthog.session_recordings.queries.test.listing_recordings.test_utils import (assert_query_matches_session_ids,@@ -19,6 +18,7 @@ from posthog.session_recordings.queries.test.listing_recordings.test_utils impor)from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL+from posthog.test.persons import create_person@freeze_time("2021-01-01T13:46:23")@@ -46,7 +46,7 @@ class TestPersonPropertyHybridQuery(ClickhouseTestMixin, APIBaseTest):identified_id = "identified_user_123"session_id_after = "session_after_identification"- Person.objects.create(+ create_person(team=self.team,distinct_ids=[anonymous_id, identified_id],properties={"email": "[email protected]"},@@ -102,7 +102,7 @@ class TestPersonPropertyHybridQuery(ClickhouseTestMixin, APIBaseTest):properties={"$session_id": session_id_before},)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[anonymous_id, identified_id],properties={"email": "[email protected]"},@@ -146,7 +146,7 @@ class TestPersonPropertyHybridQuery(ClickhouseTestMixin, APIBaseTest):session_id_2 = "session_2"session_id_3 = "session_3"- Person.objects.create(+ create_person(team=self.team,distinct_ids=[distinct_id_1, distinct_id_2, distinct_id_3],properties={"email": "[email protected]"},diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.pyindex 97c8df1e09bc..5a7a4b0d3619 100644--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.py+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_by_top_level_event_property.py@@ -10,7 +10,7 @@ from parameterized import parameterized, parameterized_classfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL-from posthog.models import EventProperty, Person+from posthog.models import EventPropertyfrom posthog.models.team import Teamfrom posthog.models.utils import uuid7from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingQueryResult@@ -21,6 +21,7 @@ from posthog.session_recordings.queries.test.listing_recordings.test_utils impor)from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL+from posthog.test.persons import create_personfrom products.actions.backend.models.action import Action@@ -111,7 +112,7 @@ class TestSessionRecordingsListByTopLevelEventProperty(ClickhouseTestMixin, APIBsession = f"{label}-session-{i}"sessions.append(session)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[user],properties=session_one_person_properties if i == 0 else session_two_person_properties,@@ -159,7 +160,7 @@ class TestSessionRecordingsListByTopLevelEventProperty(ClickhouseTestMixin, APIB@freeze_time("2021-01-21T20:00:00.000Z")@snapshot_clickhouse_queriesdef test_can_filter_for_flags(self, _name: str, properties: dict, expected: list[str]) -> None:- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})for event_name in ["foo", "bar", "baz", "$pageview"]:EventProperty.objects.create(team=self.team, event=event_name, property="$feature/target-flag")@@ -245,7 +246,7 @@ class TestSessionRecordingsListByTopLevelEventProperty(ClickhouseTestMixin, APIB@freeze_time("2021-01-21T20:00:00.000Z")@snapshot_clickhouse_queriesdef test_can_filter_for_two_is_not_event_properties(self) -> None:- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})for event_name in ["foo", "bar", "baz", "$pageview"]:EventProperty.objects.create(team=self.team, event=event_name, property="probe-one")@@ -323,7 +324,7 @@ class TestSessionRecordingsListByTopLevelEventProperty(ClickhouseTestMixin, APIB@freeze_time("2021-01-21T20:00:00.000Z")@snapshot_clickhouse_queriesdef test_can_filter_for_does_not_match_regex_event_properties(self) -> None:- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})for event_name in ["foo", "bar", "baz", "$pageview"]:EventProperty.objects.create(team=self.team, event=event_name, property="$host")@@ -400,7 +401,7 @@ class TestSessionRecordingsListByTopLevelEventProperty(ClickhouseTestMixin, APIB@freeze_time("2021-01-21T20:00:00.000Z")@snapshot_clickhouse_queriesdef test_can_filter_for_does_not_contain_event_properties(self) -> None:- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})for event_name in ["foo", "bar", "baz", "$pageview"]:EventProperty.objects.create(team=self.team, event=event_name, property="something")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.pyindex f4d7bdb8ed53..b807455a51f5 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@@ -32,7 +32,6 @@ from posthog.hogql.printer import prepare_and_print_astfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL-from posthog.models import Personfrom posthog.models.group.util import create_groupfrom posthog.models.team import Teamfrom posthog.session_recordings.queries.session_recording_list_from_query import (@@ -46,6 +45,7 @@ from posthog.session_recordings.queries.test.listing_recordings.test_utils impor)from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL+from posthog.test.persons import create_personfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.actions.backend.models.action import Action@@ -139,7 +139,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):session = f"{label}-session-{i}"sessions.append(session)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[user],properties=session_one_person_properties if i == 0 else session_two_person_properties,@@ -163,7 +163,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_basic_query(self):user = "test_basic_query-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = f"test_basic_query-{str(uuid4())}"session_id_two = f"test_basic_query-{str(uuid4())}"@@ -268,7 +268,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):self,):user = "test_basic_query-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_total_is_61 = f"test_basic_query_active_sessions-total-{str(uuid4())}"session_id_active_is_61 = f"test_basic_query_active_sessions-active-{str(uuid4())}"@@ -355,7 +355,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):self,):user = "test_sessions_with_current_data-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_inactive = f"test_sessions_with_current_data-inactive-{str(uuid4())}"session_id_active = f"test_sessions_with_current_data-active-{str(uuid4())}"@@ -400,7 +400,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_basic_query_with_paging(self):user = "test_basic_query_with_paging-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = f"id_one_test_basic_query_with_paging-{str(uuid4())}"session_id_two = f"id_two_test_basic_query_with_paging-{str(uuid4())}"@@ -512,7 +512,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_basic_query_with_ordering(self):user = "test_basic_query_with_ordering-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = f"test_basic_query_with_ordering-session-1-{str(uuid4())}"session_id_two = f"test_basic_query_with_ordering-session-2-{str(uuid4())}"@@ -569,7 +569,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_first_url_selection(self):user = "test_first_url_selection-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = f"first-url-on-first-event-{str(uuid4())}"session_id_two = f"first-url-not-on-first-event-{str(uuid4())}"@@ -702,8 +702,8 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_recordings_dont_leak_data_between_teams(self):another_team = Team.objects.create(organization=self.organization)user = "test_recordings_dont_leak_data_between_teams-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})- Person.objects.create(team=another_team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=another_team, distinct_ids=[user], properties={"email": "bla"})session_id_one = f"test_recordings_dont_leak_data_between_teams-1-{str(uuid4())}"session_id_two = f"test_recordings_dont_leak_data_between_teams-2-{str(uuid4())}"@@ -741,7 +741,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_event_filter(self):user = "test_event_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = f"test_event_filter-{str(uuid4())}"produce_replay_summary(distinct_id=user,@@ -793,7 +793,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_event_filter_has_ttl_applied_too(self):user = "test_event_filter_has_ttl_applied_too-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = f"test_event_filter_has_ttl_applied_too-{str(uuid4())}"# this is artificially incorrect data, the session events are within TTL@@ -855,7 +855,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_filter_on_session_ids(self):user = "test_session_ids-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})first_session_id = str(uuid4())second_session_id = str(uuid4())@@ -919,7 +919,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def _an_old_recording(self) -> str:user = "test_session_ids_date_window-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})ten_days_ago = self.an_hour_ago - relativedelta(days=10)old_session_id = str(uuid4())@@ -1016,7 +1016,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_retention_bound_cannot_hide_live_recordings(self) -> None:# anything older than the 5y bound is past every retention period, so never viewableuser = "test_retention_bound-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})six_years_ago = self.an_hour_ago - relativedelta(years=6)ancient_session_id = str(uuid4())@@ -1042,7 +1042,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):) -> None:# event subqueries scan within the date range even when bypassinguser = "test_session_ids_event_window-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})ten_days_ago = self.an_hour_ago - relativedelta(days=10)old_session_id = str(uuid4())@@ -1074,7 +1074,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):self,):user = "test_basic_query-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_total_is_61 = f"test_basic_query_active_sessions-total-{str(uuid4())}"session_id_active_is_61 = f"test_basic_query_active_sessions-active-{str(uuid4())}"@@ -1165,7 +1165,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_event_filter_with_properties(self):user = "test_event_filter_with_properties-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = f"test_event_filter_with_properties-{str(uuid4())}"produce_replay_summary(distinct_id=user,@@ -1293,7 +1293,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_multiple_event_filters(self):session_id = f"test_multiple_event_filters-{str(uuid4())}"user = "test_multiple_event_filters-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})produce_replay_summary(distinct_id=user,session_id=session_id,@@ -1460,7 +1460,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@freeze_time("2023-01-04")def test_action_filter(self):user = "test_action_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = f"test_action_filter-session-one"window_id = "test_action_filter-window-id"action_with_properties = self.create_action(@@ -1579,7 +1579,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_all_sessions_recording_object_keys_with_entity_filter(self):user = "test_all_sessions_recording_object_keys_with_entity_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id = f"test_all_sessions_recording_object_keys_with_entity_filter-{str(uuid4())}"window_id = str(uuid4())@@ -1650,7 +1650,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_duration_filter(self):user = "test_duration_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = "session one is 29 seconds long"produce_replay_summary(@@ -1683,10 +1683,10 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_operand_or_person_filters(self):user = "test_operand_or_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "[email protected]"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "[email protected]"})second_user = "test_operand_or_filter-second_user"- Person.objects.create(team=self.team, distinct_ids=[second_user], properties={"email": "[email protected]"})+ create_person(team=self.team, distinct_ids=[second_user], properties={"email": "[email protected]"})session_id_one = "session_id_one"produce_replay_summary(@@ -1751,10 +1751,10 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_operand_or_event_filters(self):user = "test_operand_or_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "[email protected]"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "[email protected]"})second_user = "test_operand_or_filter-second_user"- Person.objects.create(team=self.team, distinct_ids=[second_user], properties={"email": "[email protected]"})+ create_person(team=self.team, distinct_ids=[second_user], properties={"email": "[email protected]"})session_id_one = "session_id_one"produce_replay_summary(@@ -1886,7 +1886,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):expected_session_ids: list[str],) -> None:user = "test_operand_or_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_with_both_log_filters = "both_log_filters"produce_replay_summary(@@ -1915,10 +1915,10 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_operand_or_mandatory_filters(self):user = "test_operand_or_filter-user"- person = Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ person = create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})second_user = "test_operand_or_filter-second_user"- second_person = Person.objects.create(team=self.team, distinct_ids=[second_user], properties={"email": "bla"})+ second_person = create_person(team=self.team, distinct_ids=[second_user], properties={"email": "bla"})session_id_one = "session_id_one"produce_replay_summary(@@ -2015,7 +2015,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_date_from_filter(self):user = "test_date_from_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})produce_replay_summary(distinct_id=user,@@ -2059,7 +2059,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_date_from_filter_respects_ttl(self, _name: str, days_ago: int):with freeze_time(self.an_hour_ago):user = "test_date_from_filter_cannot_search_before_ttl-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})# Create a session past TTL (32 days old)produce_replay_summary(@@ -2088,7 +2088,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_date_to_filter(self):user = "test_date_to_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})produce_replay_summary(distinct_id=user,session_id="three days before base time",@@ -2115,7 +2115,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_recording_that_spans_time_bounds(self):user = "test_recording_that_spans_time_bounds-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})day_line = datetime(2021, 11, 5)session_id = f"session-one-{user}"produce_replay_summary(@@ -2142,7 +2142,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):three_user_ids = [str(uuid4()) for _ in range(3)]session_id_one = f"test_person_id_filter-{str(uuid4())}"session_id_two = f"test_person_id_filter-{str(uuid4())}"- p = Person.objects.create(+ p = create_person(team=self.team,distinct_ids=[three_user_ids[0], three_user_ids[1]],properties={"email": "bla"},@@ -2170,7 +2170,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):three_user_ids = [str(uuid4()) for _ in range(3)]target_session_id = f"test_all_filters_at_once-{str(uuid4())}"- p = Person.objects.create(+ p = create_person(team=self.team,distinct_ids=[three_user_ids[0], three_user_ids[1]],properties={"email": "bla"},@@ -2247,7 +2247,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_teams_dont_leak_event_filter(self):user = "test_teams_dont_leak_event_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})another_team = Team.objects.create(organization=self.organization)session_id = f"test_teams_dont_leak_event_filter-{str(uuid4())}"@@ -2320,7 +2320,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@also_test_with_materialized_columns(["$current_url"])def test_event_filter_with_matching_on_session_id(self):user_distinct_id = "test_event_filter_with_matching_on_session_id-user"- Person.objects.create(team=self.team, distinct_ids=[user_distinct_id], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user_distinct_id], properties={"email": "bla"})session_id = f"test_event_filter_with_matching_on_session_id-1-{str(uuid4())}"create_event(@@ -2384,7 +2384,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_event_filter_with_hogql_properties(self):user = "test_event_filter_with_hogql_properties-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id = f"test_event_filter_with_hogql_properties-1-{str(uuid4())}"create_event(@@ -2447,7 +2447,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_event_filter_with_hogql_person_properties(self):user = "test_event_filter_with_hogql_properties-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id = f"test_event_filter_with_hogql_properties-1-{str(uuid4())}"create_event(@@ -2518,7 +2518,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queries@freeze_time("2021-01-21T20:00:00.000Z")def test_any_event_filter_with_properties(self):- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})page_view_session_id = f"pageview-session-{str(uuid4())}"my_custom_event_session_id = f"my-custom-event-session-{str(uuid4())}"@@ -2650,7 +2650,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queries@freeze_time("2021-01-21T20:00:00.000Z")def test_filter_for_recordings_with_console_logs(self):- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})with_logs_session_id = f"with-logs-session-{str(uuid4())}"without_logs_session_id = f"no-logs-session-{str(uuid4())}"@@ -2706,7 +2706,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queries@freeze_time("2021-01-21T20:00:00.000Z")def test_filter_for_recordings_with_console_warns(self):- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})with_logs_session_id = f"with-logs-session-{str(uuid4())}"without_logs_session_id = f"no-logs-session-{str(uuid4())}"@@ -2758,7 +2758,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queries@freeze_time("2021-01-21T20:00:00.000Z")def test_filter_for_recordings_with_console_errors(self):- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})with_logs_session_id = f"with-logs-session-{str(uuid4())}"without_logs_session_id = f"no-logs-session-{str(uuid4())}"@@ -2810,7 +2810,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queries@freeze_time("2021-01-21T20:00:00.000Z")def test_filter_for_recordings_with_mixed_console_counts(self):- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})with_logs_session_id = f"with-logs-session-{str(uuid4())}"with_warns_session_id = f"with-warns-session-{str(uuid4())}"@@ -2943,7 +2943,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):operand: Literal["AND", "OR"],expected_session_ids: list[str],) -> None:- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})# Create sessionsproduce_replay_summary(@@ -3028,7 +3028,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_filter_for_recordings_by_snapshot_source(self):user = "test_duration_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = "session one id"produce_replay_summary(@@ -3062,7 +3062,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_filter_for_recordings_by_snapshot_library(self):user = "test_library_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = f"test_library_filter-{str(uuid4())}"produce_replay_summary(@@ -3101,7 +3101,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):recording filters for better query performance (avoids events table scan)."""user = "test_lib_conversion-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})session_id_one = f"test_lib_conversion-{str(uuid4())}"produce_replay_summary(@@ -3141,7 +3141,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):aggregated columns that only exist after GROUP BY."""user = "test_recording_prop_routing-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})short_session = f"test_recording_prop_routing-short-{str(uuid4())}"produce_replay_summary(@@ -3170,7 +3170,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_filter_for_recordings_by_visited_page(self):user = "test_visited_page_filter-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})# Session with /pricing page in recordingsession_id_one = "session one id"@@ -3253,7 +3253,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):def test_duration_always_anded_with_visited_page_under_or(self):user = "test_duration_visited_page-user"- Person.objects.create(team=self.team, distinct_ids=[user], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user], properties={"email": "bla"})# Visited /pricing but too short to clear the duration controlshort_session = "short pricing session"@@ -3315,7 +3315,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):]self.team.save()- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})produce_replay_summary(distinct_id="user",@@ -3383,8 +3383,8 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):]self.team.save()- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})- Person.objects.create(+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team,distinct_ids=["user2"],properties={"email": "not-the-other-one"},@@ -3495,8 +3495,8 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):]self.team.save()- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})- Person.objects.create(+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team,distinct_ids=["user2"],properties={"email": "not-the-other-one"},@@ -3588,8 +3588,8 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):]self.team.save()- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})- Person.objects.create(+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team,distinct_ids=["user2"],properties={"email": "not-the-other-one"},@@ -3674,8 +3674,8 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):]self.team.save()- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})- Person.objects.create(+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team,distinct_ids=["user2"],properties={"email": "not-the-other-one"},@@ -3760,8 +3760,8 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):]self.team.save()- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})- Person.objects.create(+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team,distinct_ids=["user2"],properties={"email": "not-the-other-one"},@@ -3844,8 +3844,8 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):self.team.test_account_filters = [{"key": "email", "value": ["bla"], "operator": "exact", "type": "person"}]self.team.save()- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})- Person.objects.create(+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team,distinct_ids=["user2"],properties={"email": "not-the-other-one"},@@ -3934,8 +3934,8 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):another_team = Team.objects.create(organization=self.organization)# two teams, user with the same properties- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})- Person.objects.create(team=another_team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=another_team, distinct_ids=["user"], properties={"email": "bla"})# a recording session with a pageview and a pageleaveself._a_session_with_two_events(self.team, "1")@@ -3964,7 +3964,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):@freeze_time("2021-01-21T20:00:00.000Z")@snapshot_clickhouse_queriesdef test_event_filter_with_group_filter(self):- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})session_id = f"test_event_filter_with_group_filter-ONE-{uuid4()}"different_group_session = f"test_event_filter_with_group_filter-TWO-{uuid4()}"@@ -4127,8 +4127,8 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):]self.team.save()- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})- Person.objects.create(+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team,distinct_ids=["user2"],properties={"email": "not-the-other-one"},@@ -4246,7 +4246,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):]self.team.save()- Person.objects.create(team=self.team, distinct_ids=["user"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user"], properties={"email": "bla"})# session "1": internal (localhost) AND matches a user filter ($pageview)produce_replay_summary(@@ -4304,8 +4304,8 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):# Create two users with different distinct_idsuser1 = "test-user-1"user2 = "test-user-2"- Person.objects.create(team=self.team, distinct_ids=[user1])- Person.objects.create(team=self.team, distinct_ids=[user2])+ create_person(team=self.team, distinct_ids=[user1])+ create_person(team=self.team, distinct_ids=[user2])# Create sessions for each usersession1 = f"session1-{uuid4()}"@@ -4345,7 +4345,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):identified_id = "identified-user"anonymous_id = "anon-uuid-123"- person = Person.objects.create(team=self.team, distinct_ids=[identified_id, anonymous_id])+ person = create_person(team=self.team, distinct_ids=[identified_id, anonymous_id])identified_session = f"identified-session-{uuid4()}"anonymous_session = f"anonymous-session-{uuid4()}"@@ -4770,8 +4770,8 @@ class TestClickhouseSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTsession_id_one = f"test_event_filter_with_person_properties-1-{str(uuid4())}"session_id_two = f"test_event_filter_with_person_properties-2-{str(uuid4())}"- Person.objects.create(team=self.team, distinct_ids=[user_one], properties={"email": "bla"})- Person.objects.create(team=self.team, distinct_ids=[user_two], properties={"email": "bla2"})+ create_person(team=self.team, distinct_ids=[user_one], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=[user_two], properties={"email": "bla2"})self._add_replay_with_pageview(session_id_one, user_one)produce_replay_summary(@@ -4869,12 +4869,12 @@ class TestClickhouseSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTsession_id_two = f"test_person_id_filter-session-two"session_id_three = f"test_person_id_filter-session-three"- p = Person.objects.create(+ p = create_person(team=self.team,distinct_ids=[three_user_ids[0], three_user_ids[1]],properties={"email": "bla"},)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[three_user_ids[2]],properties={"email": "bla2"},diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.pyindex 944e5e13f31b..1acad2d2de5e 100644--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.py+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_cohort.py@@ -1,4 +1,4 @@-from uuid import uuid4+from uuid import UUID, uuid4from freezegun import freeze_timefrom posthog.test.base import (@@ -15,13 +15,13 @@ from dateutil.relativedelta import relativedeltafrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL-from posthog.models import Personfrom posthog.session_recordings.queries.test.listing_recordings.test_utils import (assert_query_matches_session_ids,create_event,)from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL+from posthog.test.persons import create_personfrom products.cohorts.backend.models.cohort import Cohort@@ -55,8 +55,8 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):session_id_one = "session_not_in_cohort"session_id_two = "session_in_cohort"- Person.objects.create(team=self.team, distinct_ids=[user_one], properties={"email": "bla"})- Person.objects.create(+ create_person(team=self.team, distinct_ids=[user_one], properties={"email": "bla"})+ create_person(team=self.team,distinct_ids=[user_two],properties={"email": "bla2", "$some_prop": "some_val"},@@ -156,16 +156,23 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):f"not-in-any-cohort-test_filter_with_static_and_dynamic_cohort_properties-4-{str(uuid4())}")- Person.objects.create(team=self.team, distinct_ids=[user_one], properties={"email": "[email protected]"})- Person.objects.create(+ create_person(+ team=self.team,+ distinct_ids=[user_one],+ properties={"email": "[email protected]"},+ uuid=UUID("00000000-0000-0000-0000-000000000001"),+ )+ create_person(team=self.team,distinct_ids=[user_two],properties={"email": "[email protected]", "$some_prop": "some_val"},+ uuid=UUID("00000000-0000-0000-0000-000000000002"),)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[user_three],properties={"email": "[email protected]", "$some_prop": "some_val"},+ uuid=UUID("00000000-0000-0000-0000-000000000003"),)dynamic_cohort = Cohort.objects.create(@@ -287,9 +294,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):# and now with users not in any cohort- Person.objects.create(- team=self.team, distinct_ids=[user_four], properties={"email": "[email protected]"}- )+ create_person(team=self.team, distinct_ids=[user_four], properties={"email": "[email protected]"})produce_replay_summary(distinct_id=user_four,session_id=session_id_four,@@ -326,8 +331,8 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):session_id_one = f"test_filter_with_events_and_cohorts-1-{str(uuid4())}"session_id_two = f"test_filter_with_events_and_cohorts-2-{str(uuid4())}"- Person.objects.create(team=self.team, distinct_ids=[user_one], properties={"email": "bla"})- Person.objects.create(+ create_person(team=self.team, distinct_ids=[user_one], properties={"email": "bla"})+ create_person(team=self.team,distinct_ids=[user_two],properties={"email": "bla2", "$some_prop": "some_val"},@@ -444,8 +449,8 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):session_id_one = "session_not_in_cohort"session_id_two = "session_in_cohort"- Person.objects.create(team=self.team, distinct_ids=[user_one], properties={"email": "bla"})- Person.objects.create(+ create_person(team=self.team, distinct_ids=[user_one], properties={"email": "bla"})+ create_person(team=self.team,distinct_ids=[user_two],properties={"email": "bla2", "$some_prop": "some_val"},@@ -529,7 +534,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):session_id = "session-should-not-be-filtered"# Create person A (will be in cohort, then merged away)- person_a = Person.objects.create(+ person_a = create_person(team=self.team,distinct_ids=[distinct_id],properties={"$some_prop": "some_val"},@@ -554,7 +559,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):cohort.calculate_people_ch(pending_version=0)# Create person B (not in cohort)- person_b = Person.objects.create(+ person_b = create_person(team=self.team,distinct_ids=["another-distinct-id"],properties={"other_prop": "other_val"},@@ -645,7 +650,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):external_sessions = [f"session-external-{i}" for i in range(5)]# Create internal user (in cohort)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[internal_user],properties={"email": internal_user, "is_internal": True},@@ -653,7 +658,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):# Create external users (not in cohort)for user in external_users:- Person.objects.create(+ create_person(team=self.team,distinct_ids=[user],properties={"email": user, "is_internal": False},@@ -735,7 +740,7 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):user = "[email protected]"session_id = "session-with-empty-cohort"- Person.objects.create(+ create_person(team=self.team,distinct_ids=[user],properties={"email": user},@@ -813,17 +818,17 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):session_free = "session-free"# Create users with different properties- Person.objects.create(+ create_person(team=self.team,distinct_ids=[internal_user],properties={"is_internal": True, "plan": "internal"},)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[premium_external],properties={"is_internal": False, "plan": "premium"},)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[free_external],properties={"is_internal": False, "plan": "free"},@@ -899,17 +904,17 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):session_regular = "session-regular"# Create users- Person.objects.create(+ create_person(team=self.team,distinct_ids=[internal_user],properties={"is_internal": True, "is_beta": False},)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[beta_user],properties={"is_internal": False, "is_beta": True},)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[regular_user],properties={"is_internal": False, "is_beta": False},@@ -980,17 +985,17 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):session_beta = "session-beta-or"session_regular = "session-regular-or"- Person.objects.create(+ create_person(team=self.team,distinct_ids=[internal_user],properties={"is_internal": True, "is_beta": False},)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[beta_user],properties={"is_internal": False, "is_beta": True},)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[regular_user],properties={"is_internal": False, "is_beta": False},@@ -1095,12 +1100,12 @@ class TestSessionRecordingsListByCohort(ClickhouseTestMixin, APIBaseTest):session_external = "session-external"session_anonymous = "session-anonymous"- Person.objects.create(+ create_person(team=self.team,distinct_ids=[internal_user],properties={"user_group": "internal"},)- Person.objects.create(+ create_person(team=self.team,distinct_ids=[external_user],properties={"user_group": "external"},diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_group_properties.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_group_properties.pyindex bc578659a3d3..c5abc9a97dde 100644--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_group_properties.py+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recordings_list_by_group_properties.py@@ -7,11 +7,11 @@ from dateutil.relativedelta import relativedeltafrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.log_entries import TRUNCATE_LOG_ENTRIES_TABLE_SQL-from posthog.models import Personfrom posthog.models.group.util import create_groupfrom posthog.session_recordings.queries.test.listing_recordings.test_utils import assert_query_matches_session_idsfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL+from posthog.test.persons import create_personfrom posthog.test.test_utils import create_group_type_mapping_without_created_at@@ -37,7 +37,7 @@ class TestSessionRecordingsListByGroupProperties(ClickhouseTestMixin, APIBaseTes@snapshot_clickhouse_queriesdef test_filter_with_group_properties(self) -> None:# there is one person- Person.objects.create(team_id=self.team.pk, distinct_ids=["p1"], properties={"$browser": "test"})+ create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"$browser": "test"})# there are two groupscreate_group_type_mapping_without_created_at(diff --git a/posthog/session_recordings/test/test_session_recording_personhog.py b/posthog/session_recordings/test/test_session_recording_personhog.pyindex d6baec87564b..cfda9c2a3d44 100644--- a/posthog/session_recordings/test/test_session_recording_personhog.py+++ b/posthog/session_recordings/test/test_session_recording_personhog.py@@ -1,18 +1,19 @@"""Tests for session recording person loading via the personhog path.TestLoadPersonRouting — Pattern A routing test (gate/fallback logic).-TestLoadPersonIntegration — parameterized integration test (ORM + personhog).+TestLoadPersonIntegration — integration test for person loading."""from posthog.test.base import BaseTest-from unittest.mock import MagicMock, PropertyMock, patch+from unittest.mock import ANY, MagicMock, PropertyMock, patchfrom django.test import SimpleTestCase-from parameterized import parameterized, parameterized_class+from parameterized import parameterized-from posthog.personhog_client.test_helpers import PersonhogTestMixin+from posthog.models.person import Personfrom posthog.session_recordings.models.session_recording import SessionRecording+from posthog.test.persons import create_personclass TestLoadPersonRouting(SimpleTestCase):@@ -76,8 +77,6 @@ class TestLoadPersonRouting(SimpleTestCase):else:mock_fetch_personhog.return_value = None- from posthog.models.person import Person-mock_orm_person = MagicMock()if person_found:mock_person_objects.db_manager.return_value.get.return_value = mock_orm_person@@ -98,9 +97,7 @@ class TestLoadPersonRouting(SimpleTestCase):with patch.object(type(recording), "team", new_callable=PropertyMock, return_value=mock_team):recording.load_person()- mock_routing_counter.labels.assert_called_with(- operation="load_person", source=expected_source, client_name="posthog-django"- )+ mock_routing_counter.labels.assert_called_with(operation="load_person", source=expected_source, client_name=ANY)if gate_on and grpc_exception is None:mock_person_objects.db_manager.assert_not_called()@@ -116,10 +113,9 @@ class TestLoadPersonRouting(SimpleTestCase):mock_errors_counter.labels.assert_called_once()-@parameterized_class(("personhog",), [(False,), (True,)])-class TestLoadPersonIntegration(PersonhogTestMixin, BaseTest):+class TestLoadPersonIntegration(BaseTest):def test_person_found(self):- person = self._seed_person(team=self.team, distinct_ids=["test_user"], properties={"email": "[email protected]"})+ person = create_person(team=self.team, distinct_ids=["test_user"], properties={"email": "[email protected]"})recording = SessionRecording(team=self.team, session_id="test_session", distinct_id="test_user")recording.load_person()@@ -127,18 +123,16 @@ class TestLoadPersonIntegration(PersonhogTestMixin, BaseTest):assert recording._person is not Noneassert str(recording._person.uuid) == str(person.uuid)assert recording._person.properties == {"email": "[email protected]"}- self._assert_personhog_called("get_person_by_distinct_id")def test_person_not_found(self):recording = SessionRecording(team=self.team, session_id="test_session", distinct_id="nonexistent_user")recording.load_person()assert recording._person is None- self._assert_personhog_called("get_person_by_distinct_id")def test_cross_team_isolation(self):other_team = self.organization.teams.create(name="Other Team")- self._seed_person(team=other_team, distinct_ids=["shared_did"], properties={"email": "[email protected]"})+ create_person(team=other_team, distinct_ids=["shared_did"], properties={"email": "[email protected]"})recording = SessionRecording(team=self.team, session_id="test_session", distinct_id="shared_did")recording.load_person()diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.pyindex 823b708d69a0..e0023bbeb1b0 100644--- a/posthog/session_recordings/test/test_session_recordings.py+++ b/posthog/session_recordings/test/test_session_recordings.py@@ -28,11 +28,12 @@ from rest_framework import statusfrom posthog.schema import LogEntryPropertyFilter, RecordingsQueryfrom posthog.errors import CHQueryErrorCannotScheduleTask, CHQueryErrorTooManySimultaneousQueries-from posthog.models import Organization, Person, SessionRecording, User+from posthog.models import Organization, SessionRecording, Userfrom posthog.models.team import Teamfrom posthog.models.utils import uuid7from posthog.session_recordings.models.session_recording_event import SessionRecordingViewedfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary+from posthog.test.persons import create_personclass TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest):@@ -122,7 +123,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)# Create users and recordings based on configfor config in user_configs:- user = Person.objects.create(+ user = create_person(team=self.team,distinct_ids=config["distinct_ids"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -180,7 +181,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)def test_get_session_recordings_includes_person_data(self) -> None:"""Test that person data is properly included in recordings response"""- person = Person.objects.create(+ person = create_person(team=self.team,distinct_ids=["test_user"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -266,12 +267,12 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)# varies which makes the snapshot uselesstwelve_distinct_ids: list[str] = [f"user_one_{i}" for i in range(12)]- Person.objects.create(+ create_person(team=self.team,distinct_ids=twelve_distinct_ids, # that's too many! we should limit themproperties={"$some_prop": "something", "email": "[email protected]"},)- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user2"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -374,7 +375,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)self.client.get(f"/api/projects/{self.team.id}/session_recordings")def _person_with_snapshots(self, base_time: datetime, distinct_id: str = "user", session_id: str = "1") -> None:- Person.objects.create(+ create_person(team=self.team,distinct_ids=[distinct_id],properties={"$some_prop": "something", "email": "[email protected]"},@@ -385,12 +386,12 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)def test_session_recordings_dont_leak_teams(self) -> None:another_team = Team.objects.create(organization=self.organization)- Person.objects.create(+ create_person(team=another_team,distinct_ids=["user"],properties={"$some_prop": "something", "email": "[email protected]"},)- home_team_person = Person.objects.create(+ home_team_person = create_person(team=self.team,distinct_ids=["user"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -455,7 +456,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)except ImportError:pytest.skip("EE summary models are not available in this build")- Person.objects.create(+ create_person(team=self.team,distinct_ids=["d1"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -499,7 +500,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)def test_session_recording_for_user_with_multiple_distinct_ids(self) -> None:base_time = (now() - timedelta(days=1)).replace(microsecond=0)- p = Person.objects.create(+ p = create_person(team=self.team,distinct_ids=["d1", "d2"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -520,7 +521,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)from posthog.personhog_client.fake_client import fake_personhog_clientbase_time = (now() - timedelta(days=1)).replace(microsecond=0)- p = Person.objects.create(+ p = create_person(team=self.team,distinct_ids=["d1", "d2"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -550,7 +551,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)assert results_by_session["2"]["person"]["distinct_ids"] == ["d2"]def test_viewed_state_of_session_recording_version(self):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["u1"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -653,7 +654,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)assert self._result_ids(response) == ["unviewed-mid", "unviewed-old"]def test_setting_viewed_state_of_session_recording(self):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["u1"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -696,7 +697,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)def test_update_session_recording_viewed(self, mock_capture: MagicMock):session_id = "test_update_viewed_state"base_time = (now() - relativedelta(days=1)).replace(microsecond=0)- Person.objects.create(+ create_person(team=self.team,distinct_ids=["u1"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -793,7 +794,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)@freeze_time("2023-01-01T12:00:00.000Z")def test_get_single_session_recording_metadata(self):- p = Person.objects.create(+ p = create_person(team=self.team,distinct_ids=["d1"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -866,7 +867,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)except ImportError:pytest.skip("EE summary models are not available in this build")- Person.objects.create(+ create_person(team=self.team,distinct_ids=["d1"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -899,7 +900,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)except ImportError:pytest.skip("EE summary models are not available in this build")- Person.objects.create(+ create_person(team=self.team,distinct_ids=["d1"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -1053,7 +1054,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest))def test_session_ids_filter(self, use_recording_events: bool, api_version: int):with freeze_time("2020-09-13T12:26:40.000Z"):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -1087,7 +1088,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)def test_session_ids_filter_returns_recordings_outside_default_date_range(self):with freeze_time("2020-09-13T12:26:40.000Z"):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -1107,7 +1108,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)def test_empty_list_session_ids_filter_returns_no_recordings(self):with freeze_time("2020-09-13T12:26:40.000Z"):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user"],properties={"$some_prop": "something", "email": "[email protected]"},@@ -1379,7 +1380,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)return_value=[],)def test_bulk_delete_session_recordings(self, _mock_delete_via_recording_api):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1", "user2"],properties={"email": "[email protected]"},@@ -1443,7 +1444,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)return_value=[],)def test_bulk_delete_sends_all_accessible_recordings_to_recording_api(self, mock_delete_via_recording_api):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1"],properties={"email": "[email protected]"},@@ -1490,7 +1491,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)return_value=[],)def test_bulk_delete_mixed_existing_and_nonexistent(self, _mock_delete_via_recording_api):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1"],properties={"email": "[email protected]"},@@ -1520,7 +1521,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)return_value=[],)def test_bulk_delete_works_for_clickhouse_only_recordings(self, _mock_delete_via_recording_api):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1"],properties={"email": "[email protected]"},@@ -1549,7 +1550,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest))@patch("posthog.session_recordings.session_recording_api.logger")def test_bulk_delete_logging(self, mock_logger, _mock_delete_via_recording_api):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1"],properties={"email": "[email protected]"},@@ -1578,7 +1579,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)def test_bulk_delete_doesnt_leak_teams(self):other_team = Team.objects.create(organization=self.organization)- Person.objects.create(+ create_person(team=other_team,distinct_ids=["user1"],properties={"email": "[email protected]"},@@ -1604,7 +1605,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)assert response_data["total_requested"] == 1def test_bulk_viewed_session_recordings(self):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1", "user2"],properties={"email": "[email protected]"},@@ -1636,7 +1637,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)assert viewed_record is not Nonedef test_bulk_viewed_handles_duplicates(self):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1"],properties={"email": "[email protected]"},@@ -1675,7 +1676,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)assert viewed_record is not Nonedef test_bulk_not_viewed_session_recordings(self):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1"],properties={"email": "[email protected]"},@@ -1719,7 +1720,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)).exists()def test_bulk_not_viewed_handles_already_not_viewed(self):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1"],properties={"email": "[email protected]"},@@ -1859,7 +1860,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)_description: str,_mock_delete_via_recording_api,):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1"],properties={"email": "[email protected]"},@@ -1901,7 +1902,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)return_value=[],)def test_bulk_delete_with_date_from_parameter(self, _mock_delete_via_recording_api):- Person.objects.create(team=self.team, distinct_ids=["user1"], properties={"email": "bla"})+ create_person(team=self.team, distinct_ids=["user1"], properties={"email": "bla"})# Set team retention to 90 daysself.team.session_recording_retention_period = "90d"@@ -2472,7 +2473,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)return_value=[],)def test_bulk_delete_with_recording_api_enabled(self, mock_bulk_delete):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1"],properties={"email": "[email protected]"},@@ -2505,7 +2506,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)return_value=["bulk_partial_3"],)def test_bulk_delete_with_recording_api_partial_failure_logs_warning(self, mock_bulk_delete, mock_logger):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["user1"],properties={"email": "[email protected]"},diff --git a/posthog/tasks/test/test_deletion_tasks.py b/posthog/tasks/test/test_deletion_tasks.pyindex 79ca911523d1..33c1fd475adc 100644--- a/posthog/tasks/test/test_deletion_tasks.py+++ b/posthog/tasks/test/test_deletion_tasks.py@@ -11,6 +11,7 @@ from posthog.models.project import Projectfrom posthog.models.team import Teamfrom posthog.personhog_client.fake_client import fake_personhog_clientfrom posthog.tasks.tasks import delete_organization_data_and_notify_task, delete_project_data_and_notify_task+from posthog.test.persons import create_personclass TestDeleteProjectDataAndNotifyTask(BaseTest):@@ -81,9 +82,9 @@ class TestDeleteProjectPersonsEndToEnd(BaseTest):team = Team.objects.create(organization=self.organization, name="Team to delete")other_team = Team.objects.create(organization=self.organization, name="Other team")- p1 = Person.objects.create(team=team, distinct_ids=["a", "b"])- p2 = Person.objects.create(team=team, distinct_ids=["c"])- p_other = Person.objects.create(team=other_team, distinct_ids=["d"])+ p1 = create_person(team=team, distinct_ids=["a", "b"])+ p2 = create_person(team=team, distinct_ids=["c"])+ p_other = create_person(team=other_team, distinct_ids=["d"])with fake_personhog_client(gate_enabled=personhog_enabled) as fake:if personhog_enabled:diff --git a/posthog/tasks/test/test_early_access_feature.py b/posthog/tasks/test/test_early_access_feature.pyindex 529abeb7affe..6406f5d952b1 100644--- a/posthog/tasks/test/test_early_access_feature.py+++ b/posthog/tasks/test/test_early_access_feature.py@@ -3,9 +3,9 @@ from unittest.mock import MagicMock, patchfrom posthog.hogql.constants import DEFAULT_RETURNED_ROWS-from posthog.models.person.person import Personfrom posthog.models.team import Teamfrom posthog.tasks.early_access_feature import send_events_for_early_access_feature_stage_change+from posthog.test.persons import create_personfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -24,7 +24,7 @@ class TestSendEventsForEarlyAccessFeatureStageChange(APIBaseTest):stage=EarlyAccessFeature.Stage.BETA,)- Person.objects.create(+ create_person(team=team,distinct_ids=["abc123"],properties={f"$feature_enrollment/{feature_flag.key}": True, "email": "[email protected]"},@@ -59,7 +59,7 @@ class TestSendEventsForEarlyAccessFeatureStageChange(APIBaseTest):)# Person on a different team, but with the same feature flag key- Person.objects.create(+ create_person(team=team2,distinct_ids=["other123"],properties={f"$feature_enrollment/{feature_flag.key}": True, "email": "[email protected]"},@@ -85,7 +85,7 @@ class TestSendEventsForEarlyAccessFeatureStageChange(APIBaseTest):persons = []for i in range(persons_count):- person = Person.objects.create(+ person = create_person(team=team,distinct_ids=[f"user_{i}"],properties={f"$feature_enrollment/{feature_flag.key}": True, "email": f"user_{i}@example.com"},diff --git a/posthog/temporal/tests/backfill_group_type_created_at/test_activities.py b/posthog/temporal/tests/backfill_group_type_created_at/test_activities.pyindex 2a59279afe2c..c4e35927e518 100644--- a/posthog/temporal/tests/backfill_group_type_created_at/test_activities.py+++ b/posthog/temporal/tests/backfill_group_type_created_at/test_activities.py@@ -20,6 +20,7 @@ from posthog.temporal.backfill_group_type_created_at.types import (GroupTypeUpdate,PlanBackfillInput,)+from posthog.test.persons import create_group_type_mappingfrom posthog.test.test_utils import create_group_type_mapping_without_created_atCREATED_AT = datetime(2026, 5, 31, 22, 33, tzinfo=UTC)@@ -83,7 +84,7 @@ def _seed_mapping(team: Team, index: int, group_type: str, created_at: datetimeteam=team, project_id=team.project_id, group_type=group_type, group_type_index=index)else:- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=team,project_id=team.project_id,group_type=group_type,@@ -313,7 +314,7 @@ class TestApplyGroupTypeCreatedAtBackfillIntegration:def seed():_seed_mapping(self.team, 0, "organization", MAPPING_CREATED_AT)other_team = Team.objects.create(organization=organization, name="other-project")- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=other_team,project_id=other_team.project_id,group_type="organization",diff --git a/posthog/test/AGENTS.md b/posthog/test/AGENTS.mdnew file mode 100644index 000000000000..dc0e8b21cf0b--- /dev/null+++ b/posthog/test/AGENTS.md@@ -0,0 +1,78 @@+# Test infrastructure for person, group, and cohort data++## The rule++**Never use `Person.objects.create()`, `Group.objects.create()`, `GroupTypeMapping.objects.create()`, or `CohortPeople.objects.create()` directly in tests.**++Use the centralized helpers in `posthog/test/persons.py` instead.+They write to Postgres AND seed the active personhog fake so both read paths see the data.++Direct ORM calls skip the fake — tests will silently return empty results from any code path that reads through personhog.++## Quick reference++```python+from posthog.test.persons import (+ create_person, # immediate: ORM + fake+ delete_person, # unseed fake + delete from Postgres+ add_distinct_id, # add a distinct ID to an existing person+ update_person, # person.save() + re-seed fake+ create_group,+ update_group,+ create_group_type_mapping,+ update_group_type_mapping,+ add_cohort_members,+ remove_cohort_members,+)+```++### Creating a person++```python+# Immediate creation (writes to Postgres now, seeds fake)+person = create_person(team=self.team, distinct_ids=["user1"], properties={"email": "[email protected]"})++# team_id= also works+person = create_person(team_id=self.team.pk, distinct_ids=["user1"])++# Adding a distinct ID to an existing person+add_distinct_id(person=person, distinct_id="another_id", version=0)+```++### Deferred (batched) creation++The `_create_person()` → `flush_persons_and_events()` pattern from `BaseTest` still works.+Under the hood, `_create_person` calls `stage_person_for_bulk_create` which defers writes until `flush_persons_and_events()` bulk-inserts to Postgres + ClickHouse + seeds the fake.++Use this when you need persons and events synced to ClickHouse together.++### Groups and group type mappings++```python+create_group_type_mapping(team=self.team, group_type="organization", group_type_index=0)+create_group(team=self.team, group_type_index=0, group_key="org:5", group_properties={"industry": "tech"})+```++### Cohort members++```python+add_cohort_members(cohort=cohort, persons=[person1, person2])+remove_cohort_members(cohort=cohort, persons=[person1])+```++## Why this exists++PostHog is migrating person/group reads from the Django ORM to a gRPC service (personhog).+In tests, a `FakePersonHogClient` stands in for the real service.+The helpers ensure both the ORM (for code that still reads from Postgres) and the fake (for code that reads through personhog) stay in sync.++When the ORM fallback is fully removed, the ORM writes in these helpers get deleted — one place to change, not 75+ test files.++## Other test utilities that create persons++- `posthog/test/test_journeys.py` → `journeys_for()` / `update_or_create_person()` — these already seed the fake internally+- `posthog/test/base.py` → `_create_person()` — thin wrapper around `stage_person_for_bulk_create`+- `posthog/test/test_utils.py` → `create_group_type_mapping_without_created_at()` — uses the helper internally++If you add a new utility that creates person/group data, it must seed the fake.+Import `_seed_person_into_fake` / `_seed_group_into_fake` / etc. from `posthog.test.persons` and call them after the ORM write.diff --git a/posthog/test/CLAUDE.md b/posthog/test/CLAUDE.mdnew file mode 120000index 000000000000..47dc3e3d863c--- /dev/null+++ b/posthog/test/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/posthog/test/base.py b/posthog/test/base.pyindex d67ec7f1361d..7992991401a1 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -125,7 +125,6 @@ from posthog.models.exchange_rate.sql import (from posthog.models.group.sql import TRUNCATE_GROUPS_TABLE_SQLfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.organization import OrganizationMembership-from posthog.models.person import Personfrom posthog.models.person.sql import (DROP_PERSON_TABLE_SQL,PERSONS_TABLE_SQL,@@ -134,7 +133,6 @@ from posthog.models.person.sql import (TRUNCATE_PERSON_DISTINCT_ID_TABLE_SQL,TRUNCATE_PERSON_STATIC_COHORT_TABLE_SQL,)-from posthog.models.person.util import bulk_create_personsfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.precalculated_events.sql import (DROP_PRECALCULATED_EVENTS_KAFKA_TABLE_SQL,@@ -223,9 +221,9 @@ cast(Any, freezegun).configure(extend_ignore_list=["posthog.test.assert_faster_than", "transformers"],)-persons_cache_tests: list[dict[str, Any]] = []events_cache_tests: list[dict[str, Any]] = []-persons_ordering_int: int = 0++from posthog.test.persons import stage_person_for_bulk_create # noqa: E402# Expand string diffsunittest.util._MAX_LENGTH = 2000 # type: ignore@@ -696,8 +694,10 @@ class PostHogTestCase(SimpleTestCase):_setup_test_data(self)def tearDown(self):- if len(persons_cache_tests) > 0:- persons_cache_tests.clear()+ from posthog.test.persons import has_unflushed_persons, reset_persons_state++ if has_unflushed_persons():+ reset_persons_state()raise Exception("Some persons created in this test weren't flushed, which can lead to inconsistent test results. Add flush_persons_and_events() right after creating all persons.")@@ -709,8 +709,7 @@ class PostHogTestCase(SimpleTestCase):)# We might be using memory cache in tests at Django level, but we also use `redis` directly in some places, so we need to clear Redisredis.get_client().flushdb()- global persons_ordering_int- persons_ordering_int = 0+ reset_persons_state()super().tearDown()def validate_basic_html(self, html_message, site_url, preheader=None):@@ -1540,10 +1539,9 @@ def flush_persons_and_events():pass of writing a test. Only consider adding it after the test has failed, and you think that lack of flushing isthe cause."""- person_mapping = {}- if len(persons_cache_tests) > 0:- person_mapping = bulk_create_persons(persons_cache_tests)- persons_cache_tests.clear()+ from posthog.test.persons import flush_persons_to_db_and_clickhouse++ person_mapping = flush_persons_to_db_and_clickhouse()if len(events_cache_tests) > 0:bulk_create_events(events_cache_tests, person_mapping)_flush_ai_events(events_cache_tests, person_mapping)@@ -1603,27 +1601,8 @@ def _warn_if_session_id_malformed(session_id: str):def _create_person(*args, **kwargs):- """- Create a person in tests. NOTE: all persons get batched and only created when sync_execute is called- Pass immediate=True to create immediately and get a pk back- """- global persons_ordering_int- if not (kwargs.get("uuid")):- kwargs["uuid"] = uuid.UUID(- int=persons_ordering_int, version=4- ) # make sure the ordering of uuids is always consistent- persons_ordering_int += 1- # If we've done freeze_time just create straight away- if kwargs.get("immediate") or (- hasattr(dt.datetime.now(), "__module__") and dt.datetime.now().__module__ == "freezegun.api"- ):- kwargs.pop("immediate", None)- return Person.objects.create(**kwargs)- if len(args) > 0:- kwargs["distinct_ids"] = [args[0]] # allow calling _create_person("distinct_id")-- persons_cache_tests.append(kwargs)- return Person(**{key: value for key, value in kwargs.items() if key != "distinct_ids"})+ """Thin wrapper — delegates to posthog.test.persons.stage_person_for_bulk_create."""+ return stage_person_for_bulk_create(*args, **kwargs)def _create_action(**kwargs):diff --git a/posthog/test/personhog_fake.py b/posthog/test/personhog_fake.pynew file mode 100644index 000000000000..4f2c5c4b784b--- /dev/null+++ b/posthog/test/personhog_fake.py@@ -0,0 +1,278 @@+"""Personhog fake activation and write-mirroring for tests.++activate_personhog_fake() patches get_personhog_client and use_personhog so all+person/group reads route through a FakePersonHogClient.++MirroringFakePersonHogClient mirrors personhog writes (deletes, version floors,+cohort membership) back to Postgres for tests that still assert ORM state.++Transitional: once the ORM fallback and persons DB connection are removed,+MirroringFakePersonHogClient can be deleted.+"""++from __future__ import annotations++import json+from contextlib import contextmanager+from typing import TYPE_CHECKING++from unittest.mock import patch++from django.db import connections, router++from posthog.personhog_client.fake_client import FakePersonHogClient+from posthog.personhog_client.proto.generated.personhog.types.v1 import cohort_pb2, group_pb2, person_pb2++if TYPE_CHECKING:+ pass+++_active_fake: FakePersonHogClient | None = None+++def set_active_fake(fake: FakePersonHogClient | None) -> None:+ global _active_fake+ _active_fake = fake+++def get_active_fake() -> FakePersonHogClient:+ assert _active_fake is not None, "get_active_fake() called outside activate_personhog_fake() context"+ return _active_fake+++def _persons_db_alias() -> str:+ from posthog.models.person import Person as _Person # noqa: PLC0415++ return router.db_for_write(_Person) or "default"+++@contextmanager+def activate_personhog_fake():+ """Activate a MirroringFakePersonHogClient for the duration of a test.++ Patches get_personhog_client and use_personhog so all reads route through+ the fake. Test helpers in posthog.test.persons seed the fake explicitly+ when creating data — no signals are used.+ """+ fake = MirroringFakePersonHogClient()+ set_active_fake(fake)+ with (+ patch("posthog.personhog_client.client.get_personhog_client", return_value=fake),+ patch("posthog.personhog_client.gate.use_personhog", return_value=True),+ ):+ try:+ yield fake+ finally:+ set_active_fake(None)+++# ── MirroringFakePersonHogClient ─────────────────────────────────────+++class MirroringFakePersonHogClient(FakePersonHogClient):+ """FakePersonHogClient that mirrors writes back to Postgres.++ Transitional: keeps ORM state in sync with personhog-only operations so+ existing tests that assert ORM state continue to pass. Will be removed+ when the persons DB connection is dropped.+ """++ def create_group(+ self,+ request: group_pb2.CreateGroupRequest,+ ) -> group_pb2.CreateGroupResponse:+ import datetime # noqa: PLC0415++ from posthog.models.group.group import Group as _Group # noqa: PLC0415++ response = super().create_group(request)+ group_obj, _ = _Group.objects.get_or_create( # nosemgrep: no-direct-persons-db-orm+ team_id=request.team_id,+ group_type_index=request.group_type_index,+ group_key=request.group_key,+ defaults={+ "group_properties": json.loads(request.group_properties) if request.group_properties else {},+ "created_at": datetime.datetime.fromtimestamp(request.created_at / 1000, tz=datetime.UTC)+ if request.created_at+ else None,+ "version": 0,+ },+ )+ response.group.id = group_obj.pk+ stored = self._groups.get((request.team_id, request.group_type_index, request.group_key))+ if stored is not None:+ stored.id = group_obj.pk+ return response++ def update_group(+ self,+ request: group_pb2.UpdateGroupRequest,+ ) -> group_pb2.UpdateGroupResponse:+ from posthog.models.group.group import Group as _Group # noqa: PLC0415++ response = super().update_group(request)+ updates: dict[str, object] = {}+ for field in request.update_mask:+ if field == "group_properties":+ updates["group_properties"] = json.loads(request.group_properties) if request.group_properties else {}+ elif field == "properties_last_updated_at":+ updates["properties_last_updated_at"] = (+ json.loads(request.properties_last_updated_at) if request.properties_last_updated_at else {}+ )+ elif field == "properties_last_operation":+ updates["properties_last_operation"] = (+ json.loads(request.properties_last_operation) if request.properties_last_operation else {}+ )+ if updates:+ _Group.objects.filter( # nosemgrep: no-direct-persons-db-orm+ team_id=request.team_id,+ group_type_index=request.group_type_index,+ group_key=request.group_key,+ ).update(**updates)+ return response++ def update_group_type_mapping(+ self,+ request: group_pb2.UpdateGroupTypeMappingRequest,+ ) -> group_pb2.UpdateGroupTypeMappingResponse:+ from posthog.models import GroupTypeMapping as _GTM # noqa: PLC0415++ response = super().update_group_type_mapping(request)+ updates: dict[str, object] = {}+ for field in request.update_mask:+ if field == "name_singular":+ updates["name_singular"] = request.name_singular or None+ elif field == "name_plural":+ updates["name_plural"] = request.name_plural or None+ elif field == "detail_dashboard_id":+ updates["detail_dashboard_id"] = request.detail_dashboard_id or None+ elif field == "default_columns":+ updates["default_columns"] = json.loads(request.default_columns) if request.default_columns else None+ if updates:+ _GTM.objects.filter( # nosemgrep: no-direct-persons-db-orm+ project_id=request.project_id,+ group_type_index=request.group_type_index,+ ).update(**updates)+ return response++ def delete_group_type_mapping(+ self,+ request: group_pb2.DeleteGroupTypeMappingRequest,+ ) -> group_pb2.DeleteGroupTypeMappingResponse:+ from posthog.models import GroupTypeMapping as _GTM # noqa: PLC0415++ response = super().delete_group_type_mapping(request)+ _GTM.objects.filter( # nosemgrep: no-direct-persons-db-orm+ project_id=request.project_id,+ group_type_index=request.group_type_index,+ ).delete()+ return response++ def delete_persons(+ self,+ request: person_pb2.DeletePersonsRequest,+ timeout: float | None = None,+ ) -> person_pb2.DeletePersonsResponse:+ from posthog.models.person import Person as _Person # noqa: PLC0415++ response = super().delete_persons(request, timeout)+ if response.deleted_count > 0:+ uuids = [str(u) for u in request.person_uuids]+ db = _persons_db_alias()+ table = _Person._meta.db_table+ with connections[db].cursor() as cursor:+ placeholders = ", ".join(["%s"] * len(uuids))+ cursor.execute(+ f"DELETE FROM posthog_persondistinctid WHERE person_id IN "+ f"(SELECT id FROM {table} WHERE team_id = %s AND uuid IN ({placeholders}))",+ [request.team_id, *uuids],+ )+ cursor.execute(+ f"DELETE FROM {table} WHERE team_id = %s AND uuid IN ({placeholders})",+ [request.team_id, *uuids],+ )+ return response++ def set_person_version_floor(+ self,+ request: person_pb2.SetPersonVersionFloorRequest,+ timeout: float | None = None,+ ) -> person_pb2.SetPersonVersionFloorResponse:+ from posthog.models.person import Person as _Person # noqa: PLC0415++ response = super().set_person_version_floor(request, timeout)+ if response.updated:+ db = _persons_db_alias()+ table = _Person._meta.db_table+ with connections[db].cursor() as cursor:+ cursor.execute(+ f"UPDATE {table} SET version = %s "+ f"WHERE team_id = %s AND id = %s AND (version IS NULL OR version < %s)",+ [request.min_version, request.team_id, request.person_id, request.min_version],+ )+ return response++ def set_person_distinct_id_version_floor(+ self,+ request: person_pb2.SetPersonDistinctIdVersionFloorRequest,+ timeout: float | None = None,+ ) -> person_pb2.SetPersonDistinctIdVersionFloorResponse:+ response = super().set_person_distinct_id_version_floor(request, timeout)+ db = _persons_db_alias()+ with connections[db].cursor() as cursor:+ cursor.execute(+ "UPDATE posthog_persondistinctid SET version = %s "+ "WHERE team_id = %s AND distinct_id = %s AND (version IS NULL OR version < %s)",+ [request.min_version, request.team_id, request.distinct_id, request.min_version],+ )+ return response++ def insert_cohort_members(+ self,+ request: cohort_pb2.InsertCohortMembersRequest,+ timeout: float | None = None,+ ) -> cohort_pb2.InsertCohortMembersResponse:+ from products.cohorts.backend.models.cohort import CohortPeople # noqa: PLC0415++ response = super().insert_cohort_members(request, timeout)+ if response.inserted_count > 0:+ for pid in request.person_ids:+ CohortPeople.objects.get_or_create(+ cohort_id=request.cohort_id,+ person_id=pid,+ defaults={"version": 0},+ )+ return response++ def delete_cohort_member(+ self,+ request: cohort_pb2.DeleteCohortMemberRequest,+ timeout: float | None = None,+ ) -> cohort_pb2.DeleteCohortMemberResponse:+ response = super().delete_cohort_member(request, timeout)+ if response.deleted:+ db = _persons_db_alias()+ with connections[db].cursor() as cursor:+ cursor.execute(+ "DELETE FROM posthog_cohortpeople WHERE cohort_id = %s AND person_id = %s",+ [request.cohort_id, request.person_id],+ )+ return response++ def delete_cohort_members_bulk(+ self,+ request: cohort_pb2.DeleteCohortMembersBulkRequest,+ timeout: float | None = None,+ ) -> cohort_pb2.DeleteCohortMembersBulkResponse:+ response = super().delete_cohort_members_bulk(request, timeout)+ if response.deleted_count > 0:+ cohort_ids = list(request.cohort_ids)+ if cohort_ids:+ placeholders = ", ".join(["%s"] * len(cohort_ids))+ db = _persons_db_alias()+ with connections[db].cursor() as cursor:+ cursor.execute(+ f"DELETE FROM posthog_cohortpeople WHERE cohort_id IN ({placeholders})",+ cohort_ids,+ )+ return responsediff --git a/posthog/test/persons.py b/posthog/test/persons.pynew file mode 100644index 000000000000..71bd22211485--- /dev/null+++ b/posthog/test/persons.py@@ -0,0 +1,382 @@+"""Centralized test helpers for person, group, and cohort data creation.++Every test that needs person/group/cohort data should use these helpers+rather than calling ORM methods directly. Each helper writes to the ORM+(Postgres) and seeds the active personhog fake so both read paths see the data.++Transitional: when the ORM fallback and persons DB connection are removed,+the ORM writes in these helpers can be deleted — only the fake-seeding remains.+That's the single place to change.+"""++from __future__ import annotations++import uuid+import datetime as dt+from typing import TYPE_CHECKING, Any++from posthog.models.group.group import Group+from posthog.models.group_type_mapping import GroupTypeMapping+from posthog.models.person import Person, PersonDistinctId++if TYPE_CHECKING:+ from posthog.models.team import Team++ from products.cohorts.backend.models.cohort import Cohort+++# ── Internal state for deferred (batched) creation ───────────────────++_persons_cache: list[dict[str, Any]] = []+_persons_ordering_int: int = 0+++def _next_deterministic_uuid() -> uuid.UUID:+ """Generate a deterministic UUID for consistent test ordering."""+ global _persons_ordering_int+ result = uuid.UUID(int=_persons_ordering_int, version=4)+ _persons_ordering_int += 1+ return result+++def reset_persons_state() -> None:+ """Reset deferred persons cache and UUID counter. Called from BaseTest.tearDown."""+ global _persons_ordering_int+ _persons_cache.clear()+ _persons_ordering_int = 0+++def has_unflushed_persons() -> bool:+ return len(_persons_cache) > 0+++def clear_persons_cache() -> None:+ _persons_cache.clear()+++# ── Fake seeding internals ───────────────────────────────────────────+++def _get_active_fake():+ from posthog.test.personhog_fake import _active_fake # noqa: PLC0415++ return _active_fake+++def _datetime_to_ms(val: dt.datetime | None) -> int:+ if val is None:+ return 0+ return int(val.timestamp() * 1000)+++def _seed_person_into_fake(person: Person, distinct_ids: list[str], *, created_at_ms: int | None = None) -> None:+ """Seed a person + distinct IDs into the active fake. No-op if no fake is active."""+ fake = _get_active_fake()+ if fake is None:+ return++ existing_dids = {d.distinct_id for d in fake._distinct_ids.get((person.team_id, person.pk), [])}+ new_dids = [str(did) for did in distinct_ids if str(did) not in existing_dids]++ distinct_id_versions: dict[str, int] = {}+ if new_dids:+ for pdi in PersonDistinctId.objects.filter( # nosemgrep: no-direct-persons-db-orm+ team_id=person.team_id, person_id=person.pk, distinct_id__in=new_dids+ ):+ distinct_id_versions[pdi.distinct_id] = pdi.version or 0++ person_proto = fake.add_person(+ team_id=person.team_id,+ person_id=person.pk,+ uuid=str(person.uuid),+ properties=person.properties or {},+ created_at=created_at_ms if created_at_ms is not None else _datetime_to_ms(person.created_at),+ version=person.version or 0,+ is_identified=person.is_identified,+ distinct_ids=new_dids,+ distinct_id_versions=distinct_id_versions,+ )++ for did_with_ver in fake._distinct_ids.get((person.team_id, person.pk), []):+ fake._persons_by_distinct_id[(person.team_id, did_with_ver.distinct_id)] = person_proto+++def _reseed_person_into_fake(person: Person) -> None:+ """Re-seed an existing person into the fake after an update (e.g. property change)."""+ fake = _get_active_fake()+ if fake is None:+ return++ person_proto = fake.add_person(+ team_id=person.team_id,+ person_id=person.pk,+ uuid=str(person.uuid),+ properties=person.properties or {},+ created_at=_datetime_to_ms(person.created_at),+ version=person.version or 0,+ is_identified=person.is_identified,+ )+ for did_with_ver in fake._distinct_ids.get((person.team_id, person.pk), []):+ fake._persons_by_distinct_id[(person.team_id, did_with_ver.distinct_id)] = person_proto+++def _seed_distinct_id_into_fake(team_id: int, person_id: int, distinct_id: str, version: int = 0) -> None:+ """Seed a single distinct ID into the fake. No-op if no fake is active."""+ fake = _get_active_fake()+ if fake is None:+ return++ from posthog.personhog_client.proto.generated.personhog.types.v1 import person_pb2 # noqa: PLC0415++ person_proto = fake._persons_by_id.get((team_id, person_id))+ if person_proto is None:+ return++ existing_dids = {d.distinct_id for d in fake._distinct_ids.get((team_id, person_id), [])}+ if distinct_id in existing_dids:+ return++ fake._persons_by_distinct_id[(team_id, distinct_id)] = person_proto+ fake._distinct_ids.setdefault((team_id, person_id), []).append(+ person_pb2.DistinctIdWithVersion(distinct_id=distinct_id, version=version)+ )+++def _seed_group_into_fake(group: Group) -> None:+ fake = _get_active_fake()+ if fake is None:+ return+ fake.add_group(+ team_id=group.team_id,+ group_type_index=group.group_type_index,+ group_key=group.group_key,+ group_properties=group.group_properties or {},+ id=group.pk,+ created_at=_datetime_to_ms(group.created_at),+ version=group.version or 0,+ )+++def _seed_group_type_mapping_into_fake(instance: GroupTypeMapping) -> None:+ fake = _get_active_fake()+ if fake is None:+ return++ project_mappings = fake._group_type_mappings_by_project.get(instance.project_id, [])+ fake._group_type_mappings_by_project[instance.project_id] = [+ m for m in project_mappings if m.group_type_index != instance.group_type_index+ ]+ if instance.team_id:+ team_mappings = fake._group_type_mappings_by_team.get(instance.team_id, [])+ fake._group_type_mappings_by_team[instance.team_id] = [+ m+ for m in team_mappings+ if not (m.project_id == instance.project_id and m.group_type_index == instance.group_type_index)+ ]++ fake.add_group_type_mapping(+ project_id=instance.project_id,+ team_id=instance.team_id,+ group_type=instance.group_type,+ group_type_index=instance.group_type_index,+ id=instance.pk,+ name_singular=instance.name_singular or "",+ name_plural=instance.name_plural or "",+ detail_dashboard_id=instance.detail_dashboard_id or 0,+ default_columns=list(instance.default_columns) if instance.default_columns else None,+ created_at=_datetime_to_ms(instance.created_at),+ )+++def _seed_cohort_member_into_fake(cohort_id: int, person_id: int) -> None:+ fake = _get_active_fake()+ if fake is None:+ return+ if (cohort_id, person_id) not in fake._cohort_members:+ fake.add_cohort_membership(person_id=person_id, cohort_id=cohort_id, is_member=True)+++def _remove_cohort_member_from_fake(cohort_id: int, person_id: int) -> None:+ fake = _get_active_fake()+ if fake is None:+ return+ fake._cohort_members.pop((cohort_id, person_id), None)+ memberships = fake._cohort_memberships.get(person_id)+ if memberships is not None:+ fake._cohort_memberships[person_id] = [m for m in memberships if m.cohort_id != cohort_id]+++# ── Public helpers: Person ───────────────────────────────────────────+++def create_person(*, team: Team | None = None, distinct_ids: list[str] | None = None, **kwargs: Any) -> Person:+ """Create a person immediately in Postgres and seed the personhog fake."""+ if team is None and "team_id" not in kwargs:+ raise TypeError("create_person() requires 'team' or 'team_id'")+ create_kwargs: dict[str, Any] = {**kwargs}+ if team is not None:+ create_kwargs["team"] = team+ if distinct_ids:+ create_kwargs["distinct_ids"] = distinct_ids+ person = Person.objects.create(**create_kwargs) # nosemgrep: no-direct-persons-db-orm+ _seed_person_into_fake(person, distinct_ids or [])+ return person+++def delete_person(person: Person) -> None:+ """Delete a person via the personhog fake (unseeds) and from Postgres."""+ fake = _get_active_fake()+ if fake is None:+ person.delete() # nosemgrep: no-direct-persons-db-orm+ return+ from posthog.personhog_client.proto.generated.personhog.types.v1 import person_pb2 # noqa: PLC0415++ fake.delete_persons(person_pb2.DeletePersonsRequest(team_id=person.team_id, person_uuids=[str(person.uuid)]))+++def update_person(person: Person) -> None:+ """Save a person to Postgres and re-seed the personhog fake."""+ person.save() # nosemgrep: no-direct-persons-db-orm+ _reseed_person_into_fake(person)+++def add_distinct_id(*, person: Person, distinct_id: str, version: int = 0) -> PersonDistinctId:+ """Create a PersonDistinctId in Postgres and seed it into the personhog fake."""+ pdi = PersonDistinctId.objects.create( # nosemgrep: no-direct-persons-db-orm+ team_id=person.team_id,+ person=person,+ distinct_id=distinct_id,+ version=version,+ )+ _seed_distinct_id_into_fake(person.team_id, person.pk, distinct_id, version=version)+ return pdi+++def stage_person_for_bulk_create(*args: Any, **kwargs: Any) -> Person:+ """Stage a person for deferred bulk creation.++ Does NOT write to Postgres or ClickHouse immediately. Call+ flush_persons_and_events() to bulk-insert all staged persons into+ Postgres + ClickHouse + personhog fake.++ Returns an unsaved Person instance (no pk). The pk is only available+ after flush.+ """+ if not kwargs.get("uuid"):+ kwargs["uuid"] = _next_deterministic_uuid()+ else:+ _next_deterministic_uuid()++ if kwargs.get("immediate") or (+ hasattr(dt.datetime.now(), "__module__") and dt.datetime.now().__module__ == "freezegun.api"+ ):+ kwargs.pop("immediate", None)+ return create_person(**kwargs)++ if len(args) > 0:+ kwargs["distinct_ids"] = [args[0]]++ _persons_cache.append(kwargs)+ return Person(**{key: value for key, value in kwargs.items() if key != "distinct_ids"})+++def flush_persons_to_db_and_clickhouse() -> dict[str, Person]:+ """Bulk-insert all staged persons into Postgres + ClickHouse + personhog fake.++ Returns the person_mapping (distinct_id → Person) for event flushing.+ Called by flush_persons_and_events() in base.py.+ """+ from posthog.models.person.util import bulk_create_persons # noqa: PLC0415++ if len(_persons_cache) == 0:+ return {}++ person_mapping = bulk_create_persons(_persons_cache)+ _persons_cache.clear()+ _seed_persons_from_bulk_mapping(person_mapping)+ return person_mapping+++def _seed_persons_from_bulk_mapping(person_mapping: dict[str, Person]) -> None:+ """Seed the fake from bulk_create_persons output with timestamp spreading."""+ fake = _get_active_fake()+ if fake is None:+ return++ by_person: dict[int, tuple[Person, list[str]]] = {}+ for distinct_id, person in person_mapping.items():+ _, dids = by_person.setdefault(person.pk, (person, []))+ dids.append(str(distinct_id))++ prev_ms = 0+ for pk in sorted(by_person):+ person, dids = by_person[pk]+ created_at_ms = max(_datetime_to_ms(person.created_at), prev_ms + 1)+ prev_ms = created_at_ms+ _seed_person_into_fake(person, dids, created_at_ms=created_at_ms)+++# ── Public helpers: Group ────────────────────────────────────────────+++def create_group(*, team: Team | None = None, group_type_index: int, group_key: str, **kwargs: Any) -> Group:+ """Create a group in Postgres and seed the personhog fake."""+ if team is None and "team_id" not in kwargs:+ raise TypeError("create_group() requires 'team' or 'team_id'")+ create_kwargs: dict[str, Any] = {"group_type_index": group_type_index, "group_key": group_key, **kwargs}+ if team is not None:+ create_kwargs["team"] = team+ group = Group.objects.create(**create_kwargs) # nosemgrep: no-direct-persons-db-orm+ _seed_group_into_fake(group)+ return group+++def update_group(group: Group) -> None:+ """Save a group to Postgres and re-seed the personhog fake."""+ group.save() # nosemgrep: no-direct-persons-db-orm+ _seed_group_into_fake(group)+++# ── Public helpers: GroupTypeMapping ─────────────────────────────────+++def create_group_type_mapping(*, team: Team | None = None, **kwargs: Any) -> GroupTypeMapping:+ """Create a group type mapping in Postgres and seed the personhog fake."""+ if team is not None:+ kwargs["team"] = team+ mapping = GroupTypeMapping.objects.create(**kwargs) # nosemgrep: no-direct-persons-db-orm+ _seed_group_type_mapping_into_fake(mapping)+ return mapping+++def update_group_type_mapping(mapping: GroupTypeMapping) -> None:+ """Save a group type mapping to Postgres and re-seed the personhog fake."""+ mapping.save() # nosemgrep: no-direct-persons-db-orm+ _seed_group_type_mapping_into_fake(mapping)+++# ── Public helpers: Cohort membership ────────────────────────────────+++def add_cohort_members(cohort: Cohort, persons: list[Person]) -> None:+ """Add persons to a cohort in Postgres and seed the personhog fake."""+ from products.cohorts.backend.models.cohort import CohortPeople # noqa: PLC0415++ for person in persons:+ CohortPeople.objects.get_or_create( # nosemgrep: no-direct-persons-db-orm+ cohort_id=cohort.pk,+ person_id=person.pk,+ defaults={"version": 0},+ )+ _seed_cohort_member_into_fake(cohort.pk, person.pk)+++def remove_cohort_members(cohort: Cohort, persons: list[Person]) -> None:+ """Remove persons from a cohort in Postgres and the personhog fake."""+ from products.cohorts.backend.models.cohort import CohortPeople # noqa: PLC0415++ for person in persons:+ CohortPeople.objects.filter( # nosemgrep: no-direct-persons-db-orm+ cohort_id=cohort.pk, person_id=person.pk+ ).delete()+ _remove_cohort_member_from_fake(cohort.pk, person.pk)diff --git a/posthog/test/playwright_setup_functions.py b/posthog/test/playwright_setup_functions.pyindex 810676fb48a8..9ad0352dc67c 100644--- a/posthog/test/playwright_setup_functions.py+++ b/posthog/test/playwright_setup_functions.py@@ -444,10 +444,13 @@ def _create_events_and_persons(data: PlaywrightWorkspaceSetupData, team: Team) -import uuid as uuid_module- from posthog.models import Person, PersonDistinctIdfrom posthog.models.event.util import create_eventfrom posthog.models.person.util import create_person, create_person_distinct_idfrom posthog.models.utils import UUIDT+ from posthog.test.persons import (+ add_distinct_id,+ create_person as create_test_person,+ )person_uuids: dict[str, str] = {}@@ -457,10 +460,10 @@ def _create_events_and_persons(data: PlaywrightWorkspaceSetupData, team: Team) -person_uuid = str(UUIDT())props = person_spec.properties or {}create_person(team_id=team.pk, version=0, uuid=person_uuid, properties=props)- pg_person = Person.objects.create(team=team, uuid=person_uuid, properties=props)+ pg_person = create_test_person(team=team, uuid=person_uuid, properties=props)for distinct_id in person_spec.distinct_ids:create_person_distinct_id(team_id=team.pk, distinct_id=distinct_id, person_id=person_uuid)- PersonDistinctId.objects.create(team=team, person=pg_person, distinct_id=distinct_id)+ add_distinct_id(person=pg_person, distinct_id=distinct_id)person_uuids[distinct_id] = person_uuidif not data.events:@@ -482,8 +485,8 @@ def _create_events_and_persons(data: PlaywrightWorkspaceSetupData, team: Team) -props = person_props.get(distinct_id, {})create_person(team_id=team.pk, version=0, uuid=person_uuid, properties=props)create_person_distinct_id(team_id=team.pk, distinct_id=distinct_id, person_id=person_uuid)- pg_person = Person.objects.create(team=team, uuid=person_uuid, properties=props)- PersonDistinctId.objects.create(team=team, person=pg_person, distinct_id=distinct_id)+ pg_person = create_test_person(team=team, uuid=person_uuid, properties=props)+ add_distinct_id(person=pg_person, distinct_id=distinct_id)baseline_count = _count_events_in_clickhouse(team.pk)diff --git a/posthog/test/test_cohort_model.py b/posthog/test/test_cohort_model.pyindex 305e5739f522..9ae53e470d52 100644--- a/posthog/test/test_cohort_model.py+++ b/posthog/test/test_cohort_model.py@@ -10,7 +10,8 @@ from parameterized import parameterizedfrom posthog.clickhouse.client import sync_executefrom posthog.helpers.batch_iterators import FunctionBatchIterator-from posthog.models import Person, Team+from posthog.models import Team+from posthog.test.persons import add_cohort_members, create_personfrom products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.sql import GET_COHORTPEOPLE_BY_COHORT_ID@@ -21,12 +22,12 @@ class TestCohort(BaseTest):CLASS_DATA_LEVEL_SETUP = False # So that each test gets a different team_id, ensuring separation of CH datadef test_insert_by_distinct_id(self):- Person.objects.create(team=self.team, distinct_ids=["000"])- Person.objects.create(team=self.team, distinct_ids=["123"])- Person.objects.create(team=self.team)+ create_person(team=self.team, distinct_ids=["000"])+ create_person(team=self.team, distinct_ids=["123"])+ create_person(team=self.team)# Team leakageteam2 = Team.objects.create(organization=self.organization)- Person.objects.create(team=team2, distinct_ids=["123"])+ create_person(team=team2, distinct_ids=["123"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)cohort.insert_users_by_list(["a header or something", "123", "000", "[email protected]"])@@ -45,17 +46,17 @@ class TestCohort(BaseTest):self.assertEqual(cohort.is_calculating, False)def test_insert_by_distinct_id_in_batches(self):- Person.objects.create(team=self.team, distinct_ids=["000"])- Person.objects.create(team=self.team, distinct_ids=["001"])- Person.objects.create(team=self.team, distinct_ids=["002", "011"])- Person.objects.create(team=self.team, distinct_ids=["003", "012"])- Person.objects.create(team=self.team, distinct_ids=["004"])- Person.objects.create(team=self.team, distinct_ids=["005"])- Person.objects.create(team=self.team, distinct_ids=["006"])- Person.objects.create(team=self.team, distinct_ids=["007"])- Person.objects.create(team=self.team, distinct_ids=["008"])- Person.objects.create(team=self.team, distinct_ids=["009"])- Person.objects.create(team=self.team, distinct_ids=["010"])+ create_person(team=self.team, distinct_ids=["000"])+ create_person(team=self.team, distinct_ids=["001"])+ create_person(team=self.team, distinct_ids=["002", "011"])+ create_person(team=self.team, distinct_ids=["003", "012"])+ create_person(team=self.team, distinct_ids=["004"])+ create_person(team=self.team, distinct_ids=["005"])+ create_person(team=self.team, distinct_ids=["006"])+ create_person(team=self.team, distinct_ids=["007"])+ create_person(team=self.team, distinct_ids=["008"])+ create_person(team=self.team, distinct_ids=["009"])+ create_person(team=self.team, distinct_ids=["010"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)batch_count = cohort.insert_users_by_list(@@ -73,13 +74,13 @@ class TestCohort(BaseTest):groups=[{"properties": [{"key": "$some_prop", "value": "something", "type": "person"}]}],name="cohort1",)- person1 = Person.objects.create(+ person1 = create_person(distinct_ids=["person1"],team_id=self.team.pk,properties={"$some_prop": "something"},)- Person.objects.create(distinct_ids=["person2"], team_id=self.team.pk, properties={})- person3 = Person.objects.create(+ create_person(distinct_ids=["person2"], team_id=self.team.pk, properties={})+ person3 = create_person(distinct_ids=["person3"],team_id=self.team.pk,properties={"$some_prop": "something"},@@ -335,7 +336,7 @@ class TestCohort(BaseTest):"345b621a-26e1-4888-a9eb-175329f7923b",]for person_uuid in uuids:- Person.objects.create(team=self.team, uuid=person_uuid)+ create_person(team=self.team, uuid=person_uuid)cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)# Insert all users into the cohort using batching (batchsize=3)@@ -353,7 +354,7 @@ class TestCohort(BaseTest):"""Test that batching with duplicates works correctly - people already in cohort are not re-inserted."""# Create people with distinct IDsfor i in range(10):- Person.objects.create(team=self.team, distinct_ids=[f"user{i}"])+ create_person(team=self.team, distinct_ids=[f"user{i}"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)@@ -384,7 +385,7 @@ class TestCohort(BaseTest):def test_insert_users_list_by_uuid_with_different_db_aliases(self):from unittest.mock import patch- person = Person.objects.create(team=self.team, distinct_ids=["cross-db-test"])+ person = create_person(team=self.team, distinct_ids=["cross-db-test"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True)# Simulate production config where db_for_read returns a different@@ -448,7 +449,7 @@ class TestCohort(BaseTest):)for age in excluded_ages:- Person.objects.create(+ create_person(distinct_ids=[str(uuid.uuid4())],team_id=self.team.pk,properties={"age": age},@@ -456,7 +457,7 @@ class TestCohort(BaseTest):expected_people = []for age in included_ages:- person = Person.objects.create(+ person = create_person(distinct_ids=[str(uuid.uuid4())],team_id=self.team.pk,properties={"age": age},@@ -484,15 +485,15 @@ class TestCohort(BaseTest):from products.cohorts.backend.models.util import get_static_cohort_size# Create persons- person1 = Person.objects.create(team=self.team, distinct_ids=["person1"])- person2 = Person.objects.create(team=self.team, distinct_ids=["person2"])- person3 = Person.objects.create(team=self.team, distinct_ids=["person3"])+ person1 = create_person(team=self.team, distinct_ids=["person1"])+ person2 = create_person(team=self.team, distinct_ids=["person2"])+ person3 = create_person(team=self.team, distinct_ids=["person3"])# Create a static cohortcohort = Cohort.objects.create(team=self.team, name="Test Static Cohort", is_static=True)- # Add persons to cohort using the many-to-many relationship- cohort.people.add(person1, person2, person3)+ # Add persons to cohort+ add_cohort_members(cohort, [person1, person2, person3])# Test that get_static_cohort_size returns the correct countsize = get_static_cohort_size(cohort_id=cohort.id, team_id=self.team.id)@@ -506,11 +507,11 @@ class TestCohort(BaseTest):# in count_cohort_members), not by person.team_id. The previous join through# posthog_person was a hot per-PK lookup on the write replica that we# dropped for IOPS reasons — production cannot reach this state via the- # supported APIs, and a raw M2M add() like the one below is what would have+ # supported APIs, and a cross-team add like the one below is what would have# had to break for a count discrepancy to surface in real traffic.team2 = Team.objects.create(organization=self.organization)- person4 = Person.objects.create(team=team2, distinct_ids=["person4"])- cohort.people.add(person4)+ person4 = create_person(team=team2, distinct_ids=["person4"])+ add_cohort_members(cohort, [person4])size = get_static_cohort_size(cohort_id=cohort.id, team_id=self.team.id)assert size == 4, f"Expected 4 cohort rows after cross-team add, got {size}"diff --git a/posthog/test/test_email.py b/posthog/test/test_email.pyindex 178d5ce6ce68..a285e6c2aeda 100644--- a/posthog/test/test_email.py+++ b/posthog/test/test_email.py@@ -20,12 +20,16 @@ from posthog.email import CUSTOMER_IO_TEMPLATE_ID_MAP, EmailMessage, _send_emailfrom posthog.models import Organization, Person, Team, Userfrom posthog.models.instance_setting import override_instance_configfrom posthog.models.messaging import MessagingRecord, get_email_hash, get_email_hashes+from posthog.test.persons import (+ add_distinct_id as add_test_distinct_id,+ create_person as create_test_person,+)class TestEmail(BaseTest):def create_person(self, team: Team, base_distinct_id: str = "") -> Person:- person = Person.objects.create(team=team)- person.add_distinct_id(base_distinct_id)+ person = create_test_person(team=team)+ add_test_distinct_id(person=person, distinct_id=base_distinct_id)return person@freeze_time("2020-09-21")diff --git a/posthog/test/test_journeys.py b/posthog/test/test_journeys.pyindex 1512b62b33f1..126ae21e9d7d 100644--- a/posthog/test/test_journeys.py+++ b/posthog/test/test_journeys.py@@ -210,4 +210,7 @@ def update_or_create_person(distinct_ids: list[str], team_id: int, **kwargs):"distinct_id": distinct_id,},)+ from posthog.test.persons import _seed_person_into_fake # noqa: PLC0415++ _seed_person_into_fake(person, distinct_ids)return persondiff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.pyindex bfb6b24f159c..b672cf63cab7 100644--- a/posthog/test/test_utils.py+++ b/posthog/test/test_utils.py@@ -851,9 +851,14 @@ class TestFlatten(TestCase):def create_group_type_mapping_without_created_at(**kwargs) -> "GroupTypeMapping":- instance = GroupTypeMapping.objects.create(**kwargs)+ from posthog.test.persons import create_group_type_mapping # noqa: PLC0415++ instance = create_group_type_mapping(**kwargs)GroupTypeMapping.objects.filter(id=instance.id).update(created_at=None)instance.refresh_from_db()+ from posthog.test.persons import _seed_group_type_mapping_into_fake # noqa: PLC0415++ _seed_group_type_mapping_into_fake(instance)return instancediff --git a/products/access_control/backend/tests/test_property_access_control_api.py b/products/access_control/backend/tests/test_property_access_control_api.pyindex 038a6d1703fe..017d265e52fd 100644--- a/products/access_control/backend/tests/test_property_access_control_api.py+++ b/products/access_control/backend/tests/test_property_access_control_api.py@@ -3,6 +3,7 @@ from posthog.test.base import BaseTestfrom posthog.constants import AvailableFeaturefrom posthog.models import PropertyDefinitionfrom posthog.models.event.util import ClickhouseEventSerializer+from posthog.test.persons import create_personfrom products.access_control.backend.models.property_access_control import PropertyAccessControlfrom products.access_control.backend.property_access_control import PropertyAccessLevel@@ -70,9 +71,7 @@ class TestClickhouseEventSerializerPropertyAccess(BaseTest):assert "$browser" in data["properties"]def test_restricted_person_property_stripped_from_embedded_person(self):- from posthog.models import Person-- person = Person.objects.create(+ person = create_person(team=self.team,distinct_ids=["user1"],properties={"email": "[email protected]", "name": "Test User"},@@ -93,9 +92,7 @@ class TestPersonSerializerPropertyAccess(BaseTest):def setUp(self):super().setUp()_enable_property_access_control(self.organization)- from posthog.models import Person-- self.person = Person.objects.create(+ self.person = create_person(team=self.team,distinct_ids=["user1"],properties={diff --git a/products/cohorts/backend/models/test/test_cohort_personhog.py b/products/cohorts/backend/models/test/test_cohort_personhog.pyindex 847bd06afd11..7e1d8104ad1d 100644--- a/products/cohorts/backend/models/test/test_cohort_personhog.py+++ b/products/cohorts/backend/models/test/test_cohort_personhog.py@@ -1,39 +1,36 @@"""Tests that cohort person-lookup methods produce identical results-via the ORM and personhog paths."""+via the personhog path."""from posthog.test.base import BaseTestfrom unittest.mock import patch-from parameterized import parameterized_class--from posthog.models import Person, Team-from posthog.personhog_client.fake_client import fake_personhog_client-from posthog.personhog_client.test_helpers import PersonhogTestMixin+from posthog.models import Team+from posthog.test.personhog_fake import get_active_fake+from posthog.test.persons import add_cohort_members, create_personfrom products.cohorts.backend.models.cohort import Cohort, CohortPeople-@parameterized_class(("personhog",), [(False,), (True,)])-class TestGetPersonUuidsByDistinctIds(PersonhogTestMixin, BaseTest):+class TestGetPersonUuidsByDistinctIds(BaseTest):def _get_uuids(self, distinct_ids: list[str]) -> list[str]:from posthog.models.person.util import get_person_uuids_by_distinct_idsreturn get_person_uuids_by_distinct_ids(self.team.pk, distinct_ids)def test_returns_uuids_for_matching_distinct_ids(self):- p1 = self._seed_person(team=self.team, distinct_ids=["d1", "d2"])- p2 = self._seed_person(team=self.team, distinct_ids=["d3"])+ p1 = create_person(team=self.team, distinct_ids=["d1", "d2"])+ p2 = create_person(team=self.team, distinct_ids=["d3"])result = self._get_uuids(["d1", "d3"])assert set(result) == {str(p1.uuid), str(p2.uuid)}- self._assert_personhog_called("get_persons_by_distinct_ids_in_team")+ get_active_fake().assert_called("get_persons_by_distinct_ids_in_team")def test_returns_empty_list_for_empty_input(self):result = self._get_uuids([])assert result == []- self._assert_personhog_not_called("get_persons_by_distinct_ids_in_team")+ get_active_fake().assert_not_called("get_persons_by_distinct_ids_in_team")def test_returns_empty_list_when_no_persons_match(self):result = self._get_uuids(["nonexistent"])@@ -42,66 +39,45 @@ class TestGetPersonUuidsByDistinctIds(PersonhogTestMixin, BaseTest):def test_cross_team_isolation(self):other_team = self.organization.teams.create(name="Other Team")- self._seed_person(team=other_team, distinct_ids=["d1"])+ create_person(team=other_team, distinct_ids=["d1"])result = self._get_uuids(["d1"])assert result == []def test_deduplicates_persons_with_multiple_distinct_ids(self):- p = self._seed_person(team=self.team, distinct_ids=["d1", "d2", "d3"])+ p = create_person(team=self.team, distinct_ids=["d1", "d2", "d3"])result = self._get_uuids(["d1", "d2", "d3"])assert result == [str(p.uuid)]def test_handles_mix_of_found_and_missing_distinct_ids(self):- p = self._seed_person(team=self.team, distinct_ids=["exists"])+ p = create_person(team=self.team, distinct_ids=["exists"])result = self._get_uuids(["exists", "missing1", "missing2"])assert result == [str(p.uuid)]def test_multiple_persons_each_with_single_distinct_id(self):- persons = [self._seed_person(team=self.team, distinct_ids=[f"d{i}"]) for i in range(5)]+ persons = [create_person(team=self.team, distinct_ids=[f"d{i}"]) for i in range(5)]result = self._get_uuids([f"d{i}" for i in range(5)])assert set(result) == {str(p.uuid) for p in persons}-class TestGetPersonUuidsByDistinctIdsFallback(BaseTest):- """Routing test: verifies ORM fallback when the personhog gate is disabled."""-- def test_falls_back_to_orm_when_personhog_disabled(self):- from posthog.models.person.util import get_person_uuids_by_distinct_ids-- p = Person.objects.create(team=self.team, distinct_ids=["d1"])-- with fake_personhog_client(gate_enabled=False) as fake:- result = get_person_uuids_by_distinct_ids(self.team.pk, ["d1"])-- assert result == [str(p.uuid)]- fake.assert_not_called("get_persons_by_distinct_ids_in_team")--class TestGetPersonUuidsByDistinctIdsFieldMask(BaseTest):"""Verify the personhog path sends a UUID-only field mask."""def test_sends_uuid_only_field_mask(self):from posthog.models.person.util import get_person_uuids_by_distinct_ids- p = Person.objects.create(team=self.team, distinct_ids=["d1"])+ create_person(team=self.team, distinct_ids=["d1"])- with fake_personhog_client(gate_enabled=True) as fake:- fake.add_person(- team_id=self.team.pk,- person_id=p.pk,- uuid=str(p.uuid),- distinct_ids=["d1"],- )- get_person_uuids_by_distinct_ids(self.team.pk, ["d1"])+ get_person_uuids_by_distinct_ids(self.team.pk, ["d1"])+ fake = get_active_fake()calls = fake.assert_called("get_persons_by_distinct_ids_in_team", times=1)mask = list(calls[0].request.read_options.field_mask)assert "uuid" in mask@@ -110,8 +86,7 @@ class TestGetPersonUuidsByDistinctIdsFieldMask(BaseTest):assert "properties" not in mask-@parameterized_class(("personhog",), [(False,), (True,)])-class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):+class TestRemoveUserByUuid(BaseTest):CLASS_DATA_LEVEL_SETUP = Falsedef _create_static_cohort(self) -> Cohort:@@ -120,30 +95,25 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):@patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")@patch("products.cohorts.backend.models.util.get_static_cohort_size", return_value=0)def test_removes_existing_cohort_member(self, mock_get_size, mock_remove_ch):- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()- CohortPeople.objects.create(cohort=cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=True)+ add_cohort_members(cohort, [person])result = cohort.remove_user_by_uuid(str(person.uuid), team_id=self.team.id)assert result is True- if self.personhog:- assert self._fake_client is not None- assert (cohort.id, person.id) not in self._fake_client._cohort_members- else:- assert not CohortPeople.objects.filter(cohort=cohort, person=person).exists()+ assert (cohort.id, person.id) not in get_active_fake()._cohort_membersmock_remove_ch.assert_called_once()call_args = mock_remove_ch.call_argsassert call_args[0][0] == person.uuidassert call_args[0][1] == cohort.pkassert call_args[1]["team_id"] == self.team.id- self._assert_personhog_called("check_cohort_membership")+ get_active_fake().assert_called("check_cohort_membership")@patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")@patch("products.cohorts.backend.models.util.get_static_cohort_size", return_value=0)def test_returns_true_for_person_not_in_cohort(self, mock_get_size, mock_remove_ch):- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()result = cohort.remove_user_by_uuid(str(person.uuid), team_id=self.team.id)@@ -162,7 +132,7 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):@patch("products.cohorts.backend.models.util.get_static_cohort_size", return_value=0)def test_cross_team_isolation(self, mock_get_size, mock_remove_ch):other_team = Team.objects.create(organization=self.organization)- person = self._seed_person(team=other_team, distinct_ids=["d1"])+ person = create_person(team=other_team, distinct_ids=["d1"])cohort = self._create_static_cohort()result = cohort.remove_user_by_uuid(str(person.uuid), team_id=self.team.id)@@ -176,16 +146,12 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):"""Calling remove_user_by_uuid with a team_id that does not own thecohort must not touch CohortPeople rows for that cohort."""other_team = Team.objects.create(organization=self.organization)- person = self._seed_person(team=other_team, distinct_ids=["d1"])- # Cohort lives on other_team; caller claims to be self.team.+ person = create_person(team=other_team, distinct_ids=["d1"])other_team_cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")- CohortPeople.objects.create(cohort=other_team_cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=other_team_cohort.id, is_member=True)+ add_cohort_members(other_team_cohort, [person])result = other_team_cohort.remove_user_by_uuid(str(person.uuid), team_id=self.team.id)- # Person isn't resolvable under self.team → removal is a no-op (returns False)- # and the CohortPeople row for the other team's cohort stays put.assert result is Falseassert CohortPeople.objects.filter(cohort=other_team_cohort, person=person).exists()mock_remove_ch.assert_not_called()@@ -193,10 +159,9 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):@patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")@patch("products.cohorts.backend.models.util.get_static_cohort_size", return_value=5)def test_updates_cohort_count_after_removal(self, mock_get_size, mock_remove_ch):- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()- CohortPeople.objects.create(cohort=cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=True)+ add_cohort_members(cohort, [person])cohort.remove_user_by_uuid(str(person.uuid), team_id=self.team.id)@@ -206,50 +171,43 @@ class TestRemoveUserByUuid(PersonhogTestMixin, BaseTest):@patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")@patch("products.cohorts.backend.models.util.get_static_cohort_size", side_effect=Exception("count failed"))def test_count_error_does_not_prevent_removal(self, mock_get_size, mock_remove_ch):- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()- CohortPeople.objects.create(cohort=cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=True)+ add_cohort_members(cohort, [person])result = cohort.remove_user_by_uuid(str(person.uuid), team_id=self.team.id)assert result is True- if self.personhog:- assert self._fake_client is not None- assert (cohort.id, person.id) not in self._fake_client._cohort_members- else:- assert not CohortPeople.objects.filter(cohort=cohort, person=person).exists()+ assert (cohort.id, person.id) not in get_active_fake()._cohort_membersmock_remove_ch.assert_called_once()@patch("products.cohorts.backend.models.util.remove_person_from_static_cohort")@patch("products.cohorts.backend.models.util.get_static_cohort_size", return_value=0)def test_personhog_resolves_person_for_removal(self, mock_get_size, mock_remove_ch):- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()cohort.remove_user_by_uuid(str(person.uuid), team_id=self.team.id)- self._assert_personhog_called("get_person_by_uuid")+ get_active_fake().assert_called("get_person_by_uuid")-@parameterized_class(("personhog",), [(False,), (True,)])-class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):+class TestCheckCohortMembership(BaseTest):def test_returns_true_for_member(self):from products.cohorts.backend.models.util import check_cohort_membership, is_person_in_cohort- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=True)+ add_cohort_members(cohort, [person])assert is_person_in_cohort(team_id=self.team.id, person_id=person.id, cohort_id=cohort.id) is Trueassert check_cohort_membership(self.team.id, person.id, [cohort.id]) == {cohort.id: True}- self._assert_personhog_called("check_cohort_membership")+ get_active_fake().assert_called("check_cohort_membership")def test_returns_false_for_non_member(self):from products.cohorts.backend.models.util import is_person_in_cohort- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")assert is_person_in_cohort(team_id=self.team.id, person_id=person.id, cohort_id=cohort.id) is False@@ -257,22 +215,20 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):def test_returns_empty_dict_for_empty_cohort_ids(self):from products.cohorts.backend.models.util import check_cohort_membership- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])assert check_cohort_membership(self.team.id, person.id, []) == {}- self._assert_personhog_not_called("check_cohort_membership")+ get_active_fake().assert_not_called("check_cohort_membership")def test_mixed_membership(self):from products.cohorts.backend.models.util import check_cohort_membership- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])c1 = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")c2 = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c2")c3 = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c3")- CohortPeople.objects.create(cohort=c1, person=person)- CohortPeople.objects.create(cohort=c3, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=c1.id, is_member=True)- self._seed_cohort_membership(person_id=person.id, cohort_id=c3.id, is_member=True)+ add_cohort_members(c1, [person])+ add_cohort_members(c3, [person])result = check_cohort_membership(self.team.id, person.id, [c1.id, c2.id, c3.id])@@ -286,18 +242,14 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):from products.cohorts.backend.models.util import check_cohort_membershipother_team = Team.objects.create(organization=self.organization)- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])other_team_cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")- # Plant a real CohortPeople row (ORM-path leak canary) and a fake- # membership (personhog-path leak canary). If scoping were missing on- # either path the assertion would flip to True.- CohortPeople.objects.create(cohort=other_team_cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=other_team_cohort.id, is_member=True)+ add_cohort_members(other_team_cohort, [person])result = check_cohort_membership(self.team.id, person.id, [other_team_cohort.id])assert result == {other_team_cohort.id: False}- self._assert_personhog_not_called("check_cohort_membership")+ get_active_fake().assert_not_called("check_cohort_membership")def test_isolates_cross_team_cohort_mixed_with_in_team(self):"""When a mix of in-team and out-of-team cohort_ids is passed, only the@@ -306,52 +258,30 @@ class TestCheckCohortMembership(PersonhogTestMixin, BaseTest):from products.cohorts.backend.models.util import check_cohort_membershipother_team = Team.objects.create(organization=self.organization)- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])in_team_cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="in")other_team_cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="out")- CohortPeople.objects.create(cohort=in_team_cohort, person=person)- CohortPeople.objects.create(cohort=other_team_cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=in_team_cohort.id, is_member=True)- self._seed_cohort_membership(person_id=person.id, cohort_id=other_team_cohort.id, is_member=True)+ add_cohort_members(in_team_cohort, [person])+ add_cohort_members(other_team_cohort, [person])result = check_cohort_membership(self.team.id, person.id, [in_team_cohort.id, other_team_cohort.id])assert result == {in_team_cohort.id: True, other_team_cohort.id: False}-class TestCheckCohortMembershipFallback(BaseTest):- """Routing test: verifies ORM fallback when the personhog gate is disabled."""-- def test_falls_back_to_orm_when_personhog_disabled(self):- from products.cohorts.backend.models.util import is_person_in_cohort-- person = Person.objects.create(team=self.team, distinct_ids=["d1"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=person)-- with fake_personhog_client(gate_enabled=False) as fake:- assert is_person_in_cohort(team_id=self.team.id, person_id=person.id, cohort_id=cohort.id) is True-- fake.assert_not_called("check_cohort_membership")---@parameterized_class(("personhog",), [(False,), (True,)])-class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):+class TestListCohortMemberIds(BaseTest):def test_returns_member_ids(self):from products.cohorts.backend.models.util import list_cohort_member_ids- p1 = self._seed_person(team=self.team, distinct_ids=["d1"])- p2 = self._seed_person(team=self.team, distinct_ids=["d2"])+ p1 = create_person(team=self.team, distinct_ids=["d1"])+ p2 = create_person(team=self.team, distinct_ids=["d2"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=p1)- CohortPeople.objects.create(cohort=cohort, person=p2)- self._seed_cohort_membership(person_id=p1.id, cohort_id=cohort.id, is_member=True)- self._seed_cohort_membership(person_id=p2.id, cohort_id=cohort.id, is_member=True)+ add_cohort_members(cohort, [p1, p2])result = list_cohort_member_ids(team_id=self.team.id, cohort_id=cohort.id)assert sorted(result) == sorted([p1.id, p2.id])- self._assert_personhog_called("list_cohort_member_ids")+ get_active_fake().assert_called("list_cohort_member_ids")def test_returns_empty_for_empty_cohort(self):from products.cohorts.backend.models.util import list_cohort_member_ids@@ -365,14 +295,12 @@ class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):def test_excludes_non_members(self):from products.cohorts.backend.models.util import list_cohort_member_ids- p1 = self._seed_person(team=self.team, distinct_ids=["d1"])- p2 = self._seed_person(team=self.team, distinct_ids=["d2"])+ p1 = create_person(team=self.team, distinct_ids=["d1"])+ p2 = create_person(team=self.team, distinct_ids=["d2"])c1 = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")c2 = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c2")- CohortPeople.objects.create(cohort=c1, person=p1)- CohortPeople.objects.create(cohort=c2, person=p2)- self._seed_cohort_membership(person_id=p1.id, cohort_id=c1.id, is_member=True)- self._seed_cohort_membership(person_id=p2.id, cohort_id=c2.id, is_member=True)+ add_cohort_members(c1, [p1])+ add_cohort_members(c2, [p2])result = list_cohort_member_ids(team_id=self.team.id, cohort_id=c1.id)@@ -382,34 +310,17 @@ class TestListCohortMemberIds(PersonhogTestMixin, BaseTest):from products.cohorts.backend.models.util import list_cohort_member_idsother_team = Team.objects.create(organization=self.organization)- person = self._seed_person(team=other_team, distinct_ids=["d1"])+ person = create_person(team=other_team, distinct_ids=["d1"])other_team_cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")- CohortPeople.objects.create(cohort=other_team_cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=other_team_cohort.id, is_member=True)+ add_cohort_members(other_team_cohort, [person])result = list_cohort_member_ids(team_id=self.team.id, cohort_id=other_team_cohort.id)assert result == []- self._assert_personhog_not_called("list_cohort_member_ids")---class TestListCohortMemberIdsFallback(BaseTest):- def test_falls_back_to_orm_when_personhog_disabled(self):- from products.cohorts.backend.models.util import list_cohort_member_ids-- person = Person.objects.create(team=self.team, distinct_ids=["d1"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=person)-- with fake_personhog_client(gate_enabled=False) as fake:- result = list_cohort_member_ids(team_id=self.team.id, cohort_id=cohort.id)+ get_active_fake().assert_not_called("list_cohort_member_ids")- assert result == [person.id]- fake.assert_not_called("list_cohort_member_ids")--@parameterized_class(("personhog",), [(False,), (True,)])-class TestInsertCohortMembers(PersonhogTestMixin, BaseTest):+class TestInsertCohortMembers(BaseTest):CLASS_DATA_LEVEL_SETUP = Falsedef _create_static_cohort(self) -> Cohort:@@ -418,35 +329,27 @@ class TestInsertCohortMembers(PersonhogTestMixin, BaseTest):def test_inserts_members(self):from products.cohorts.backend.models.util import insert_cohort_members- p1 = self._seed_person(team=self.team, distinct_ids=["d1"])- p2 = self._seed_person(team=self.team, distinct_ids=["d2"])+ p1 = create_person(team=self.team, distinct_ids=["d1"])+ p2 = create_person(team=self.team, distinct_ids=["d2"])cohort = self._create_static_cohort()inserted = insert_cohort_members(self.team.id, cohort.id, [p1.id, p2.id], version=1)assert inserted > 0- if self.personhog:- assert self._fake_client is not None- assert (cohort.id, p1.id) in self._fake_client._cohort_members- assert (cohort.id, p2.id) in self._fake_client._cohort_members- else:- assert CohortPeople.objects.filter(cohort=cohort).count() == 2- self._assert_personhog_called("insert_cohort_members")+ assert (cohort.id, p1.id) in get_active_fake()._cohort_members+ assert (cohort.id, p2.id) in get_active_fake()._cohort_members+ get_active_fake().assert_called("insert_cohort_members")def test_deduplicates_existing_members(self):from products.cohorts.backend.models.util import insert_cohort_members- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()- CohortPeople.objects.create(cohort=cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=True)+ add_cohort_members(cohort, [person])inserted = insert_cohort_members(self.team.id, cohort.id, [person.id], version=1)- if self.personhog:- assert inserted == 0- else:- assert CohortPeople.objects.filter(cohort=cohort).count() == 1+ assert inserted == 0def test_returns_zero_for_empty_list(self):from products.cohorts.backend.models.util import insert_cohort_members@@ -454,51 +357,36 @@ class TestInsertCohortMembers(PersonhogTestMixin, BaseTest):cohort = self._create_static_cohort()assert insert_cohort_members(self.team.id, cohort.id, [], version=1) == 0- self._assert_personhog_not_called("insert_cohort_members")+ get_active_fake().assert_not_called("insert_cohort_members")def test_rejects_cross_team_cohort(self):from products.cohorts.backend.models.util import insert_cohort_membersother_team = Team.objects.create(organization=self.organization)- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])other_cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")inserted = insert_cohort_members(self.team.id, other_cohort.id, [person.id], version=1)assert inserted == 0assert not CohortPeople.objects.filter(cohort=other_cohort).exists()- self._assert_personhog_not_called("insert_cohort_members")+ get_active_fake().assert_not_called("insert_cohort_members")def test_skip_ownership_check_bypasses_team_validation(self):from products.cohorts.backend.models.util import insert_cohort_membersother_team = Team.objects.create(organization=self.organization)- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")- self._seed_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=False)+ get_active_fake().add_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=False)inserted = insert_cohort_members(self.team.id, cohort.id, [person.id], version=1, _skip_ownership_check=True)assert inserted > 0- self._assert_personhog_called("insert_cohort_members")+ get_active_fake().assert_called("insert_cohort_members")-class TestInsertCohortMembersFallback(BaseTest):- def test_falls_back_to_orm_when_personhog_disabled(self):- from products.cohorts.backend.models.util import insert_cohort_members-- person = Person.objects.create(team=self.team, distinct_ids=["d1"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")-- with fake_personhog_client(gate_enabled=False) as fake:- insert_cohort_members(self.team.id, cohort.id, [person.id], version=1)-- assert CohortPeople.objects.filter(cohort=cohort, person=person).exists()- fake.assert_not_called("insert_cohort_members")---@parameterized_class(("personhog",), [(False,), (True,)])-class TestDeleteCohortMember(PersonhogTestMixin, BaseTest):+class TestDeleteCohortMember(BaseTest):CLASS_DATA_LEVEL_SETUP = Falsedef _create_static_cohort(self) -> Cohort:@@ -507,22 +395,19 @@ class TestDeleteCohortMember(PersonhogTestMixin, BaseTest):def test_deletes_existing_member(self):from products.cohorts.backend.models.util import delete_cohort_member- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()- CohortPeople.objects.create(cohort=cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=cohort.id, is_member=True)+ add_cohort_members(cohort, [person])result = delete_cohort_member(self.team.id, cohort.id, person.id)assert result is True- if not self.personhog:- assert not CohortPeople.objects.filter(cohort=cohort, person=person).exists()- self._assert_personhog_called("delete_cohort_member")+ get_active_fake().assert_called("delete_cohort_member")def test_returns_false_for_non_member(self):from products.cohorts.backend.models.util import delete_cohort_member- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()result = delete_cohort_member(self.team.id, cohort.id, person.id)@@ -533,78 +418,40 @@ class TestDeleteCohortMember(PersonhogTestMixin, BaseTest):from products.cohorts.backend.models.util import delete_cohort_memberother_team = Team.objects.create(organization=self.organization)- person = self._seed_person(team=other_team, distinct_ids=["d1"])+ person = create_person(team=other_team, distinct_ids=["d1"])other_cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")- CohortPeople.objects.create(cohort=other_cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=other_cohort.id, is_member=True)+ add_cohort_members(other_cohort, [person])result = delete_cohort_member(self.team.id, other_cohort.id, person.id)assert result is Falseassert CohortPeople.objects.filter(cohort=other_cohort, person=person).exists()- self._assert_personhog_not_called("delete_cohort_member")---class TestDeleteCohortMemberFallback(BaseTest):- def test_falls_back_to_orm_when_personhog_disabled(self):- from products.cohorts.backend.models.util import delete_cohort_member+ get_active_fake().assert_not_called("delete_cohort_member")- person = Person.objects.create(team=self.team, distinct_ids=["d1"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=person)-- with fake_personhog_client(gate_enabled=False) as fake:- result = delete_cohort_member(self.team.id, cohort.id, person.id)-- assert result is True- assert not CohortPeople.objects.filter(cohort=cohort, person=person).exists()- fake.assert_not_called("delete_cohort_member")--@parameterized_class(("personhog",), [(False,), (True,)])-class TestDeleteCohortMembersBulk(PersonhogTestMixin, BaseTest):+class TestDeleteCohortMembersBulk(BaseTest):CLASS_DATA_LEVEL_SETUP = Falsedef test_deletes_all_members_for_cohorts(self):from products.cohorts.backend.models.util import delete_cohort_members_bulk- p1 = self._seed_person(team=self.team, distinct_ids=["d1"])- p2 = self._seed_person(team=self.team, distinct_ids=["d2"])+ p1 = create_person(team=self.team, distinct_ids=["d1"])+ p2 = create_person(team=self.team, distinct_ids=["d2"])c1 = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")c2 = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c2")- CohortPeople.objects.create(cohort=c1, person=p1)- CohortPeople.objects.create(cohort=c2, person=p2)- self._seed_cohort_membership(person_id=p1.id, cohort_id=c1.id, is_member=True)- self._seed_cohort_membership(person_id=p2.id, cohort_id=c2.id, is_member=True)+ add_cohort_members(c1, [p1])+ add_cohort_members(c2, [p2])deleted = delete_cohort_members_bulk(self.team.id, [c1.id, c2.id])assert deleted >= 2- if not self.personhog:- assert CohortPeople.objects.filter(cohort_id__in=[c1.id, c2.id]).count() == 0- self._assert_personhog_called("delete_cohort_members_bulk")+ get_active_fake().assert_called("delete_cohort_members_bulk")def test_returns_zero_for_empty_list(self):from products.cohorts.backend.models.util import delete_cohort_members_bulkassert delete_cohort_members_bulk(self.team.id, []) == 0- self._assert_personhog_not_called("delete_cohort_members_bulk")---class TestDeleteCohortMembersBulkFallback(BaseTest):- def test_falls_back_to_orm_when_personhog_disabled(self):- from products.cohorts.backend.models.util import delete_cohort_members_bulk-- person = Person.objects.create(team=self.team, distinct_ids=["d1"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=person)-- with fake_personhog_client(gate_enabled=False) as fake:- deleted = delete_cohort_members_bulk(self.team.id, [cohort.id])-- assert deleted == 1- assert not CohortPeople.objects.filter(cohort=cohort).exists()- fake.assert_not_called("delete_cohort_members_bulk")+ get_active_fake().assert_not_called("delete_cohort_members_bulk")class TestDeleteCohortMembersBulkMaxIterations(BaseTest):@@ -629,21 +476,17 @@ class TestDeleteCohortMembersBulkMaxIterations(BaseTest):assert total == 100 * max_iters-@parameterized_class(("personhog",), [(False,), (True,)])-class TestCountCohortMembers(PersonhogTestMixin, BaseTest):+class TestCountCohortMembers(BaseTest):def test_returns_count(self):from products.cohorts.backend.models.util import count_cohort_members- p1 = self._seed_person(team=self.team, distinct_ids=["d1"])- p2 = self._seed_person(team=self.team, distinct_ids=["d2"])+ p1 = create_person(team=self.team, distinct_ids=["d1"])+ p2 = create_person(team=self.team, distinct_ids=["d2"])cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=p1)- CohortPeople.objects.create(cohort=cohort, person=p2)- self._seed_cohort_membership(person_id=p1.id, cohort_id=cohort.id, is_member=True)- self._seed_cohort_membership(person_id=p2.id, cohort_id=cohort.id, is_member=True)+ add_cohort_members(cohort, [p1, p2])assert count_cohort_members(self.team.id, cohort.id) == 2- self._assert_personhog_called("count_cohort_members")+ get_active_fake().assert_called("count_cohort_members")def test_returns_zero_for_empty_cohort(self):from products.cohorts.backend.models.util import count_cohort_members@@ -656,31 +499,15 @@ class TestCountCohortMembers(PersonhogTestMixin, BaseTest):from products.cohorts.backend.models.util import count_cohort_membersother_team = Team.objects.create(organization=self.organization)- person = self._seed_person(team=other_team, distinct_ids=["d1"])+ person = create_person(team=other_team, distinct_ids=["d1"])other_cohort = Cohort.objects.create(team=other_team, groups=[], is_static=True, name="other")- CohortPeople.objects.create(cohort=other_cohort, person=person)- self._seed_cohort_membership(person_id=person.id, cohort_id=other_cohort.id, is_member=True)+ add_cohort_members(other_cohort, [person])assert count_cohort_members(self.team.id, other_cohort.id) == 0- self._assert_personhog_not_called("count_cohort_members")-+ get_active_fake().assert_not_called("count_cohort_members")-class TestCountCohortMembersFallback(BaseTest):- def test_falls_back_to_orm_when_personhog_disabled(self):- from products.cohorts.backend.models.util import count_cohort_members- person = Person.objects.create(team=self.team, distinct_ids=["d1"])- cohort = Cohort.objects.create(team=self.team, groups=[], is_static=True, name="c1")- CohortPeople.objects.create(cohort=cohort, person=person)-- with fake_personhog_client(gate_enabled=False) as fake:- assert count_cohort_members(self.team.id, cohort.id) == 1-- fake.assert_not_called("count_cohort_members")---@parameterized_class(("personhog",), [(False,), (True,)])-class TestInsertUsersListWithBatchingPersonhog(PersonhogTestMixin, BaseTest):+class TestInsertUsersListWithBatchingPersonhog(BaseTest):CLASS_DATA_LEVEL_SETUP = Falsedef _create_static_cohort(self) -> Cohort:@@ -688,37 +515,28 @@ class TestInsertUsersListWithBatchingPersonhog(PersonhogTestMixin, BaseTest):@patch("products.cohorts.backend.models.util.insert_static_cohort")def test_insert_users_by_uuid(self, mock_insert_ch):- p1 = self._seed_person(team=self.team, distinct_ids=["d1"])- p2 = self._seed_person(team=self.team, distinct_ids=["d2"])+ p1 = create_person(team=self.team, distinct_ids=["d1"])+ p2 = create_person(team=self.team, distinct_ids=["d2"])cohort = self._create_static_cohort()cohort.insert_users_list_by_uuid([str(p1.uuid), str(p2.uuid)], team_id=self.team.id)- if self.personhog:- self._assert_personhog_called("insert_cohort_members")- else:- assert CohortPeople.objects.filter(cohort=cohort).count() == 2+ get_active_fake().assert_called("insert_cohort_members")@patch("products.cohorts.backend.models.util.insert_static_cohort")def test_insert_users_by_distinct_id(self, mock_insert_ch):- self._seed_person(team=self.team, distinct_ids=["d1"])- self._seed_person(team=self.team, distinct_ids=["d2"])+ create_person(team=self.team, distinct_ids=["d1"])+ create_person(team=self.team, distinct_ids=["d2"])cohort = self._create_static_cohort()cohort.insert_users_by_list(["d1", "d2"], team_id=self.team.id)- if self.personhog:- self._assert_personhog_called("insert_cohort_members")- else:- assert CohortPeople.objects.filter(cohort=cohort).count() == 2+ get_active_fake().assert_called("insert_cohort_members")@patch("products.cohorts.backend.models.util.insert_static_cohort")def test_insert_idempotent(self, mock_insert_ch):- person = self._seed_person(team=self.team, distinct_ids=["d1"])+ person = create_person(team=self.team, distinct_ids=["d1"])cohort = self._create_static_cohort()cohort.insert_users_list_by_uuid([str(person.uuid)], team_id=self.team.id)cohort.insert_users_list_by_uuid([str(person.uuid)], team_id=self.team.id)-- if not self.personhog:- assert CohortPeople.objects.filter(cohort=cohort).count() == 1diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex b480cae2ae4f..6ed1f0566fd8 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -17,7 +17,7 @@ from unittest.mock import patchfrom django.db import transactionfrom django.utils import timezone-from parameterized import parameterized, parameterized_class+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.schema import HogQLQueryModifiers, MaterializationMode@@ -26,8 +26,7 @@ from posthog.hogql import astfrom posthog.hogql.query import execute_hogql_queryfrom posthog.models import ActivityLog, Comment, Organization, Tag, User-from posthog.models.person import Person-from posthog.personhog_client.test_helpers import PersonhogTestMixin+from posthog.test.persons import create_personfrom products.conversations.backend.api.tickets import TicketReplyRequestSerializerfrom products.conversations.backend.models import Ticket, TicketAssignment@@ -688,7 +687,7 @@ class TestTicketAPI(APIBaseTest):distinct_id=f"user-{i}",)# Create person for this ticket- Person.objects.create(+ create_person(team=self.team,distinct_ids=[f"user-{i}"],properties={"email": f"user{i}@example.com"},@@ -713,11 +712,10 @@ class TestTicketAPI(APIBaseTest):# Query count should be constant regardless of number of tickets# Includes: session, user, org, team, permissions, feature flag permission org lookup,- # count query, tickets query, persons query (batch), distinct_ids prefetch,- # tagged_items prefetch, and the session-activity metadata write (deferred to on_commit,- # which this test class patches to run synchronously)- # Note: message stats are denormalized, no subqueries needed- with self.assertNumQueries(14):+ # count query, tickets query, tagged_items prefetch, and the session-activity metadata+ # write (deferred to on_commit, which this test class patches to run synchronously)+ # Note: person reads go through personhog (no DB queries)+ with self.assertNumQueries(12):response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/")self.assertEqual(response.status_code, status.HTTP_200_OK)# Should have original ticket + 10 new tickets = 11 total@@ -1301,12 +1299,8 @@ class TestTicketManager(BaseTest):self.assertEqual(ticket2.ticket_number, 2)-@parameterized_class(("personhog",), [(False,), (True,)])@patch.object(transaction, "on_commit", side_effect=immediate_on_commit)-class TestTicketPersonData(PersonhogTestMixin, APIBaseTest):- """Tests that ticket person enrichment produces identical results- via the ORM and personhog paths."""-+class TestTicketPersonData(APIBaseTest):def setUp(self):super().setUp()self.ticket = Ticket.objects.create_with_number(@@ -1318,7 +1312,7 @@ class TestTicketPersonData(PersonhogTestMixin, APIBaseTest):)def test_retrieve_ticket_includes_person_data(self, mock_on_commit):- person = self._seed_person(+ person = create_person(team=self.team,distinct_ids=["user-123", "[email protected]", "another-id"],properties={"email": "[email protected]", "name": "Test User"},@@ -1340,7 +1334,7 @@ class TestTicketPersonData(PersonhogTestMixin, APIBaseTest):assert response.json()["person"] is Nonedef test_list_tickets_includes_person_data(self, mock_on_commit):- self._seed_person(+ create_person(team=self.team,distinct_ids=["user-123", "[email protected]"],properties={"email": "[email protected]"},@@ -1354,7 +1348,6 @@ class TestTicketPersonData(PersonhogTestMixin, APIBaseTest):assert person_data is not Noneassert person_data["properties"]["email"] == "[email protected]"assert set(person_data["distinct_ids"]) == {"user-123", "[email protected]"}- self._assert_personhog_called("get_persons_by_distinct_ids_in_team")def test_list_tickets_person_null_when_no_person(self, mock_on_commit):response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/")@@ -1365,7 +1358,7 @@ class TestTicketPersonData(PersonhogTestMixin, APIBaseTest):def test_person_data_scoped_to_team(self, mock_on_commit):other_team = self.organization.teams.create(name="Other Team")- self._seed_person(+ create_person(team=other_team,distinct_ids=["user-123"],properties={"email": "[email protected]"},diff --git a/products/dashboards/backend/api/test/test_run_widgets.py b/products/dashboards/backend/api/test/test_run_widgets.pyindex cdc02fa56f7d..d1b394f84edc 100644--- a/products/dashboards/backend/api/test/test_run_widgets.py+++ b/products/dashboards/backend/api/test/test_run_widgets.py@@ -14,7 +14,7 @@ from posthog.schema import RecordingOrder, RecordingOrderDirectionfrom posthog.api.test.dashboards import DashboardAPIfrom posthog.clickhouse.client.execute import UntaggedQueryErrorfrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags-from posthog.models import Person, Team+from posthog.models import Teamfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.rbac.user_access_control import AccessControlLevel, UserAccessControl@@ -23,6 +23,7 @@ from posthog.session_recordings.models.session_recording import SessionRecordingfrom posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylistfrom posthog.session_recordings.models.session_recording_playlist_item import SessionRecordingPlaylistItemfrom posthog.slo.types import SloOperation, SloOutcome+from posthog.test.persons import create_personfrom products.dashboards.backend.api import widget_openapi_serializers as widget_openapi_serializers_modulefrom products.dashboards.backend.constants import (@@ -1044,7 +1045,7 @@ class TestDashboardRunWidgets(APIBaseTest):@patch("posthog.session_recordings.session_recording_api.list_recordings_from_query")def test_session_replay_widget_serializes_recordings_with_person(self, mock_list_recordings: MagicMock) -> None:- person = Person.objects.create(team=self.team, properties={"email": "[email protected]"})+ person = create_person(team=self.team, properties={"email": "[email protected]"})recording = SessionRecording(session_id="019e6a07-04fe-792c-b828-49375b8d42e8",team=self.team,diff --git a/products/early_access_features/backend/test/test_early_access_feature.py b/products/early_access_features/backend/test/test_early_access_feature.pyindex bf7fc025d3de..0cd905743198 100644--- a/products/early_access_features/backend/test/test_early_access_feature.py+++ b/products/early_access_features/backend/test/test_early_access_feature.py@@ -11,8 +11,8 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTest-from posthog.models import Personfrom posthog.models.team.team_caching import set_team_in_cache+from posthog.test.persons import create_personfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -875,7 +875,7 @@ class TestPreviewList(BaseTest, QueryMatchingTest):@snapshot_postgres_queriesdef test_early_access_features(self):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["example_id"],properties={"email": "[email protected]"},@@ -932,7 +932,7 @@ class TestPreviewList(BaseTest, QueryMatchingTest):@snapshot_postgres_queriesdef test_early_access_features_with_pre_env_cached_team(self):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["example_id"],properties={"email": "[email protected]"},@@ -989,7 +989,7 @@ class TestPreviewList(BaseTest, QueryMatchingTest):@snapshot_postgres_queriesdef test_early_access_features_with_cached_team(self):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["example_id"],properties={"email": "[email protected]"},@@ -1034,7 +1034,7 @@ class TestPreviewList(BaseTest, QueryMatchingTest):)def test_early_access_features_beta_only(self):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["example_id"],properties={"email": "[email protected]"},@@ -1153,7 +1153,7 @@ class TestPreviewList(BaseTest, QueryMatchingTest):@snapshot_postgres_queriesdef test_early_access_features_includes_payload_in_preview(self):- Person.objects.create(+ create_person(team=self.team,distinct_ids=["example_id"],properties={"email": "[email protected]"},diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambrindex 8d7348765a9a..5cfffa054747 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambr@@ -1808,6 +1808,16 @@'''# ---# name: TestExperimentQueryRunner.test_query_runner_with_internal_filters_3_cohort_static+ '''+ SELECT person_id+ FROM person_static_cohort+ WHERE team_id = 99999+ AND cohort_id = 99999+ AND person_id IN ['00000000-0000-4000-8000-000000000001', '00000000-0000-4000-8000-000000000002', '00000000-0000-4000-8000-000000000010']+ GROUP BY person_id+ '''+# ---+# name: TestExperimentQueryRunner.test_query_runner_with_internal_filters_3_cohort_static.1'''WITH exposures AS(SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,@@ -1872,7 +1882,7 @@use_hive_partitioning=0'''# ----# name: TestExperimentQueryRunner.test_query_runner_with_internal_filters_3_cohort_static.1+# name: TestExperimentQueryRunner.test_query_runner_with_internal_filters_3_cohort_static.2'''WITH exposures AS(SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_data_warehouse_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_data_warehouse_metric.ambrindex c09ab7e00673..4c5fb329215a 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_data_warehouse_metric.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_data_warehouse_metric.ambr@@ -972,6 +972,16 @@'''# ---# name: TestExperimentQueryRunner.test_query_runner_with_data_warehouse_internal_filters_3_cohort_static+ '''+ SELECT person_id+ FROM person_static_cohort+ WHERE team_id = 99999+ AND cohort_id = 99999+ AND person_id IN ['00000000-0000-4000-8000-000000000000', '00000000-0000-4000-8000-000000000001', '00000000-0000-4000-8000-000000000002', '00000000-0000-4000-8000-000000000003', '00000000-0000-4000-8000-000000000004', '00000000-0000-4000-8000-000000000005']+ GROUP BY person_id+ '''+# ---+# name: TestExperimentQueryRunner.test_query_runner_with_data_warehouse_internal_filters_3_cohort_static.1'''WITH exposures AS(SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,@@ -1031,7 +1041,7 @@use_hive_partitioning=0'''# ----# name: TestExperimentQueryRunner.test_query_runner_with_data_warehouse_internal_filters_3_cohort_static.1+# name: TestExperimentQueryRunner.test_query_runner_with_data_warehouse_internal_filters_3_cohort_static.2'''WITH exposures AS(SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.pyindex 50bda131b489..212493766e3b 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py@@ -1098,7 +1098,6 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):],])- @override_settings(PERSONHOG_ENABLED=False)@snapshot_clickhouse_queriesdef test_query_runner_with_internal_filters(self, filter_name: str, filter: dict, expected_results: dict):feature_flag = self.create_feature_flag()diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/utils.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/utils.pyindex a6f14879bdf6..e21f886cdd6f 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/utils.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/utils.py@@ -4,15 +4,15 @@ from posthog.test.base import _create_event, _create_personfrom posthog.models.filters.utils import GroupTypeIndexfrom posthog.models.group.util import create_group-from posthog.models.group_type_mapping import GroupTypeMappingfrom posthog.models.team.team import Team+from posthog.test.persons import create_group_type_mappingfrom products.feature_flags.backend.models.feature_flag import FeatureFlagdef create_standard_group_test_events(team: Team, feature_flag: FeatureFlag):group_type_index: GroupTypeIndex = 0- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=team,project_id=team.project_id,group_type_index=group_type_index,diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambrindex 33d02272055d..0fc181dc46b5 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr@@ -252,6 +252,16 @@'''# ---# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts+ '''+ SELECT person_id+ FROM person_static_cohort+ WHERE team_id = 99999+ AND cohort_id = 99999+ AND person_id IN ['00000000-0000-4000-8000-000000000000', '00000000-0000-4000-8000-000000000001', '00000000-0000-4000-8000-000000000002']+ GROUP BY person_id+ '''+# ---+# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts.1'''/* user_id:0 request:_snapshot_ */SELECT count(DISTINCT persons.id) AS `count(DISTINCT persons.id)`@@ -287,7 +297,7 @@use_hive_partitioning=0'''# ----# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts.1+# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts.2'''/* user_id:0 request:_snapshot_ */SELECT count(1)@@ -299,7 +309,7 @@HAVING max(is_deleted) = 0 SETTINGS optimize_aggregation_in_order = 1)'''# ----# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts.2+# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts.3'''SELECT count(DISTINCT person_id)@@ -309,7 +319,7 @@AND version = 0'''# ----# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts.3+# name: TestBlastRadius.test_user_blast_radius_with_multiple_static_cohorts.4'''/* user_id:0 request:_snapshot_ */SELECT count(DISTINCT persons.id) AS `count(DISTINCT persons.id)`@@ -1363,6 +1373,17 @@'''# ---# name: TestFeatureFlag.test_creating_static_cohort.27+ '''+ /* user_id:0 celery:posthog.tasks.calculate_cohort.insert_cohort_from_feature_flag */+ SELECT person_id+ FROM person_static_cohort+ WHERE team_id = 99999+ AND cohort_id = 99999+ AND person_id IN ['00000000-0000-4000-8000-000000000000']+ GROUP BY person_id+ '''+# ---+# name: TestFeatureFlag.test_creating_static_cohort.28'''/* user_id:0 request:_snapshot_ */SELECT iddiff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex eaecb859119e..b6b493307878 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -29,15 +29,18 @@ from posthog import redisfrom posthog.api.cohort import BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS, get_cohort_actors_for_feature_flagfrom posthog.api.services.flags_service import FlagVersionConflictErrorfrom posthog.constants import AvailableFeature-from posthog.models import GroupTypeMapping, TaggedItem, User-from posthog.models.group.group import Group+from posthog.models import TaggedItem, Userfrom posthog.models.group.util import create_groupfrom posthog.models.organization import Organization, OrganizationMembership-from posthog.models.person import Personfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Teamfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.test.db_context_capturing import capture_db_queries+from posthog.test.persons import (+ create_group as create_test_group,+ create_group_type_mapping,+ create_person,+)from posthog.test.test_utils import create_group_type_mapping_without_created_atfrom products.cohorts.backend.models.calculation_history import CohortCalculationHistory@@ -5265,7 +5268,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):)def test_mixed_aggregation_types_across_condition_sets(self):- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)@@ -5301,7 +5304,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(groups[1]["aggregation_group_type_index"], 0)def test_mixed_aggregation_round_trip(self):- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)@@ -5329,7 +5332,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(filters["groups"][1]["aggregation_group_type_index"], 0)def test_mixed_aggregation_with_properties(self):- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)@@ -5372,7 +5375,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(groups[1]["aggregation_group_type_index"], 0)def test_patch_uniform_flag_to_mixed(self):- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)@@ -5412,7 +5415,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):def test_per_condition_aggregation_normalization(self):"""Test that flag-level aggregation is distributed to condition sets without one"""- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)@@ -5439,7 +5442,7 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):def test_per_condition_aggregation_roundtrip(self):"""Test that per-condition aggregation values persist through create/read"""- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)@@ -6743,17 +6746,17 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):)def test_feature_flag_includes_group_key_names(self):- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0)- Group.objects.create(+ create_test_group(team=self.team,group_key="org-uuid-1",group_type_index=0,group_properties={"name": "Acme Corp"},version=0,)- Group.objects.create(+ create_test_group(team=self.team,group_key="org-uuid-2",group_type_index=0,@@ -8187,7 +8190,6 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):with (self.settings(DEBUG=False),- patch("posthog.personhog_client.gate.use_personhog", return_value=False),patch("products.cohorts.backend.models.util.insert_static_cohort",side_effect=Exception("clickhouse insert failed"),@@ -8806,7 +8808,7 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):@snapshot_clickhouse_queriesdef test_user_blast_radius_with_group_key_property(self):"""Test that $group_key property correctly identifies groups by their key"""- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="organization",@@ -8932,7 +8934,7 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):def test_user_blast_radius_with_group_key_operators(self, _name, value, operator, expected_affected, expected_total):- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="organization",@@ -8984,7 +8986,7 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):def test_user_blast_radius_with_group_key_and_regular_properties(self):"""Test combining $group_key with regular group properties"""- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="organization",@@ -9150,7 +9152,7 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):def test_user_blast_radius_with_group_key_unsupported_operator(self):"""Test that unsupported operators on $group_key raise validation errors"""- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="organization",@@ -9189,7 +9191,7 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):def test_user_blast_radius_with_group_key_exact_list_values(self):"""Test that EXACT operator with list values uses IN logic"""- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="organization",@@ -9243,7 +9245,7 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):def test_user_blast_radius_with_group_key_is_not_list_values(self):"""Test that IS_NOT operator with list values uses NOT IN logic"""- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="organization",@@ -9300,7 +9302,7 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):def test_user_blast_radius_with_group_key_icontains_list_values_raises_error(self):"""Test that ICONTAINS operator with list values raises validation error"""- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="organization",@@ -9623,7 +9625,7 @@ class TestBlastRadius(ClickhouseTestMixin, APIBaseTest):def test_user_blast_radius_with_semver_operators_on_groups(self):"""Test semver operators work with group properties"""- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="organization",@@ -12224,9 +12226,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):key="test-flag",filters={"groups": [{"properties": [{"key": "email", "type": "person", "value": "[email protected]"}]}]},)- person = Person.objects.create(- team=self.team, distinct_ids=["test-user"], properties={"email": "[email protected]"}- )+ person = create_person(team=self.team, distinct_ids=["test-user"], properties={"email": "[email protected]"})# Mock person lookupmock_get_person.return_value = (person, ["test-user"])@@ -12282,7 +12282,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):distinct_id back, otherwise feature_flag:read tokens could enumeratedistinct_ids for any person UUID."""flag = FeatureFlag.objects.create(team=self.team, key="test-flag")- person = Person.objects.create(team=self.team, distinct_ids=["zzz", "aaa", "mmm"])+ person = create_person(team=self.team, distinct_ids=["zzz", "aaa", "mmm"])# Hand the resolver back distinct_ids in deliberately non-sorted order# to prove the sort happens in feature_flag.py, not upstream.@@ -12326,7 +12326,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):ensure_experience_continuity=True,)- Person.objects.create(team=self.team, distinct_ids=["test-user"])+ create_person(team=self.team, distinct_ids=["test-user"])mock_get_flags.return_value = {"flags": {@@ -12419,7 +12419,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):def test_test_evaluation_missing_internal_token_error(self, mock_get_flags):"""Test 500 when INTERNAL_REQUEST_TOKEN is not set."""flag = FeatureFlag.objects.create(team=self.team, key="test-flag")- Person.objects.create(team=self.team, distinct_ids=["test-user"])+ create_person(team=self.team, distinct_ids=["test-user"])response = self.client.post(f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/test_evaluation/",@@ -12435,7 +12435,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):def test_test_evaluation_historical_missing_conditions_502(self, mock_get_flags):"""Test 502 when historical evaluation returns no conditions (misconfigured token)."""flag = FeatureFlag.objects.create(team=self.team, key="test-flag")- Person.objects.create(team=self.team, distinct_ids=["test-user"])+ create_person(team=self.team, distinct_ids=["test-user"])# Mock service to return flag dict without 'conditions' key - indicates token issuemock_get_flags.return_value = {@@ -12470,7 +12470,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):def test_test_evaluation_current_missing_conditions_200(self, mock_get_flags):"""Test 200 when current evaluation returns no conditions (no 502 for current evaluation)."""flag = FeatureFlag.objects.create(team=self.team, key="test-flag")- Person.objects.create(team=self.team, distinct_ids=["test-user"])+ create_person(team=self.team, distinct_ids=["test-user"])# Mock service to return flag dict without 'conditions' keymock_get_flags.return_value = {@@ -12501,7 +12501,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):def test_test_evaluation_build_properties_failure(self, mock_build_props):"""Test 500 when build_person_properties_at_time raises exception."""flag = FeatureFlag.objects.create(team=self.team, key="test-flag")- Person.objects.create(team=self.team, distinct_ids=["test-user"])+ create_person(team=self.team, distinct_ids=["test-user"])# Mock exception during property buildingmock_build_props.side_effect = Exception("Database error")@@ -12524,7 +12524,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):key="test-flag",filters={"groups": [{"properties": [{"key": "email", "type": "person", "value": "[email protected]"}]}]},)- Person.objects.create(+ create_person(team=self.team,distinct_ids=["test-user"],properties={"email": "[email protected]", "name": "Test User", "age": 30},@@ -12572,7 +12572,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):filters={"feature_enrollment": True, "groups": [{"properties": []}]},)enrollment_key = f"$feature_enrollment/{flag.key}"- Person.objects.create(+ create_person(team=self.team,distinct_ids=["test-user"],properties={enrollment_key: True, "email": "[email protected]"},@@ -12606,7 +12606,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):def test_test_evaluation_unexpected_response_type(self, mock_get_flags):"""Test 502 when flag service returns unexpected response format."""flag = FeatureFlag.objects.create(team=self.team, key="test-flag")- Person.objects.create(team=self.team, distinct_ids=["test-user"])+ create_person(team=self.team, distinct_ids=["test-user"])# Mock unexpected response format (not a dict)mock_get_flags.return_value = {"flags": {"test-flag": "unexpected_string"}}@@ -12679,7 +12679,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):ensure_experience_continuity=True,)- Person.objects.create(team=self.team, distinct_ids=["test-user"])+ create_person(team=self.team, distinct_ids=["test-user"])with patch("products.feature_flags.backend.api.feature_flag.build_person_properties_at_time"@@ -12721,7 +12721,7 @@ class TestFeatureFlagTestEvaluation(APIBaseTest, ClickhouseTestMixin):created_by=self.user,filters={"groups": [{"properties": [], "rollout_percentage": 100}]},)- Person.objects.create(team=self.team, distinct_ids=["test-user"])+ create_person(team=self.team, distinct_ids=["test-user"])mock_get_flags.return_value = {"flags": {"test-flag": {diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.pyindex 3d97cba7485e..1e1a1d544cb9 100644--- a/products/feature_flags/backend/test/test_local_evaluation.py+++ b/products/feature_flags/backend/test/test_local_evaluation.py@@ -15,6 +15,8 @@ from posthog.models.group_type_mapping import (from posthog.models.project import Projectfrom posthog.models.tag import Tagfrom posthog.models.team.team import Team+from posthog.test.personhog_fake import get_active_fake+from posthog.test.persons import _seed_group_type_mapping_into_fake, create_group_type_mappingfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom posthog.utils import safe_cache_delete@@ -342,6 +344,9 @@ class TestUpdateFlagCachesGroupMappingGuards(BaseTest):def test_writes_when_genuinely_empty(self, mock_emptied_counter):# A team that truly has no group types must still rebuild normallyGroupTypeMapping.objects.filter(team_id=self.team.id).delete()+ fake = get_active_fake()+ fake._group_type_mappings_by_project.pop(self.team.project_id, None)+ fake._group_type_mappings_by_team.pop(self.team.id, None)self._clear_stale()clear_flag_definition_caches(self.team)@@ -1255,10 +1260,10 @@ class TestLocalEvaluationBatch(BaseTest):filters={"groups": [{"rollout_percentage": 100}]},)- with self.assertNumQueries(3):- # Expected queries: survey flag IDs, flags (with evaluation- # tags via ArrayAgg), and group type mappings. No cohort- # query should be issued.+ with self.assertNumQueries(2):+ # Expected queries: survey flag IDs and flags (with evaluation+ # tags via ArrayAgg). Group type mappings are read from+ # personhog, not SQL. No cohort query should be issued.results = _get_flags_response_for_local_evaluation_batch([team], True)assert results[team.id]["cohorts"] == {}@@ -1611,7 +1616,7 @@ class TestVerifyFlagDefinitions(BaseTest):assert len(cohorts_diff) == 1def test_verify_returns_mismatch_when_group_type_mapping_changed(self):- GroupTypeMapping.objects.create(+ create_group_type_mapping(team=self.team,project_id=self.team.project_id,group_type="company",@@ -1633,6 +1638,7 @@ class TestVerifyFlagDefinitions(BaseTest):mapping = GroupTypeMapping.objects.get(team=self.team, group_type_index=0)mapping.group_type = "organization"mapping.save()+ _seed_group_type_mapping_into_fake(mapping)result = verify_team_flag_definitions(self.team, include_cohorts=True, verbose=True)diff --git a/products/feature_flags/backend/test/test_max_tools.py b/products/feature_flags/backend/test/test_max_tools.pyindex df8eebf58973..8d3459d977b9 100644--- a/products/feature_flags/backend/test/test_max_tools.py+++ b/products/feature_flags/backend/test/test_max_tools.py@@ -7,6 +7,7 @@ from posthog.schema import FeatureFlagGroupType, GroupPropertyFilter, PersonPropfrom posthog.models.group_type_mapping import GroupTypeMappingfrom posthog.sync import database_sync_to_async+from posthog.test.persons import _seed_group_type_mapping_into_fakefrom products.feature_flags.backend.max_tools import (CreateFeatureFlagTool,@@ -182,13 +183,14 @@ class TestCreateFeatureFlagTool(APIBaseTest):assert len(flag.filters["groups"][0]["properties"]) == 1async def test_create_flag_with_group_type(self):- await GroupTypeMapping.objects.acreate(+ mapping = await GroupTypeMapping.objects.acreate(team=self.team,project_id=self.team.project_id,group_type="organization",group_type_index=0,name_plural="Organizations",)+ _seed_group_type_mapping_into_fake(mapping)tool = self._create_tool()@@ -209,13 +211,14 @@ class TestCreateFeatureFlagTool(APIBaseTest):assert flag.filters["aggregation_group_type_index"] == 0async def test_create_flag_with_group_and_property(self):- await GroupTypeMapping.objects.acreate(+ mapping = await GroupTypeMapping.objects.acreate(team=self.team,project_id=self.team.project_id,group_type="organization",group_type_index=0,name_plural="Organizations",)+ _seed_group_type_mapping_into_fake(mapping)tool = self._create_tool()@@ -392,13 +395,14 @@ class TestCreateFeatureFlagTool(APIBaseTest):assert not existsasync def test_create_multivariate_with_property_filters(self):- await GroupTypeMapping.objects.acreate(+ mapping = await GroupTypeMapping.objects.acreate(team=self.team,project_id=self.team.project_id,group_type="organization",group_type_index=0,name_plural="Organizations",)+ _seed_group_type_mapping_into_fake(mapping)tool = self._create_tool()diff --git a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.pyindex 9842af306f09..683eba5280d0 100644--- a/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py+++ b/products/marketing_analytics/backend/hogql_queries/test_conversion_goal_processor.py@@ -1,13 +1,6 @@import pytestfrom freezegun import freeze_time-from posthog.test.base import (- BaseTest,- ClickhouseTestMixin,- _create_event,- _create_person,- events_cache_tests,- persons_cache_tests,-)+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, events_cache_testsfrom parameterized import parameterized@@ -29,7 +22,6 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.hogql.test.utils import pretty_print_in_testsfrom posthog.models.event.util import bulk_create_events-from posthog.models.person.util import bulk_create_personsfrom products.actions.backend.models.action import Actionfrom products.marketing_analytics.backend.hogql_queries.conversion_goal_processor import (@@ -54,13 +46,11 @@ def flush_persons_and_events_in_batches(batch_size: int = 25):Custom flush function that processes events in smaller batches to avoid memory limits.This helps prevent ClickHouse memory exceeded errors during bulk inserts."""- person_mapping = {}- if len(persons_cache_tests) > 0:- person_mapping = bulk_create_persons(persons_cache_tests)- persons_cache_tests.clear()+ from posthog.test.persons import flush_persons_to_db_and_clickhouse++ person_mapping = flush_persons_to_db_and_clickhouse()if len(events_cache_tests) > 0:- # Process events in smaller batches to avoid memory issuesfor i in range(0, len(events_cache_tests), batch_size):batch = events_cache_tests[i : i + batch_size]bulk_create_events(batch, person_mapping)diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.pyindex a3cd74208f07..2e6036806963 100644--- a/products/product_analytics/backend/api/test/test_insight.py+++ b/products/product_analytics/backend/api/test/test_insight.py@@ -51,9 +51,10 @@ from posthog.caching.insight_cache import update_cachefrom posthog.caching.insight_caching_state import TargetCacheAgefrom posthog.constants import AvailableFeaturefrom posthog.hogql_queries.query_runner import ExecutionMode-from posthog.models import Filter, OrganizationMembership, Person, SharingConfiguration, Team, User+from posthog.models import Filter, OrganizationMembership, SharingConfiguration, Team, Userfrom posthog.models.project import Projectfrom posthog.test.db_context_capturing import capture_db_queries+from posthog.test.persons import create_personfrom products.cohorts.backend.models.cohort import Cohortfrom products.dashboards.backend.models.dashboard import Dashboard@@ -2919,7 +2920,7 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):self.assertEqual(len(lines), 3, response.content)def _create_one_person_cohort(self, properties: list[dict[str, Any]]) -> int:- Person.objects.create(team=self.team, properties=properties)+ create_person(team=self.team, properties=properties)cohort_one_id = self.client.post(f"/api/projects/{self.team.id}/cohorts",data={"name": "whatever", "groups": [{"properties": properties}]},diff --git a/products/replay_vision/backend/tests/test_scanner_candidate_query.py b/products/replay_vision/backend/tests/test_scanner_candidate_query.pyindex 7f0952da6384..cd33e929b13c 100644--- a/products/replay_vision/backend/tests/test_scanner_candidate_query.py+++ b/products/replay_vision/backend/tests/test_scanner_candidate_query.py@@ -11,6 +11,7 @@ from posthog.hogql import astfrom posthog.clickhouse.client import sync_executefrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summaryfrom posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL+from posthog.test.persons import create_personfrom products.replay_vision.backend.queries.scanner_candidate_query import (DEFAULT_CANDIDATE_LIMIT,@@ -355,10 +356,8 @@ class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):}]team.save(update_fields=["test_account_filters"])- from posthog.models.person import Person-- Person.objects.create(team=team, distinct_ids=["internal"], properties={"email": "[email protected]"})- Person.objects.create(team=team, distinct_ids=["external"], properties={"email": "[email protected]"})+ create_person(team=team, distinct_ids=["internal"], properties={"email": "[email protected]"})+ create_person(team=team, distinct_ids=["external"], properties={"email": "[email protected]"})self._produce(team.id,diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex f1759e2c19f1..6bf7449c9198 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -24,8 +24,9 @@ from rest_framework import statusfrom posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTestfrom posthog.constants import AvailableFeature-from posthog.models import Person, Team+from posthog.models import Teamfrom posthog.models.organization import Organization, OrganizationMembership+from posthog.test.persons import create_personfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort@@ -5356,8 +5357,8 @@ class TestSurveyStats(ClickhouseTestMixin, APIBaseTest):archived=True,)- user_1 = Person.objects.create(team=self.team, distinct_ids=[str(uuid.uuid4())])- user_2 = Person.objects.create(team=self.team, distinct_ids=[str(uuid.uuid4())])+ user_1 = create_person(team=self.team, distinct_ids=[str(uuid.uuid4())])+ user_2 = create_person(team=self.team, distinct_ids=[str(uuid.uuid4())])# Insert events for both surveysevents = [@@ -5408,9 +5409,9 @@ class TestSurveyStats(ClickhouseTestMixin, APIBaseTest):)sub_id_1 = str(uuid.uuid4())sub_id_2 = str(uuid.uuid4())- user_1 = Person.objects.create(team=self.team, distinct_ids=[str(uuid.uuid4())])- user_2 = Person.objects.create(team=self.team, distinct_ids=[str(uuid.uuid4())])- user_3 = Person.objects.create(team=self.team, distinct_ids=[str(uuid.uuid4())])+ user_1 = create_person(team=self.team, distinct_ids=[str(uuid.uuid4())])+ user_2 = create_person(team=self.team, distinct_ids=[str(uuid.uuid4())])+ user_3 = create_person(team=self.team, distinct_ids=[str(uuid.uuid4())])# Events:# user_1: shown -> sent (legacy) -> sent (partial 1, ts1) -> sent (partial 1, ts2)@@ -5528,7 +5529,7 @@ class TestSurveyStats(ClickhouseTestMixin, APIBaseTest):type="popover",questions=[{"type": "open", "question": "How are you?"}],)- user = Person.objects.create(team=self.team, distinct_ids=[str(uuid.uuid4())])+ user = create_person(team=self.team, distinct_ids=[str(uuid.uuid4())])_create_event(team=self.team,@@ -5565,7 +5566,7 @@ class TestSurveyStats(ClickhouseTestMixin, APIBaseTest):)response_uuid = str(uuid.uuid4())- user = Person.objects.create(team=self.team, distinct_ids=[str(uuid.uuid4())])+ user = create_person(team=self.team, distinct_ids=[str(uuid.uuid4())])_create_event(team=self.team,@@ -6669,7 +6670,7 @@ class TestSurveyResponsesList(ClickhouseTestMixin, APIBaseTest):self.assertEqual(data["offset"], 0)def test_returns_rows_with_resolved_question_text(self):- person = Person.objects.create(team=self.team, distinct_ids=["user-1"])+ person = create_person(team=self.team, distinct_ids=["user-1"])self._create_response_event("user-1", "2024-06-10 09:05:00", "9", "Loved the UX")flush_persons_and_events()@@ -6695,8 +6696,8 @@ class TestSurveyResponsesList(ClickhouseTestMixin, APIBaseTest):assert person # silence unuseddef test_score_lte_filters_detractors(self):- Person.objects.create(team=self.team, distinct_ids=["detractor"])- Person.objects.create(team=self.team, distinct_ids=["promoter"])+ create_person(team=self.team, distinct_ids=["detractor"])+ create_person(team=self.team, distinct_ids=["promoter"])self._create_response_event("detractor", "2024-06-10 09:05:00", "3", "Frustrating")self._create_response_event("promoter", "2024-06-10 09:06:00", "10", "Amazing")flush_persons_and_events()@@ -6715,9 +6716,9 @@ class TestSurveyResponsesList(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)def test_pagination_has_more(self):- Person.objects.create(team=self.team, distinct_ids=["u-1"])- Person.objects.create(team=self.team, distinct_ids=["u-2"])- Person.objects.create(team=self.team, distinct_ids=["u-3"])+ create_person(team=self.team, distinct_ids=["u-1"])+ create_person(team=self.team, distinct_ids=["u-2"])+ create_person(team=self.team, distinct_ids=["u-3"])self._create_response_event("u-1", "2024-06-10 09:01:00", "8", "a")self._create_response_event("u-2", "2024-06-10 09:02:00", "8", "b")self._create_response_event("u-3", "2024-06-10 09:03:00", "8", "c")@@ -6735,8 +6736,8 @@ class TestSurveyResponsesList(ClickhouseTestMixin, APIBaseTest):self.assertFalse(data2["has_more"])def test_since_filter(self):- Person.objects.create(team=self.team, distinct_ids=["old"])- Person.objects.create(team=self.team, distinct_ids=["new"])+ create_person(team=self.team, distinct_ids=["old"])+ create_person(team=self.team, distinct_ids=["new"])self._create_response_event("old", "2024-06-01 09:00:00", "8", "old")self._create_response_event("new", "2024-06-15 09:00:00", "8", "new")flush_persons_and_events()@@ -6747,8 +6748,8 @@ class TestSurveyResponsesList(ClickhouseTestMixin, APIBaseTest):self.assertEqual(data["results"][0]["distinct_id"], "new")def test_exclude_archived(self):- Person.objects.create(team=self.team, distinct_ids=["kept"])- Person.objects.create(team=self.team, distinct_ids=["archived"])+ create_person(team=self.team, distinct_ids=["kept"])+ create_person(team=self.team, distinct_ids=["archived"])archived_uuid = str(uuid.uuid4())self._create_response_event("kept", "2024-06-10 09:05:00", "8", "kept")self._create_response_event("archived", "2024-06-10 09:06:00", "3", "archived", event_uuid=archived_uuid)@@ -6961,11 +6962,11 @@ class TestSurveyStatsPerQuestion(ClickhouseTestMixin, APIBaseTest):self.assertNotIn("per_question_stats", response.json())def test_per_question_stats_when_requested(self):- Person.objects.create(team=self.team, distinct_ids=["u-1"])- Person.objects.create(team=self.team, distinct_ids=["u-2"])- Person.objects.create(team=self.team, distinct_ids=["u-3"])+ create_person(team=self.team, distinct_ids=["u-1"])+ create_person(team=self.team, distinct_ids=["u-2"])+ create_person(team=self.team, distinct_ids=["u-3"])# u-4 picks the open-choice "Other" with free text — must be redacted to <other>.- Person.objects.create(team=self.team, distinct_ids=["u-4"])+ create_person(team=self.team, distinct_ids=["u-4"])for distinct_id, rating, choice, text in [("u-1", "9", "yes", "Loved it"),("u-2", "7", "yes", "Good"),diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_goals.py b/products/web_analytics/backend/hogql_queries/test/test_web_goals.pyindex 3f8242267c4e..676fa0f4fa75 100644--- a/products/web_analytics/backend/hogql_queries/test/test_web_goals.py+++ b/products/web_analytics/backend/hogql_queries/test/test_web_goals.py@@ -25,6 +25,7 @@ from posthog.clickhouse.client import sync_executefrom posthog.models import Element, Personfrom posthog.models.person.sql import PERSON_DISTINCT_ID_OVERRIDES_TABLEfrom posthog.models.utils import uuid7+from posthog.test.persons import add_cohort_membersfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort@@ -395,7 +396,7 @@ class TestWebGoalsQueryRunner(ClickhouseTestMixin, APIBaseTest):)# Add persons to the cohort- cohort.people.add(p1, p2)+ add_cohort_members(cohort, [p1, p2])# Insert person_distinct_id_overrides that create the scenario for any() function# This creates multiple overrides for the same distinct_id in ClickHouse with the same version